@amplitude/session-replay-browser 1.46.0 → 1.47.0-sr-trc-debug-log.1

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.
Files changed (65) hide show
  1. package/lib/cjs/config/joined-config.d.ts +6 -1
  2. package/lib/cjs/config/joined-config.d.ts.map +1 -1
  3. package/lib/cjs/config/joined-config.js +63 -19
  4. package/lib/cjs/config/joined-config.js.map +1 -1
  5. package/lib/cjs/config/local-config.d.ts +5 -1
  6. package/lib/cjs/config/local-config.d.ts.map +1 -1
  7. package/lib/cjs/config/local-config.js +19 -1
  8. package/lib/cjs/config/local-config.js.map +1 -1
  9. package/lib/cjs/config/types.d.ts +19 -1
  10. package/lib/cjs/config/types.d.ts.map +1 -1
  11. package/lib/cjs/config/types.js.map +1 -1
  12. package/lib/cjs/diagnostics.d.ts +43 -0
  13. package/lib/cjs/diagnostics.d.ts.map +1 -0
  14. package/lib/cjs/diagnostics.js +54 -0
  15. package/lib/cjs/diagnostics.js.map +1 -0
  16. package/lib/cjs/session-replay.d.ts +25 -0
  17. package/lib/cjs/session-replay.d.ts.map +1 -1
  18. package/lib/cjs/session-replay.js +250 -51
  19. package/lib/cjs/session-replay.js.map +1 -1
  20. package/lib/cjs/targeting/targeting-manager.d.ts +4 -1
  21. package/lib/cjs/targeting/targeting-manager.d.ts.map +1 -1
  22. package/lib/cjs/targeting/targeting-manager.js +47 -10
  23. package/lib/cjs/targeting/targeting-manager.js.map +1 -1
  24. package/lib/cjs/version.d.ts +1 -1
  25. package/lib/cjs/version.d.ts.map +1 -1
  26. package/lib/cjs/version.js +1 -1
  27. package/lib/cjs/version.js.map +1 -1
  28. package/lib/esm/config/joined-config.d.ts +6 -1
  29. package/lib/esm/config/joined-config.d.ts.map +1 -1
  30. package/lib/esm/config/joined-config.js +63 -19
  31. package/lib/esm/config/joined-config.js.map +1 -1
  32. package/lib/esm/config/local-config.d.ts +5 -1
  33. package/lib/esm/config/local-config.d.ts.map +1 -1
  34. package/lib/esm/config/local-config.js +20 -2
  35. package/lib/esm/config/local-config.js.map +1 -1
  36. package/lib/esm/config/types.d.ts +19 -1
  37. package/lib/esm/config/types.d.ts.map +1 -1
  38. package/lib/esm/config/types.js.map +1 -1
  39. package/lib/esm/diagnostics.d.ts +43 -0
  40. package/lib/esm/diagnostics.d.ts.map +1 -0
  41. package/lib/esm/diagnostics.js +51 -0
  42. package/lib/esm/diagnostics.js.map +1 -0
  43. package/lib/esm/session-replay.d.ts +25 -0
  44. package/lib/esm/session-replay.d.ts.map +1 -1
  45. package/lib/esm/session-replay.js +250 -51
  46. package/lib/esm/session-replay.js.map +1 -1
  47. package/lib/esm/targeting/targeting-manager.d.ts +4 -1
  48. package/lib/esm/targeting/targeting-manager.d.ts.map +1 -1
  49. package/lib/esm/targeting/targeting-manager.js +47 -10
  50. package/lib/esm/targeting/targeting-manager.js.map +1 -1
  51. package/lib/esm/version.d.ts +1 -1
  52. package/lib/esm/version.d.ts.map +1 -1
  53. package/lib/esm/version.js +1 -1
  54. package/lib/esm/version.js.map +1 -1
  55. package/lib/scripts/index-min.js +1 -1
  56. package/lib/scripts/index-min.js.gz +0 -0
  57. package/lib/scripts/index-min.js.map +1 -1
  58. package/lib/scripts/observers-min.js +1 -1
  59. package/lib/scripts/observers-min.js.gz +0 -0
  60. package/lib/scripts/session-replay-browser-min.js +1 -1
  61. package/lib/scripts/session-replay-browser-min.js.gz +0 -0
  62. package/lib/scripts/session-replay-browser-min.js.map +1 -1
  63. package/lib/scripts/targeting-min.js +1 -1
  64. package/lib/scripts/targeting-min.js.gz +0 -0
  65. package/package.json +4 -4
@@ -1,2 +1,2 @@
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";var c,d;!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"}(c||(c={})),function(e){e.IDENTIFY="$identify",e.GROUP_IDENTIFY="$groupidentify",e.REVENUE="revenue_amount"}(d||(d={}));var u,h="$default_instance",g="https://api2.amplitude.com/2/httpapi";!function(e){e.Unknown="unknown",e.Skipped="skipped",e.Success="success",e.RateLimit="rate_limit",e.PayloadTooLarge="payload_too_large",e.Invalid="invalid",e.Failed="failed",e.Timeout="Timeout",e.SystemError="SystemError"}(u||(u={}));var v,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=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"}(v||(v={}));var b="Amplitude Logger ",S=function(){function e(){this.logLevel=v.None}return e.prototype.disable=function(){this.logLevel=v.None},e.prototype.enable=function(e){void 0===e&&(e=v.Warn),this.logLevel=e},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<v.Verbose||console.log("".concat(b,"[Log]: ").concat(e.join(" ")))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<v.Warn||console.warn("".concat(b,"[Warn]: ").concat(e.join(" ")))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<v.Error||console.error("".concat(b,"[Error]: ").concat(e.join(" ")))},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<v.Debug||console.log("".concat(b,"[Debug]: ").concat(e.join(" ")))},e}(),I=function(){return{flushMaxRetries:12,flushQueueSize:200,flushIntervalMillis:1e4,instanceName:h,logLevel:v.Warn,loggerProvider:new S,offline:!1,optOut:!1,serverUrl:g,serverZone:"US",useBatch:!1}},C=function(){function e(e){var t,i,n,s;this._optOut=!1;var r=I();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=e.instanceName||r.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=k(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}(),w=function(e,t){return"EU"===e?t?"https://api.eu.amplitude.com/batch":"https://api.eu.amplitude.com/2/httpapi":t?"https://api2.amplitude.com/batch":g},k=function(e,t,i){if(void 0===e&&(e=""),void 0===t&&(t=I().serverZone),void 0===i&&(i=I().useBatch),e)return{serverUrl:e,serverZone:void 0};var n=["US","EU"].includes(t)?t:I().serverZone;return{serverZone:n,serverUrl:w(n,i)}};var P=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<v.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}},E=function(){function e(){}return e.prototype.getApplicationContext=function(){return{versionName:this.versionName,language:M(),platform:"Web",os:void 0,deviceModel:void 0}},e}(),M=function(){return"undefined"!=typeof navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||""},T=function(){function e(){this.queue=[]}return e.prototype.logEvent=function(e){this.receiver?this.receiver(e):this.queue.length<512&&this.queue.push(e)},e.prototype.setEventReceiver=function(e){this.receiver=e,this.queue.length>0&&(this.queue.forEach(function(t){e(t)}),this.queue=[])},e}(),O=function(){return O=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var s in t=arguments[i])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},O.apply(this,arguments)};function R(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function x(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,s,r=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=r.next()).done;)o.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(i=r.return)&&i.call(r)}finally{if(s)throw s.error}}return o}"function"==typeof SuppressedError&&SuppressedError;var _=function(e,t){var i,n,s=typeof e;if(s!==typeof t)return!1;try{for(var r=R(["string","number","boolean","undefined"]),o=r.next();!o.done;o=r.next()){if(o.value===s)return e===t}}catch(e){i={error:e}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}if(null==e&&null==t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;var a=Array.isArray(e),l=Array.isArray(t);if(a!==l)return!1;if(!a||!l){var c=Object.keys(e).sort(),d=Object.keys(t).sort();if(!_(c,d))return!1;var u=!0;return Object.keys(e).forEach(function(i){_(e[i],t[i])||(u=!1)}),u}for(var h=0;h<e.length;h++)if(!_(e[h],t[h]))return!1;return!0};Object.entries||(Object.entries=function(e){for(var t=Object.keys(e),i=t.length,n=new Array(i);i--;)n[i]=[t[i],e[t[i]]];return n});var L,F=function(){function e(){this.identity={userProperties:{}},this.listeners=new Set}return e.prototype.editIdentity=function(){var e=this,t=O({},this.identity.userProperties),i=O(O({},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:function(e){return i.optOut=e,this},updateUserProperties:function(e){var t,n,s,r,o,a,l=i.userProperties||{};try{for(var c=R(Object.entries(e)),d=c.next();!d.done;d=c.next()){var u=x(d.value,2),h=u[0],g=u[1];switch(h){case"$set":try{for(var v=(s=void 0,R(Object.entries(g))),f=v.next();!f.done;f=v.next()){var p=x(f.value,2),m=p[0],y=p[1];l[m]=y}}catch(e){s={error:e}}finally{try{f&&!f.done&&(r=v.return)&&r.call(v)}finally{if(s)throw s.error}}break;case"$unset":try{for(var b=(o=void 0,R(Object.keys(g))),S=b.next();!S.done;S=b.next()){delete l[m=S.value]}}catch(e){o={error:e}}finally{try{S&&!S.done&&(a=b.return)&&a.call(b)}finally{if(o)throw o.error}}break;case"$clearAll":l={}}}}catch(e){t={error:e}}finally{try{d&&!d.done&&(n=c.return)&&n.call(c)}finally{if(t)throw t.error}}return i.userProperties=l,this},commit:function(){return e.setIdentity(i),this}}},e.prototype.getIdentity=function(){return O({},this.identity)},e.prototype.setIdentity=function(e){var t=O({},this.identity);this.identity=O({},e),_(t,this.identity)||this.listeners.forEach(function(t){t(e)})},e.prototype.addIdentityListener=function(e){this.listeners.add(e)},e.prototype.removeIdentityListener=function(e){this.listeners.delete(e)},e}(),$="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:self,q=function(){function e(){this.identityStore=new F,this.eventBridge=new T,this.applicationContextProvider=new E}return e.getInstance=function(t){return $.analyticsConnectorInstances||($.analyticsConnectorInstances={}),$.analyticsConnectorInstances[t]||($.analyticsConnectorInstances[t]=new e),$.analyticsConnectorInstances[t]},e}(),D=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},j=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,h,g,v,f,p,m,y,b,S,I,C,w;if("object"!=typeof e)return null;var k=e.code||0,P=this.buildStatus(k);switch(P){case u.Success:return{status:P,statusCode:k,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 u.Invalid:return{status:P,statusCode:k,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!==(h=e.silenced_devices)&&void 0!==h?h:[],silencedEvents:null!==(g=e.silenced_events)&&void 0!==g?g:[],throttledDevices:null!==(v=e.throttled_devices)&&void 0!==v?v:{},throttledEvents:null!==(f=e.throttled_events)&&void 0!==f?f:[]}};case u.PayloadTooLarge:return{status:P,statusCode:k,body:{error:null!==(p=e.error)&&void 0!==p?p:""}};case u.RateLimit:return{status:P,statusCode:k,body:{error:null!==(m=e.error)&&void 0!==m?m:"",epsThreshold:null!==(y=e.eps_threshold)&&void 0!==y?y:0,throttledDevices:null!==(b=e.throttled_devices)&&void 0!==b?b:{},throttledUsers:null!==(S=e.throttled_users)&&void 0!==S?S:{},exceededDailyQuotaDevices:null!==(I=e.exceeded_daily_quota_devices)&&void 0!==I?I:{},exceededDailyQuotaUsers:null!==(C=e.exceeded_daily_quota_users)&&void 0!==C?C:{},throttledEvents:null!==(w=e.throttled_events)&&void 0!==w?w:[]}};case u.Timeout:default:return{status:P,statusCode:k}}},e.prototype.buildStatus=function(e){return function(e){return e>=200&&e<300}(e)?u.Success:429===e?u.RateLimit:413===e?u.PayloadTooLarge:408===e?u.Timeout:e>=400&&e<500?u.Invalid:e>=500?u.Failed:u.Unknown},e}(),N=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}(j),A=function(){function e(e,t){this.key="AMP_remote_config_".concat(e.substring(0,10)),this.logger=t}return e.prototype.fetchConfig=function(){var e=null,t={remoteConfig:null,lastFetch:new Date};try{e=localStorage.getItem(this.key)}catch(e){return this.logger.debug("Remote config localstorage failed to access: ",e),Promise.resolve(t)}if(null===e)return this.logger.debug("Remote config localstorage gets null because the key does not exist"),Promise.resolve(t);try{var i=JSON.parse(e);return this.logger.debug("Remote config localstorage parsed successfully: ".concat(JSON.stringify(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){try{return localStorage.setItem(this.key,JSON.stringify(e)),this.logger.debug("Remote config localstorage set successfully."),Promise.resolve(!0)}catch(e){this.logger.debug("Remote config localstorage failed to set: ",e)}return Promise.resolve(!1)},e}(),U=401,B=403,W=429,z=function(){function e(e,t,i,n){void 0===i&&(i="US"),this.callbackInfos=[],this.lastSuccessfulFetch=null,this.fetchPromise=null,this.isLastFetchInvalidApiKey=!1,this.apiKey=e,this.serverUrl=n||("US"===i?"https://sr-client-cfg.amplitude.com/config":"https://sr-client-cfg.eu.amplitude.com/config"),this.logger=t,this.storage=new A(e,t)}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;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,7,8,9]),[4,fetch(o.getUrlParams(),{method:"GET",headers:{Accept:"*/*"},signal:a.signal})];case 2:return(d=s.sent()).ok?[3,4]:[4,d.text()];case 3:return u=s.sent(),o.logger.debug("Remote config client fetch with retry time ".concat(e," failed with ").concat(d.status,": ").concat(u)),d.status===U||d.status===B?(o.logger.error("Remote config client fetch failed with ".concat(d.status,". Invalid API key; future fetches will be skipped.")),o.isLastFetchInvalidApiKey=!0,r=!1):d.status>=400&&d.status<500&&d.status!==W&&(r=!1),[3,6];case 4:return[4,d.json()];case 5:return[2,{value:{remoteConfig:s.sent(),lastFetch:new Date}}];case 6:return[3,9];case 7:return(h=s.sent())instanceof Error&&"AbortError"===h.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: "),h),[3,9];case 8:return clearTimeout(l),[7];case 9:return r?n<e-1?[4,new Promise(function(e){return setTimeout(e,c.getJitterDelay(i))})]:[3,11]:[2,"break"];case 10:s.sent(),s.label=11;case 11:return[2]}})},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 t=encodeURIComponent(this.apiKey),i=new URLSearchParams;return i.append("config_group",e.CONFIG_GROUP),"".concat(this.serverUrl,"/").concat(t,"?").concat(i.toString())},e.CONFIG_GROUP="browser",e}();!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}(L||(L={}));var K,H="https://app.amplitude.com",Q={US:H,EU:"https://app.eu.amplitude.com",STAGING:"https://apps.stag2.amplitude.com"};var G="__AMPLITUDE_MESSENGER_INSTANCE__",J="__AMPLITUDE_MESSENGER__",Z=function(){function e(e){var t=(void 0===e?{}:e).origin,i=void 0===t?H:t;this[K]=!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===H&&(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[J])===this&&delete e[J]},e}();function X(e){var t,i=f(),n=null==i?void 0:i[J];if("object"==typeof(t=n)&&null!==t&&G in t&&!0===t[G])return n;var s=new Z(e);return i&&(i[J]=s),s}K=G;var V="__AMPLITUDE_BACKGROUND_CAPTURE__";const Y="[Amplitude]",ee=`${Y} Session Replay ID`,te=L.US,ie={enabled:!0},ne=1e3,se=`${Y} Session Replay Debug`,re="amp-mask",oe="amp-unmask",ae="https://api-sr.amplitude.com/sessions/v2/track",le="https://api-sr.eu.amplitude.com/sessions/v2/track",ce="https://api-sr.stag2.amplitude.com/sessions/v2/track",de=9e6,ue=/payload.*exceed/i,he=500,ge=1e4,ve=1024,fe="amplitude-sr-iframe";var pe;!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"}(pe||(pe={}));class me{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()}}const ye="medium";function be(e,t){return t||("STAGING"===e?ce:"EU"===e?le:ae)}const Se=(e,t,i)=>{switch(t){case"light":{if("input"!==e)return!1;const t=i?function(e){const t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?t.toLowerCase():null}(i):"";return!!t&&(!!["password","hidden","email","tel"].includes(t)||!!i.autocomplete.startsWith("cc-"))}case"medium":return"input"===e;case"conservative":return!0;default:return Se(e,ye,i)}},Ie=(e,t)=>{var i;if(e&&t.urlMaskLevels)for(const i of t.urlMaskLevels)if(Me(i.match).test(e))return i.maskLevel;return null!==(i=t.defaultMaskLevel)&&void 0!==i?i:ye},Ce=(e,t={defaultMaskLevel:ye},i,n)=>{var s,r;if(i){if(i.closest("."+re))return!0;const e=(null!==(s=t.maskSelector)&&void 0!==s?s:[]).some(e=>i.closest(e));if(e)return!0;if(i.closest("."+oe))return!1;const n=(null!==(r=t.unmaskSelector)&&void 0!==r?r:[]).some(e=>i.closest(e));if(n)return!1}return Se(e,Ie(n,t),i)},we=(e,t,i)=>(n,s)=>Ce(e,t,s,null==i?void 0:i())?n.replace(/[^\s]/g,"*"):n,ke=(e,t)=>(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;const o=["INPUT","SELECT","TEXTAREA"].includes(s.tagName)?"input":"text";return Ce(o,e,s,null==t?void 0:t())?n.replace(/[^\s]/g,"*"):n},Pe=()=>{const e=f();return(null==e?void 0:e.location)?e.location.href:""},Ee=new Map,Me=e=>{const t=Ee.get(e);if(t)return t;const i="\0TRAIL\0",n="\0MID\0",s="\0DS\0",r="\0ST\0",o="\0QU\0";let a=e;a=a.replace(/\/\*\*$/,i),a=a.replace(/\/\*\*\//g,n),a=a.replace(/\*\*/g,s),a=a.replace(/\*/g,r),a=a.replace(/\?/g,o),a=a.replace(/[.+^${}()|[\]\\]/g,"\\$&"),a=a.split(i).join("(/.*)?"),a=a.split(n).join("/(.*\\/)?"),a=a.split(s).join(".*"),a=a.split(r).join(".*"),a=a.split(o).join(".");const l=new RegExp(`^${a}$`);return Ee.set(e,l),l},Te=(e,t)=>{for(const i of t){const t=Me(i.selector);if(t.test(e))return e.replace(t,i.replacement)}return e},Oe=()=>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/ve):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:""}}),Re=e=>{const t=Object.assign({},e),{apiKey:i}=t;return t.apiKey=`****${i.substring(i.length-4)}`,t},xe=()=>({flushMaxRetries:2,logLevel:v.Warn,loggerProvider:new S,transportProvider:new N});class _e extends C{constructor(e,t){var i,n,s,r,o,a,l,c,d,u,h,g,v,f;const p=xe();super(Object.assign(Object.assign({transportProvider:p.transportProvider,loggerProvider:new me(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.serverZone=t.serverZone||te,this.configServerUrl=t.configServerUrl,this.trackServerUrl=t.trackServerUrl,this.shouldInlineStylesheet=t.shouldInlineStylesheet,this.version=t.version,this.performanceConfig=t.performanceConfig||ie,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:ne,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=De(t.maxPersistedEventsSizeBytes,Fe,$e,"maxPersistedEventsSizeBytes",this.loggerProvider)),void 0!==t.maxSingleEventSizeBytes&&(this.maxSingleEventSizeBytes=De(t.maxSingleEventSizeBytes,Fe,qe,"maxSingleEventSizeBytes",this.loggerProvider)),this.privacyConfig=Object.assign(Object.assign({},null!==(l=t.privacyConfig)&&void 0!==l?l:{}),{unmaskSelector:Array.from(new Set([`.${oe}`,...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<Le?(t.warn(`flushIntervalConfig.minIntervalMs ${e.minIntervalMs} is below floor ${Le}ms; clamping.`),s.minIntervalMs=Le):s.minIntervalMs=e.minIntervalMs);void 0!==e.maxIntervalMs&&(Number.isNaN(e.maxIntervalMs)||e.maxIntervalMs<Le?(t.warn(`flushIntervalConfig.maxIntervalMs ${e.maxIntervalMs} is below floor ${Le}ms; clamping.`),s.maxIntervalMs=Le):s.maxIntervalMs=e.maxIntervalMs);if(void 0!==s.minIntervalMs||void 0!==s.maxIntervalMs){const e=null!==(i=s.minIntervalMs)&&void 0!==i?i:he,r=null!==(n=s.maxIntervalMs)&&void 0!==n?n:ge;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}}}const Le=100,Fe=1e3,$e=8e6,qe=1e7;function De(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 je=(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))(je||{}),Ne=(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))(Ne||{}),Ae=(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))(Ae||{});class Ue{constructor(e,t){this.localConfig=t,this.remoteConfigClient=e}generateJoinedConfig(){var e,t,i,s,r,o,a;return n(this,void 0,void 0,function*(){const n=Object.assign({},this.localConfig);let l;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,c=o.sr_privacy_config,d=o.sr_targeting_config,u=null===(r=n.interactionConfig)||void 0===r?void 0:r.ugcFilterRules;n.interactionConfig=o.sr_interaction_config,n.interactionConfig&&u&&(n.interactionConfig.ugcFilterRules=u),n.loggingConfig=o.sr_logging_config,(a||c||d)&&(l={},a&&(l.sr_sampling_config=a),c&&(l.sr_privacy_config=c),d&&(l.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(!l)return{localConfig:this.localConfig,joinedConfig:n,remoteConfig:l};const{sr_sampling_config:c,sr_privacy_config:d,sr_targeting_config:u}=l;if(c&&Object.keys(c).length>0?(Object.prototype.hasOwnProperty.call(c,"capture_enabled")?n.captureEnabled=c.capture_enabled:n.captureEnabled=!1,Object.prototype.hasOwnProperty.call(c,"sample_rate")&&(n.sampleRate=c.sample_rate),Object.prototype.hasOwnProperty.call(c,"min_session_duration_ms")&&(n.minSessionDurationMs=this.sanitizeMinSessionDurationMs(c.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.")),d){const l=null!==(e=n.privacyConfig)&&void 0!==e?e:{},c={defaultMaskLevel:null!==(i=null!==(t=d.defaultMaskLevel)&&void 0!==t?t:l.defaultMaskLevel)&&void 0!==i?i:"medium",blockSelector:[],maskSelector:[],unmaskSelector:[],maskAttributes:[...new Set([...null!==(s=l.maskAttributes)&&void 0!==s?s:[],...null!==(r=d.maskAttributes)&&void 0!==r?r:[]])],urlMaskLevels:[...null!==(o=d.urlMaskLevels)&&void 0!==o?o:[],...null!==(a=l.urlMaskLevels)&&void 0!==a?a:[]]},u=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({},u(l)),u(d));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=((e,t)=>{const i=document.createDocumentFragment(),n=(e=[])=>{if("string"==typeof e&&(e=[e]),e=e.filter(e=>{try{i.querySelector(e)}catch(i){return t.warn(`[session-replay-browser] omitting selector "${e}" because it is invalid`),!1}return!0}),0!==e.length)return e};return e.blockSelector=n(e.blockSelector),e.maskSelector=n(e.maskSelector),e.unmaskSelector=n(e.unmaskSelector),e})(c,this.localConfig.loggerProvider)}return u&&Object.keys(u).length>0&&(n.targetingConfig=u),this.localConfig.loggerProvider.debug(JSON.stringify({name:"session replay joined config",config:Re(n)},null,2)),{localConfig:this.localConfig,joinedConfig:n,remoteConfig:l}})}sanitizeMinSessionDurationMs(e){if("number"==typeof e&&Number.isFinite(e)){if(!(e<0))return e>Be?(this.localConfig.loggerProvider.warn(`min_session_duration_ms remote value ${e} exceeds ${Be}ms ceiling; clamping.`),Be):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 Be=6e4;function We(e){if(e.type!==je.IncrementalSnapshot)return!1;const t=e.data;return t.source===Ne.Mutation&&!t.isAttachIframe}function ze(e){const t={};for(const i of e)for(const e of Object.keys(i))t[e]=i[e];return t}function Ke(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=ze(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 He(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:Ne.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:Ke(f)};return Object.assign(Object.assign({},t),{data:p})}function Qe(e){if(e.length<=1)return e;const t=[];let i=0;for(;i<e.length;){if(!We(e[i])){t.push(e[i]),i++;continue}let n=i+1;for(;n<e.length&&We(e[n]);)n++;t.push(n>i+1?He(e.slice(i,n)):e[i]),i=n}return t}class Ge{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=new Blob([e]).size;n>(null!==(i=this.config.maxSingleEventSizeBytes)&&void 0!==i?i:de)?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.eventsManager&&this.deviceId&&this.eventsManager.addEvent({event:{type:"replay",data:e},sessionId:t,deviceId:this.deviceId})},this.addCompressedEvent=(e,t)=>{if(this.worker)try{this.worker.postMessage({event:e,sessionId:t})}catch(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===je.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=Qe(e.slice(n,s).map(e=>e.event));for(const e of r)i.push({event:e,sessionId:t});n=s}return i}}const Je="Session replay event batch rejected due to exceeded retry count",Ze="Failed to store session replay events in IndexedDB",Xe="Session replay event batch dropped: server signalled capture disabled or session out of valid range for this session",Ve="1.46.0";class Ye{constructor({trackServerUrl:e,loggerProvider:t,payloadBatcher:i,workerScript:n,enableTransportCompression:s,sendTimeoutMs:r}){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,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}))}}},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=>new Blob([e]).size;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;const d=new URLSearchParams({device_id:i,session_id:String(t),type:"replay",api_key:n}),u=`${be(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:Xe}),!1):e.attempts<(e.flushMaxRetries||0)?(e.attempts+=1,!0):(this.completeRequest({context:e,err:Je}),!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=r.events.reduce((e,t)=>e+new Blob([t]).size,0);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:Xe});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,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:Pe(),sdkVersion:Ve,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}}sendOnMainThread(e,t,i,s,r){var o,a,l,c,d,u,h;return n(this,void 0,void 0,function*(){const g=Pe(),v=Ve,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:new Blob([t]).size,c=new AbortController,b={headers: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"}:{}),body:null!=a?a:t,method:"POST",keepalive:l<=65536,signal:c.signal},S=`${be(i.serverZone,this.trackServerUrl)}?${m.toString()}`;if(0===s.events.length)return void this.completeRequest({context:i});const I=this.sendTimeoutMs>0?setTimeout(()=>{c.abort()},this.sendTimeoutMs):void 0;let C;try{C=yield fetch(S,b)}finally{I&&clearTimeout(I)}if(null===C)return void this.completeRequest({context:i,err:"Unexpected error occurred"});if(C.status>=200&&C.status<300){const e=null!==(h=null===(u=null===(d=C.headers)||void 0===d?void 0:d.get)||void 0===u?void 0:u.call(d,"X-Session-Replay-Event-Skipped"))&&void 0!==h?h:null;this.applyServerDirective(i.sessionId,e)}if(r){let e="";if(413===C.status)try{e=yield C.text()}catch(e){}yield this.handleReponse(C.status,i,e)}else{let e="";try{e=JSON.stringify(C.body,null,2)}catch(e){}this.completeRequest({context:i,success:`${C.status}: ${e}`})}}catch(e){!!e&&"object"==typeof e&&"AbortError"===e.name&&r?yield this.handleOtherResponse(i):this.completeRequest({context:i,err:e})}})}handleReponse(e,t,i=""){return n(this,void 0,void 0,function*(){switch((new j).buildStatus(e)){case u.Success:this.handleSuccessResponse(t);break;case u.Failed:case u.Timeout:case u.RateLimit:yield this.handleOtherResponse(t);break;case u.PayloadTooLarge:this.handlePayloadTooLargeResponse(t,ue.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)/ve);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(new Blob(e.events).size/ve);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:Je}):(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:Xe}):i.push(t);this.queue=i}}class et{get timeAtLastSplit(){return this._timeAtLastSplit}constructor(e){var t,i,n;this.minInterval=he,this.maxInterval=ge,this.maxPersistedEventsSize=6e6,this._timeAtLastSplit=Date.now(),this.shouldSplitEventsList=(e,t)=>{const i=this.getStringSize(t);return this.getEventsArraySize(e)+i>=this.maxPersistedEventsSize||!!(Date.now()-this.timeAtLastSplit>this.interval&&e.length)&&(this.interval=Math.min(this.maxInterval,this.interval+this.minInterval),this._timeAtLastSplit=Date.now(),!0)},this.loggerProvider=e.loggerProvider,this.minInterval=null!==(t=e.minInterval)&&void 0!==t?t:this.minInterval,this.maxInterval=null!==(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}getStringSize(e){let t=0;for(let i=0;i<e.length;i++){const n=e.charCodeAt(i);if(n<=127)t++;else if(n<=2047)t+=2;else if(n>=55296&&n<=56319){const n=i+1<e.length?e.charCodeAt(i+1):NaN;n>=56320&&n<=57343?(t+=4,i++):t+=3}else t+=3}return t}getEventsArraySize(e){let t=0;for(const i of e)t+=this.getStringSize(i);return t+(2+Math.max(0,e.length-1)+2*e.length)}}const tt=(e,t,i)=>{var n;"object"==typeof(n=i)&&null!==n&&"AbortError"===n.name?e.debug(t):e.warn(t)};const it="sessionCurrentSequence",nt="sequencesToSend",st=5e3;function rt(e,t,i){const n=setTimeout(i,t);return e.then(()=>clearTimeout(n),()=>clearTimeout(n)),()=>clearTimeout(n)}const ot=e=>{let t,i;return e.objectStoreNames.contains(it)||(i=e.createObjectStore(it,{keyPath:"sessionId"})),e.objectStoreNames.contains(nt)||(t=e.createObjectStore(nt,{keyPath:"sequenceId",autoIncrement:!0}),t.createIndex("sessionId","sessionId")),{sequencesStore:t,currentSequenceStore:i}},at=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:ot}),2e3,"IDB openDB timed out")});class lt extends et{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||(tt(this.loggerProvider,`${Ze}: ${i}`,i),this.recordFailure())});const s=rt(n.done,st,()=>{e||t||(t=!0,tt(this.loggerProvider,`${Ze}: 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,tt(this.loggerProvider,`${Ze}: ${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([it,nt],"readwrite");n.done.catch(e=>{t||i||(tt(this.loggerProvider,`${Ze}: ${e}`,e),this.recordFailure())});const s=rt(n.done,st,()=>{t||i||(i=!0,tt(this.loggerProvider,`${Ze}: transaction timed out`),this.recordFailure())}),r=yield n.objectStore(it).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(nt).put({sessionId:e,events:r.events,tabId:this.tabId});yield n.objectStore(it).put({sessionId:e,events:[],tabId:this.tabId}),this.recordSuccess(),s();const{tabId:l}=r,c=a(r,["tabId"]);return Object.assign(Object.assign({},c),{sessionId:e,sequenceId:o})}catch(e){i||(t=!0,tt(this.loggerProvider,`${Ze}: ${e}`,e),this.recordFailure())}}),this.addEventToCurrentSequence=(e,t)=>n(this,void 0,void 0,function*(){let i=!1,n=!1;try{const s=this.db.transaction([it,nt],"readwrite");s.done.catch(e=>{i||n||(tt(this.loggerProvider,`${Ze}: ${e}`,e),this.recordFailure())});const r=rt(s.done,st,()=>{i||n||(n=!0,tt(this.loggerProvider,`${Ze}: transaction timed out`),this.recordFailure())}),o=yield s.objectStore(it).get(e);if((null==o?void 0:o.tabId)&&o.tabId!==this.tabId)return o.events.length>0&&(yield s.objectStore(nt).put({sessionId:e,events:o.events,tabId:o.tabId})),yield s.objectStore(it).put({sessionId:e,events:[t],tabId:this.tabId}),this.recordSuccess(),void r();const a=o;if(!a)return yield s.objectStore(it).put({sessionId:e,events:[t],tabId:this.tabId}),this.recordSuccess(),void r();if(!this.shouldSplitEventsList(a.events,t))return yield s.objectStore(it).put({sessionId:e,events:a.events.concat(t),tabId:this.tabId}),this.recordSuccess(),void r();const l=a.events;if(0===l.length)return this.maybeLogEmptyFiltered("addEventToCurrentSequence"),yield s.objectStore(it).put({sessionId:e,events:[t],tabId:this.tabId}),this.recordSuccess(),void r();yield s.objectStore(it).put({sessionId:e,events:[t],tabId:this.tabId});const c=yield s.objectStore(nt).put({sessionId:e,events:l,tabId:this.tabId});return this.recordSuccess(),r(),{events:l,sessionId:e,sequenceId:c}}catch(e){n||(i=!0,tt(this.loggerProvider,`${Ze}: ${e}`,e),this.recordFailure())}}),this.storeSendingEvents=(e,t)=>n(this,void 0,void 0,function*(){try{const i=yield this.db.put(nt,{sessionId:e,events:t,tabId:this.tabId});return this.recordSuccess(),i}catch(e){tt(this.loggerProvider,`${Ze}: ${e}`,e),this.recordFailure()}}),this.cleanUpSessionEventsStore=(e,t)=>n(this,void 0,void 0,function*(){if(t)try{yield this.db.delete(nt,t),this.recordSuccess()}catch(e){tt(this.loggerProvider,`${Ze}: ${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 at(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 lt(Object.assign(Object.assign({},t),{db:r,tabId:o}))}catch(e){tt(t.loggerProvider,`${Ze}: ${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 ct extends et{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 dt=({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:de,h=new Ye(Object.assign(Object.assign({},e),{loggerProvider:e.loggerProvider,payloadBatcher:o,workerScript:l})),g=()=>new ct({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 lt.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})=>{const a=t.map(e=>({event:e,bytes:new Blob([e]).size})),l=a.filter(e=>e.bytes>u);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.bytes/1024)} KB`).join(", ")}. If this recurs, please open a GitHub issue at https://github.com/amplitude/Amplitude-TypeScript/issues or contact Amplitude support.`);const c=l.length>0?a.filter(e=>e.bytes<=u).map(e=>e.event):t;0!==c.length?(e.debugMode&&Oe().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:c,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 ut{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 ht,gt,vt;function ft(e,t){if(vt=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};ht=Object.assign(Object.assign({},i),t),gt=function(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return e;if(e===t.root)return e.ownerDocument;return e}(ht.root,i);let n=pt(e,"all",()=>pt(e,"two",()=>pt(e,"one",()=>pt(e,"none"))));if(n){const t=_t(Lt(n,e));return t.length>0&&(n=t[0]),yt(n)}throw new Error("Selector was not found.")}function pt(e,t,i){let n=null,s=[],r=e,o=0;for(;r;){const e=(new Date).getTime()-vt.getTime();if(void 0!==ht.timeoutMs&&e>ht.timeoutMs)throw new Error(`Timeout: Can't find a unique selector after ${e}ms`);let a=Ot(It(r))||Ot(...Ct(r))||Ot(...wt(r))||Ot(kt(r))||[Pt()];const l=Et(r);if("all"==t)l&&(a=a.concat(a.filter(Tt).map(e=>Mt(e,l))));else if("two"==t)a=a.slice(0,1),l&&(a=a.concat(a.filter(Tt).map(e=>Mt(e,l))));else if("one"==t){const[e]=a=a.slice(0,1);l&&Tt(e)&&(a=[Mt(e,l)])}else"none"==t&&(a=[Pt()],l&&(a=[Mt(a[0],l)]));for(let e of a)e.level=o;if(s.push(a),s.length>=ht.seedMinLength&&(n=mt(s,i),n))break;r=r.parentElement,o++}return n||(n=mt(s,i)),!n&&i?i():n}function mt(e,t){const i=_t(xt(e));if(i.length>ht.threshold)return t?t():null;for(let e of i)if(St(e))return e;return null}function yt(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 bt(e){return e.map(e=>e.penalty).reduce((e,t)=>e+t,0)}function St(e){const t=yt(e);switch(gt.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 It(e){const t=e.getAttribute("id");return t&&ht.idName(t)?{name:"#"+CSS.escape(t),penalty:0}:null}function Ct(e){const t=Array.from(e.attributes).filter(e=>ht.attr(e.name,e.value));return t.map(e=>({name:`[${CSS.escape(e.name)}="${CSS.escape(e.value)}"]`,penalty:.5}))}function wt(e){return Array.from(e.classList).filter(ht.className).map(e=>({name:"."+CSS.escape(e),penalty:1}))}function kt(e){const t=e.tagName.toLowerCase();return ht.tagName(t)?{name:t,penalty:2}:null}function Pt(){return{name:"*",penalty:3}}function Et(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 Mt(e,t){return{name:e.name+`:nth-child(${t})`,penalty:e.penalty+1}}function Tt(e){return"html"!==e.name&&!e.name.startsWith("#")}function Ot(...e){const t=e.filter(Rt);return t.length>0?t:null}function Rt(e){return null!=e}function*xt(e,t=[]){if(e.length>0)for(let i of e[0])yield*xt(e.slice(1,e.length),t.concat(i));else yield t}function _t(e){return[...e].sort((e,t)=>bt(e)-bt(t))}function*Lt(e,t,i={counter:0,visited:new Map}){if(e.length>2&&e.length>ht.optimizedMinLength)for(let n=1;n<e.length-1;n++){if(i.counter>ht.maxNumberOfTries)return;i.counter+=1;const s=[...e];s.splice(n,1);const r=yt(s);if(i.visited.has(r))return;St(s)&&Ft(s,t)&&(yield s,i.visited.set(r,!0),yield*Lt(s,t,i))}}function Ft(e,t){return gt.querySelector(yt(e))===t}const $t=({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}},qt=({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 Dt{constructor(e,t){this.createHook=({eventsManager:e,sessionId:t,deviceIdFn:i,mirror:n,ugcFilterRules:s,performanceOptions:r})=>o=>{if(o.type!==Ae.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=ft(g,r)}catch(e){this.logger.debug("error resolving selector from finder")}const p=Te(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 jt(){const e=f();return(null==e?void 0:e.innerHeight)||document.documentElement&&document.documentElement.clientHeight||0}function Nt(){const e=f();return(null==e?void 0:e.innerWidth)||document.documentElement&&document.documentElement.clientWidth||0}class At{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=be(t.serverZone,t.trackServerUrl),this.apiKey=t.apiKey,this.context=e}send(e,t){const{sessionId:i,type:n}=this.context,s=new URLSearchParams({device_id:e,session_id:String(i),type:String(n),api_key:this.apiKey}),r=`${this.basePageUrl}?${s.toString()}`;this.sendBeacon(r,t)||this.sendXhr(r,t)}}class Ut{static default(e,t){return new Ut(new At(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:jt(),viewportWidth:Nt(),pageUrl:Te(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=Nt(),this._maxScrollHeight=jt(),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=Nt();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=jt();this._maxScrollY=e.y;const n=e.y+i;n>this._maxScrollHeight&&(this._maxScrollHeight=n),this.timestamp=t}}}class Bt{constructor({sessionId:e,deviceId:t}){this.deviceId=t,this.sessionId=e,e&&t&&(this.sessionReplayId=((e,t)=>`${t}/${e}`)(e,t))}}const Wt=864e5,zt=e=>`AMP_SR_START_${e.substring(0,10)}_`,Kt=(e,t)=>`${zt(e)}${t}`,Ht=()=>{try{const e=f();return null==e?void 0:e.localStorage}catch(e){return}};const Qt=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){tt(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){tt(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){tt(e,`Failed to clear old targeting matches for sessions: ${t}`,t)}})}},Gt=2654435761,Jt=2246822519,Zt=3266489917,Xt=374761393;function Vt(e,t){return(e<<t|e>>>32-t)>>>0}function Yt(e,t){return e=Vt(e=e+Math.imul(t,Jt)>>>0,13),e=Math.imul(e,Gt)>>>0}function ei(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function ti(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+Gt+Jt>>>0,o=t+Jt>>>0,a=t>>>0,l=t-Gt>>>0;for(;r<=n-16;)e=Yt(e,ei(i,r)),r+=4,o=Yt(o,ei(i,r)),r+=4,a=Yt(a,ei(i,r)),r+=4,l=Yt(l,ei(i,r)),r+=4;s=Vt(e,1)+Vt(o,7)+Vt(a,12)+Vt(l,18)>>>0}else s=t+Xt>>>0;for(s=s+n>>>0;r<=n-4;)s=s+Math.imul(ei(i,r),Zt)>>>0,s=Math.imul(Vt(s,17),668265263)>>>0,r+=4;for(;r<n;)s=s+Math.imul(i[r],Xt)>>>0,s=Math.imul(Vt(s,11),Gt)>>>0,r++;return s^=s>>>15,s=Math.imul(s,Jt)>>>0,s^=s>>>13,s=Math.imul(s,Zt)>>>0,s^=s>>>16,s>>>0}const ii="__amplitude_url_tracking_patched__",ni=new WeakMap;function si(e,t,i={}){if(!(null==e?void 0:e.location))return()=>{};const{enablePolling:n=!1,pollingInterval:s=ne}=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=ni.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[ii]=!0,t},a=e.history;if(null==a?void 0:a.pushState){const e=Reflect.get(a,"pushState");e[ii]||(a.pushState=o(e))}if(null==a?void 0:a.replaceState){const e=Reflect.get(a,"replaceState");e[ii]||(a.replaceState=o(e))}r={callbacks:i,notify:s,onPopStateOrHashChange:()=>s(),listenersAttached:!1},ni.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 ri(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:ne,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?Te(s,l):s,title:r,viewportHeight:e,viewportWidth:t,type:"url-change-event"}})();t(n)}},f=si(i,()=>v(),c?{enablePolling:!0,pollingInterval:d}:{});return v(),()=>f()},options:e}}class oi{constructor(){this.pendingLoadListeners=new Map}start(){var e;null===(e=this.mutationObserver)||void 0===e||e.disconnect();f()&&(this.sendToAllIframes({type:fe,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:fe,action:"stop"})}sendToIframeAfterLoad(e){const t=()=>{this.pendingLoadListeners.delete(e),this.sendToIframe(e,{type:fe,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 ai{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.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.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,i=!1,s=!1)=>n(this,void 0,void 0,function*(){var r,o,a,l,c,u;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(d).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!==(u=e.page)&&void 0!==u?u:""!==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 Qt.clearStoreOfOldSessions({loggerProvider:i,apiKey:s,currentSessionId:e}),!0===(yield Qt.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),Qt.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!==pe.METADATA&&(n={config:Re(s),version:Ve},i)){const e=yield Oe();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.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 me(new S)}init(e,t){return y(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=si(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.loggerProvider=new me(t.loggerProvider||new S),Object.prototype.hasOwnProperty.call(t,"logLevel")&&this.loggerProvider.enable(t.logLevel),this.currentPageUrl=Pe(),this.identifiers=new Bt({sessionId:t.sessionId,deviceId:t.deviceId});const y=Date.now();((e,t,i)=>{const n=Ht();if(!n)return;const s=zt(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>=Wt)&&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=Ht();if(!s)return;const r=Kt(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<Wt)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 _e(e,t),n=new z(e,i.loggerProvider,i.serverZone,t.configServerUrl);return new Ue(n,i)}))(e,t);const{joinedConfig:b,localConfig:I,remoteConfig:C}=yield this.joinedConfigGenerator.generateJoinedConfig();if(this.config=b,this.setMetadata(t.sessionId,b,I,C,null===(r=t.version)||void 0===r?void 0:r.version,Ve,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=Ut.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 Dt(this.loggerProvider,e)}const w=[];let k,P,{storeType:E}=this.config;"idb"!==E||(null===(l=f())||void 0===l?void 0:l.indexedDB)||(E="memory",this.loggerProvider.warn("Could not use preferred indexedDB storage, reverting to in memory option.")),this.loggerProvider.log(`Using ${E} for event storage.`);const M=f();if(this.config.useWebWorker&&M&&M.Worker){const{compressionScript:e,trackDestinationScript:t}=yield import("./worker-min.js");k=e,P=t}let T;try{T=yield dt({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:E,trackDestinationWorkerScript:P,shouldSend:()=>!this.isBelowMinSessionDuration()}),this.rrwebEventManager=T,w.push({name:"replay",manager:T})}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?qt:$t;try{const t=yield dt({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:E,trackDestinationWorkerScript:P});w.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 ut(...w),this.eventCompressor&&this.eventCompressor.terminate();const O=!0===this.config.eagerFullSnapshotSend?()=>this.sendEvents():void 0;if(this.eventCompressor=new Ge(this.eventsManager,this.config,this.getDeviceId(),k,O),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)||!T)return;const t=T.getBeaconEvents();if(!t.length)return;const i=this.getDeviceId();i&&(this.isBelowMinSessionDuration()||T.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=X();!function(e,t){var i,n=e;if(!0!==n[V]){n[V]=!0;var s=null!==(i=null==t?void 0:t.scriptUrl)&&void 0!==i?i:"https://cdn.amplitude.com/libs/background-capture-1.0.1.js.gz",r=null,o=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(){var t,i;null===(i=null===(t=e.logger)||void 0===t?void 0:t.debug)||void 0===i||i.call(t,"Initializing background capture (external script)");var n=new URL(s,e.endpoint).toString();e.loadScriptOnce(n).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)"),r=null===(n=null===window||void 0===window?void 0:window.amplitudeBackgroundCapture)||void 0===n?void 0:n.call(window,{messenger:e,onBackgroundCapture:o}),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==r?void 0:r.close)||void 0===e||e.call(r),r=null})}}(e),e.setup(Object.assign({logger:this.loggerProvider},this.config.serverZone&&{endpoint:Q[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 y(this.asyncSetSessionId(e,t))}asyncSetSessionId(e,t,i){var s,r,o;return n(this,void 0,void 0,function*(){this.latestUrlChangeTargetingEvaluationId++,this.sessionTargetingMatch=!1,this.lastShouldRecordDecision=void 0;const n=this.identifiers&&this.identifiers.sessionId;n&&this.sendEvents(n);const a=n!==e;a&&(null===(s=this.rrwebEventManager)||void 0===s||s.dropPendingBeaconEvents());const l=t||this.getDeviceId();if(this.identifiers=new Bt({sessionId:e,deviceId:l}),a&&(this.sessionStartTime=Date.now(),this.suppressedSendCount=0,this.hasEmittedGateDecision=!1,(null===(r=this.config)||void 0===r?void 0:r.apiKey)&&(((e,t,i,n)=>{const s=Ht();if(s)try{s.setItem(Kt(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=Ht();if(n)try{n.removeItem(Kt(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===(o=this.config)||void 0===o?void 0:o.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={[ee]:t.sessionReplayId?t.sessionReplayId:null},e.debugMode&&(n[se]=JSON.stringify({appHash:D(e.apiKey).toString()}))),this.addCustomRRWebEvent(pe.GET_SR_PROPS,{shouldRecord:i,eventProperties:n},10===this.eventCount),10===this.eventCount&&(this.eventCount=0),this.eventCount++,n}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(pe.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,void 0===n&&(n=h),q.getInstance(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.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,ti(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(pe.TARGETING_DECISION,{message:t,sessionId:this.identifiers.sessionId,matched:i,targetingParams:this.lastTargetingParams}),this.lastShouldRecordDecision=e),e}getBlockSelectors(){var e,t,i;const n=null!==(i=null===(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)||void 0===t?void 0:t.blockSelector)&&void 0!==i?i:[];if(0!==n.length)return n}getMaskTextSelectors(){var e,t;const i=null===(e=this.config)||void 0===e?void 0:e.privacyConfig;if("conservative"===(i?Ie(this.currentPageUrl,i):void 0))return"*";if(null===(t=null==i?void 0:i.urlMaskLevels)||void 0===t?void 0:t.some(e=>"conservative"===e.maskLevel))return"*";const n=null==i?void 0:i.urlMaskLevels;if("conservative"===(null==i?void 0:i.defaultMaskLevel)&&n&&n.length>0)return"*";const s=null==i?void 0:i.maskSelector;return s||void 0}getRecordingPlugins(e){var t,i,s,r,o,a;return n(this,void 0,void 0,function*(){const n=[];try{const e=ri({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}}})}_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;this.stopRecordingEvents();const h=yield this.getRecordFunction();if(!h)return;yield this.initializeNetworkObservers();const g=null===(i=n.loggingConfig)||void 0===i?void 0:i.network,v=be(n.serverZone,n.trackServerUrl),p=[ae,le,ce,v];null===(s=this.networkObservers)||void 0===s||s.start(e=>{p.some(t=>e.url.startsWith(t))||this.addCustomRRWebEvent(pe.FETCH_REQUEST,e)},g);const{interactionConfig:m,loggingConfig:y}=n,b=(null==m?void 0:m.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:h.mirror,ugcFilterRules:null!==(o=m.ugcFilterRules)&&void 0!==o?o:[],performanceOptions:null===(a=n.performanceConfig)||void 0===a?void 0:a.interaction})),scroll:this.scrollHook}:{},S=(null==m?void 0:m.enabled)&&m.ugcFilterRules?m.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 void(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)===fe&&("start"===n.action?e.onStart():"stop"===n.action&&e.onStop())}return t.addEventListener("message",n),()=>t.removeEventListener("message",n)}({onStart:()=>this._recordEventsInChildMode(h,u,n,b),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()}`)}}}));this.recordCancelCallback=h(Object.assign(Object.assign({},this.buildRRWebRecordOptions(n,b,e=>{if(this.shouldOptOut())return this.loggerProvider.log(`Opting session ${u} out of recording due to optOut config.`),this.stopRecordingEvents(),void this.sendEvents();e.type===je.Meta&&(e.data.href=Te(e.data.href,S)),this.eventCompressor?this.eventCompressor.enqueueEvent(e,u):this.pendingEmitEvents.push({event:e,sessionId:u})},"Error while capturing replay: ")),{plugins:yield this.getRecordingPlugins(y),recordCrossOriginIframes:t})),t&&!s&&i&&(this.crossOriginIframeCoordinator||(this.crossOriginIframeCoordinator=new oi),this.crossOriginIframeCoordinator.start()),this.addCustomRRWebEvent(pe.DEBUG_INFO),e&&this.addCustomRRWebEvent(pe.METADATA,this.metadata)}catch(e){this.loggerProvider.warn("Failed to initialize session replay:",e)}})}buildRRWebRecordOptions(e,t,i,n){const{privacyConfig:s}=e;return Object.assign(Object.assign({emit:i,inlineStylesheet:e.shouldInlineStylesheet,hooks:t,maskAllInputs:!0,maskTextClass:re,blockClass:"amp-block",blockSelector:this.getBlockSelectors(),applyBackgroundColorToBlockedElements:e.applyBackgroundColorToBlockedElements,maskInputFn:we("input",s,()=>this.currentPageUrl),maskTextFn:we("text",s,()=>this.currentPageUrl),maskAttributeFn:ke(s,()=>this.currentPageUrl),maskTextSelector:this.getMaskTextSelectors()},void 0!==e.fullSnapshotIntervalMs&&{checkoutEveryNms:e.fullSnapshotIntervalMs}),{recordCanvas:!1,captureAdoptedStyleSheets:e.captureAdoptedStyleSheets,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},errorHandler: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}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;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())?D(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 li=e=>()=>{const{config:t}=e,{loggerProvider:i,logLevel:n}=t||xe();return{logger:i,logLevel:n}};var ci=(()=>{const e=new ai;return{init:P(e.init.bind(e),"init",li(e)),evaluateTargetingAndCapture:P(e.evaluateTargetingAndCapture.bind(e),"evaluateTargetingAndRecord",li(e)),setSessionId:P(e.setSessionId.bind(e),"setSessionId",li(e)),getSessionId:P(e.getSessionId.bind(e),"getSessionId",li(e)),getSessionReplayProperties:P(e.getSessionReplayProperties.bind(e),"getSessionReplayProperties",li(e)),flush:P(e.flush.bind(e),"flush",li(e)),shutdown:P(e.shutdown.bind(e),"shutdown",li(e))}})();const{init:di,setSessionId:ui,getSessionId:hi,getSessionReplayProperties:gi,flush:vi,shutdown:fi,evaluateTargetingAndCapture:pi}=ci;export{me as S,hi as a,gi as b,fi as c,pi as e,vi as f,f as g,di as i,ui as s};
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";var c,d;!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"}(c||(c={})),function(e){e.IDENTIFY="$identify",e.GROUP_IDENTIFY="$groupidentify",e.REVENUE="revenue_amount"}(d||(d={}));var u,h="$default_instance",g="https://api2.amplitude.com/2/httpapi";!function(e){e.Unknown="unknown",e.Skipped="skipped",e.Success="success",e.RateLimit="rate_limit",e.PayloadTooLarge="payload_too_large",e.Invalid="invalid",e.Failed="failed",e.Timeout="Timeout",e.SystemError="SystemError"}(u||(u={}));var v,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=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"}(v||(v={}));var b="Amplitude Logger ",S=function(){function e(){this.logLevel=v.None}return e.prototype.disable=function(){this.logLevel=v.None},e.prototype.enable=function(e){void 0===e&&(e=v.Warn),this.logLevel=e},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<v.Verbose||console.log("".concat(b,"[Log]: ").concat(e.join(" ")))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<v.Warn||console.warn("".concat(b,"[Warn]: ").concat(e.join(" ")))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<v.Error||console.error("".concat(b,"[Error]: ").concat(e.join(" ")))},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<v.Debug||console.log("".concat(b,"[Debug]: ").concat(e.join(" ")))},e}(),I=function(){return{flushMaxRetries:12,flushQueueSize:200,flushIntervalMillis:1e4,instanceName:h,logLevel:v.Warn,loggerProvider:new S,offline:!1,optOut:!1,serverUrl:g,serverZone:"US",useBatch:!1}},C=function(){function e(e){var t,i,n,s;this._optOut=!1;var r=I();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=e.instanceName||r.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(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}(),w=function(e,t){return"EU"===e?t?"https://api.eu.amplitude.com/batch":"https://api.eu.amplitude.com/2/httpapi":t?"https://api2.amplitude.com/batch":g},E=function(e,t,i){if(void 0===e&&(e=""),void 0===t&&(t=I().serverZone),void 0===i&&(i=I().useBatch),e)return{serverUrl:e,serverZone:void 0};var n=["US","EU"].includes(t)?t:I().serverZone;return{serverZone:n,serverUrl:w(n,i)}};var k=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<v.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}},P=function(){function e(){}return e.prototype.getApplicationContext=function(){return{versionName:this.versionName,language:T(),platform:"Web",os:void 0,deviceModel:void 0}},e}(),T=function(){return"undefined"!=typeof navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||""},M=function(){function e(){this.queue=[]}return e.prototype.logEvent=function(e){this.receiver?this.receiver(e):this.queue.length<512&&this.queue.push(e)},e.prototype.setEventReceiver=function(e){this.receiver=e,this.queue.length>0&&(this.queue.forEach(function(t){e(t)}),this.queue=[])},e}(),O=function(){return O=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var s in t=arguments[i])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e},O.apply(this,arguments)};function D(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function R(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,s,r=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=r.next()).done;)o.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(i=r.return)&&i.call(r)}finally{if(s)throw s.error}}return o}"function"==typeof SuppressedError&&SuppressedError;var x=function(e,t){var i,n,s=typeof e;if(s!==typeof t)return!1;try{for(var r=D(["string","number","boolean","undefined"]),o=r.next();!o.done;o=r.next()){if(o.value===s)return e===t}}catch(e){i={error:e}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}if(null==e&&null==t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;var a=Array.isArray(e),l=Array.isArray(t);if(a!==l)return!1;if(!a||!l){var c=Object.keys(e).sort(),d=Object.keys(t).sort();if(!x(c,d))return!1;var u=!0;return Object.keys(e).forEach(function(i){x(e[i],t[i])||(u=!1)}),u}for(var h=0;h<e.length;h++)if(!x(e[h],t[h]))return!1;return!0};Object.entries||(Object.entries=function(e){for(var t=Object.keys(e),i=t.length,n=new Array(i);i--;)n[i]=[t[i],e[t[i]]];return n});var _,F=function(){function e(){this.identity={userProperties:{}},this.listeners=new Set}return e.prototype.editIdentity=function(){var e=this,t=O({},this.identity.userProperties),i=O(O({},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:function(e){return i.optOut=e,this},updateUserProperties:function(e){var t,n,s,r,o,a,l=i.userProperties||{};try{for(var c=D(Object.entries(e)),d=c.next();!d.done;d=c.next()){var u=R(d.value,2),h=u[0],g=u[1];switch(h){case"$set":try{for(var v=(s=void 0,D(Object.entries(g))),f=v.next();!f.done;f=v.next()){var p=R(f.value,2),m=p[0],y=p[1];l[m]=y}}catch(e){s={error:e}}finally{try{f&&!f.done&&(r=v.return)&&r.call(v)}finally{if(s)throw s.error}}break;case"$unset":try{for(var b=(o=void 0,D(Object.keys(g))),S=b.next();!S.done;S=b.next()){delete l[m=S.value]}}catch(e){o={error:e}}finally{try{S&&!S.done&&(a=b.return)&&a.call(b)}finally{if(o)throw o.error}}break;case"$clearAll":l={}}}}catch(e){t={error:e}}finally{try{d&&!d.done&&(n=c.return)&&n.call(c)}finally{if(t)throw t.error}}return i.userProperties=l,this},commit:function(){return e.setIdentity(i),this}}},e.prototype.getIdentity=function(){return O({},this.identity)},e.prototype.setIdentity=function(e){var t=O({},this.identity);this.identity=O({},e),x(t,this.identity)||this.listeners.forEach(function(t){t(e)})},e.prototype.addIdentityListener=function(e){this.listeners.add(e)},e.prototype.removeIdentityListener=function(e){this.listeners.delete(e)},e}(),$="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:self,L=function(){function e(){this.identityStore=new F,this.eventBridge=new M,this.applicationContextProvider=new P}return e.getInstance=function(t){return $.analyticsConnectorInstances||($.analyticsConnectorInstances={}),$.analyticsConnectorInstances[t]||($.analyticsConnectorInstances[t]=new e),$.analyticsConnectorInstances[t]},e}(),j=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},q=function(e,t){var i=j(e.toString());return 31*Math.abs(i)%1e5/1e5<t},N="tags",A="counters",U="histograms",B="events",z="internal",W="last_flush_timestamp",H=function(){function e(e,t){this.dbPromise=null,this.logger=t,this.dbName="AMP_diagnostics_".concat(e.substring(0,10))}return e.isSupported=function(){var e;return void 0!==(null===(e=f())||void 0===e?void 0:e.indexedDB)},e.prototype.getDB=function(){return i(this,void 0,void 0,function(){return n(this,function(e){return this.dbPromise||(this.dbPromise=this.openDB()),[2,this.dbPromise]})})},e.prototype.openDB=function(){var e=this;return new Promise(function(t,i){var n=indexedDB.open(e.dbName,1);n.onerror=function(){e.dbPromise=null,i(new Error("Failed to open IndexedDB"))},n.onsuccess=function(){var i=n.result;i.onclose=function(){e.dbPromise=null,e.logger.debug("DiagnosticsStorage: DB connection closed.")},i.onerror=function(t){e.logger.debug("DiagnosticsStorage: A global database error occurred.",t),i.close()},t(i)},n.onupgradeneeded=function(t){var i=t.target.result;e.createTables(i)}})},e.prototype.createTables=function(e){(e.objectStoreNames.contains(N)||e.createObjectStore(N,{keyPath:"key"}),e.objectStoreNames.contains(A)||e.createObjectStore(A,{keyPath:"key"}),e.objectStoreNames.contains(U)||e.createObjectStore(U,{keyPath:"key"}),e.objectStoreNames.contains(B))||e.createObjectStore(B,{keyPath:"id",autoIncrement:!0}).createIndex("time_idx","time",{unique:!1});e.objectStoreNames.contains(z)||e.createObjectStore(z,{keyPath:"key"})},e.prototype.setTags=function(e){return i(this,void 0,void 0,function(){var i,s,r,o,a=this;return n(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),0===Object.entries(e).length?[2]:[4,this.getDB()];case 1:return i=n.sent(),s=i.transaction([N],"readwrite"),r=s.objectStore(N),[2,new Promise(function(i){var n=Object.entries(e);s.oncomplete=function(){i()},s.onabort=function(e){a.logger.debug("DiagnosticsStorage: Failed to set tags",e),i()},n.forEach(function(e){var i=t(e,2),n=i[0],s=i[1];r.put({key:n,value:s}).onerror=function(e){a.logger.debug("DiagnosticsStorage: Failed to set tag",n,s,e)}})})];case 2:return o=n.sent(),this.logger.debug("DiagnosticsStorage: Failed to set tags",o),[3,3];case 3:return[2]}})})},e.prototype.incrementCounters=function(e){return i(this,void 0,void 0,function(){var i,s,r,o,a=this;return n(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),0===Object.entries(e).length?[2]:[4,this.getDB()];case 1:return i=n.sent(),s=i.transaction([A],"readwrite"),r=s.objectStore(A),[2,new Promise(function(i){var n=Object.entries(e);s.oncomplete=function(){i()},s.onabort=function(e){a.logger.debug("DiagnosticsStorage: Failed to increment counters",e),i()},n.forEach(function(e){var i=t(e,2),n=i[0],s=i[1],o=r.get(n);o.onsuccess=function(){var e=o.result,t=e?e.value:0;r.put({key:n,value:t+s}).onerror=function(e){a.logger.debug("DiagnosticsStorage: Failed to update counter",n,e)}},o.onerror=function(e){a.logger.debug("DiagnosticsStorage: Failed to read existing counter",n,e)}})})];case 2:return o=n.sent(),this.logger.debug("DiagnosticsStorage: Failed to increment counters",o),[3,3];case 3:return[2]}})})},e.prototype.setHistogramStats=function(e){return i(this,void 0,void 0,function(){var i,s,r,o,a=this;return n(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),0===Object.entries(e).length?[2]:[4,this.getDB()];case 1:return i=n.sent(),s=i.transaction([U],"readwrite"),r=s.objectStore(U),[2,new Promise(function(i){var n=Object.entries(e);s.oncomplete=function(){i()},s.onabort=function(e){a.logger.debug("DiagnosticsStorage: Failed to set histogram stats",e),i()},n.forEach(function(e){var i=t(e,2),n=i[0],s=i[1],o=r.get(n);o.onsuccess=function(){var e,t=o.result;e=t?{key:n,count:t.count+s.count,min:Math.min(t.min,s.min),max:Math.max(t.max,s.max),sum:t.sum+s.sum}:{key:n,count:s.count,min:s.min,max:s.max,sum:s.sum},r.put(e).onerror=function(e){a.logger.debug("DiagnosticsStorage: Failed to set histogram stats",n,e)}},o.onerror=function(e){a.logger.debug("DiagnosticsStorage: Failed to read existing histogram stats",n,e)}})})];case 2:return o=n.sent(),this.logger.debug("DiagnosticsStorage: Failed to set histogram stats",o),[3,3];case 3:return[2]}})})},e.prototype.addEventRecords=function(e){return i(this,void 0,void 0,function(){var t,i,s,r,o=this;return n(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),0===e.length?[2]:[4,this.getDB()];case 1:return t=n.sent(),i=t.transaction([B],"readwrite"),s=i.objectStore(B),[2,new Promise(function(t){i.oncomplete=function(){t()},i.onabort=function(e){o.logger.debug("DiagnosticsStorage: Failed to add event records",e),t()};var n=s.count();n.onsuccess=function(){var t=n.result,i=Math.max(0,10-t);i<e.length&&o.logger.debug("DiagnosticsStorage: Only added ".concat(i," of ").concat(e.length," events due to storage limit")),e.slice(0,i).forEach(function(e){s.add(e).onerror=function(e){o.logger.debug("DiagnosticsStorage: Failed to add event record",e)}})},n.onerror=function(e){o.logger.debug("DiagnosticsStorage: Failed to count existing events",e)}})];case 2:return r=n.sent(),this.logger.debug("DiagnosticsStorage: Failed to add event records",r),[3,3];case 3:return[2]}})})},e.prototype.setInternal=function(e,t){return i(this,void 0,void 0,function(){var i,s,r,o;return n(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,this.getDB()];case 1:return i=n.sent(),s=i.transaction([z],"readwrite"),r=s.objectStore(z),[2,new Promise(function(i,n){s.onabort=function(){return n(new Error("Failed to set internal value"))};var o=r.put({key:e,value:t});o.onsuccess=function(){return i()},o.onerror=function(){return n(new Error("Failed to set internal value"))}})];case 2:return o=n.sent(),this.logger.debug("DiagnosticsStorage: Failed to set internal value",o),[3,3];case 3:return[2]}})})},e.prototype.getInternal=function(e){return i(this,void 0,void 0,function(){var t,i,s,r;return n(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,this.getDB()];case 1:return t=n.sent(),i=t.transaction([z],"readonly"),s=i.objectStore(z),[2,new Promise(function(t,n){i.onabort=function(){return n(new Error("Failed to get internal value"))};var r=s.get(e);r.onsuccess=function(){return t(r.result)},r.onerror=function(){return n(new Error("Failed to get internal value"))}})];case 2:return r=n.sent(),this.logger.debug("DiagnosticsStorage: Failed to get internal value",r),[2,void 0];case 3:return[2]}})})},e.prototype.getLastFlushTimestamp=function(){return i(this,void 0,void 0,function(){var e,t;return n(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this.getInternal(W)];case 1:return[2,(e=i.sent())?parseInt(e.value,10):void 0];case 2:return t=i.sent(),this.logger.debug("DiagnosticsStorage: Failed to get last flush timestamp",t),[2,void 0];case 3:return[2]}})})},e.prototype.setLastFlushTimestamp=function(e){return i(this,void 0,void 0,function(){var t;return n(this,function(i){switch(i.label){case 0:return i.trys.push([0,2,,3]),[4,this.setInternal(W,e.toString())];case 1:return i.sent(),[3,3];case 2:return t=i.sent(),this.logger.debug("DiagnosticsStorage: Failed to set last flush timestamp",t),[3,3];case 3:return[2]}})})},e.prototype.clearTable=function(e,t){return new Promise(function(i,n){var s=e.objectStore(t).clear();s.onsuccess=function(){return i()},s.onerror=function(){return n(new Error("Failed to clear table ".concat(t)))}})},e.prototype.getAllAndClear=function(){return i(this,void 0,void 0,function(){var e,i,s,r,o,a,l,c;return n(this,function(n){switch(n.label){case 0:return n.trys.push([0,4,,5]),[4,this.getDB()];case 1:return e=n.sent(),i=e.transaction([N,A,U,B],"readwrite"),[4,Promise.all([this.getAllFromStore(i,N),this.getAllFromStore(i,A),this.getAllFromStore(i,U),this.getAllFromStore(i,B)])];case 2:return s=t.apply(void 0,[n.sent(),4]),r=s[0],o=s[1],a=s[2],l=s[3],[4,Promise.all([this.clearTable(i,A),this.clearTable(i,U),this.clearTable(i,B)])];case 3:return n.sent(),[2,{tags:r,counters:o,histogramStats:a,events:l}];case 4:return c=n.sent(),this.logger.debug("DiagnosticsStorage: Failed to get all and clear data",c),[2,{tags:[],counters:[],histogramStats:[],events:[]}];case 5:return[2]}})})},e.prototype.getAllFromStore=function(e,t){return new Promise(function(i,n){var s=e.objectStore(t).getAll();s.onsuccess=function(){return i(s.result)},s.onerror=function(){return n(new Error("Failed to get all from ".concat(t)))}})},e}(),K=function(e){var t,i,n=function(){var e=f();if(!e)return[];var t=e.__AMPLITUDE_SCRIPT_URL__;return Array.isArray(t)?t:"string"==typeof t?[t]:[]}();if(0!==n.length)try{for(var s=r(n),o=s.next();!o.done;o=s.next()){var a=o.value;if(e.filename&&e.filename.includes(a))return"filename";if(e.stack&&e.stack.includes(a))return"stack"}}catch(e){t={error:e}}finally{try{o&&!o.done&&(i=s.return)&&i.call(s)}finally{if(t)throw t.error}}},Q=function(e){if(e){var t=e.match(/(https?:\/\/\S+?)(?=[)\s]|$)/);return t?t[1]:void 0}},J=function(e){if("string"==typeof e)return e;try{return JSON.stringify(e)}catch(e){return"[object Object]"}},G=3e5,Z=1e4,X=function(){function r(e,t,i,n){void 0===i&&(i="US"),this.inMemoryTags={},this.inMemoryCounters={},this.inMemoryHistograms={},this.inMemoryEvents=[],this.saveTimer=null,this.flushTimer=null,this.apiKey=e,this.logger=t,this.serverUrl="US"===i?"https://diagnostics.prod.us-west-2.amplitude.com/v1/capture":"https://diagnostics.prod.eu-central-1.amplitude.com/v1/capture",this.logger.debug("DiagnosticsClient: Initializing with options",JSON.stringify(n,null,2)),this.config=s({enabled:!0,sampleRate:0},n),this.startTimestamp=Date.now(),this.shouldTrack=q(this.startTimestamp,this.config.sampleRate)&&this.config.enabled,H.isSupported()?this.storage=new H(e,t):this.logger.debug("DiagnosticsClient: IndexedDB is not supported"),this.initializeFlushInterval(),this.shouldTrack&&(this.increment("sdk.diagnostics.sampled.in.and.enabled"),function(e){var t=f();if(t&&"function"==typeof t.addEventListener){var i=function(t){e.recordEvent("sdk.error.uncaught",s({type:t.type,message:t.message,filename:t.filename,error_name:t.errorName,stack:t.stack},t.metadata))};t.addEventListener("error",function(e){var t=e.error instanceof Error?e.error:void 0,n=null==t?void 0:t.stack,s=K({filename:e.filename,stack:n});s&&i({type:"error",message:e.message,stack:n,filename:e.filename,errorName:null==t?void 0:t.name,metadata:{colno:e.colno,lineno:e.lineno,isTrusted:e.isTrusted,matchReason:s}})},!0),t.addEventListener("unhandledrejection",function(e){var t,n=e.reason instanceof Error?e.reason:void 0,s=null==n?void 0:n.stack,r=Q(s),o=K({filename:r,stack:s});o&&i({type:"unhandledrejection",message:null!==(t=null==n?void 0:n.message)&&void 0!==t?t:J(e.reason),stack:s,filename:r,errorName:null==n?void 0:n.name,metadata:{isTrusted:e.isTrusted,matchReason:o}})},!0)}}(this))}return r.prototype.isStorageAndTrackEnabled=function(){return Boolean(this.storage)&&Boolean(this.shouldTrack)},r.prototype.setTag=function(e,t){this.isStorageAndTrackEnabled()&&(Object.keys(this.inMemoryTags).length>=Z?this.logger.debug("DiagnosticsClient: Early return setTags as reaching memory limit"):(this.inMemoryTags[e]=t,this.startTimersIfNeeded()))},r.prototype.increment=function(e,t){void 0===t&&(t=1),this.isStorageAndTrackEnabled()&&(Object.keys(this.inMemoryCounters).length>=Z?this.logger.debug("DiagnosticsClient: Early return increment as reaching memory limit"):(this.inMemoryCounters[e]=(this.inMemoryCounters[e]||0)+t,this.startTimersIfNeeded()))},r.prototype.recordHistogram=function(e,t){if(this.isStorageAndTrackEnabled())if(Object.keys(this.inMemoryHistograms).length>=Z)this.logger.debug("DiagnosticsClient: Early return recordHistogram as reaching memory limit");else{var i=this.inMemoryHistograms[e];i?(i.count+=1,i.min=Math.min(i.min,t),i.max=Math.max(i.max,t),i.sum+=t):this.inMemoryHistograms[e]={count:1,min:t,max:t,sum:t},this.startTimersIfNeeded()}},r.prototype.recordEvent=function(e,t){this.isStorageAndTrackEnabled()&&(this.inMemoryEvents.length>=10?this.logger.debug("DiagnosticsClient: Early return recordEvent as reaching memory limit"):(this.inMemoryEvents.push({event_name:e,time:Date.now(),event_properties:t}),this.startTimersIfNeeded()))},r.prototype.startTimersIfNeeded=function(){var e=this;this.saveTimer||(this.saveTimer=setTimeout(function(){e.saveAllDataToStorage().catch(function(t){e.logger.debug("DiagnosticsClient: Failed to save all data to storage",t)}).finally(function(){e.saveTimer=null})},1e3)),this.flushTimer||(this.flushTimer=setTimeout(function(){e._flush().catch(function(t){e.logger.debug("DiagnosticsClient: Failed to flush",t)}).finally(function(){e.flushTimer=null})},G))},r.prototype.saveAllDataToStorage=function(){return i(this,void 0,void 0,function(){var i,r,o,a;return n(this,function(n){switch(n.label){case 0:return this.storage?(i=s({},this.inMemoryTags),r=s({},this.inMemoryCounters),o=s({},this.inMemoryHistograms),a=e([],t(this.inMemoryEvents),!1),this.inMemoryEvents=[],this.inMemoryTags={},this.inMemoryCounters={},this.inMemoryHistograms={},[4,Promise.all([this.storage.setTags(i),this.storage.incrementCounters(r),this.storage.setHistogramStats(o),this.storage.addEventRecords(a)])]):[2];case 1:return n.sent(),[2]}})})},r.prototype._flush=function(){return i(this,void 0,void 0,function(){var e,t,i,s,r,o,a,l,c,d;return n(this,function(n){switch(n.label){case 0:return this.storage?[4,this.saveAllDataToStorage()]:[2];case 1:return n.sent(),this.saveTimer=null,this.flushTimer=null,[4,this.storage.getAllAndClear()];case 2:return e=n.sent(),t=e.tags,i=e.counters,s=e.histogramStats,r=e.events,this.storage.setLastFlushTimestamp(Date.now()),o={},t.forEach(function(e){o[e.key]=e.value}),a={},i.forEach(function(e){a[e.key]=e.value}),l={},s.forEach(function(e){l[e.key]={count:e.count,min:e.min,max:e.max,avg:Math.round(e.sum/e.count*100)/100}}),c=r.map(function(e){return{event_name:e.event_name,time:e.time,event_properties:e.event_properties}}),0===Object.keys(a).length&&0===Object.keys(l).length&&0===c.length?[2]:(d={tags:o,histogram:l,counters:a,events:c},this.fetch(d),[2])}})})},r.prototype.fetch=function(e){return i(this,void 0,void 0,function(){var t;return n(this,function(i){switch(i.label){case 0:if(i.trys.push([0,2,,3]),!f())throw new Error("DiagnosticsClient: Fetch is not supported");return[4,fetch(this.serverUrl,{method:"POST",headers:{"X-ApiKey":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify(e)})];case 1:return i.sent().ok?(this.logger.debug("DiagnosticsClient: Successfully sent diagnostics data"),[3,3]):(this.logger.debug("DiagnosticsClient: Failed to send diagnostics data."),[2]);case 2:return t=i.sent(),this.logger.debug("DiagnosticsClient: Failed to send diagnostics data. ",t),[3,3];case 3:return[2]}})})},r.prototype.initializeFlushInterval=function(){return i(this,void 0,void 0,function(){var e,t,i;return n(this,function(n){switch(n.label){case 0:return this.storage?(e=Date.now(),[4,this.storage.getLastFlushTimestamp()]):[2];case 1:return-1===(t=n.sent()||-1)?(this.storage.setLastFlushTimestamp(e),this._setFlushTimer(G),[2]):(i=e-t)>=G?(this._flush(),[2]):(this._setFlushTimer(G-i),[2])}})})},r.prototype._setFlushTimer=function(e){var t=this;this.flushTimer=setTimeout(function(){t._flush().catch(function(e){t.logger.debug("DiagnosticsClient: Failed to flush",e)}).finally(function(){t.flushTimer=null})},e)},r.prototype._setSampleRate=function(e){this.logger.debug("DiagnosticsClient: Setting sample rate to",e),this.config.sampleRate=e,this.shouldTrack=q(this.startTimestamp,this.config.sampleRate)&&this.config.enabled,this.logger.debug("DiagnosticsClient: Should track is",this.shouldTrack)},r}(),V=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,h,g,v,f,p,m,y,b,S,I,C,w;if("object"!=typeof e)return null;var E=e.code||0,k=this.buildStatus(E);switch(k){case u.Success:return{status:k,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 u.Invalid:return{status:k,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!==(h=e.silenced_devices)&&void 0!==h?h:[],silencedEvents:null!==(g=e.silenced_events)&&void 0!==g?g:[],throttledDevices:null!==(v=e.throttled_devices)&&void 0!==v?v:{},throttledEvents:null!==(f=e.throttled_events)&&void 0!==f?f:[]}};case u.PayloadTooLarge:return{status:k,statusCode:E,body:{error:null!==(p=e.error)&&void 0!==p?p:""}};case u.RateLimit:return{status:k,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 u.Timeout:default:return{status:k,statusCode:E}}},e.prototype.buildStatus=function(e){return function(e){return e>=200&&e<300}(e)?u.Success:429===e?u.RateLimit:413===e?u.PayloadTooLarge:408===e?u.Timeout:e>=400&&e<500?u.Invalid:e>=500?u.Failed:u.Unknown},e}(),Y=function(e){function t(t){void 0===t&&(t={});var i=e.call(this)||this;return i.customHeaders=t,i}return o(t,e),t.prototype.send=function(e,t){return i(this,void 0,void 0,function(){var i,r,o;return n(this,function(n){switch(n.label){case 0:if("undefined"==typeof fetch)throw new Error("FetchTransport is not supported");return i={headers:s({"Content-Type":"application/json",Accept:"*/*"},this.customHeaders),body:JSON.stringify(t),method:"POST"},[4,fetch(e,i)];case 1:return[4,(r=n.sent()).text()];case 2:o=n.sent();try{return[2,this.buildResponse(JSON.parse(o))]}catch(e){return[2,this.buildResponse({code:r.status})]}return[2]}})})},t}(V),ee=function(){function e(e,t){this.key="AMP_remote_config_".concat(e.substring(0,10)),this.logger=t}return e.prototype.fetchConfig=function(){var e=null,t={remoteConfig:null,lastFetch:new Date};try{e=localStorage.getItem(this.key)}catch(e){return this.logger.debug("Remote config localstorage failed to access: ",e),Promise.resolve(t)}if(null===e)return this.logger.debug("Remote config localstorage gets null because the key does not exist"),Promise.resolve(t);try{var i=JSON.parse(e);return this.logger.debug("Remote config localstorage parsed successfully: ".concat(JSON.stringify(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){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}(),te=401,ie=403,ne=429,se=function(){function e(e,t,i,n){void 0===i&&(i="US"),this.callbackInfos=[],this.lastSuccessfulFetch=null,this.fetchPromise=null,this.isLastFetchInvalidApiKey=!1,this.apiKey=e,this.serverUrl=n||("US"===i?"https://sr-client-cfg.amplitude.com/config":"https://sr-client-cfg.eu.amplitude.com/config"),this.logger=t,this.storage=new ee(e,t)}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 i(this,void 0,void 0,function(){var e,t=this;return n(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 i(this,void 0,void 0,function(){var t,i,s,r=this;return n(this,function(n){switch(n.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!==(s=n.sent())&&(this.logger.debug("Remote config client subscription all mode fetched from cache: ".concat(JSON.stringify(s))),null!==s.remoteConfig?this.sendCallback(e,s,"cache"):this.logger.debug("Remote config client skips sending callback because cache is empty (first time user).")),[4,t];case 2:return n.sent(),[2]}})})},e.prototype.subscribeWaitForRemote=function(e,t){return i(this,void 0,void 0,function(){var i,s;return n(this,function(n){switch(n.label){case 0:i=new Promise(function(e,i){setTimeout(function(){i("Timeout exceeded")},t)}),n.label=1;case 1:return n.trys.push([1,3,,5]),[4,Promise.race([this.getOrCreateFetchPromise(),i])];case 2:return s=n.sent(),this.logger.debug("Remote config client subscription wait for remote mode returns from remote."),this.sendCallback(e,s,"remote"),this.storage.setConfig(s),[3,5];case 3:return n.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!==(s=n.sent()).remoteConfig?(this.logger.debug("Remote config client subscription wait for remote mode returns a cached copy."),this.sendCallback(e,s,"cache")):(this.logger.debug("Remote config client subscription wait for remote mode failed to fetch cache."),this.sendCallback(e,s,"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),i(this,void 0,void 0,function(){var i,s,r,o,a,l,c=this;return n(this,function(d){switch(d.label){case 0:i=t/e,s={remoteConfig:null,lastFetch:new Date},r=function(s){var r,a,l,d,u,h;return n(this,function(n){switch(n.label){case 0:r=!0,a=new AbortController,l=setTimeout(function(){return a.abort()},t),n.label=1;case 1:return n.trys.push([1,7,8,9]),[4,fetch(o.getUrlParams(),{method:"GET",headers:{Accept:"*/*"},signal:a.signal})];case 2:return(d=n.sent()).ok?[3,4]:[4,d.text()];case 3:return u=n.sent(),o.logger.debug("Remote config client fetch with retry time ".concat(e," failed with ").concat(d.status,": ").concat(u)),d.status===te||d.status===ie?(o.logger.error("Remote config client fetch failed with ".concat(d.status,". Invalid API key; future fetches will be skipped.")),o.isLastFetchInvalidApiKey=!0,r=!1):d.status>=400&&d.status<500&&d.status!==ne&&(r=!1),[3,6];case 4:return[4,d.json()];case 5:return[2,{value:{remoteConfig:n.sent(),lastFetch:new Date}}];case 6:return[3,9];case 7:return(h=n.sent())instanceof Error&&"AbortError"===h.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: "),h),[3,9];case 8:return clearTimeout(l),[7];case 9:return r?s<e-1?[4,new Promise(function(e){return setTimeout(e,c.getJitterDelay(i))})]:[3,11]:[2,"break"];case 10:n.sent(),n.label=11;case 11:return[2]}})},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,s]}})})},e.prototype.getJitterDelay=function(e){return Math.floor(Math.random()*e)},e.prototype.getUrlParams=function(){var t=encodeURIComponent(this.apiKey),i=new URLSearchParams;return i.append("config_group",e.CONFIG_GROUP),"".concat(this.serverUrl,"/").concat(t,"?").concat(i.toString())},e.CONFIG_GROUP="browser",e}();!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}(_||(_={}));var re,oe="https://app.amplitude.com",ae={US:oe,EU:"https://app.eu.amplitude.com",STAGING:"https://apps.stag2.amplitude.com"};var le="__AMPLITUDE_MESSENGER_INSTANCE__",ce="__AMPLITUDE_MESSENGER__",de=function(){function e(e){var t=(void 0===e?{}:e).origin,i=void 0===t?oe:t;this[re]=!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,o;this.actionHandlers.has(e)&&(null===(o=null===(s=this.logger)||void 0===s?void 0:s.warn)||void 0===o||o.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=r(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 i(this,void 0,void 0,function(){var t,i,s;return n(this,function(n){switch(n.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),n.label=1;case 1:return n.trys.push([1,3,,4]),[4,i];case 2:return n.sent(),[3,4];case 3:throw s=n.sent(),this.scriptLoadPromises.delete(e),s;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===oe&&(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[ce])===this&&delete e[ce]},e}();function ue(e){var t,i=f(),n=null==i?void 0:i[ce];if("object"==typeof(t=n)&&null!==t&&le in t&&!0===t[le])return n;var s=new de(e);return i&&(i[ce]=s),s}re=le;var he="__AMPLITUDE_BACKGROUND_CAPTURE__";const ge="[Amplitude]",ve=`${ge} Session Replay ID`,fe=_.US,pe={enabled:!0},me=1e3,ye=`${ge} Session Replay Debug`,be="amp-mask",Se="amp-unmask",Ie="https://api-sr.amplitude.com/sessions/v2/track",Ce="https://api-sr.eu.amplitude.com/sessions/v2/track",we="https://api-sr.stag2.amplitude.com/sessions/v2/track",Ee=9e6,ke=/payload.*exceed/i,Pe=500,Te=1e4,Me=1024,Oe="amplitude-sr-iframe";var De;!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"}(De||(De={}));class Re{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()}}const xe="medium";function _e(e,t){return t||("STAGING"===e?we:"EU"===e?Ce:Ie)}const Fe=(e,t,i)=>{switch(t){case"light":{if("input"!==e)return!1;const t=i?function(e){const t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?t.toLowerCase():null}(i):"";return!!t&&(!!["password","hidden","email","tel"].includes(t)||!!i.autocomplete.startsWith("cc-"))}case"medium":return"input"===e;case"conservative":return!0;default:return Fe(e,xe,i)}},$e=(e,t)=>{var i;if(e&&t.urlMaskLevels)for(const i of t.urlMaskLevels)if(Ue(i.match).test(e))return i.maskLevel;return null!==(i=t.defaultMaskLevel)&&void 0!==i?i:xe},Le=(e,t={defaultMaskLevel:xe},i,n)=>{var s,r;if(i){if(i.closest("."+be))return!0;const e=(null!==(s=t.maskSelector)&&void 0!==s?s:[]).some(e=>i.closest(e));if(e)return!0;if(i.closest("."+Se))return!1;const n=(null!==(r=t.unmaskSelector)&&void 0!==r?r:[]).some(e=>i.closest(e));if(n)return!1}return Fe(e,$e(n,t),i)},je=(e,t,i)=>(n,s)=>Le(e,t,s,null==i?void 0:i())?n.replace(/[^\s]/g,"*"):n,qe=(e,t)=>(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;const o=["INPUT","SELECT","TEXTAREA"].includes(s.tagName)?"input":"text";return Le(o,e,s,null==t?void 0:t())?n.replace(/[^\s]/g,"*"):n},Ne=()=>{const e=f();return(null==e?void 0:e.location)?e.location.href:""},Ae=new Map,Ue=e=>{const t=Ae.get(e);if(t)return t;const i="\0TRAIL\0",n="\0MID\0",s="\0DS\0",r="\0ST\0",o="\0QU\0";let a=e;a=a.replace(/\/\*\*$/,i),a=a.replace(/\/\*\*\//g,n),a=a.replace(/\*\*/g,s),a=a.replace(/\*/g,r),a=a.replace(/\?/g,o),a=a.replace(/[.+^${}()|[\]\\]/g,"\\$&"),a=a.split(i).join("(/.*)?"),a=a.split(n).join("/(.*\\/)?"),a=a.split(s).join(".*"),a=a.split(r).join(".*"),a=a.split(o).join(".");const l=new RegExp(`^${a}$`);return Ae.set(e,l),l},Be=(e,t)=>{for(const i of t){const t=Ue(i.selector);if(t.test(e))return e.replace(t,i.replacement)}return e},ze=()=>i(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/Me):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:""}}),We=e=>{const t=Object.assign({},e),{apiKey:i}=t;return t.apiKey=`****${i.substring(i.length-4)}`,t},He=()=>({flushMaxRetries:2,logLevel:v.Warn,loggerProvider:new S,transportProvider:new Y});class Ke extends C{constructor(e,t){var i,n,s,r,o,a,l,c,d,u,h,g,v,f,p;const m=He();super(Object.assign(Object.assign({transportProvider:m.transportProvider,loggerProvider:new Re(t.loggerProvider||m.loggerProvider)},t),{apiKey:e})),this.flushMaxRetries=void 0!==t.flushMaxRetries&&t.flushMaxRetries<=m.flushMaxRetries?t.flushMaxRetries:m.flushMaxRetries,this.apiKey=e,this.sampleRate=t.sampleRate||0,this.serverZone=t.serverZone||fe,this.configServerUrl=t.configServerUrl,this.trackServerUrl=t.trackServerUrl,this.shouldInlineStylesheet=t.shouldInlineStylesheet,this.version=t.version,this.performanceConfig=t.performanceConfig||pe,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:me,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=Xe(t.maxPersistedEventsSizeBytes,Je,Ge,"maxPersistedEventsSizeBytes",this.loggerProvider)),void 0!==t.maxSingleEventSizeBytes&&(this.maxSingleEventSizeBytes=Xe(t.maxSingleEventSizeBytes,Je,Ze,"maxSingleEventSizeBytes",this.loggerProvider)),this.privacyConfig=Object.assign(Object.assign({},null!==(l=t.privacyConfig)&&void 0!==l?l:{}),{unmaskSelector:Array.from(new Set([`.${Se}`,...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 y=t;this.useWebWorker=null===(g=null!==(u=t.useWebWorker)&&void 0!==u?u:null===(h=y.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<Qe?(t.warn(`flushIntervalConfig.minIntervalMs ${e.minIntervalMs} is below floor ${Qe}ms; clamping.`),s.minIntervalMs=Qe):s.minIntervalMs=e.minIntervalMs);void 0!==e.maxIntervalMs&&(Number.isNaN(e.maxIntervalMs)||e.maxIntervalMs<Qe?(t.warn(`flushIntervalConfig.maxIntervalMs ${e.maxIntervalMs} is below floor ${Qe}ms; clamping.`),s.maxIntervalMs=Qe):s.maxIntervalMs=e.maxIntervalMs);if(void 0!==s.minIntervalMs||void 0!==s.maxIntervalMs){const e=null!==(i=s.minIntervalMs)&&void 0!==i?i:Pe,r=null!==(n=s.maxIntervalMs)&&void 0!==n?n:Te;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.diagnosticsEnabled=t.diagnosticsEnabled,this.diagnosticsSampleRate=t.diagnosticsSampleRate,this.diagnosticsClient=null!==(p=t.diagnosticsClient)&&void 0!==p?p:this.createStandaloneDiagnosticsClient(e,t)}createStandaloneDiagnosticsClient(e,t){const{diagnosticsEnabled:i,diagnosticsSampleRate:n}=t;if(!0===i||"number"==typeof n&&n>0)return new X(e,this.loggerProvider,this.serverZone,{enabled:null==i||i,sampleRate:null!=n?n:0})}}const Qe=100,Je=1e3,Ge=8e6,Ze=1e7;function Xe(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 Ve=(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))(Ve||{}),Ye=(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))(Ye||{}),et=(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))(et||{});const tt="sr.trc",it={init:`${tt}.init`,configSource:e=>`${tt}.config.source.${e}`,configHasTargeting:`${tt}.config.has_targeting`,configNoTargeting:`${tt}.config.no_targeting`,configFetchFailed:`${tt}.config.fetch_failed`,configReceived:`${tt}.config.received`,evalTrigger:e=>`${tt}.eval.${e}`,evalNoConfig:`${tt}.eval.no_config`,evalMissingPrereq:`${tt}.eval.missing_prereq`,evalMatch:`${tt}.eval.match`,evalNoMatch:`${tt}.eval.no_match`,evalError:`${tt}.eval.error`,evalStaleDiscarded:`${tt}.eval.stale_discarded`,evalSkippedAlreadyMatched:`${tt}.eval.skipped_already_matched`,evalDurationMs:`${tt}.eval.duration_ms`,evalEvent:`${tt}.eval`,evalResult:`${tt}.eval.result`,recordStarted:`${tt}.record.started`,recordNoRecordFn:`${tt}.record.no_record_fn`,sendSuppressedMinDuration:`${tt}.send.suppressed_min_duration`,gateNoIdentifiers:`${tt}.gate.no_identifiers`,gateCaptureDisabled:`${tt}.gate.capture_disabled`,gateOptOut:`${tt}.gate.optout`,gateTrcMatch:`${tt}.gate.trc_match`,gateTrcNoMatch:`${tt}.gate.trc_no_match`,gateSampleIn:`${tt}.gate.sample_in`,gateSampleOut:`${tt}.gate.sample_out`,decision:`${tt}.decision`,urlChange:`${tt}.url_change`,urlChangeEvent:`${tt}.url_change`};class nt{constructor(e,t,i){this.localConfig=t,this.remoteConfigClient=e,this.sessionId=null==i?void 0:i.sessionId,this.deviceId=null==i?void 0:i.deviceId}generateJoinedConfig(){var e,t,n,s,r,o,a,l,c,d;return i(this,void 0,void 0,function*(){const i=Object.assign({},this.localConfig);let u;i.optOut=this.localConfig.optOut,i.captureEnabled=!0;try{yield new Promise((e,t)=>{this.remoteConfigClient.subscribe("configs.sessionReplay",{timeout:1500},(n,s)=>{var r,o;if(this.localConfig.loggerProvider.debug(`Session Replay remote configuration received from ${s}:`,JSON.stringify(n,null,2)),!n)return void t(new Error("No remote config received"));const a=n,l=a.sr_sampling_config,c=a.sr_privacy_config,d=a.sr_targeting_config,h=l,g=null==d?void 0:d.segments,v=null===(r=i.interactionConfig)||void 0===r?void 0:r.ugcFilterRules;i.interactionConfig=a.sr_interaction_config,i.interactionConfig&&v&&(i.interactionConfig.ugcFilterRules=v),i.loggingConfig=a.sr_logging_config;try{const e=this.localConfig.diagnosticsClient;null==e||e.increment(it.configSource(String(s))),null==e||e.increment(d?it.configHasTargeting:it.configNoTargeting),null==e||e.recordEvent(it.configReceived,{sessionId:this.sessionId,deviceId:this.deviceId,srId:null!=this.deviceId&&null!=this.sessionId?`${this.deviceId}/${this.sessionId}`:void 0,source:String(s),hasSampling:!!l,captureEnabled:null==h?void 0:h.capture_enabled,sampleRate:null==h?void 0:h.sample_rate,hasTargeting:!!d,targetingSegmentCount:Array.isArray(g)?g.length:void 0,hasPrivacy:!!c}),null===(o=null==e?void 0:e._flush)||void 0===o||o.call(e)}catch(e){}(l||c||d)&&(u={},l&&(u.sr_sampling_config=l),c&&(u.sr_privacy_config=c),d&&(u.sr_targeting_config=d)),e()})})}catch(s){this.localConfig.loggerProvider.error("Failed to generate joined config: ",s);try{null===(e=this.localConfig.diagnosticsClient)||void 0===e||e.increment(it.configFetchFailed),null===(n=null===(t=this.localConfig.diagnosticsClient)||void 0===t?void 0:t._flush)||void 0===n||n.call(t)}catch(e){}return i.captureEnabled=!1,{localConfig:this.localConfig,joinedConfig:i,remoteConfig:void 0}}if(!u)return{localConfig:this.localConfig,joinedConfig:i,remoteConfig:u};const{sr_sampling_config:h,sr_privacy_config:g,sr_targeting_config:v}=u;if(h&&Object.keys(h).length>0?(Object.prototype.hasOwnProperty.call(h,"capture_enabled")?i.captureEnabled=h.capture_enabled:i.captureEnabled=!1,Object.prototype.hasOwnProperty.call(h,"sample_rate")&&(i.sampleRate=h.sample_rate),Object.prototype.hasOwnProperty.call(h,"min_session_duration_ms")&&(i.minSessionDurationMs=this.sanitizeMinSessionDurationMs(h.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.")),g){const e=null!==(s=i.privacyConfig)&&void 0!==s?s:{},t={defaultMaskLevel:null!==(o=null!==(r=g.defaultMaskLevel)&&void 0!==r?r:e.defaultMaskLevel)&&void 0!==o?o:"medium",blockSelector:[],maskSelector:[],unmaskSelector:[],maskAttributes:[...new Set([...null!==(a=e.maskAttributes)&&void 0!==a?a:[],...null!==(l=g.maskAttributes)&&void 0!==l?l:[]])],urlMaskLevels:[...null!==(c=g.urlMaskLevels)&&void 0!==c?c:[],...null!==(d=e.urlMaskLevels)&&void 0!==d?d:[]]},n=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},u=Object.assign(Object.assign({},n(e)),n(g));for(const[e,i]of Object.entries(u))"mask"===i?t.maskSelector.push(e):"block"===i?t.blockSelector.push(e):"unmask"===i&&t.unmaskSelector.push(e);i.privacyConfig=((e,t)=>{const i=document.createDocumentFragment(),n=(e=[])=>{if("string"==typeof e&&(e=[e]),e=e.filter(e=>{try{i.querySelector(e)}catch(i){return t.warn(`[session-replay-browser] omitting selector "${e}" because it is invalid`),!1}return!0}),0!==e.length)return e};return e.blockSelector=n(e.blockSelector),e.maskSelector=n(e.maskSelector),e.unmaskSelector=n(e.unmaskSelector),e})(t,this.localConfig.loggerProvider)}return v&&Object.keys(v).length>0&&(i.targetingConfig=v),this.localConfig.loggerProvider.debug(JSON.stringify({name:"session replay joined config",config:We(i)},null,2)),{localConfig:this.localConfig,joinedConfig:i,remoteConfig:u}})}sanitizeMinSessionDurationMs(e){if("number"==typeof e&&Number.isFinite(e)){if(!(e<0))return e>st?(this.localConfig.loggerProvider.warn(`min_session_duration_ms remote value ${e} exceeds ${st}ms ceiling; clamping.`),st):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 st=6e4;function rt(e){if(e.type!==Ve.IncrementalSnapshot)return!1;const t=e.data;return t.source===Ye.Mutation&&!t.isAttachIframe}function ot(e){const t={};for(const i of e)for(const e of Object.keys(i))t[e]=i[e];return t}function at(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=ot(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 lt(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:Ye.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:at(f)};return Object.assign(Object.assign({},t),{data:p})}function ct(e){if(e.length<=1)return e;const t=[];let i=0;for(;i<e.length;){if(!rt(e[i])){t.push(e[i]),i++;continue}let n=i+1;for(;n<e.length&&rt(e[n]);)n++;t.push(n>i+1?lt(e.slice(i,n)):e[i]),i=n}return t}class dt{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=new Blob([e]).size;n>(null!==(i=this.config.maxSingleEventSizeBytes)&&void 0!==i?i:Ee)?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.eventsManager&&this.deviceId&&this.eventsManager.addEvent({event:{type:"replay",data:e},sessionId:t,deviceId:this.deviceId})},this.addCompressedEvent=(e,t)=>{if(this.worker)try{this.worker.postMessage({event:e,sessionId:t})}catch(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===Ve.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=ct(e.slice(n,s).map(e=>e.event));for(const e of r)i.push({event:e,sessionId:t});n=s}return i}}const ut="Session replay event batch rejected due to exceeded retry count",ht="Failed to store session replay events in IndexedDB",gt="Session replay event batch dropped: server signalled capture disabled or session out of valid range for this session",vt="1.47.0-sr-trc-debug-log.1";class ft{constructor({trackServerUrl:e,loggerProvider:t,payloadBatcher:i,workerScript:n,enableTransportCompression:s,sendTimeoutMs:r}){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,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}))}}},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=>new Blob([e]).size;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;const d=new URLSearchParams({device_id:i,session_id:String(t),type:"replay",api_key:n}),u=`${_e(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:gt}),!1):e.attempts<(e.flushMaxRetries||0)?(e.attempts+=1,!0):(this.completeRequest({context:e,err:ut}),!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 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 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,n,s,r,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!==(s=i.serverZone)&&void 0!==s?s:"",i.sampleRate,null!==(o=null===(r=i.version)||void 0===r?void 0:r.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 s=()=>{t&&d.push(t),t=null,n=0};for(const r of e){const e=r.events.reduce((e,t)=>e+new Blob([t]).size,0);if(null===t){t=Object.assign(Object.assign({},r),{events:[...r.events],attempts:0}),n=e;continue}if(n+e>4e6){s(),t=Object.assign(Object.assign({},r),{events:[...r.events],attempts:0}),n=e;continue}const o=t.onComplete,a=r.onComplete;t.events=t.events.concat(r.events),n+=e,t.onComplete=()=>i(this,void 0,void 0,function*(){yield Promise.allSettled([o(),a()])})}s()}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:gt});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,n,s){return i(this,void 0,void 0,function*(){const i=""+ ++this.sendIdCounter;return new Promise(r=>{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:r,timeout:a}),e.postMessage({type:"send",id:i,payload:n,useRetry:s,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:Ne(),sdkVersion:vt,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}}sendOnMainThread(e,t,n,s,r){var o,a,l,c,d,u,h;return i(this,void 0,void 0,function*(){const g=Ne(),v=vt,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(s),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"),s=n.writable.getWriter(),r=n.readable.getReader(),o=[],a=(()=>i(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:new Blob([t]).size,c=new AbortController,b={headers: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"}:{}),body:null!=a?a:t,method:"POST",keepalive:l<=65536,signal:c.signal},S=`${_e(n.serverZone,this.trackServerUrl)}?${m.toString()}`;if(0===s.events.length)return void this.completeRequest({context:n});const I=this.sendTimeoutMs>0?setTimeout(()=>{c.abort()},this.sendTimeoutMs):void 0;let C;try{C=yield fetch(S,b)}finally{I&&clearTimeout(I)}if(null===C)return void this.completeRequest({context:n,err:"Unexpected error occurred"});if(C.status>=200&&C.status<300){const e=null!==(h=null===(u=null===(d=C.headers)||void 0===d?void 0:d.get)||void 0===u?void 0:u.call(d,"X-Session-Replay-Event-Skipped"))&&void 0!==h?h:null;this.applyServerDirective(n.sessionId,e)}if(r){let e="";if(413===C.status)try{e=yield C.text()}catch(e){}yield this.handleReponse(C.status,n,e)}else{let e="";try{e=JSON.stringify(C.body,null,2)}catch(e){}this.completeRequest({context:n,success:`${C.status}: ${e}`})}}catch(e){!!e&&"object"==typeof e&&"AbortError"===e.name&&r?yield this.handleOtherResponse(n):this.completeRequest({context:n,err:e})}})}handleReponse(e,t,n=""){return i(this,void 0,void 0,function*(){switch((new V).buildStatus(e)){case u.Success:this.handleSuccessResponse(t);break;case u.Failed:case u.Timeout:case u.RateLimit:yield this.handleOtherResponse(t);break;case u.PayloadTooLarge:this.handlePayloadTooLargeResponse(t,ke.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 i=t?"WAF (compressed payload too large)":"server (event too large)",n=Math.round(e.events.reduce((e,t)=>e+t.length,0)/Me);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(new Blob(e.events).size/Me);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:ut}):(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:gt}):i.push(t);this.queue=i}}class pt{get timeAtLastSplit(){return this._timeAtLastSplit}constructor(e){var t,i,n;this.minInterval=Pe,this.maxInterval=Te,this.maxPersistedEventsSize=6e6,this._timeAtLastSplit=Date.now(),this.shouldSplitEventsList=(e,t)=>{const i=this.getStringSize(t);return this.getEventsArraySize(e)+i>=this.maxPersistedEventsSize||!!(Date.now()-this.timeAtLastSplit>this.interval&&e.length)&&(this.interval=Math.min(this.maxInterval,this.interval+this.minInterval),this._timeAtLastSplit=Date.now(),!0)},this.loggerProvider=e.loggerProvider,this.minInterval=null!==(t=e.minInterval)&&void 0!==t?t:this.minInterval,this.maxInterval=null!==(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}getStringSize(e){let t=0;for(let i=0;i<e.length;i++){const n=e.charCodeAt(i);if(n<=127)t++;else if(n<=2047)t+=2;else if(n>=55296&&n<=56319){const n=i+1<e.length?e.charCodeAt(i+1):NaN;n>=56320&&n<=57343?(t+=4,i++):t+=3}else t+=3}return t}getEventsArraySize(e){let t=0;for(const i of e)t+=this.getStringSize(i);return t+(2+Math.max(0,e.length-1)+2*e.length)}}const mt=(e,t,i)=>{var n;"object"==typeof(n=i)&&null!==n&&"AbortError"===n.name?e.debug(t):e.warn(t)};const yt="sessionCurrentSequence",bt="sequencesToSend",St=5e3;function It(e,t,i){const n=setTimeout(i,t);return e.then(()=>clearTimeout(n),()=>clearTimeout(n)),()=>clearTimeout(n)}const Ct=e=>{let t,i;return e.objectStoreNames.contains(yt)||(i=e.createObjectStore(yt,{keyPath:"sessionId"})),e.objectStoreNames.contains(bt)||(t=e.createObjectStore(bt,{keyPath:"sequenceId",autoIncrement:!0}),t.createIndex("sessionId","sessionId")),{sequencesStore:t,currentSequenceStore:i}},wt=e=>i(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:Ct}),2e3,"IDB openDB timed out")});class Et extends pt{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 i=[],n=this.db.transaction("sequencesToSend","readwrite");n.done.catch(i=>{e||t||(mt(this.loggerProvider,`${ht}: ${i}`,i),this.recordFailure())});const s=It(n.done,St,()=>{e||t||(t=!0,mt(this.loggerProvider,`${ht}: 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,mt(this.loggerProvider,`${ht}: ${i}`,i),this.recordFailure())}}),this.storeCurrentSequence=e=>i(this,void 0,void 0,function*(){let t=!1,i=!1;try{const n=this.db.transaction([yt,bt],"readwrite");n.done.catch(e=>{t||i||(mt(this.loggerProvider,`${ht}: ${e}`,e),this.recordFailure())});const s=It(n.done,St,()=>{t||i||(i=!0,mt(this.loggerProvider,`${ht}: transaction timed out`),this.recordFailure())}),r=yield n.objectStore(yt).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(bt).put({sessionId:e,events:r.events,tabId:this.tabId});yield n.objectStore(yt).put({sessionId:e,events:[],tabId:this.tabId}),this.recordSuccess(),s();const{tabId:l}=r,c=a(r,["tabId"]);return Object.assign(Object.assign({},c),{sessionId:e,sequenceId:o})}catch(e){i||(t=!0,mt(this.loggerProvider,`${ht}: ${e}`,e),this.recordFailure())}}),this.addEventToCurrentSequence=(e,t)=>i(this,void 0,void 0,function*(){let i=!1,n=!1;try{const s=this.db.transaction([yt,bt],"readwrite");s.done.catch(e=>{i||n||(mt(this.loggerProvider,`${ht}: ${e}`,e),this.recordFailure())});const r=It(s.done,St,()=>{i||n||(n=!0,mt(this.loggerProvider,`${ht}: transaction timed out`),this.recordFailure())}),o=yield s.objectStore(yt).get(e);if((null==o?void 0:o.tabId)&&o.tabId!==this.tabId)return o.events.length>0&&(yield s.objectStore(bt).put({sessionId:e,events:o.events,tabId:o.tabId})),yield s.objectStore(yt).put({sessionId:e,events:[t],tabId:this.tabId}),this.recordSuccess(),void r();const a=o;if(!a)return yield s.objectStore(yt).put({sessionId:e,events:[t],tabId:this.tabId}),this.recordSuccess(),void r();if(!this.shouldSplitEventsList(a.events,t))return yield s.objectStore(yt).put({sessionId:e,events:a.events.concat(t),tabId:this.tabId}),this.recordSuccess(),void r();const l=a.events;if(0===l.length)return this.maybeLogEmptyFiltered("addEventToCurrentSequence"),yield s.objectStore(yt).put({sessionId:e,events:[t],tabId:this.tabId}),this.recordSuccess(),void r();yield s.objectStore(yt).put({sessionId:e,events:[t],tabId:this.tabId});const c=yield s.objectStore(bt).put({sessionId:e,events:l,tabId:this.tabId});return this.recordSuccess(),r(),{events:l,sessionId:e,sequenceId:c}}catch(e){n||(i=!0,mt(this.loggerProvider,`${ht}: ${e}`,e),this.recordFailure())}}),this.storeSendingEvents=(e,t)=>i(this,void 0,void 0,function*(){try{const i=yield this.db.put(bt,{sessionId:e,events:t,tabId:this.tabId});return this.recordSuccess(),i}catch(e){mt(this.loggerProvider,`${ht}: ${e}`,e),this.recordFailure()}}),this.cleanUpSessionEventsStore=(e,t)=>i(this,void 0,void 0,function*(){if(t)try{yield this.db.delete(bt,t),this.recordSuccess()}catch(e){mt(this.loggerProvider,`${ht}: ${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}`,s=`${t.apiKey.substring(0,10)}_amp_session_replay_events${i}`,r=yield wt(s),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 Et(Object.assign(Object.assign({},t),{db:r,tabId:o}))}catch(e){mt(t.loggerProvider,`${ht}: ${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 i=a(e,["tabId"]);t.push(i)}return t})}}class kt extends pt{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 i(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 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 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 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 Pt=({config:e,minInterval:t,maxInterval:n,maxPersistedEventsSize:s,type:r,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:Ee,h=new ft(Object.assign(Object.assign({},e),{loggerProvider:e.loggerProvider,payloadBatcher:o,workerScript:l})),g=()=>new kt({loggerProvider:e.loggerProvider,maxInterval:n,minInterval:t,maxPersistedEventsSize:s});let v,f,p=!1;f="idb"===a?yield i(void 0,void 0,void 0,function*(){const o=yield Et.new(r,{loggerProvider:e.loggerProvider,minInterval:t,maxInterval:n,maxPersistedEventsSize:s,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:s,sequenceId:o})=>{const a=t.map(e=>({event:e,bytes:new Blob([e]).size})),l=a.filter(e=>e.bytes>u);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.bytes/1024)} KB`).join(", ")}. If this recurs, please open a GitHub issue at https://github.com/amplitude/Amplitude-TypeScript/issues or contact Amplitude support.`);const c=l.length>0?a.filter(e=>e.bytes<=u).map(e=>e.event):t;0!==c.length?(e.debugMode&&ze().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:c,sessionId:n,flushMaxRetries:e.flushMaxRetries,apiKey:e.apiKey,deviceId:s,sampleRate:e.sampleRate,serverZone:e.serverZone,version:e.version,type:r,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: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})=>i(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 i(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 i(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 i(this,void 0,void 0,function*(){const t=[];this.managers.forEach(i=>{t.push(i.flush(e))}),yield Promise.all(t)})}}let Mt,Ot,Dt;function Rt(e,t){if(Dt=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};Mt=Object.assign(Object.assign({},i),t),Ot=function(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return e;if(e===t.root)return e.ownerDocument;return e}(Mt.root,i);let n=xt(e,"all",()=>xt(e,"two",()=>xt(e,"one",()=>xt(e,"none"))));if(n){const t=Jt(Gt(n,e));return t.length>0&&(n=t[0]),Ft(n)}throw new Error("Selector was not found.")}function xt(e,t,i){let n=null,s=[],r=e,o=0;for(;r;){const e=(new Date).getTime()-Dt.getTime();if(void 0!==Mt.timeoutMs&&e>Mt.timeoutMs)throw new Error(`Timeout: Can't find a unique selector after ${e}ms`);let a=Ht(jt(r))||Ht(...qt(r))||Ht(...Nt(r))||Ht(At(r))||[Ut()];const l=Bt(r);if("all"==t)l&&(a=a.concat(a.filter(Wt).map(e=>zt(e,l))));else if("two"==t)a=a.slice(0,1),l&&(a=a.concat(a.filter(Wt).map(e=>zt(e,l))));else if("one"==t){const[e]=a=a.slice(0,1);l&&Wt(e)&&(a=[zt(e,l)])}else"none"==t&&(a=[Ut()],l&&(a=[zt(a[0],l)]));for(let e of a)e.level=o;if(s.push(a),s.length>=Mt.seedMinLength&&(n=_t(s,i),n))break;r=r.parentElement,o++}return n||(n=_t(s,i)),!n&&i?i():n}function _t(e,t){const i=Jt(Qt(e));if(i.length>Mt.threshold)return t?t():null;for(let e of i)if(Lt(e))return e;return null}function Ft(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 $t(e){return e.map(e=>e.penalty).reduce((e,t)=>e+t,0)}function Lt(e){const t=Ft(e);switch(Ot.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&&Mt.idName(t)?{name:"#"+CSS.escape(t),penalty:0}:null}function qt(e){const t=Array.from(e.attributes).filter(e=>Mt.attr(e.name,e.value));return t.map(e=>({name:`[${CSS.escape(e.name)}="${CSS.escape(e.value)}"]`,penalty:.5}))}function Nt(e){return Array.from(e.classList).filter(Mt.className).map(e=>({name:"."+CSS.escape(e),penalty:1}))}function At(e){const t=e.tagName.toLowerCase();return Mt.tagName(t)?{name:t,penalty:2}:null}function Ut(){return{name:"*",penalty:3}}function Bt(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 zt(e,t){return{name:e.name+`:nth-child(${t})`,penalty:e.penalty+1}}function Wt(e){return"html"!==e.name&&!e.name.startsWith("#")}function Ht(...e){const t=e.filter(Kt);return t.length>0?t:null}function Kt(e){return null!=e}function*Qt(e,t=[]){if(e.length>0)for(let i of e[0])yield*Qt(e.slice(1,e.length),t.concat(i));else yield t}function Jt(e){return[...e].sort((e,t)=>$t(e)-$t(t))}function*Gt(e,t,i={counter:0,visited:new Map}){if(e.length>2&&e.length>Mt.optimizedMinLength)for(let n=1;n<e.length-1;n++){if(i.counter>Mt.maxNumberOfTries)return;i.counter+=1;const s=[...e];s.splice(n,1);const r=Ft(s);if(i.visited.has(r))return;Lt(s)&&Zt(s,t)&&(yield s,i.visited.set(r,!0),yield*Gt(s,t,i))}}function Zt(e,t){return Ot.querySelector(Ft(e))===t}const Xt=({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}},Vt=({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 Yt{constructor(e,t){this.createHook=({eventsManager:e,sessionId:t,deviceIdFn:i,mirror:n,ugcFilterRules:s,performanceOptions:r})=>o=>{if(o.type!==et.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=Rt(g,r)}catch(e){this.logger.debug("error resolving selector from finder")}const p=Be(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 ei(){const e=f();return(null==e?void 0:e.innerHeight)||document.documentElement&&document.documentElement.clientHeight||0}function ti(){const e=f();return(null==e?void 0:e.innerWidth)||document.documentElement&&document.documentElement.clientWidth||0}class ii{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=_e(t.serverZone,t.trackServerUrl),this.apiKey=t.apiKey,this.context=e}send(e,t){const{sessionId:i,type:n}=this.context,s=new URLSearchParams({device_id:e,session_id:String(i),type:String(n),api_key:this.apiKey}),r=`${this.basePageUrl}?${s.toString()}`;this.sendBeacon(r,t)||this.sendXhr(r,t)}}class ni{static default(e,t){return new ni(new ii(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:ei(),viewportWidth:ti(),pageUrl:Be(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=ti(),this._maxScrollHeight=ei(),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=ti();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=ei();this._maxScrollY=e.y;const n=e.y+i;n>this._maxScrollHeight&&(this._maxScrollHeight=n),this.timestamp=t}}}class si{constructor({sessionId:e,deviceId:t}){this.deviceId=t,this.sessionId=e,e&&t&&(this.sessionReplayId=((e,t)=>`${t}/${e}`)(e,t))}}const ri=864e5,oi=e=>`AMP_SR_START_${e.substring(0,10)}_`,ai=(e,t)=>`${oi(e)}${t}`,li=()=>{try{const e=f();return null==e?void 0:e.localStorage}catch(e){return}};const ci=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`,i=yield this.createStore(t);return this.dbs[e]=i,i}),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),s=yield e.get("sessionTargetingMatch",i);return null==s?void 0:s.targetingMatch}catch(t){mt(e,`Failed to get targeting match for session id ${n}: ${t}`,t)}}),this.storeTargetingMatchForSession=({loggerProvider:e,apiKey:t,sessionId:n,targetingMatch:s})=>i(this,void 0,void 0,function*(){try{const e=yield this.openOrCreateDB(t),i=String(n);return yield e.put("sessionTargetingMatch",{targetingMatch:s,sessionId:i,lastUpdated:Date.now()})}catch(t){mt(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),s=e.transaction("sessionTargetingMatch","readwrite"),r=yield s.store.getAll();for(let e=0;e<r.length;e++){const t=r[e],n=Date.now()-t.lastUpdated;t.sessionId!==i&&n>1728e5&&(yield s.store.delete(t.sessionId))}yield s.done}catch(t){mt(e,`Failed to clear old targeting matches for sessions: ${t}`,t)}})}},di=2654435761,ui=2246822519,hi=3266489917,gi=374761393;function vi(e,t){return(e<<t|e>>>32-t)>>>0}function fi(e,t){return e=vi(e=e+Math.imul(t,ui)>>>0,13),e=Math.imul(e,di)>>>0}function pi(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function mi(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+di+ui>>>0,o=t+ui>>>0,a=t>>>0,l=t-di>>>0;for(;r<=n-16;)e=fi(e,pi(i,r)),r+=4,o=fi(o,pi(i,r)),r+=4,a=fi(a,pi(i,r)),r+=4,l=fi(l,pi(i,r)),r+=4;s=vi(e,1)+vi(o,7)+vi(a,12)+vi(l,18)>>>0}else s=t+gi>>>0;for(s=s+n>>>0;r<=n-4;)s=s+Math.imul(pi(i,r),hi)>>>0,s=Math.imul(vi(s,17),668265263)>>>0,r+=4;for(;r<n;)s=s+Math.imul(i[r],gi)>>>0,s=Math.imul(vi(s,11),di)>>>0,r++;return s^=s>>>15,s=Math.imul(s,ui)>>>0,s^=s>>>13,s=Math.imul(s,hi)>>>0,s^=s>>>16,s>>>0}const yi="__amplitude_url_tracking_patched__",bi=new WeakMap;function Si(e,t,i={}){if(!(null==e?void 0:e.location))return()=>{};const{enablePolling:n=!1,pollingInterval:s=me}=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=bi.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[yi]=!0,t},a=e.history;if(null==a?void 0:a.pushState){const e=Reflect.get(a,"pushState");e[yi]||(a.pushState=o(e))}if(null==a?void 0:a.replaceState){const e=Reflect.get(a,"replaceState");e[yi]||(a.replaceState=o(e))}r={callbacks:i,notify:s,onPopStateOrHashChange:()=>s(),listenersAttached:!1},bi.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 Ii(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:me,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?Be(s,l):s,title:r,viewportHeight:e,viewportWidth:t,type:"url-change-event"}})();t(n)}},f=Si(i,()=>v(),c?{enablePolling:!0,pollingInterval:d}:{});return v(),()=>f()},options:e}}class Ci{constructor(){this.pendingLoadListeners=new Map}start(){var e;null===(e=this.mutationObserver)||void 0===e||e.disconnect();f()&&(this.sendToAllIframes({type:Oe,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:Oe,action:"stop"})}sendToIframeAfterLoad(e){const t=()=>{this.pendingLoadListeners.delete(e),this.sendToIframe(e,{type:Oe,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 wi{constructor(){this.name="@amplitude/session-replay-browser",this.recordCancelCallback=null,this.eventCount=0,this.sessionTargetingMatch=!1,this.trcDiagnosticSessionId=void 0,this.pageLeaveFns=[],this.suppressedSendCount=0,this.hasEmittedGateDecision=!1,this.recordFunction=null,this.recordEventsInFlight=!1,this.pendingEmitEvents=[],this.currentPageUrl="",this.recordEventsPendingShouldLogMetadata=null,this.urlChangeCleanup=null,this.crossOriginIframeCoordinator=null,this.crossOriginParentSignalCleanup=null,this.latestUrlChangeTargetingEvaluationId=0,this.teardownEventListeners=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.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,s=!1)=>i(this,void 0,void 0,function*(){var r,o,a,l,c,u,h;if(this.incrementDiagnostic(it.evalTrigger(t?"init":s?"urlchange":"event")),!this.identifiers||!this.identifiers.sessionId||!this.config)return this.incrementDiagnostic(it.evalMissingPrereq),this.recordDiagnosticEvent(it.evalMissingPrereq,{hasIdentifiers:!!this.identifiers,hasSessionId:!!(null===(r=this.identifiers)||void 0===r?void 0:r.sessionId),hasConfig:!!this.config,hasDeviceId:!!this.getDeviceId()}),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(this.incrementDiagnostic(it.evalNoConfig),!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 g=this.config.targetingConfig;if(g&&!this.sessionTargetingMatch){const n=s?this.latestUrlChangeTargetingEvaluationId:void 0;let r=e.event;r&&Object.values(d).includes(r.event_type)&&(r=void 0);const v=null!==(u=null!==(a=null===(o=e.page)||void 0===o?void 0:o.url)&&void 0!==a?a:null===(c=null===(l=f())||void 0===l?void 0:l.location)||void 0===c?void 0:c.href)&&void 0!==u?u:"",p=null!==(h=e.page)&&void 0!==h?h:""!==v?{url:v}:void 0,m=Date.now(),y=yield(({sessionId:e,targetingConfig:t,loggerProvider:n,apiKey:s,targetingParams:r,urlChange:o=!1,diagnosticsClient:a,deviceId:l})=>i(void 0,void 0,void 0,function*(){var i,c,d,u,h,g;if(yield ci.clearStoreOfOldSessions({loggerProvider:n,apiKey:s,currentSessionId:e}),!0===(yield ci.getTargetingMatchForSession({loggerProvider:n,apiKey:s,sessionId:e}))&&!o)return!0;let v=!0;try{const{evaluateTargeting:o}=yield import("./targeting-min.js").then(function(e){return e.i}),h=Object.assign(Object.assign({},r),{flag:t,sessionId:"string"==typeof e?parseInt(e,10):e,apiKey:s,loggerProvider:n}),g=yield o(h);g&&g.sr_targeting_config&&(v="on"===g.sr_targeting_config.key);try{null==a||a.recordEvent(it.evalResult,{sessionId:e,deviceId:l,srId:null!=l&&null!=e?`${l}/${e}`:void 0,pageUrl:null===(i=null==r?void 0:r.page)||void 0===i?void 0:i.url,variantKey:null!==(d=null===(c=null==g?void 0:g.sr_targeting_config)||void 0===c?void 0:c.key)&&void 0!==d?d:null,matched:v}),null===(u=null==a?void 0:a._flush)||void 0===u||u.call(a)}catch(e){}ci.storeTargetingMatchForSession({loggerProvider:n,apiKey:s,sessionId:e,targetingMatch:v})}catch(t){const i=t;try{null==a||a.increment(it.evalError),null==a||a.recordEvent(it.evalError,{sessionId:e,deviceId:l,srId:null!=l&&null!=e?`${l}/${e}`:void 0,pageUrl:null===(h=null==r?void 0:r.page)||void 0===h?void 0:h.url,message:i.message}),null===(g=null==a?void 0:a._flush)||void 0===g||g.call(a)}catch(e){}n.warn(i.message)}return v}))({sessionId:this.identifiers.sessionId,targetingConfig:g,loggerProvider:this.loggerProvider,apiKey:this.config.apiKey,targetingParams:{userProperties:e.userProperties,event:r,page:p},urlChange:s,diagnosticsClient:this.config.diagnosticsClient,deviceId:this.getDeviceId()}),b=Date.now()-m,S=t?"init":s?"urlchange":"event";if(this.recordDiagnosticHistogram(it.evalDurationMs,b),s&&void 0!==n&&n!==this.latestUrlChangeTargetingEvaluationId)return this.incrementDiagnostic(it.evalStaleDiscarded),this.recordDiagnosticEvent(it.evalStaleDiscarded,{sessionId:this.identifiers.sessionId,pageUrl:null==p?void 0:p.url,evaluationId:n,latestEvaluationId:this.latestUrlChangeTargetingEvaluationId,evalDurationMs:b}),void this.loggerProvider.debug(`Ignoring stale URL-change targeting result #${n}; latest is #${this.latestUrlChangeTargetingEvaluationId}.`);this.incrementDiagnostic(y?it.evalMatch:it.evalNoMatch),this.sessionTargetingMatch=this.sessionTargetingMatch||y,this.recordDiagnosticEvent(it.evalEvent,{trigger:S,matched:y,sessionTargetingMatch:this.sessionTargetingMatch,pageUrl:null==p?void 0:p.url,hasDeviceId:!!this.getDeviceId(),hasEvent:!!r,eventType:null==r?void 0:r.event_type,userPropertyKeys:e.userProperties?Object.keys(e.userProperties):[],evalDurationMs:b}),this.loggerProvider.debug(JSON.stringify({name:"targeted replay capture config",sessionTargetingMatch:this.sessionTargetingMatch,event:r,targetingParams:e},null,2))}else g&&this.sessionTargetingMatch&&this.incrementDiagnostic(it.evalSkippedAlreadyMatched);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 s=this.config;if(s&&e!==De.METADATA&&(i={config:We(s),version:vt},n)){const e=yield ze();i=Object.assign(Object.assign({},e),i)}this.recordCancelCallback&&this.recordFunction?this.recordFunction.addCustomEvent(e,Object.assign(Object.assign({},t),i)):this.loggerProvider.debug(`Not able to add custom replay capture event ${e} due to no ongoing recording.`)}catch(e){this.loggerProvider.debug("Error while adding custom replay capture event: ",e)}}),this.stopRecordingEvents=()=>{var e,t,i;try{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 Re(new S)}init(e,t){return y(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=Si(i,e=>{if(this.currentPageUrl=e,this.incrementDiagnostic(it.urlChange),this.recordDiagnosticEvent(it.urlChangeEvent,{href:e,hasTargeting:n,alreadyMatched:this.sessionTargetingMatch}),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 n,s,r,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),this.loggerProvider=new Re(t.loggerProvider||new S),Object.prototype.hasOwnProperty.call(t,"logLevel")&&this.loggerProvider.enable(t.logLevel),this.currentPageUrl=Ne(),this.identifiers=new si({sessionId:t.sessionId,deviceId:t.deviceId});const b=Date.now();((e,t,i)=>{const n=li();if(!n)return;const s=oi(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>=ri)&&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,b,this.loggerProvider),this.sessionStartTime=void 0!==t.sessionId&&null!==(s=((e,t,i,n)=>{const s=li();if(!s)return;const r=ai(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<ri)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,b,this.loggerProvider))&&void 0!==s?s:b,this.joinedConfigGenerator=yield((e,t)=>i(void 0,void 0,void 0,function*(){const i=new Ke(e,t),n=new se(e,i.loggerProvider,i.serverZone,t.configServerUrl);return new nt(n,i,{sessionId:t.sessionId,deviceId:t.deviceId})}))(e,t);const{joinedConfig:I,localConfig:C,remoteConfig:w}=yield this.joinedConfigGenerator.generateJoinedConfig();if(this.config=I,this.setMetadata(t.sessionId,I,C,w,null===(r=t.version)||void 0===r?void 0:r.version,vt,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=ni.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 Yt(this.loggerProvider,e)}const E=[];let k,P,{storeType:T}=this.config;"idb"!==T||(null===(l=f())||void 0===l?void 0:l.indexedDB)||(T="memory",this.loggerProvider.warn("Could not use preferred indexedDB storage, reverting to in memory option.")),this.loggerProvider.log(`Using ${T} for event storage.`);const M=f();if(this.config.useWebWorker&&M&&M.Worker){const{compressionScript:e,trackDestinationScript:t}=yield import("./worker-min.js");k=e,P=t}let O;try{O=yield Pt({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:T,trackDestinationWorkerScript:P,shouldSend:()=>!this.isBelowMinSessionDuration()}),this.rrwebEventManager=O,E.push({name:"replay",manager:O})}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?Vt:Xt;try{const t=yield Pt({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:T,trackDestinationWorkerScript:P});E.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(...E),this.eventCompressor&&this.eventCompressor.terminate();const D=!0===this.config.eagerFullSnapshotSend?()=>this.sendEvents():void 0;if(this.eventCompressor=new dt(this.eventsManager,this.config,this.getDeviceId(),k,D),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)||!O)return;const t=O.getBeaconEvents();if(!t.length)return;const i=this.getDeviceId();i&&(this.isBelowMinSessionDuration()||O.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=ue();!function(e,t){var i,n=e;if(!0!==n[he]){n[he]=!0;var s=null!==(i=null==t?void 0:t.scriptUrl)&&void 0!==i?i:"https://cdn.amplitude.com/libs/background-capture-1.0.1.js.gz",r=null,o=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(){var t,i;null===(i=null===(t=e.logger)||void 0===t?void 0:t.debug)||void 0===i||i.call(t,"Initializing background capture (external script)");var n=new URL(s,e.endpoint).toString();e.loadScriptOnce(n).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)"),r=null===(n=null===window||void 0===window?void 0:window.amplitudeBackgroundCapture)||void 0===n?void 0:n.call(window,{messenger:e,onBackgroundCapture:o}),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==r?void 0:r.close)||void 0===e||e.call(r),r=null})}}(e),e.setup(Object.assign({logger:this.loggerProvider},this.config.serverZone&&{endpoint:ae[this.config.serverZone]}))}this.loggerProvider.log("Installing @amplitude/session-replay-browser."),this.teardownEventListeners(!1),this.incrementDiagnostic(it.init),this.recordDiagnosticEvent(it.init,{hasDeviceId:!!this.getDeviceId(),captureEnabled:this.config.captureEnabled,hasTargetingConfig:!!this.config.targetingConfig,sampleRate:this.config.sampleRate,optOut:this.shouldOptOut(),currentUrl:null===(v=this.getCurrentPageForTargeting())||void 0===v?void 0:v.url}),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 y(this.asyncSetSessionId(e,t))}asyncSetSessionId(e,t,n){var s,r,o,a;return i(this,void 0,void 0,function*(){const i=null===(s=this.identifiers)||void 0===s?void 0:s.sessionId,l=this.getDeviceId();if(!(void 0===i||i!==e||void 0!==t&&t!==l||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 c=i!==e;c&&(null===(r=this.rrwebEventManager)||void 0===r||r.dropPendingBeaconEvents());const d=t||this.getDeviceId();if(this.identifiers=new si({sessionId:e,deviceId:d}),c&&(this.sessionStartTime=Date.now(),this.suppressedSendCount=0,this.hasEmittedGateDecision=!1,(null===(o=this.config)||void 0===o?void 0:o.apiKey)&&(((e,t,i,n)=>{const s=li();if(s)try{s.setItem(ai(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!==i&&((e,t,i)=>{const n=li();if(n)try{n.removeItem(ai(e,t))}catch(e){null==i||i.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===(a=this.config)||void 0===a?void 0:a.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 i=this.getShouldRecord();let n={};return i&&(n={[ve]:t.sessionReplayId?t.sessionReplayId:null},e.debugMode&&(n[ye]=JSON.stringify({appHash:j(e.apiKey).toString()}))),this.addCustomRRWebEvent(De.GET_SR_PROPS,{shouldRecord:i,eventProperties:n},10===this.eventCount),10===this.eventCount&&(this.eventCount=0),this.eventCount++,n}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.`),this.suppressedSendCount++,void this.incrementDiagnostic(it.sendSuppressedMinDuration)}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(De.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 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 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,void 0===n&&(n=h),L.getInstance(n)).identityStore.getIdentity().optOut}var n;return void 0!==i?i:null===(t=this.config)||void 0===t?void 0:t.optOut}incrementDiagnostic(e){var t,i;try{null===(i=null===(t=this.config)||void 0===t?void 0:t.diagnosticsClient)||void 0===i||i.increment(e)}catch(e){}}recordDiagnosticHistogram(e,t){var i,n;try{null===(n=null===(i=this.config)||void 0===i?void 0:i.diagnosticsClient)||void 0===n||n.recordHistogram(e,t)}catch(e){}}recordDiagnosticEvent(e,t){var i,n,s,r,o,a;try{const l=null===(i=this.identifiers)||void 0===i?void 0:i.sessionId,c=this.getDeviceId();null===(s=null===(n=this.config)||void 0===n?void 0:n.diagnosticsClient)||void 0===s||s.recordEvent(e,Object.assign({sessionId:l,deviceId:c,srId:null!=c&&null!=l?`${c}/${l}`:void 0},t)),null===(a=null===(o=null===(r=this.config)||void 0===r?void 0:r.diagnosticsClient)||void 0===o?void 0:o._flush)||void 0===a||a.call(o)}catch(e){}}recordTrcDecisionDiagnostic(e){var t,i;const n=this.config;if(!n)return;const s=null===(t=this.identifiers)||void 0===t?void 0:t.sessionId;n.diagnosticsClient&&void 0!==s&&s!==this.trcDiagnosticSessionId&&(this.trcDiagnosticSessionId=s,this.recordDiagnosticEvent(it.decision,{shouldRecord:e,captureEnabled:n.captureEnabled,hasTargetingConfig:!!n.targetingConfig,sessionTargetingMatch:this.sessionTargetingMatch,sampleRate:n.sampleRate,pageUrl:null===(i=this.getCurrentPageForTargeting())||void 0===i?void 0:i.url,sdkVersion:vt}))}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."),this.incrementDiagnostic(it.gateNoIdentifiers),!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.`),this.incrementDiagnostic(it.gateCaptureDisabled),this.recordTrcDecisionDiagnostic(!1),!1;if(this.shouldOptOut())return this.loggerProvider.log(`Opting session ${this.identifiers.sessionId} out of recording due to optOut config.`),this.incrementDiagnostic(it.gateOptOut),this.recordTrcDecisionDiagnostic(!1),!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,this.incrementDiagnostic(it.gateTrcMatch)):(t=`Not capturing replays for session ${this.identifiers.sessionId} due to not matching targeting conditions.`,this.loggerProvider.log(t),e=!1,i=!1,this.incrementDiagnostic(it.gateTrcNoMatch));else{(n=this.identifiers.sessionId,s=this.config.sampleRate,mi(n.toString())%1e6/1e6<s)?(e=!0,i=!0,this.incrementDiagnostic(it.gateSampleIn)):(t=`Opting session ${this.identifiers.sessionId} out of recording due to sample rate.`,this.loggerProvider.log(t),e=!1,i=!1,this.incrementDiagnostic(it.gateSampleOut))}var n,s;return this.lastShouldRecordDecision!==e&&this.config.targetingConfig&&(this.addCustomRRWebEvent(De.TARGETING_DECISION,{message:t,sessionId:this.identifiers.sessionId,matched:i,targetingParams:this.lastTargetingParams}),this.lastShouldRecordDecision=e),this.recordTrcDecisionDiagnostic(e),e}getBlockSelectors(){var e,t,i;const n=null!==(i=null===(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)||void 0===t?void 0:t.blockSelector)&&void 0!==i?i:[];if(0!==n.length)return n}getMaskTextSelectors(){var e,t;const i=null===(e=this.config)||void 0===e?void 0:e.privacyConfig;if("conservative"===(i?$e(this.currentPageUrl,i):void 0))return"*";if(null===(t=null==i?void 0:i.urlMaskLevels)||void 0===t?void 0:t.some(e=>"conservative"===e.maskLevel))return"*";const n=null==i?void 0:i.urlMaskLevels;if("conservative"===(null==i?void 0:i.defaultMaskLevel)&&n&&n.length>0)return"*";const s=null==i?void 0:i.maskSelector;return s||void 0}getRecordingPlugins(e){var t,n,s,r,o,a;return i(this,void 0,void 0,function*(){const i=[];try{const e=Ii({ugcFilterRules:(null===(n=null===(t=this.config)||void 0===t?void 0:t.interactionConfig)||void 0===n?void 0:n.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});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}}})}_recordEvents(e=!0){var t,n,s,r,o,a,l,c;return i(this,void 0,void 0,function*(){const i=this.config,d=this.getShouldRecord(),u=null===(t=this.identifiers)||void 0===t?void 0:t.sessionId;if(!d||!u||!i)return;this.stopRecordingEvents();const h=yield this.getRecordFunction();if(!h)return this.incrementDiagnostic(it.recordNoRecordFn),void this.recordDiagnosticEvent(it.recordNoRecordFn,{});yield this.initializeNetworkObservers();const g=null===(n=i.loggingConfig)||void 0===n?void 0:n.network,v=_e(i.serverZone,i.trackServerUrl),p=[Ie,Ce,we,v];null===(s=this.networkObservers)||void 0===s||s.start(e=>{p.some(t=>e.url.startsWith(t))||this.addCustomRRWebEvent(De.FETCH_REQUEST,e)},g);const{interactionConfig:m,loggingConfig:y}=i,b=(null==m?void 0:m.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:h.mirror,ugcFilterRules:null!==(o=m.ugcFilterRules)&&void 0!==o?o:[],performanceOptions:null===(a=i.performanceConfig)||void 0===a?void 0:a.interaction})),scroll:this.scrollHook}:{},S=(null==m?void 0:m.enabled)&&m.ugcFilterRules?m.ugcFilterRules:[];this.loggerProvider.log(`Session Replay capture beginning for ${u}.`),this.incrementDiagnostic(it.recordStarted),this.recordDiagnosticEvent(it.recordStarted,{});try{const t=!!(null===(l=i.crossOriginIframes)||void 0===l?void 0:l.enabled),n=!1!==(null===(c=i.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&&n)return void(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)===Oe&&("start"===n.action?e.onStart():"stop"===n.action&&e.onStop())}return t.addEventListener("message",n),()=>t.removeEventListener("message",n)}({onStart:()=>this._recordEventsInChildMode(h,u,i,b),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()}`)}}}));this.recordCancelCallback=h(Object.assign(Object.assign({},this.buildRRWebRecordOptions(i,b,e=>{if(this.shouldOptOut())return this.loggerProvider.log(`Opting session ${u} out of recording due to optOut config.`),this.stopRecordingEvents(),void this.sendEvents();e.type===Ve.Meta&&(e.data.href=Be(e.data.href,S)),this.eventCompressor?this.eventCompressor.enqueueEvent(e,u):this.pendingEmitEvents.push({event:e,sessionId:u})},"Error while capturing replay: ")),{plugins:yield this.getRecordingPlugins(y),recordCrossOriginIframes:t})),t&&!s&&n&&(this.crossOriginIframeCoordinator||(this.crossOriginIframeCoordinator=new Ci),this.crossOriginIframeCoordinator.start()),this.addCustomRRWebEvent(De.DEBUG_INFO),e&&this.addCustomRRWebEvent(De.METADATA,this.metadata)}catch(e){this.loggerProvider.warn("Failed to initialize session replay:",e)}})}buildRRWebRecordOptions(e,t,i,n){const{privacyConfig:s}=e;return Object.assign(Object.assign({emit:i,inlineStylesheet:e.shouldInlineStylesheet,hooks:t,maskAllInputs:!0,maskTextClass:be,blockClass:"amp-block",blockSelector:this.getBlockSelectors(),applyBackgroundColorToBlockedElements:e.applyBackgroundColorToBlockedElements,maskInputFn:je("input",s,()=>this.currentPageUrl),maskTextFn:je("text",s,()=>this.currentPageUrl),maskAttributeFn:qe(s,()=>this.currentPageUrl),maskTextSelector:this.getMaskTextSelectors()},void 0!==e.fullSnapshotIntervalMs&&{checkoutEveryNms:e.fullSnapshotIntervalMs}),{recordCanvas:!1,captureAdoptedStyleSheets:e.captureAdoptedStyleSheets,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},errorHandler: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}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;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())?j(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,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 Ei=e=>()=>{const{config:t}=e,{loggerProvider:i,logLevel:n}=t||He();return{logger:i,logLevel:n}};var ki=(()=>{const e=new wi;return{init:k(e.init.bind(e),"init",Ei(e)),evaluateTargetingAndCapture:k(e.evaluateTargetingAndCapture.bind(e),"evaluateTargetingAndRecord",Ei(e)),setSessionId:k(e.setSessionId.bind(e),"setSessionId",Ei(e)),getSessionId:k(e.getSessionId.bind(e),"getSessionId",Ei(e)),getSessionReplayProperties:k(e.getSessionReplayProperties.bind(e),"getSessionReplayProperties",Ei(e)),flush:k(e.flush.bind(e),"flush",Ei(e)),shutdown:k(e.shutdown.bind(e),"shutdown",Ei(e))}})();const{init:Pi,setSessionId:Ti,getSessionId:Mi,getSessionReplayProperties:Oi,flush:Di,shutdown:Ri,evaluateTargetingAndCapture:xi}=ki;export{Re as S,Mi as a,Oi as b,Ri as c,xi as e,Di as f,f as g,Pi as i,Ti as s};
2
2
  //# sourceMappingURL=index-min.js.map