@amplitude/session-replay-browser 1.40.0 → 1.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +85 -0
  2. package/lib/cjs/config/local-config.d.ts +2 -1
  3. package/lib/cjs/config/local-config.d.ts.map +1 -1
  4. package/lib/cjs/config/local-config.js +3 -0
  5. package/lib/cjs/config/local-config.js.map +1 -1
  6. package/lib/cjs/config/types.d.ts +26 -0
  7. package/lib/cjs/config/types.d.ts.map +1 -1
  8. package/lib/cjs/config/types.js.map +1 -1
  9. package/lib/cjs/constants.d.ts +2 -0
  10. package/lib/cjs/constants.d.ts.map +1 -1
  11. package/lib/cjs/constants.js +3 -1
  12. package/lib/cjs/constants.js.map +1 -1
  13. package/lib/cjs/cross-origin-iframes.d.ts +28 -0
  14. package/lib/cjs/cross-origin-iframes.d.ts.map +1 -0
  15. package/lib/cjs/cross-origin-iframes.js +175 -0
  16. package/lib/cjs/cross-origin-iframes.js.map +1 -0
  17. package/lib/cjs/events/events-idb-store.d.ts +25 -4
  18. package/lib/cjs/events/events-idb-store.d.ts.map +1 -1
  19. package/lib/cjs/events/events-idb-store.js +257 -61
  20. package/lib/cjs/events/events-idb-store.js.map +1 -1
  21. package/lib/cjs/session-replay.d.ts +4 -0
  22. package/lib/cjs/session-replay.d.ts.map +1 -1
  23. package/lib/cjs/session-replay.js +118 -51
  24. package/lib/cjs/session-replay.js.map +1 -1
  25. package/lib/cjs/track-destination.d.ts.map +1 -1
  26. package/lib/cjs/track-destination.js +5 -1
  27. package/lib/cjs/track-destination.js.map +1 -1
  28. package/lib/cjs/utils/rrweb.d.ts +1 -0
  29. package/lib/cjs/utils/rrweb.d.ts.map +1 -1
  30. package/lib/cjs/utils/rrweb.js.map +1 -1
  31. package/lib/cjs/version.d.ts +1 -1
  32. package/lib/cjs/version.js +1 -1
  33. package/lib/cjs/version.js.map +1 -1
  34. package/lib/cjs/worker/index.js +1 -1
  35. package/lib/esm/config/local-config.d.ts +2 -1
  36. package/lib/esm/config/local-config.d.ts.map +1 -1
  37. package/lib/esm/config/local-config.js +3 -0
  38. package/lib/esm/config/local-config.js.map +1 -1
  39. package/lib/esm/config/types.d.ts +26 -0
  40. package/lib/esm/config/types.d.ts.map +1 -1
  41. package/lib/esm/config/types.js.map +1 -1
  42. package/lib/esm/constants.d.ts +2 -0
  43. package/lib/esm/constants.d.ts.map +1 -1
  44. package/lib/esm/constants.js +2 -0
  45. package/lib/esm/constants.js.map +1 -1
  46. package/lib/esm/cross-origin-iframes.d.ts +28 -0
  47. package/lib/esm/cross-origin-iframes.d.ts.map +1 -0
  48. package/lib/esm/cross-origin-iframes.js +170 -0
  49. package/lib/esm/cross-origin-iframes.js.map +1 -0
  50. package/lib/esm/events/events-idb-store.d.ts +25 -4
  51. package/lib/esm/events/events-idb-store.d.ts.map +1 -1
  52. package/lib/esm/events/events-idb-store.js +255 -61
  53. package/lib/esm/events/events-idb-store.js.map +1 -1
  54. package/lib/esm/session-replay.d.ts +4 -0
  55. package/lib/esm/session-replay.d.ts.map +1 -1
  56. package/lib/esm/session-replay.js +118 -51
  57. package/lib/esm/session-replay.js.map +1 -1
  58. package/lib/esm/track-destination.d.ts.map +1 -1
  59. package/lib/esm/track-destination.js +6 -2
  60. package/lib/esm/track-destination.js.map +1 -1
  61. package/lib/esm/utils/rrweb.d.ts +1 -0
  62. package/lib/esm/utils/rrweb.d.ts.map +1 -1
  63. package/lib/esm/utils/rrweb.js.map +1 -1
  64. package/lib/esm/version.d.ts +1 -1
  65. package/lib/esm/version.js +1 -1
  66. package/lib/esm/version.js.map +1 -1
  67. package/lib/esm/worker/index.js +1 -1
  68. package/lib/scripts/index-min.js +1 -1
  69. package/lib/scripts/index-min.js.gz +0 -0
  70. package/lib/scripts/index-min.js.map +1 -1
  71. package/lib/scripts/session-replay-browser-min.js +1 -1
  72. package/lib/scripts/session-replay-browser-min.js.gz +0 -0
  73. package/lib/scripts/session-replay-browser-min.js.map +1 -1
  74. package/lib/scripts/targeting-min.js +1 -1
  75. package/lib/scripts/targeting-min.js.gz +0 -0
  76. package/lib/scripts/targeting-min.js.map +1 -1
  77. package/lib/scripts/worker-min.js +1 -1
  78. package/lib/scripts/worker-min.js.gz +0 -0
  79. 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,o as a}from"./targeting-min.js";var l,c;!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"}(l||(l={})),function(e){e.IDENTIFY="$identify",e.GROUP_IDENTIFY="$groupidentify",e.REVENUE="revenue_amount"}(c||(c={}));var d,u="$default_instance",h="https://api2.amplitude.com/2/httpapi";!function(e){e.Unknown="unknown",e.Skipped="skipped",e.Success="success",e.RateLimit="rate_limit",e.PayloadTooLarge="payload_too_large",e.Invalid="invalid",e.Failed="failed",e.Timeout="Timeout",e.SystemError="SystemError"}(d||(d={}));var g,v=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},f=e([],t(Array(256).keys()),!1).map(function(e){return e.toString(16).padStart(2,"0")}),p=function(i){var n,s=v();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,p)}(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(f[s]):f[s]}).join("")},m=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"}(g||(g={}));var y="Amplitude Logger ",S=function(){function e(){this.logLevel=g.None}return e.prototype.disable=function(){this.logLevel=g.None},e.prototype.enable=function(e){void 0===e&&(e=g.Warn),this.logLevel=e},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<g.Verbose||console.log("".concat(y,"[Log]: ").concat(e.join(" ")))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<g.Warn||console.warn("".concat(y,"[Warn]: ").concat(e.join(" ")))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<g.Error||console.error("".concat(y,"[Error]: ").concat(e.join(" ")))},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<g.Debug||console.log("".concat(y,"[Debug]: ").concat(e.join(" ")))},e}(),b=function(){return{flushMaxRetries:12,flushQueueSize:200,flushIntervalMillis:1e4,instanceName:u,logLevel:g.Warn,loggerProvider:new S,offline:!1,optOut:!1,serverUrl:h,serverZone:"US",useBatch:!1}},I=function(){function e(e){var t,i,n,s;this._optOut=!1;var r=b();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=w(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}(),C=function(e,t){return"EU"===e?t?"https://api.eu.amplitude.com/batch":"https://api.eu.amplitude.com/2/httpapi":t?"https://api2.amplitude.com/batch":h},w=function(e,t,i){if(void 0===e&&(e=""),void 0===t&&(t=b().serverZone),void 0===i&&(i=b().useBatch),e)return{serverUrl:e,serverZone:void 0};var n=["US","EU"].includes(t)?t:b().serverZone;return{serverZone:n,serverUrl:C(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<g.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:E(),platform:"Web",os:void 0,deviceModel:void 0}},e}(),E=function(){return"undefined"!=typeof navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||""},R=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}(),M=function(){return M=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},M.apply(this,arguments)};function T(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 O(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=T(["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,x=function(){function e(){this.identity={userProperties:{}},this.listeners=new Set}return e.prototype.editIdentity=function(){var e=this,t=M({},this.identity.userProperties),i=M(M({},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=T(Object.entries(e)),d=c.next();!d.done;d=c.next()){var u=O(d.value,2),h=u[0],g=u[1];switch(h){case"$set":try{for(var v=(s=void 0,T(Object.entries(g))),f=v.next();!f.done;f=v.next()){var p=O(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 S=(o=void 0,T(Object.keys(g))),b=S.next();!b.done;b=S.next()){delete l[m=b.value]}}catch(e){o={error:e}}finally{try{b&&!b.done&&(a=S.return)&&a.call(S)}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 M({},this.identity)},e.prototype.setIdentity=function(e){var t=M({},this.identity);this.identity=M({},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}(),F="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:self,D=function(){function e(){this.identityStore=new x,this.eventBridge=new R,this.applicationContextProvider=new P}return e.getInstance=function(t){return F.analyticsConnectorInstances||(F.analyticsConnectorInstances={}),F.analyticsConnectorInstances[t]||(F.analyticsConnectorInstances[t]=new e),F.analyticsConnectorInstances[t]},e}(),q=function(e){var t=0;if(0===e.length)return t;for(var i=0;i<e.length;i++){t=(t<<5)-t+e.charCodeAt(i),t|=0}return t},U=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,u,h,g,v,f,p,m,y,S,b,I,C,w;if("object"!=typeof e)return null;var k=e.code||0,P=this.buildStatus(k);switch(P){case d.Success:return{status:P,statusCode:k,body:{eventsIngested:null!==(t=e.events_ingested)&&void 0!==t?t:0,payloadSizeBytes:null!==(i=e.payload_size_bytes)&&void 0!==i?i:0,serverUploadTime:null!==(n=e.server_upload_time)&&void 0!==n?n:0}};case d.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!==(u=e.exceeded_daily_quota_devices)&&void 0!==u?u:{},silencedDevices:null!==(h=e.silenced_devices)&&void 0!==h?h:[],silencedEvents:null!==(g=e.silenced_events)&&void 0!==g?g:[],throttledDevices:null!==(v=e.throttled_devices)&&void 0!==v?v:{},throttledEvents:null!==(f=e.throttled_events)&&void 0!==f?f:[]}};case d.PayloadTooLarge:return{status:P,statusCode:k,body:{error:null!==(p=e.error)&&void 0!==p?p:""}};case d.RateLimit:return{status:P,statusCode:k,body:{error:null!==(m=e.error)&&void 0!==m?m:"",epsThreshold:null!==(y=e.eps_threshold)&&void 0!==y?y:0,throttledDevices:null!==(S=e.throttled_devices)&&void 0!==S?S:{},throttledUsers:null!==(b=e.throttled_users)&&void 0!==b?b:{},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 d.Timeout:default:return{status:P,statusCode:k}}},e.prototype.buildStatus=function(e){return function(e){return e>=200&&e<300}(e)?d.Success:429===e?d.RateLimit:413===e?d.PayloadTooLarge:408===e?d.Timeout:e>=400&&e<500?d.Invalid:e>=500?d.Failed:d.Unknown},e}(),j=function(e){function 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}(U),$=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}(),N=401,A=403,W=429,B=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 $(e,t)}return e.prototype.subscribe=function(e,t,i){var n=p(),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===N||d.status===A?(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 z,H="https://app.amplitude.com",K={US:H,EU:"https://app.eu.amplitude.com",STAGING:"https://apps.stag2.amplitude.com"};var J="__AMPLITUDE_MESSENGER_INSTANCE__",Q="__AMPLITUDE_MESSENGER__",G=function(){function e(e){var t=(void 0===e?{}:e).origin,i=void 0===t?H:t;this[z]=!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=v();(null==e?void 0:e[Q])===this&&delete e[Q]},e}();function Z(e){var t,i=v(),n=null==i?void 0:i[Q];if("object"==typeof(t=n)&&null!==t&&J in t&&!0===t[J])return n;var s=new G(e);return i&&(i[Q]=s),s}z=J;var X="__AMPLITUDE_BACKGROUND_CAPTURE__";const V="[Amplitude]",Y=`${V} Session Replay ID`,ee=L.US,te={enabled:!0},ie=1e3,ne=`${V} Session Replay Debug`,se="amp-mask",re="https://api-sr.amplitude.com/sessions/v2/track",oe="https://api-sr.eu.amplitude.com/sessions/v2/track",ae="https://api-sr.stag2.amplitude.com/sessions/v2/track";var le;!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"}(le||(le={}));class ce{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 de="medium";function ue(e,t){return t||("STAGING"===e?ae:"EU"===e?oe:re)}const he=(e,t,i)=>{switch(t){case"light":{if("input"!==e)return!0;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":case"conservative":return!0;default:return he(e,de,i)}},ge=(e,t)=>{var i;if(e&&t.urlMaskLevels)for(const i of t.urlMaskLevels)if(Se(i.match).test(e))return i.maskLevel;return null!==(i=t.defaultMaskLevel)&&void 0!==i?i:de},ve=(e,t={defaultMaskLevel:de},i,n)=>{var s,r;if(i){if(i.closest("."+se))return!0;const e=(null!==(s=t.maskSelector)&&void 0!==s?s:[]).some(e=>i.closest(e));if(e)return!0;if(i.closest(".amp-unmask"))return!1;const n=(null!==(r=t.unmaskSelector)&&void 0!==r?r:[]).some(e=>i.closest(e));if(n)return!1}return he(e,ge(n,t),i)},fe=(e,t,i)=>(n,s)=>ve(e,t,s,null==i?void 0:i())?n.replace(/[^\s]/g,"*"):n,pe=(e,t)=>(i,n,s)=>{var r;return"style"===i?n:(null!==(r=null==e?void 0:e.maskAttributes)&&void 0!==r?r:[]).includes(i)&&ve("text",e,s,null==t?void 0:t())?n.replace(/[^\s]/g,"*"):n},me=()=>{const e=v();return(null==e?void 0:e.location)?e.location.href:""},ye=new Map,Se=e=>{const t=ye.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 ye.set(e,l),l},be=(e,t)=>{for(const i of t){const t=Se(i.selector);if(t.test(e))return e.replace(t,i.replacement)}return e},Ie=()=>n(void 0,void 0,void 0,function*(){try{const e=v();if(e){const{usage:t,quota:i,usageDetails:n}=yield e.navigator.storage.estimate(),s=t?Math.round(t/1024):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:""}}),Ce=e=>{const t=Object.assign({},e),{apiKey:i}=t;return t.apiKey=`****${i.substring(i.length-4)}`,t},we=()=>({flushMaxRetries:2,logLevel:g.Warn,loggerProvider:new S,transportProvider:new j});class ke extends I{constructor(e,t){var i,n,s,r,o,a,l;const c=we();if(super(Object.assign(Object.assign({transportProvider:c.transportProvider,loggerProvider:new ce(t.loggerProvider||c.loggerProvider)},t),{apiKey:e})),this.flushMaxRetries=void 0!==t.flushMaxRetries&&t.flushMaxRetries<=c.flushMaxRetries?t.flushMaxRetries:c.flushMaxRetries,this.apiKey=e,this.sampleRate=t.sampleRate||0,this.serverZone=t.serverZone||ee,this.configServerUrl=t.configServerUrl,this.trackServerUrl=t.trackServerUrl,this.shouldInlineStylesheet=t.shouldInlineStylesheet,this.version=t.version,this.performanceConfig=t.performanceConfig||te,this.storeType=null!==(i=t.storeType)&&void 0!==i?i:"idb",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:ie,this.captureDocumentTitle=null!==(o=t.captureDocumentTitle)&&void 0!==o&&o,t.privacyConfig&&(this.privacyConfig=t.privacyConfig),t.interactionConfig&&(this.interactionConfig=t.interactionConfig,this.interactionConfig.ugcFilterRules&&(e=>{if(!e.every(e=>"string"==typeof e.selector&&"string"==typeof e.replacement))throw new Error("ugcFilterRules must be an array of objects with selector and replacement properties");if(!e.every(e=>{return"string"==typeof(t=e.selector)&&""!==t.trim()&&!!/^\/|^https?:\/\/[^\s]+$/.test(t);var t}))throw new Error("ugcFilterRules must be an array of objects with valid globs")})(this.interactionConfig.ugcFilterRules)),t.debugMode&&(this.debugMode=t.debugMode),void 0!==t.useWebWorker)this.useWebWorker=t.useWebWorker;else{const e=t;void 0!==(null===(a=e.experimental)||void 0===a?void 0:a.useWebWorker)&&(this.useWebWorker=e.experimental.useWebWorker)}t.omitElementTags&&(this.omitElementTags=t.omitElementTags),this.captureAdoptedStyleSheets=null===(l=t.captureAdoptedStyleSheets)||void 0===l||l}}var Pe=(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))(Pe||{}),Ee=(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))(Ee||{}),Re=(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))(Re||{});class Me{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","all",(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)):(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:Ce(n)},null,2)),{localConfig:this.localConfig,joinedConfig:n,remoteConfig:l}})}}function Te(e){if(e.type!==Pe.IncrementalSnapshot)return!1;const t=e.data;return t.source===Ee.Mutation&&!t.isAttachIframe}function Oe(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={source:Ee.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:d?v.filter(e=>!a.has(e.id)&&!l.has(e.id)&&!c.has(e.id)):v};return Object.assign(Object.assign({},t),{data:f})}function _e(e){if(e.length<=1)return e;const t=[];let i=0;for(;i<e.length;){if(!Te(e[i])){t.push(e[i]),i++;continue}let n=i+1;for(;n<e.length&&Te(e[n]);)n++;t.push(n>i+1?Oe(e.slice(i,n)):e[i]),i=n}return t}class Le{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)=>{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.terminate=()=>{var e;null===(e=this.worker)||void 0===e||e.terminate()};const o=v();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===Pe.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(!(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=_e(e.slice(n,s).map(e=>e.event));for(const e of r)i.push({event:e,sessionId:t});n=s}return i}}const xe="Session replay event batch rejected due to exceeded retry count",Fe="Failed to store session replay events in IndexedDB",De="1.40.0";class qe{constructor({trackServerUrl:e,loggerProvider:t,payloadBatcher:i,workerScript:n}){if(this.storageKey="",this.retryTimeout=1e3,this.scheduled=null,this.queue=[],this.sendIdCounter=0,this.pendingWorkerRequests=new Map,this.loggerProvider=t,this.payloadBatcher=i||(e=>e),this.trackServerUrl=e,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)t.warn(`Session replay event send failed due to worker crash: ${e.message}`),i.resolve();this.pendingWorkerRequests.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("complete"===i.type){const e=this.pendingWorkerRequests.get(i.id);e&&(this.completeRequest({context:e.context}),e.resolve(),this.pendingWorkerRequests.delete(i.id))}},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}))}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=`${ue(s,this.trackServerUrl)}?${d.toString()}`,h=v();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=>e.attempts<(e.flushMaxRetries||0)?(e.attempts+=1,!0):(this.completeRequest({context:e,err:xe}),!1)).forEach(e=>{this.queue=this.queue.concat(e),this.schedule(0)})}schedule(e){this.scheduled||(this.scheduled=setTimeout(()=>{this.flush(!0).then(()=>{this.queue.length>0&&this.schedule(e)})},e))}flush(e=!1){return n(this,void 0,void 0,function*(){const t=this.queue;this.queue=[],this.scheduled&&(clearTimeout(this.scheduled),this.scheduled=null);for(const i of t)yield this.send(i,e)})}send(e,t=!0){return n(this,void 0,void 0,function*(){const i=e.apiKey;if(!i)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing api key"});const 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;this.pendingWorkerRequests.set(n,{context:t,resolve:r}),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:me(),sdkVersion:De}})})})}sendOnMainThread(e,t,i,s,r){var o,a,l,c;return n(this,void 0,void 0,function*(){const d=me(),u=De,h=i.sampleRate,g=new URLSearchParams({device_id:t,session_id:`${i.sessionId}`,type:`${i.type}`}),f=`${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:u}`;try{const t=JSON.stringify(s),o=v(),a=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={headers:Object.assign({"Content-Type":"application/json",Accept:"*/*",Authorization:`Bearer ${e}`,"X-Client-Version":u,"X-Client-Library":f,"X-Client-Url":d.substring(0,1e3),"X-Client-Sample-Rate":`${h}`,"X-Sampling-Hash-Alg":"xxhash32"},a?{"Content-Encoding":"gzip"}:{}),body:null!=a?a:t,method:"POST"},c=`${ue(i.serverZone,this.trackServerUrl)}?${g.toString()}`,p=yield fetch(c,l);if(null===p)return void this.completeRequest({context:i,err:"Unexpected error occurred"});if(r)yield this.handleReponse(p.status,i);else{let e="";try{e=JSON.stringify(p.body,null,2)}catch(e){}this.completeRequest({context:i,success:`${p.status}: ${e}`})}}catch(e){this.completeRequest({context:i,err:e})}})}handleReponse(e,t){return n(this,void 0,void 0,function*(){switch((new U).buildStatus(e)){case d.Success:this.handleSuccessResponse(t);break;case d.Failed:case d.Timeout:case d.RateLimit:yield this.handleOtherResponse(t);break;default:if(499===e){yield this.handleOtherResponse(t);break}this.completeRequest({context:t,err:"Network error occurred, event batch rejected"})}})}handleSuccessResponse(e){const t=Math.round(new Blob(e.events).size/1024);this.completeRequest({context:e,success:`Session replay event batch tracked successfully for session id ${e.sessionId}, size of events: ${t} KB`})}handleOtherResponse(e){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:xe}):(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)}}class Ue{get timeAtLastSplit(){return this._timeAtLastSplit}constructor(e){var t,i,n;this.minInterval=500,this.maxInterval=1e4,this.maxPersistedEventsSize=1e6,this.interval=this.minInterval,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}getStringSize(e){return e.length}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 je=(e,t,i)=>{var n;"object"==typeof(n=i)&&null!==n&&"AbortError"===n.name?e.debug(t):e.warn(t)},$e="sessionCurrentSequence",Ne="sequencesToSend",Ae=e=>{let t,i;return e.objectStoreNames.contains($e)||(i=e.createObjectStore($e,{keyPath:"sessionId"})),e.objectStoreNames.contains(Ne)||(t=e.createObjectStore(Ne,{keyPath:"sequenceId",autoIncrement:!0}),t.createIndex("sessionId","sessionId")),{sequencesStore:t,currentSequenceStore:i}};class We extends Ue{constructor(e){var t;super(e),this.consecutiveFailures=0,this.hasTriggeredFallback=!1,this.getSequencesToSend=()=>n(this,void 0,void 0,function*(){let e=!1;try{const t=[],i=this.db.transaction("sequencesToSend");i.done.catch(t=>{e||je(this.loggerProvider,`${Fe}: ${t}`,t)});let n=yield i.store.openCursor();for(;n;){const{sessionId:e,events:i}=n.value;t.push({events:i,sequenceId:n.key,sessionId:e}),n=yield n.continue()}return this.recordSuccess(),t}catch(t){e=!0,je(this.loggerProvider,`${Fe}: ${t}`,t),this.recordFailure()}}),this.storeCurrentSequence=e=>n(this,void 0,void 0,function*(){try{const t=yield this.db.get($e,e);if(!t)return void this.recordSuccess();const i=yield this.db.put(Ne,{sessionId:e,events:t.events});return yield this.db.put($e,{sessionId:e,events:[]}),this.recordSuccess(),Object.assign(Object.assign({},t),{sessionId:e,sequenceId:i})}catch(e){je(this.loggerProvider,`${Fe}: ${e}`,e),this.recordFailure()}}),this.addEventToCurrentSequence=(e,t)=>n(this,void 0,void 0,function*(){let i=!1;try{const n=this.db.transaction([$e,Ne],"readwrite");n.done.catch(e=>{i||je(this.loggerProvider,`${Fe}: ${e}`,e)});const s=yield n.objectStore($e).get(e);if(!s)return yield n.objectStore($e).put({sessionId:e,events:[t]}),void this.recordSuccess();if(!this.shouldSplitEventsList(s.events,t))return yield n.objectStore($e).put({sessionId:e,events:s.events.concat(t)}),void this.recordSuccess();const r=s.events;yield n.objectStore($e).put({sessionId:e,events:[t]});const o=yield n.objectStore(Ne).put({sessionId:e,events:r});return this.recordSuccess(),{events:r,sessionId:e,sequenceId:o}}catch(e){i=!0,je(this.loggerProvider,`${Fe}: ${e}`,e),this.recordFailure()}}),this.storeSendingEvents=(e,t)=>n(this,void 0,void 0,function*(){try{const i=yield this.db.put(Ne,{sessionId:e,events:t});return this.recordSuccess(),i}catch(e){je(this.loggerProvider,`${Fe}: ${e}`,e),this.recordFailure()}}),this.cleanUpSessionEventsStore=(e,t)=>n(this,void 0,void 0,function*(){if(t)try{yield this.db.delete(Ne,t),this.recordSuccess()}catch(e){je(this.loggerProvider,`${Fe}: ${e}`,e),this.recordFailure()}}),this.db=e.db,this.onPersistentFailure=e.onPersistentFailure,this.consecutiveFailureThreshold=null!==(t=e.consecutiveFailureThreshold)&&void 0!==t?t:3}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){return n(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(e=>n(void 0,void 0,void 0,function*(){return yield a(e,1,{upgrade:Ae})}))(s);return new We(Object.assign(Object.assign({},t),{db:r}))}catch(e){je(t.loggerProvider,`${Fe}: ${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;return[t]}const t=[];for(const e of yield this.db.getAll("sessionCurrentSequence"))t.push(e);return t})}}class Be extends Ue{constructor(){super(...arguments),this.finalizedSequences={},this.sequences={},this.sequenceId=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}}getSequencesToSend(){return n(this,void 0,void 0,function*(){return Object.entries(this.finalizedSequences).map(([e,{sessionId:t,events:i}])=>({sequenceId:Number(e),sessionId:t,events:i}))})}storeCurrentSequence(e){return n(this,void 0,void 0,function*(){if(this.sequences[e])return this.addSequence(e)})}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)&&(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 ze=({config:e,minInterval:t,maxInterval:i,type:s,payloadBatcher:r,storeType:o,trackDestinationWorkerScript:a})=>n(void 0,void 0,void 0,function*(){const l=new qe(Object.assign(Object.assign({},e),{loggerProvider:e.loggerProvider,payloadBatcher:r,workerScript:a})),c=()=>new Be({loggerProvider:e.loggerProvider,maxInterval:i,minInterval:t});let d,u,h=!1;u="idb"===o?yield n(void 0,void 0,void 0,function*(){const r=yield We.new(s,{loggerProvider:e.loggerProvider,minInterval:t,maxInterval:i,apiKey:e.apiKey,onPersistentFailure:()=>{n(void 0,void 0,void 0,function*(){if(!h)return;h=!1,e.loggerProvider.warn("IDB store is experiencing repeated failures; falling back to in-memory event store.");const t=d?yield u.getSequencesToSend():void 0;if(u=c(),t&&d){const e=d;t.forEach(t=>{p({sequenceId:t.sequenceId,events:t.events,sessionId:t.sessionId,deviceId:e})})}})}});return r?(h=!0,r):(e.loggerProvider.log("Failed to initialize idb store, falling back to memory store."),c())}):c();const g=[];let v=0;const f=e=>{if(e<=v)return;const t=Math.min(e-v,g.length);t>0&&(g.splice(0,t),v=e)},p=({events:t,sessionId:i,deviceId:r,sequenceId:o})=>{e.debugMode&&Ie().then(({totalStorageSize:t,percentOfQuota:i,usageDetails:n})=>{e.loggerProvider.debug(`Total storage size: ${t} KB, percentage of quota: ${i}%, usage details: ${n}`)}).catch(()=>{}),l.sendEventsList({events:t,sessionId:i,flushMaxRetries:e.flushMaxRetries,apiKey:e.apiKey,deviceId:r,sampleRate:e.sampleRate,serverZone:e.serverZone,version:e.version,type:s,onComplete:()=>n(void 0,void 0,void 0,function*(){yield u.cleanUpSessionEventsStore(i,o)})})};return{sendCurrentSequenceEvents:({sessionId:t,deviceId:i})=>{d=i;const n=v+g.length;u.storeCurrentSequence(t).then(e=>{e&&(f(n),p({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})=>{d=n;const s=v+g.length;g.push(t.data),u.addEventToCurrentSequence(i,t.data).then(e=>{e&&(f(s),p({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:n}))}).catch(t=>{e.loggerProvider.warn("Failed to add event to session replay capture:",t)})},sendStoredEvents:({deviceId:e})=>n(void 0,void 0,void 0,function*(){d=e;const t=yield u.getSequencesToSend();t&&t.forEach(t=>{p({sequenceId:t.sequenceId,events:t.events,sessionId:t.sessionId,deviceId:e})})}),flush:function(e=!1){return n(this,void 0,void 0,function*(){return l.flush(e)})},getBeaconEvents:()=>[...g],trackDestination:l}});class He{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 Ke,Je,Qe;function Ge(e,t){if(Qe=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};Ke=Object.assign(Object.assign({},i),t),Je=function(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return e;if(e===t.root)return e.ownerDocument;return e}(Ke.root,i);let n=Ze(e,"all",()=>Ze(e,"two",()=>Ze(e,"one",()=>Ze(e,"none"))));if(n){const t=ht(gt(n,e));return t.length>0&&(n=t[0]),Ve(n)}throw new Error("Selector was not found.")}function Ze(e,t,i){let n=null,s=[],r=e,o=0;for(;r;){const e=(new Date).getTime()-Qe.getTime();if(void 0!==Ke.timeoutMs&&e>Ke.timeoutMs)throw new Error(`Timeout: Can't find a unique selector after ${e}ms`);let a=ct(tt(r))||ct(...it(r))||ct(...nt(r))||ct(st(r))||[rt()];const l=ot(r);if("all"==t)l&&(a=a.concat(a.filter(lt).map(e=>at(e,l))));else if("two"==t)a=a.slice(0,1),l&&(a=a.concat(a.filter(lt).map(e=>at(e,l))));else if("one"==t){const[e]=a=a.slice(0,1);l&&lt(e)&&(a=[at(e,l)])}else"none"==t&&(a=[rt()],l&&(a=[at(a[0],l)]));for(let e of a)e.level=o;if(s.push(a),s.length>=Ke.seedMinLength&&(n=Xe(s,i),n))break;r=r.parentElement,o++}return n||(n=Xe(s,i)),!n&&i?i():n}function Xe(e,t){const i=ht(ut(e));if(i.length>Ke.threshold)return t?t():null;for(let e of i)if(et(e))return e;return null}function Ve(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 Ye(e){return e.map(e=>e.penalty).reduce((e,t)=>e+t,0)}function et(e){const t=Ve(e);switch(Je.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 tt(e){const t=e.getAttribute("id");return t&&Ke.idName(t)?{name:"#"+CSS.escape(t),penalty:0}:null}function it(e){const t=Array.from(e.attributes).filter(e=>Ke.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(Ke.className).map(e=>({name:"."+CSS.escape(e),penalty:1}))}function st(e){const t=e.tagName.toLowerCase();return Ke.tagName(t)?{name:t,penalty:2}:null}function rt(){return{name:"*",penalty:3}}function ot(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 at(e,t){return{name:e.name+`:nth-child(${t})`,penalty:e.penalty+1}}function lt(e){return"html"!==e.name&&!e.name.startsWith("#")}function ct(...e){const t=e.filter(dt);return t.length>0?t:null}function dt(e){return null!=e}function*ut(e,t=[]){if(e.length>0)for(let i of e[0])yield*ut(e.slice(1,e.length),t.concat(i));else yield t}function ht(e){return[...e].sort((e,t)=>Ye(e)-Ye(t))}function*gt(e,t,i={counter:0,visited:new Map}){if(e.length>2&&e.length>Ke.optimizedMinLength)for(let n=1;n<e.length-1;n++){if(i.counter>Ke.maxNumberOfTries)return;i.counter+=1;const s=[...e];s.splice(n,1);const r=Ve(s);if(i.visited.has(r))return;et(s)&&vt(s,t)&&(yield s,i.visited.set(r,!0),yield*gt(s,t,i))}}function vt(e,t){return Je.querySelector(Ve(e))===t}const ft=({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}},pt=({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 mt{constructor(e,t){this.createHook=({eventsManager:e,sessionId:t,deviceIdFn:i,mirror:n,ugcFilterRules:s,performanceOptions:r})=>o=>{if(o.type!==Re.Click)return;const a=v();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 f;if(g)try{f=Ge(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:f,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 yt(){const e=v();return(null==e?void 0:e.innerHeight)||document.documentElement&&document.documentElement.clientHeight||0}function St(){const e=v();return(null==e?void 0:e.innerWidth)||document.documentElement&&document.documentElement.clientWidth||0}class bt{constructor(e,t){const i=v();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=ue(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 It{static default(e,t){return new It(new bt(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=v();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:yt(),viewportWidth:St(),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=St(),this._maxScrollHeight=yt(),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=St();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=yt();this._maxScrollY=e.y;const n=e.y+i;n>this._maxScrollHeight&&(this._maxScrollHeight=n),this.timestamp=t}}}class Ct{constructor({sessionId:e,deviceId:t}){this.deviceId=t,this.sessionId=e,e&&t&&(this.sessionReplayId=((e,t)=>`${t}/${e}`)(e,t))}}const wt=new class{constructor(){this.dbs={},this.createStore=e=>n(this,void 0,void 0,function*(){return yield a(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){je(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){je(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){je(e,`Failed to clear old targeting matches for sessions: ${t}`,t)}})}},kt=2654435761,Pt=2246822519,Et=3266489917,Rt=374761393;function Mt(e,t){return(e<<t|e>>>32-t)>>>0}function Tt(e,t){return e=Mt(e=e+Math.imul(t,Pt)>>>0,13),e=Math.imul(e,kt)>>>0}function Ot(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function _t(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+kt+Pt>>>0,o=t+Pt>>>0,a=t>>>0,l=t-kt>>>0;for(;r<=n-16;)e=Tt(e,Ot(i,r)),r+=4,o=Tt(o,Ot(i,r)),r+=4,a=Tt(a,Ot(i,r)),r+=4,l=Tt(l,Ot(i,r)),r+=4;s=Mt(e,1)+Mt(o,7)+Mt(a,12)+Mt(l,18)>>>0}else s=t+Rt>>>0;for(s=s+n>>>0;r<=n-4;)s=s+Math.imul(Ot(i,r),Et)>>>0,s=Math.imul(Mt(s,17),668265263)>>>0,r+=4;for(;r<n;)s=s+Math.imul(i[r],Rt)>>>0,s=Math.imul(Mt(s,11),kt)>>>0,r++;return s^=s>>>15,s=Math.imul(s,Pt)>>>0,s^=s>>>13,s=Math.imul(s,Et)>>>0,s^=s>>>16,s>>>0}const Lt="__amplitude_url_tracking_patched__",xt=new WeakMap;function Ft(e,t,i={}){if(!(null==e?void 0:e.location))return()=>{};const{enablePolling:n=!1,pollingInterval:s=ie}=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=xt.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[Lt]=!0,t},a=e.history;if(null==a?void 0:a.pushState){const e=Reflect.get(a,"pushState");e[Lt]||(a.pushState=o(e))}if(null==a?void 0:a.replaceState){const e=Reflect.get(a,"replaceState");e[Lt]||(a.replaceState=o(e))}r={callbacks:i,notify:s,onPopStateOrHashChange:()=>s(),listenersAttached:!1},xt.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 Dt(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:ie,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=Ft(i,()=>v(),c?{enablePolling:!0,pollingInterval:d}:{});return v(),()=>f()},options:e}}class qt{constructor(){this.name="@amplitude/session-replay-browser",this.recordCancelCallback=null,this.eventCount=0,this.sessionTargetingMatch=!1,this.pageLeaveFns=[],this.recordFunction=null,this.recordEventsInFlight=!1,this.currentPageUrl="",this.recordEventsPendingShouldLogMetadata=null,this.urlChangeCleanup=null,this.latestUrlChangeTargetingEvaluationId=0,this.teardownEventListeners=e=>{const t=v();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=()=>{if(this.recordCancelCallback&&this.recordFunction)try{this.recordFunction.takeFullSnapshot(!0)}catch(e){this.loggerProvider.warn("Failed to take full snapshot on focus:",e)}else this.recordEventsInFlight||this.recordEvents(!1)},this.pageLeaveListener=e=>{this.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,d,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(c).includes(i.event_type)&&(i=void 0);const g=null!==(d=null!==(o=null===(r=e.page)||void 0===r?void 0:r.url)&&void 0!==o?o:null===(l=null===(a=v())||void 0===a?void 0:a.location)||void 0===l?void 0:l.href)&&void 0!==d?d:"",f=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 wt.clearStoreOfOldSessions({loggerProvider:i,apiKey:s,currentSessionId:e}),!0===(yield wt.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),wt.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:f},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!==le.METADATA&&(n={config:Ce(s),version:De},i)){const e=yield Ie();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;try{this.loggerProvider.log("Session Replay capture stopping."),this.recordCancelCallback&&this.recordCancelCallback(),this.recordCancelCallback=null,null===(e=this.networkObservers)||void 0===e||e.stop()}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while stopping replay capture: ${t.toString()}`)}},this.loggerProvider=new ce(new S)}init(e,t){return m(this._init(e,t))}setupUrlChangeListener(){var e,t;null===(e=this.urlChangeCleanup)||void 0===e||e.call(this);const i=v();if(!(null==i?void 0:i.location))return;const n=!!(null===(t=this.config)||void 0===t?void 0:t.targetingConfig),s=Ft(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}}getCurrentPageForTargeting(){var e,t;const i=null===(t=null===(e=v())||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;return n(this,void 0,void 0,function*(){null===(i=this.urlChangeCleanup)||void 0===i||i.call(this),this.loggerProvider=new ce(t.loggerProvider||new S),Object.prototype.hasOwnProperty.call(t,"logLevel")&&this.loggerProvider.enable(t.logLevel),this.currentPageUrl=me(),this.identifiers=new Ct({sessionId:t.sessionId,deviceId:t.deviceId}),this.joinedConfigGenerator=yield((e,t)=>n(void 0,void 0,void 0,function*(){const i=new ke(e,t),n=new B(e,i.loggerProvider,i.serverZone,t.configServerUrl);return new Me(n,i)}))(e,t);const{joinedConfig:f,localConfig:p,remoteConfig:m}=yield this.joinedConfigGenerator.generateJoinedConfig();if(this.config=f,this.setMetadata(t.sessionId,f,p,m,null===(s=t.version)||void 0===s?void 0:s.version,De,null===(r=t.version)||void 0===r?void 0:r.type),this.pageLeaveFns=[],t.sessionId&&(null===(o=this.config.interactionConfig)||void 0===o?void 0:o.enabled)){const e=It.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 mt(this.loggerProvider,e)}const y=[];let b,I,{storeType:C}=this.config;"idb"!==C||(null===(a=v())||void 0===a?void 0:a.indexedDB)||(C="memory",this.loggerProvider.warn("Could not use preferred indexedDB storage, reverting to in memory option.")),this.loggerProvider.log(`Using ${C} for event storage.`);const w=v();if(this.config.useWebWorker&&w&&w.Worker){const{compressionScript:e,trackDestinationScript:t}=yield import("./worker-min.js");b=e,I=t}let k;try{k=yield ze({config:this.config,type:"replay",storeType:C,trackDestinationWorkerScript:I}),y.push({name:"replay",manager:k})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating replay events manager: ${t.toString()}`)}if(null===(l=this.config.interactionConfig)||void 0===l?void 0:l.enabled){const e=this.config.interactionConfig.batch?pt:ft;try{const t=yield ze({config:this.config,type:"interaction",minInterval:null!==(c=this.config.interactionConfig.trackEveryNms)&&void 0!==c?c:3e4,maxInterval:6e4,payloadBatcher:e,storeType:C,trackDestinationWorkerScript:I});y.push({name:"interaction",manager:t})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating interaction events manager: ${t.toString()}`)}}if(this.eventsManager=new He(...y),this.eventCompressor&&this.eventCompressor.terminate(),this.eventCompressor=new Le(this.eventsManager,this.config,this.getDeviceId(),b,()=>this.sendEvents()),this.pageLeaveFns=[...this.pageLeaveFns,()=>{var e;if(!this.config||!(null===(e=this.identifiers)||void 0===e?void 0:e.sessionId)||!k)return;const t=k.getBeaconEvents();if(!t.length)return;const i=this.getDeviceId();i&&k.trackDestination.sendBeacon({events:t,sessionId:this.identifiers.sessionId,deviceId:i,apiKey:this.config.apiKey,serverZone:this.config.serverZone})}],yield this.initializeNetworkObservers(),null===(d=v())||void 0===d?void 0:d.opener){const e=Z();!function(e,t){var i,n=e;if(!0!==n[X]){n[X]=!0;var s=null!==(i=null==t?void 0:t.scriptUrl)&&void 0!==i?i:"https://cdn.amplitude.com/libs/background-capture-1.0.0-alpha.3.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:K[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!==(g=null===(h=null===(u=this.config.privacyConfig)||void 0===u?void 0:u.urlMaskLevels)||void 0===h?void 0:h.length)&&void 0!==g?g:0)>0)&&this.setupUrlChangeListener()})}setSessionId(e,t){return m(this.asyncSetSessionId(e,t))}asyncSetSessionId(e,t,i){var s;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 r=t||this.getDeviceId();if(this.identifiers=new Ct({sessionId:e,deviceId:r}),this.joinedConfigGenerator&&n){const{joinedConfig:e}=yield this.joinedConfigGenerator.generateJoinedConfig();this.config=e}(null===(s=this.config)||void 0===s?void 0:s.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={[Y]:t.sessionReplayId?t.sessionReplayId:null},e.debugMode&&(n[ne]=JSON.stringify({appHash:q(e.apiKey).toString()}))),this.addCustomRRWebEvent(le.GET_SR_PROPS,{shouldRecord:i,eventProperties:n},10===this.eventCount),10===this.eventCount&&(this.eventCount=0),this.eventCount++,n}sendEvents(e){var t;const i=e||(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId),n=this.getDeviceId();this.eventsManager&&i&&n&&this.eventsManager.sendCurrentSequenceEvents({sessionId:i,deviceId:n})}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=u),D.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,_t(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(le.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?ge(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=Dt({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=ue(n.serverZone,n.trackServerUrl),f=[re,oe,ae,v];null===(s=this.networkObservers)||void 0===s||s.start(e=>{f.some(t=>e.url.startsWith(t))||this.addCustomRRWebEvent(le.FETCH_REQUEST,e)},g);const{privacyConfig:p,interactionConfig:m,loggingConfig:y}=n,S=(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}:{},b=(null==m?void 0:m.enabled)&&m.ugcFilterRules?m.ugcFilterRules:[];this.loggerProvider.log(`Session Replay capture beginning for ${u}.`);try{this.recordCancelCallback=h({emit: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===Pe.Meta&&(e.data.href=be(e.data.href,b)),this.eventCompressor&&this.eventCompressor.enqueueEvent(e,u)},inlineStylesheet:n.shouldInlineStylesheet,hooks:S,maskAllInputs:!0,maskTextClass:se,blockClass:"amp-block",blockSelector:this.getBlockSelectors(),applyBackgroundColorToBlockedElements:n.applyBackgroundColorToBlockedElements,maskInputFn:fe("input",p,()=>this.currentPageUrl),maskTextFn:fe("text",p,()=>this.currentPageUrl),maskAttributeFn:pe(p,()=>this.currentPageUrl),maskTextSelector:this.getMaskTextSelectors(),recordCanvas:!1,captureAdoptedStyleSheets:n.captureAdoptedStyleSheets,slimDOMOptions:{script:null===(l=n.omitElementTags)||void 0===l?void 0:l.script,comment:null===(c=n.omitElementTags)||void 0===c?void 0:c.comment},errorHandler:e=>{const t=e;if(t.message.includes("insertRule")&&t.message.includes("CSSStyleSheet"))throw t;if(t._external_)throw t;return this.loggerProvider.warn("Error while capturing replay: ",t.toString()),!0},plugins:yield this.getRecordingPlugins(y)}),this.addCustomRRWebEvent(le.DEBUG_INFO),e&&this.addCustomRRWebEvent(le.METADATA,this.metadata)}catch(e){this.loggerProvider.warn("Failed to initialize session replay:",e)}})}getDeviceId(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.deviceId}getSessionId(){var e;return null===(e=this.identifiers)||void 0===e?void 0:e.sessionId}flush(e=!1){var t;return n(this,void 0,void 0,function*(){return null===(t=this.eventsManager)||void 0===t?void 0:t.flush(e)})}shutdown(){var e;null===(e=this.urlChangeCleanup)||void 0===e||e.call(this),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())?q(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 Ut=e=>()=>{const{config:t}=e,{loggerProvider:i,logLevel:n}=t||we();return{logger:i,logLevel:n}};var jt=(()=>{const e=new qt;return{init:k(e.init.bind(e),"init",Ut(e)),evaluateTargetingAndCapture:k(e.evaluateTargetingAndCapture.bind(e),"evaluateTargetingAndRecord",Ut(e)),setSessionId:k(e.setSessionId.bind(e),"setSessionId",Ut(e)),getSessionId:k(e.getSessionId.bind(e),"getSessionId",Ut(e)),getSessionReplayProperties:k(e.getSessionReplayProperties.bind(e),"getSessionReplayProperties",Ut(e)),flush:k(e.flush.bind(e),"flush",Ut(e)),shutdown:k(e.shutdown.bind(e),"shutdown",Ut(e))}})();const{init:$t,setSessionId:Nt,getSessionId:At,getSessionReplayProperties:Wt,flush:Bt,shutdown:zt,evaluateTargetingAndCapture:Ht}=jt;export{ce as S,At as a,Wt as b,zt as c,Ht as e,Bt as f,v as g,$t as i,Nt as s};
1
+ import{_ as e,a as t,b as i,c as n,d as r,e as s,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,r=f();if(!(null===(n=null==r?void 0:r.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 s=r.crypto.getRandomValues(new Uint8Array(16));return s[6]=15&s[6]|64,s[8]=63&s[8]|128,e([],t(s.entries()),!1).map(function(e){var i=t(e,2),n=i[0],r=i[1];return[4,6,8,10].includes(n)?"-".concat(p[r]):p[r]}).join("")},y=function(e){return{promise:e||Promise.resolve()}};!function(e){e[e.None=0]="None",e[e.Error=1]="Error",e[e.Warn=2]="Warn",e[e.Verbose=3]="Verbose",e[e.Debug=4]="Debug"}(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,r;this._optOut=!1;var s=I();this.apiKey=e.apiKey,this.flushIntervalMillis=null!==(t=e.flushIntervalMillis)&&void 0!==t?t:s.flushIntervalMillis,this.flushMaxRetries=e.flushMaxRetries||s.flushMaxRetries,this.flushQueueSize=e.flushQueueSize||s.flushQueueSize,this.instanceName=e.instanceName||s.instanceName,this.loggerProvider=e.loggerProvider||s.loggerProvider,this.logLevel=null!==(i=e.logLevel)&&void 0!==i?i:s.logLevel,this.minIdLength=e.minIdLength,this.plan=e.plan,this.ingestionMetadata=e.ingestionMetadata,this.offline=void 0!==e.offline?e.offline:s.offline,this.optOut=null!==(n=e.optOut)&&void 0!==n?n:s.optOut,this.serverUrl=e.serverUrl,this.serverZone=e.serverZone||s.serverZone,this.storageProvider=e.storageProvider,this.transportProvider=e.transportProvider,this.useBatch=null!==(r=e.useBatch)&&void 0!==r?r:s.useBatch,this.loggerProvider.enable(this.logLevel);var o=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,r){return void 0===r&&(r=null),function(){for(var s=[],o=0;o<arguments.length;o++)s[o]=arguments[o];var a=i(),l=a.logger,c=a.logLevel;if(c&&c<v.Debug||!c||!l)return e.apply(r,s);var d,u={type:"invoke public method",name:t,args:s,stacktrace:(d=1,void 0===d&&(d=0),((new Error).stack||"").split("\n").slice(2+d).map(function(e){return e.trim()})),time:{start:(new Date).toISOString()},states:{}};n&&u.states&&(u.states.before=n());var h=e.apply(r,s);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:O(),platform:"Web",os:void 0,deviceModel:void 0}},e}(),O=function(){return"undefined"!=typeof navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||""},R=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}(),M=function(){return M=Object.assign||function(e){for(var t,i=1,n=arguments.length;i<n;i++)for(var r in t=arguments[i])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},M.apply(this,arguments)};function T(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,r,s=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=s.next()).done;)o.push(n.value)}catch(e){r={error:e}}finally{try{n&&!n.done&&(i=s.return)&&i.call(s)}finally{if(r)throw r.error}}return o}"function"==typeof SuppressedError&&SuppressedError;var _=function(e,t){var i,n,r=typeof e;if(r!==typeof t)return!1;try{for(var s=T(["string","number","boolean","undefined"]),o=s.next();!o.done;o=s.next()){if(o.value===r)return e===t}}catch(e){i={error:e}}finally{try{o&&!o.done&&(n=s.return)&&n.call(s)}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=M({},this.identity.userProperties),i=M(M({},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,r,s,o,a,l=i.userProperties||{};try{for(var c=T(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=(r=void 0,T(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){r={error:e}}finally{try{f&&!f.done&&(s=v.return)&&s.call(v)}finally{if(r)throw r.error}}break;case"$unset":try{for(var b=(o=void 0,T(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 M({},this.identity)},e.prototype.setIdentity=function(e){var t=M({},this.identity);this.identity=M({},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}(),D="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:self,j=function(){function e(){this.identityStore=new F,this.eventBridge=new R,this.applicationContextProvider=new E}return e.getInstance=function(t){return D.analyticsConnectorInstances||(D.analyticsConnectorInstances={}),D.analyticsConnectorInstances[t]||(D.analyticsConnectorInstances[t]=new e),D.analyticsConnectorInstances[t]},e}(),q=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},$=function(){function e(){}return e.prototype.send=function(e,t,i){return Promise.resolve(null)},e.prototype.buildResponse=function(e){var t,i,n,r,s,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!==(r=e.error)&&void 0!==r?r:"",missingField:null!==(s=e.missing_field)&&void 0!==s?s:"",eventsWithInvalidFields:null!==(o=e.events_with_invalid_fields)&&void 0!==o?o:{},eventsWithMissingFields:null!==(a=e.events_with_missing_fields)&&void 0!==a?a:{},eventsWithInvalidIdLengths:null!==(l=e.events_with_invalid_id_lengths)&&void 0!==l?l:{},epsThreshold:null!==(c=e.eps_threshold)&&void 0!==c?c:0,exceededDailyQuotaDevices:null!==(d=e.exceeded_daily_quota_devices)&&void 0!==d?d:{},silencedDevices:null!==(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}(),U=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 r(this,function(r){switch(r.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,(n=r.sent()).text()];case 2:o=r.sent();try{return[2,this.buildResponse(JSON.parse(o))]}catch(e){return[2,this.buildResponse({code:n.status})]}return[2]}})})},t}($),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}(),N=401,W=403,B=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(),r={id:n,key:e,deliveryMode:t,callback:i};return this.callbackInfos.push(r),"all"===t?this.subscribeAll(r):this.subscribeWaitForRemote(r,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 r(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,s=this;return r(this,function(r){switch(r.label){case 0:return t=this.getOrCreateFetchPromise().then(function(t){s.logger.debug("Remote config client subscription all mode fetched from remote: ".concat(JSON.stringify(t))),s.sendCallback(e,t,"remote"),s.storage.setConfig(t)}),i=this.storage.fetchConfig().then(function(e){return e}),[4,Promise.race([t,i])];case 1:return void 0!==(n=r.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 r.sent(),[2]}})})},e.prototype.subscribeWaitForRemote=function(e,t){return n(this,void 0,void 0,function(){var i,n;return r(this,function(r){switch(r.label){case 0:i=new Promise(function(e,i){setTimeout(function(){i("Timeout exceeded")},t)}),r.label=1;case 1:return r.trys.push([1,3,,5]),[4,Promise.race([this.getOrCreateFetchPromise(),i])];case 2:return n=r.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 r.sent(),this.logger.debug("Remote config client subscription wait for remote mode exceeded timeout. Try to fetch from cache."),[4,this.storage.fetchConfig()];case 4:return null!==(n=r.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,s,o,a,l,c=this;return r(this,function(d){switch(d.label){case 0:i=t/e,n={remoteConfig:null,lastFetch:new Date},s=function(n){var s,a,l,d,u,h;return r(this,function(r){switch(r.label){case 0:s=!0,a=new AbortController,l=setTimeout(function(){return a.abort()},t),r.label=1;case 1:return r.trys.push([1,7,8,9]),[4,fetch(o.getUrlParams(),{method:"GET",headers:{Accept:"*/*"},signal:a.signal})];case 2:return(d=r.sent()).ok?[3,4]:[4,d.text()];case 3:return u=r.sent(),o.logger.debug("Remote config client fetch with retry time ".concat(e," failed with ").concat(d.status,": ").concat(u)),d.status===N||d.status===W?(o.logger.error("Remote config client fetch failed with ".concat(d.status,". Invalid API key; future fetches will be skipped.")),o.isLastFetchInvalidApiKey=!0,s=!1):d.status>=400&&d.status<500&&d.status!==B&&(s=!1),[3,6];case 4:return[4,d.json()];case 5:return[2,{value:{remoteConfig:r.sent(),lastFetch:new Date}}];case 6:return[3,9];case 7:return(h=r.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 s?n<e-1?[4,new Promise(function(e){return setTimeout(e,c.getJitterDelay(i))})]:[3,11]:[2,"break"];case 10:r.sent(),r.label=11;case 11:return[2]}})},o=this,a=0,d.label=1;case 1:return a<e?[5,s(a)]:[3,4];case 2:if("object"==typeof(l=d.sent()))return[2,l.value];if("break"===l)return[3,4];d.label=3;case 3:return a++,[3,1];case 4:return[2,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 H,K="https://app.amplitude.com",J={US:K,EU:"https://app.eu.amplitude.com",STAGING:"https://apps.stag2.amplitude.com"};var Q="__AMPLITUDE_MESSENGER_INSTANCE__",G="__AMPLITUDE_MESSENGER__",Z=function(){function e(e){var t=(void 0===e?{}:e).origin,i=void 0===t?K:t;this[H]=!0,this.isSetup=!1,this.messageHandler=null,this.requestCallbacks={},this.actionHandlers=new Map,this.pendingMessages=new Map,this.scriptLoadPromises=new Map,this.endpoint=i}return e.prototype.notify=function(e){var t,i,n,r;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===(r=null===(n=window.opener)||void 0===n?void 0:n.postMessage)||void 0===r||r.call(n,e,this.endpoint)},e.prototype.sendRequest=function(e,t,i){var n=this;void 0===i&&(i={timeout:15e3});var r="".concat(Date.now(),"-").concat(Math.random().toString(36).substr(2,9)),s={id:r,action:e,args:t};return new Promise(function(t,o){n.requestCallbacks[r]={resolve:t,reject:o},n.notify(s),i.timeout>0&&setTimeout(function(){o(new Error("".concat(e," timed out (id: ").concat(r,")"))),delete n.requestCallbacks[r]},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,r,s;this.actionHandlers.has(e)&&(null===(s=null===(r=this.logger)||void 0===r?void 0:r.warn)||void 0===s||s.call(r,"Overwriting existing action handler for: ".concat(e))),this.actionHandlers.set(e,t);var a=this.pendingMessages.get(e);if(a){this.pendingMessages.delete(e);try{for(var l=o(a),c=l.next();!c.done;c=l.next()){t(c.value)}}catch(e){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 r(this,function(r){switch(r.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 r=document.createElement("script");r.type="text/javascript",r.async=!0,r.src=e,r.addEventListener("load",function(){t({status:!0})},{once:!0}),r.addEventListener("error",function(){i({status:!1,message:"Failed to load the script ".concat(e)})}),null===(n=document.head)||void 0===n||n.appendChild(r)}catch(e){i(e)}})}(e).then(function(){}),this.scriptLoadPromises.set(e,i),r.label=1;case 1:return r.trys.push([1,3,,4]),[4,i];case 2:return r.sent(),[3,4];case 3:throw n=r.sent(),this.scriptLoadPromises.delete(e),n;case 4:return[2]}})})},e.prototype.setup=function(e){var t,i,n=this,r=void 0===e?{}:e,s=r.logger,o=r.endpoint;s&&(this.logger=s),o&&this.endpoint===K&&(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,r,s,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===(s=null===(r=n.logger)||void 0===r?void 0:r.debug)||void 0===s||s.call(r,"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[G])===this&&delete e[G]},e}();function X(e){var t,i=f(),n=null==i?void 0:i[G];if("object"==typeof(t=n)&&null!==t&&Q in t&&!0===t[Q])return n;var r=new Z(e);return i&&(i[G]=r),r}H=Q;var V="__AMPLITUDE_BACKGROUND_CAPTURE__";const Y="[Amplitude]",ee=`${Y} Session Replay ID`,te=L.US,ie={enabled:!0},ne=1e3,re=`${Y} Session Replay Debug`,se="amp-mask",oe="https://api-sr.amplitude.com/sessions/v2/track",ae="https://api-sr.eu.amplitude.com/sessions/v2/track",le="https://api-sr.stag2.amplitude.com/sessions/v2/track",ce="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"}(de||(de={}));class ue{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 he="medium";function ge(e,t){return t||("STAGING"===e?le:"EU"===e?ae:oe)}const ve=(e,t,i)=>{switch(t){case"light":{if("input"!==e)return!0;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":case"conservative":return!0;default:return ve(e,he,i)}},fe=(e,t)=>{var i;if(e&&t.urlMaskLevels)for(const i of t.urlMaskLevels)if(Ie(i.match).test(e))return i.maskLevel;return null!==(i=t.defaultMaskLevel)&&void 0!==i?i:he},pe=(e,t={defaultMaskLevel:he},i,n)=>{var r,s;if(i){if(i.closest("."+se))return!0;const e=(null!==(r=t.maskSelector)&&void 0!==r?r:[]).some(e=>i.closest(e));if(e)return!0;if(i.closest(".amp-unmask"))return!1;const n=(null!==(s=t.unmaskSelector)&&void 0!==s?s:[]).some(e=>i.closest(e));if(n)return!1}return ve(e,fe(n,t),i)},me=(e,t,i)=>(n,r)=>pe(e,t,r,null==i?void 0:i())?n.replace(/[^\s]/g,"*"):n,ye=(e,t)=>(i,n,r)=>{var s;return"style"===i?n:(null!==(s=null==e?void 0:e.maskAttributes)&&void 0!==s?s:[]).includes(i)&&pe("text",e,r,null==t?void 0:t())?n.replace(/[^\s]/g,"*"):n},be=()=>{const e=f();return(null==e?void 0:e.location)?e.location.href:""},Se=new Map,Ie=e=>{const t=Se.get(e);if(t)return t;const i="\0TRAIL\0",n="\0MID\0",r="\0DS\0",s="\0ST\0",o="\0QU\0";let a=e;a=a.replace(/\/\*\*$/,i),a=a.replace(/\/\*\*\//g,n),a=a.replace(/\*\*/g,r),a=a.replace(/\*/g,s),a=a.replace(/\?/g,o),a=a.replace(/[.+^${}()|[\]\\]/g,"\\$&"),a=a.split(i).join("(/.*)?"),a=a.split(n).join("/(.*\\/)?"),a=a.split(r).join(".*"),a=a.split(s).join(".*"),a=a.split(o).join(".");const l=new RegExp(`^${a}$`);return Se.set(e,l),l},Ce=(e,t)=>{for(const i of t){const t=Ie(i.selector);if(t.test(e))return e.replace(t,i.replacement)}return e},we=()=>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(),r=t?Math.round(t/1024):0;return{totalStorageSize:r,percentOfQuota:t&&i?Math.round(1e3*(t/i+Number.EPSILON))/1e3:0,usageDetails:JSON.stringify(n)}}}catch(e){}return{totalStorageSize:0,percentOfQuota:0,usageDetails:""}}),ke=e=>{const t=Object.assign({},e),{apiKey:i}=t;return t.apiKey=`****${i.substring(i.length-4)}`,t},Pe=()=>({flushMaxRetries:2,logLevel:v.Warn,loggerProvider:new S,transportProvider:new U});class Ee extends C{constructor(e,t){var i,n,r,s,o,a,l;const c=Pe();if(super(Object.assign(Object.assign({transportProvider:c.transportProvider,loggerProvider:new ue(t.loggerProvider||c.loggerProvider)},t),{apiKey:e})),this.flushMaxRetries=void 0!==t.flushMaxRetries&&t.flushMaxRetries<=c.flushMaxRetries?t.flushMaxRetries:c.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:"idb",this.applyBackgroundColorToBlockedElements=null!==(n=t.applyBackgroundColorToBlockedElements)&&void 0!==n&&n,this.enableUrlChangePolling=null!==(r=t.enableUrlChangePolling)&&void 0!==r&&r,this.urlChangePollingInterval=null!==(s=t.urlChangePollingInterval)&&void 0!==s?s:ne,this.captureDocumentTitle=null!==(o=t.captureDocumentTitle)&&void 0!==o&&o,t.privacyConfig&&(this.privacyConfig=t.privacyConfig),t.interactionConfig&&(this.interactionConfig=t.interactionConfig,this.interactionConfig.ugcFilterRules&&(e=>{if(!e.every(e=>"string"==typeof e.selector&&"string"==typeof e.replacement))throw new Error("ugcFilterRules must be an array of objects with selector and replacement properties");if(!e.every(e=>{return"string"==typeof(t=e.selector)&&""!==t.trim()&&!!/^\/|^https?:\/\/[^\s]+$/.test(t);var t}))throw new Error("ugcFilterRules must be an array of objects with valid globs")})(this.interactionConfig.ugcFilterRules)),t.debugMode&&(this.debugMode=t.debugMode),void 0!==t.useWebWorker)this.useWebWorker=t.useWebWorker;else{const e=t;void 0!==(null===(a=e.experimental)||void 0===a?void 0:a.useWebWorker)&&(this.useWebWorker=e.experimental.useWebWorker)}t.omitElementTags&&(this.omitElementTags=t.omitElementTags),this.captureAdoptedStyleSheets=null===(l=t.captureAdoptedStyleSheets)||void 0===l||l,t.crossOriginIframes&&(this.crossOriginIframes=t.crossOriginIframes)}}var Oe=(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))(Oe||{}),Re=(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))(Re||{}),Me=(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))(Me||{});class Te{constructor(e,t){this.localConfig=t,this.remoteConfigClient=e}generateJoinedConfig(){var e,t,i,r,s,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","all",(i,r)=>{var s;if(this.localConfig.loggerProvider.debug(`Session Replay remote configuration received from ${r}:`,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===(s=n.interactionConfig)||void 0===s?void 0:s.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)):(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!==(r=l.maskAttributes)&&void 0!==r?r:[],...null!==(s=d.maskAttributes)&&void 0!==s?s:[]])],urlMaskLevels:[...null!==(o=d.urlMaskLevels)&&void 0!==o?o:[],...null!==(a=l.urlMaskLevels)&&void 0!==a?a:[]]},u=e=>{var t,i,n;const r={};"string"==typeof e.blockSelector&&(e.blockSelector=[e.blockSelector]);for(const i of null!==(t=e.blockSelector)&&void 0!==t?t:[])r[i]="block";for(const t of null!==(i=e.maskSelector)&&void 0!==i?i:[])r[t]="mask";for(const t of null!==(n=e.unmaskSelector)&&void 0!==n?n:[])r[t]="unmask";return r},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:ke(n)},null,2)),{localConfig:this.localConfig,joinedConfig:n,remoteConfig:l}})}}function xe(e){if(e.type!==Oe.IncrementalSnapshot)return!1;const t=e.data;return t.source===Re.Mutation&&!t.isAttachIframe}function _e(e){const t=e[0],i=new Map,n=new Map,r=new Map,s=new Map,o=new Map;e.forEach((e,t)=>{const a=e.data;for(const e of a.adds)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)r.has(e.id)||r.set(e.id,t),s.set(e.id,t)});const a=new Set,l=new Set;for(const[e,t]of i){const i=r.get(e);if(void 0===i)continue;n.get(e)>=s.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=r.get(t),s=i.get(t);void 0!==n&&void 0!==s&&n<s?l.add(t):void 0!==n&&void 0!==s&&n===s?c.add(t):a.add(t),e=!0}}}const d=a.size>0||l.size>0||c.size>0,u=[];e.forEach((e,t)=>{for(const 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={source:Re.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:d?v.filter(e=>!a.has(e.id)&&!l.has(e.id)&&!c.has(e.id)):v};return Object.assign(Object.assign({},t),{data:f})}function Le(e){if(e.length<=1)return e;const t=[];let i=0;for(;i<e.length;){if(!xe(e[i])){t.push(e[i]),i++;continue}let n=i+1;for(;n<e.length&&xe(e[n]);)n++;t.push(n>i+1?_e(e.slice(i,n)):e[i]),i=n}return t}class Fe{constructor(e,t,i,n,r){var s;this.taskQueue=[],this.pendingQueue=[],this.isProcessing=!1,this.compressEvent=e=>{const{type:t,timestamp:i,delay:n,data:r}=e;return null!=n?JSON.stringify({type:t,timestamp:i,delay:n,data:r}):JSON.stringify({type:t,timestamp:i,data:r})},this.addCompressedEventToManager=(e,t)=>{this.eventsManager&&this.deviceId&&this.eventsManager.addEvent({event:{type:"replay",data:e},sessionId:t,deviceId:this.deviceId})},this.addCompressedEvent=(e,t)=>{if(this.worker)try{this.worker.postMessage({event:e,sessionId:t})}catch(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.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===(s=t.performanceConfig)||void 0===s?void 0:s.timeout)||2e3,this.onFullSnapshotProcessed=r,n){t.loggerProvider.log("Enabling web worker for compression");try{const e=new Blob([n],{type:"application/javascript"}),i=URL.createObjectURL(e),r=new Worker(i);r.onerror=e=>{e.preventDefault(),t.loggerProvider.error(`Worker failed, falling back to non-worker compression: ${e.message} (${e.filename}:${e.lineno})`),r.terminate(),this.worker=void 0},r.onmessage=e=>{const{compressedEvent:t,sessionId:i}=e.data;this.addCompressedEventToManager(t,i)},this.worker=r}catch(e){t.loggerProvider.error("Failed to create worker, falling back to non-worker compression:",e)}}}scheduleIdleProcessing(){this.isProcessing||(this.isProcessing=!0,requestIdleCallback(e=>{this.processQueue(e)},{timeout:this.timeout}))}enqueueEvent(e,t){var i,n;if(e.type===Oe.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(!(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 r=n+1;for(;r<e.length&&e[r].sessionId===t;)r++;const s=Le(e.slice(n,r).map(e=>e.event));for(const e of s)i.push({event:e,sessionId:t});n=r}return i}}const De="Session replay event batch rejected due to exceeded retry count",je="Failed to store session replay events in IndexedDB",qe="1.41.0";class $e{constructor({trackServerUrl:e,loggerProvider:t,payloadBatcher:i,workerScript:n}){if(this.storageKey="",this.retryTimeout=1e3,this.scheduled=null,this.queue=[],this.sendIdCounter=0,this.pendingWorkerRequests=new Map,this.loggerProvider=t,this.payloadBatcher=i||(e=>e),this.trackServerUrl=e,n)try{const e=new Blob([n],{type:"application/javascript"}),i=URL.createObjectURL(e),r=new Worker(i);r.onerror=e=>{e.preventDefault(),t.error(`Track destination worker failed, falling back to main-thread sending: ${e.message} (${e.filename}:${e.lineno})`),r.terminate(),this.worker=void 0;for(const[,i]of this.pendingWorkerRequests)t.warn(`Session replay event send failed due to worker crash: ${e.message}`),i.resolve();this.pendingWorkerRequests.clear()},r.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("complete"===i.type){const e=this.pendingWorkerRequests.get(i.id);e&&(this.completeRequest({context:e.context}),e.resolve(),this.pendingWorkerRequests.delete(i.id))}},this.worker=r}catch(e){t.error("Failed to create track destination worker, falling back to main-thread sending:",e)}}sendEventsList(e){this.addToQueue(Object.assign(Object.assign({},e),{attempts:0,timeout:0}))}sendBeacon({events:e,sessionId:t,deviceId:i,apiKey:n,serverZone:r}){var s,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=`${ge(r,this.trackServerUrl)}?${d.toString()}`,h=f();try{const e=new Blob([c],{type:"application/json"});!1===(null===(o=null===(s=null==h?void 0:h.navigator)||void 0===s?void 0:s.sendBeacon)||void 0===o?void 0:o.call(s,u,e))&&this.loggerProvider.warn("sendBeacon failed to queue session replay payload")}catch(e){}}addToQueue(...e){e.filter(e=>e.attempts<(e.flushMaxRetries||0)?(e.attempts+=1,!0):(this.completeRequest({context:e,err:De}),!1)).forEach(e=>{this.queue=this.queue.concat(e),this.schedule(0)})}schedule(e){this.scheduled||(this.scheduled=setTimeout(()=>{this.flush(!0).then(()=>{this.queue.length>0&&this.schedule(e)})},e))}flush(e=!1){return n(this,void 0,void 0,function*(){const t=this.queue;this.queue=[],this.scheduled&&(clearTimeout(this.scheduled),this.scheduled=null);for(const i of t)yield this.send(i,e)})}send(e,t=!0){return n(this,void 0,void 0,function*(){const i=e.apiKey;if(!i)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing api key"});const n=e.deviceId;if(!n)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing device ID"});const r=this.payloadBatcher({version:1,events:e.events});if(0===r.events.length)return void this.completeRequest({context:e});const{worker:s}=this;return s?this.sendViaWorker(s,e,r,t):this.sendOnMainThread(i,n,e,r,t)})}sendViaWorker(e,t,i,r){return n(this,void 0,void 0,function*(){const n=""+ ++this.sendIdCounter;return new Promise(s=>{var o;this.pendingWorkerRequests.set(n,{context:t,resolve:s}),e.postMessage({type:"send",id:n,payload:i,useRetry:r,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:be(),sdkVersion:qe}})})})}sendOnMainThread(e,t,i,r,s){var o,a,l,c;return n(this,void 0,void 0,function*(){const d=be(),u=qe,h=i.sampleRate,g=new URLSearchParams({device_id:t,session_id:`${i.sessionId}`,type:`${i.type}`}),v=`${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:u}`;try{const t=JSON.stringify(r),o=f(),a=o&&"CompressionStream"in o?yield function(e,t){return n(this,void 0,void 0,function*(){try{const i=new(0,t.CompressionStream)("gzip"),r=i.writable.getWriter(),s=i.readable.getReader(),o=[],a=(()=>n(this,void 0,void 0,function*(){for(;;){const{done:e,value:t}=yield s.read();if(e)break;o.push(t)}}))();yield r.write((new TextEncoder).encode(e)),yield r.close(),yield a;const l=o.reduce((e,t)=>e+t.length,0),c=new Uint8Array(l);let d=0;for(const e of o)c.set(e,d),d+=e.length;return c}catch(e){return null}})}(t,o):null,l=a?a.byteLength:new Blob([t]).size,c={headers:Object.assign({"Content-Type":"application/json",Accept:"*/*",Authorization:`Bearer ${e}`,"X-Client-Version":u,"X-Client-Library":v,"X-Client-Url":d.substring(0,1e3),"X-Client-Sample-Rate":`${h}`,"X-Sampling-Hash-Alg":"xxhash32"},a?{"Content-Encoding":"gzip"}:{}),body:null!=a?a:t,method:"POST",keepalive:l<=65536},p=`${ge(i.serverZone,this.trackServerUrl)}?${g.toString()}`,m=yield fetch(p,c);if(null===m)return void this.completeRequest({context:i,err:"Unexpected error occurred"});if(s)yield this.handleReponse(m.status,i);else{let e="";try{e=JSON.stringify(m.body,null,2)}catch(e){}this.completeRequest({context:i,success:`${m.status}: ${e}`})}}catch(e){this.completeRequest({context:i,err:e})}})}handleReponse(e,t){return n(this,void 0,void 0,function*(){switch((new $).buildStatus(e)){case u.Success:this.handleSuccessResponse(t);break;case u.Failed:case u.Timeout:case u.RateLimit:yield this.handleOtherResponse(t);break;default:if(499===e){yield this.handleOtherResponse(t);break}this.completeRequest({context:t,err:"Network error occurred, event batch rejected"})}})}handleSuccessResponse(e){const t=Math.round(new Blob(e.events).size/1024);this.completeRequest({context:e,success:`Session replay event batch tracked successfully for session id ${e.sessionId}, size of events: ${t} KB`})}handleOtherResponse(e){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:De}):(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)}}class Ue{get timeAtLastSplit(){return this._timeAtLastSplit}constructor(e){var t,i,n;this.minInterval=500,this.maxInterval=1e4,this.maxPersistedEventsSize=1e6,this.interval=this.minInterval,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}getStringSize(e){return e.length}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 Ae=(e,t,i)=>{var n;"object"==typeof(n=i)&&null!==n&&"AbortError"===n.name?e.debug(t):e.warn(t)};const Ne="sessionCurrentSequence",We="sequencesToSend",Be=5e3;function ze(e,t,i){const n=setTimeout(i,t);return e.then(()=>clearTimeout(n),()=>clearTimeout(n)),()=>clearTimeout(n)}const He=e=>{let t,i;return e.objectStoreNames.contains(Ne)||(i=e.createObjectStore(Ne,{keyPath:"sessionId"})),e.objectStoreNames.contains(We)||(t=e.createObjectStore(We,{keyPath:"sequenceId",autoIncrement:!0}),t.createIndex("sessionId","sessionId")),{sequencesStore:t,currentSequenceStore:i}},Ke=e=>n(void 0,void 0,void 0,function*(){return yield function(e,t,i="IDB operation timed out"){return new Promise((n,r)=>{const s=setTimeout(()=>r(new Error(`${i} after ${t}ms`)),t);e.then(e=>{clearTimeout(s),n(e)},e=>{clearTimeout(s),r(e)})})}(l(e,1,{upgrade:He}),2e3,"IDB openDB timed out")});class Je extends Ue{constructor(e){var t;super(e),this.consecutiveFailures=0,this.hasTriggeredFallback=!1,this.getSequencesToSend=()=>n(this,void 0,void 0,function*(){let e=!1,t=!1;try{const i=[],n=this.db.transaction("sequencesToSend");n.done.catch(i=>{e||t||(Ae(this.loggerProvider,`${je}: ${i}`,i),this.recordFailure())});const r=ze(n.done,Be,()=>{e||t||(t=!0,Ae(this.loggerProvider,`${je}: transaction timed out`),this.recordFailure())});let s=yield n.store.openCursor();for(;s;){const{sessionId:e,events:t}=s.value;i.push({events:t,sequenceId:s.key,sessionId:e}),s=yield s.continue()}return this.recordSuccess(),r(),i}catch(i){t||(e=!0,Ae(this.loggerProvider,`${je}: ${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([Ne,We],"readwrite");n.done.catch(e=>{t||i||(Ae(this.loggerProvider,`${je}: ${e}`,e),this.recordFailure())});const r=ze(n.done,Be,()=>{t||i||(i=!0,Ae(this.loggerProvider,`${je}: transaction timed out`),this.recordFailure())}),s=yield n.objectStore(Ne).get(e);if(!s||s.tabId&&s.tabId!==this.tabId)return void r();if(0===s.events.length)return void r();const o=yield n.objectStore(We).put({sessionId:e,events:s.events,tabId:this.tabId});yield n.objectStore(Ne).put({sessionId:e,events:[],tabId:this.tabId}),this.recordSuccess(),r();const{tabId:l}=s,c=a(s,["tabId"]);return Object.assign(Object.assign({},c),{sessionId:e,sequenceId:o})}catch(e){i||(t=!0,Ae(this.loggerProvider,`${je}: ${e}`,e),this.recordFailure())}}),this.addEventToCurrentSequence=(e,t)=>n(this,void 0,void 0,function*(){let i=!1,n=!1;try{const r=this.db.transaction([Ne,We],"readwrite");r.done.catch(e=>{i||n||(Ae(this.loggerProvider,`${je}: ${e}`,e),this.recordFailure())});const s=ze(r.done,Be,()=>{i||n||(n=!0,Ae(this.loggerProvider,`${je}: transaction timed out`),this.recordFailure())}),o=yield r.objectStore(Ne).get(e);if((null==o?void 0:o.tabId)&&o.tabId!==this.tabId)return o.events.length>0&&(yield r.objectStore(We).put({sessionId:e,events:o.events,tabId:o.tabId})),yield r.objectStore(Ne).put({sessionId:e,events:[t],tabId:this.tabId}),this.recordSuccess(),void s();const a=o;if(!a)return yield r.objectStore(Ne).put({sessionId:e,events:[t],tabId:this.tabId}),this.recordSuccess(),void s();if(!this.shouldSplitEventsList(a.events,t))return yield r.objectStore(Ne).put({sessionId:e,events:a.events.concat(t),tabId:this.tabId}),this.recordSuccess(),void s();const l=a.events;yield r.objectStore(Ne).put({sessionId:e,events:[t],tabId:this.tabId});const c=yield r.objectStore(We).put({sessionId:e,events:l,tabId:this.tabId});return this.recordSuccess(),s(),{events:l,sessionId:e,sequenceId:c}}catch(e){n||(i=!0,Ae(this.loggerProvider,`${je}: ${e}`,e),this.recordFailure())}}),this.storeSendingEvents=(e,t)=>n(this,void 0,void 0,function*(){try{const i=yield this.db.put(We,{sessionId:e,events:t,tabId:this.tabId});return this.recordSuccess(),i}catch(e){Ae(this.loggerProvider,`${je}: ${e}`,e),this.recordFailure()}}),this.cleanUpSessionEventsStore=(e,t)=>n(this,void 0,void 0,function*(){if(t)try{yield this.db.delete(We,t),this.recordSuccess()}catch(e){Ae(this.loggerProvider,`${je}: ${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}`,r=`${t.apiKey.substring(0,10)}_amp_session_replay_events${n}`,s=yield Ke(r),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 Je(Object.assign(Object.assign({},t),{db:s,tabId:o}))}catch(e){Ae(t.loggerProvider,`${je}: ${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 Qe extends Ue{constructor(){super(...arguments),this.finalizedSequences={},this.sequences={},this.sequenceId=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}}getSequencesToSend(){return n(this,void 0,void 0,function*(){return Object.entries(this.finalizedSequences).map(([e,{sessionId:t,events:i}])=>({sequenceId:Number(e),sessionId:t,events:i}))})}storeCurrentSequence(e){return n(this,void 0,void 0,function*(){if(this.sequences[e])return this.addSequence(e)})}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)&&(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 Ge=({config:e,minInterval:t,maxInterval:i,type:r,payloadBatcher:s,storeType:o,trackDestinationWorkerScript:a})=>n(void 0,void 0,void 0,function*(){const l=new $e(Object.assign(Object.assign({},e),{loggerProvider:e.loggerProvider,payloadBatcher:s,workerScript:a})),c=()=>new Qe({loggerProvider:e.loggerProvider,maxInterval:i,minInterval:t});let d,u,h=!1;u="idb"===o?yield n(void 0,void 0,void 0,function*(){const s=yield Je.new(r,{loggerProvider:e.loggerProvider,minInterval:t,maxInterval:i,apiKey:e.apiKey,onPersistentFailure:()=>{n(void 0,void 0,void 0,function*(){if(!h)return;h=!1,e.loggerProvider.warn("IDB store is experiencing repeated failures; falling back to in-memory event store.");const t=d?yield u.getSequencesToSend():void 0;if(u=c(),t&&d){const e=d;t.forEach(t=>{p({sequenceId:t.sequenceId,events:t.events,sessionId:t.sessionId,deviceId:e})})}})}});return s?(h=!0,s):(e.loggerProvider.log("Failed to initialize idb store, falling back to memory store."),c())}):c();const g=[];let v=0;const f=e=>{if(e<=v)return;const t=Math.min(e-v,g.length);t>0&&(g.splice(0,t),v=e)},p=({events:t,sessionId:i,deviceId:s,sequenceId:o})=>{e.debugMode&&we().then(({totalStorageSize:t,percentOfQuota:i,usageDetails:n})=>{e.loggerProvider.debug(`Total storage size: ${t} KB, percentage of quota: ${i}%, usage details: ${n}`)}).catch(()=>{}),l.sendEventsList({events:t,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 u.cleanUpSessionEventsStore(i,o)})})};return{sendCurrentSequenceEvents:({sessionId:t,deviceId:i})=>{d=i;const n=v+g.length;u.storeCurrentSequence(t).then(e=>{e&&(f(n),p({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})=>{d=n;const r=v+g.length;g.push(t.data),u.addEventToCurrentSequence(i,t.data).then(e=>{e&&(f(r),p({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:n}))}).catch(t=>{e.loggerProvider.warn("Failed to add event to session replay capture:",t)})},sendStoredEvents:({deviceId:e})=>n(void 0,void 0,void 0,function*(){d=e;const t=yield u.getSequencesToSend();t&&t.forEach(t=>{p({sequenceId:t.sequenceId,events:t.events,sessionId:t.sessionId,deviceId:e})})}),flush:function(e=!1){return n(this,void 0,void 0,function*(){return l.flush(e)})},getBeaconEvents:()=>[...g],trackDestination:l}});class Ze{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 Xe,Ve,Ye;function et(e,t){if(Ye=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};Xe=Object.assign(Object.assign({},i),t),Ve=function(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return e;if(e===t.root)return e.ownerDocument;return e}(Xe.root,i);let n=tt(e,"all",()=>tt(e,"two",()=>tt(e,"one",()=>tt(e,"none"))));if(n){const t=mt(yt(n,e));return t.length>0&&(n=t[0]),nt(n)}throw new Error("Selector was not found.")}function tt(e,t,i){let n=null,r=[],s=e,o=0;for(;s;){const e=(new Date).getTime()-Ye.getTime();if(void 0!==Xe.timeoutMs&&e>Xe.timeoutMs)throw new Error(`Timeout: Can't find a unique selector after ${e}ms`);let a=vt(ot(s))||vt(...at(s))||vt(...lt(s))||vt(ct(s))||[dt()];const l=ut(s);if("all"==t)l&&(a=a.concat(a.filter(gt).map(e=>ht(e,l))));else if("two"==t)a=a.slice(0,1),l&&(a=a.concat(a.filter(gt).map(e=>ht(e,l))));else if("one"==t){const[e]=a=a.slice(0,1);l&&gt(e)&&(a=[ht(e,l)])}else"none"==t&&(a=[dt()],l&&(a=[ht(a[0],l)]));for(let e of a)e.level=o;if(r.push(a),r.length>=Xe.seedMinLength&&(n=it(r,i),n))break;s=s.parentElement,o++}return n||(n=it(r,i)),!n&&i?i():n}function it(e,t){const i=mt(pt(e));if(i.length>Xe.threshold)return t?t():null;for(let e of i)if(st(e))return e;return null}function nt(e){let t=e[0],i=t.name;for(let n=1;n<e.length;n++){const r=e[n].level||0;i=t.level===r-1?`${e[n].name} > ${i}`:`${e[n].name} ${i}`,t=e[n]}return i}function rt(e){return e.map(e=>e.penalty).reduce((e,t)=>e+t,0)}function st(e){const t=nt(e);switch(Ve.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 ot(e){const t=e.getAttribute("id");return t&&Xe.idName(t)?{name:"#"+CSS.escape(t),penalty:0}:null}function at(e){const t=Array.from(e.attributes).filter(e=>Xe.attr(e.name,e.value));return t.map(e=>({name:`[${CSS.escape(e.name)}="${CSS.escape(e.value)}"]`,penalty:.5}))}function lt(e){return Array.from(e.classList).filter(Xe.className).map(e=>({name:"."+CSS.escape(e),penalty:1}))}function ct(e){const t=e.tagName.toLowerCase();return Xe.tagName(t)?{name:t,penalty:2}:null}function dt(){return{name:"*",penalty:3}}function ut(e){const t=e.parentNode;if(!t)return null;let i=t.firstChild;if(!i)return null;let n=0;for(;i&&(i.nodeType===Node.ELEMENT_NODE&&n++,i!==e);)i=i.nextSibling;return n}function ht(e,t){return{name:e.name+`:nth-child(${t})`,penalty:e.penalty+1}}function gt(e){return"html"!==e.name&&!e.name.startsWith("#")}function vt(...e){const t=e.filter(ft);return t.length>0?t:null}function ft(e){return null!=e}function*pt(e,t=[]){if(e.length>0)for(let i of e[0])yield*pt(e.slice(1,e.length),t.concat(i));else yield t}function mt(e){return[...e].sort((e,t)=>rt(e)-rt(t))}function*yt(e,t,i={counter:0,visited:new Map}){if(e.length>2&&e.length>Xe.optimizedMinLength)for(let n=1;n<e.length-1;n++){if(i.counter>Xe.maxNumberOfTries)return;i.counter+=1;const r=[...e];r.splice(n,1);const s=nt(r);if(i.visited.has(s))return;st(r)&&bt(r,t)&&(yield r,i.visited.set(s,!0),yield*yt(r,t,i))}}function bt(e,t){return Ve.querySelector(nt(e))===t}const St=({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}},It=({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:r,timestamp:s}=t,o=s-s%36e5,a=`${i}:${n}:${null!=r?r:""}:${o}`;return e[a]?e[a].count+=1:e[a]=Object.assign(Object.assign({},t),{timestamp:o,count:1}),e},{});return{version:e,events:Object.values(n)}};class Ct{constructor(e,t){this.createHook=({eventsManager:e,sessionId:t,deviceIdFn:i,mirror:n,ugcFilterRules:r,performanceOptions:s})=>o=>{if(o.type!==Me.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=et(g,s)}catch(e){this.logger.debug("error resolving selector from finder")}const p=Ce(l.href,r),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 wt(){const e=f();return(null==e?void 0:e.innerHeight)||document.documentElement&&document.documentElement.clientHeight||0}function kt(){const e=f();return(null==e?void 0:e.innerWidth)||document.documentElement&&document.documentElement.clientWidth||0}class Pt{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=ge(t.serverZone,t.trackServerUrl),this.apiKey=t.apiKey,this.context=e}send(e,t){const{sessionId:i,type:n}=this.context,r=new URLSearchParams({device_id:e,session_id:String(i),type:String(n),api_key:this.apiKey}),s=`${this.basePageUrl}?${r.toString()}`;this.sendBeacon(s,t)||this.sendXhr(s,t)}}class Et{static default(e,t){return new Et(new Pt(e,t),t)}constructor(e,t){this.timestamp=Date.now(),this.hook=e=>{this.update(e)},this.send=e=>t=>{var i,n,r,s;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:wt(),viewportWidth:kt(),pageUrl:Ce(a.location.href,null!==(s=null===(r=this.config.interactionConfig)||void 0===r?void 0:r.ugcFilterRules)&&void 0!==s?s:[]),timestamp:this.timestamp,type:"scroll"}]})}},this._maxScrollX=0,this._maxScrollY=0,this._currentScrollX=0,this._currentScrollY=0,this._maxScrollWidth=kt(),this._maxScrollHeight=wt(),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=kt();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=wt();this._maxScrollY=e.y;const n=e.y+i;n>this._maxScrollHeight&&(this._maxScrollHeight=n),this.timestamp=t}}}class Ot{constructor({sessionId:e,deviceId:t}){this.deviceId=t,this.sessionId=e,e&&t&&(this.sessionReplayId=((e,t)=>`${t}/${e}`)(e,t))}}const Rt=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),r=yield e.get("sessionTargetingMatch",n);return null==r?void 0:r.targetingMatch}catch(t){Ae(e,`Failed to get targeting match for session id ${i}: ${t}`,t)}}),this.storeTargetingMatchForSession=({loggerProvider:e,apiKey:t,sessionId:i,targetingMatch:r})=>n(this,void 0,void 0,function*(){try{const e=yield this.openOrCreateDB(t),n=String(i);return yield e.put("sessionTargetingMatch",{targetingMatch:r,sessionId:n,lastUpdated:Date.now()})}catch(t){Ae(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),r=e.transaction("sessionTargetingMatch","readwrite"),s=yield r.store.getAll();for(let e=0;e<s.length;e++){const t=s[e],i=Date.now()-t.lastUpdated;t.sessionId!==n&&i>1728e5&&(yield r.store.delete(t.sessionId))}yield r.done}catch(t){Ae(e,`Failed to clear old targeting matches for sessions: ${t}`,t)}})}},Mt=2654435761,Tt=2246822519,xt=3266489917,_t=374761393;function Lt(e,t){return(e<<t|e>>>32-t)>>>0}function Ft(e,t){return e=Lt(e=e+Math.imul(t,Tt)>>>0,13),e=Math.imul(e,Mt)>>>0}function Dt(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function jt(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 r,s=0;if(n>=16){let e=t+Mt+Tt>>>0,o=t+Tt>>>0,a=t>>>0,l=t-Mt>>>0;for(;s<=n-16;)e=Ft(e,Dt(i,s)),s+=4,o=Ft(o,Dt(i,s)),s+=4,a=Ft(a,Dt(i,s)),s+=4,l=Ft(l,Dt(i,s)),s+=4;r=Lt(e,1)+Lt(o,7)+Lt(a,12)+Lt(l,18)>>>0}else r=t+_t>>>0;for(r=r+n>>>0;s<=n-4;)r=r+Math.imul(Dt(i,s),xt)>>>0,r=Math.imul(Lt(r,17),668265263)>>>0,s+=4;for(;s<n;)r=r+Math.imul(i[s],_t)>>>0,r=Math.imul(Lt(r,11),Mt)>>>0,s++;return r^=r>>>15,r=Math.imul(r,Tt)>>>0,r^=r>>>13,r=Math.imul(r,xt)>>>0,r^=r>>>16,r>>>0}const qt="__amplitude_url_tracking_patched__",$t=new WeakMap;function Ut(e,t,i={}){if(!(null==e?void 0:e.location))return()=>{};const{enablePolling:n=!1,pollingInterval:r=ne}=i;if(n){const i=()=>{var t;return null!==(t=e.location.href)&&void 0!==t?t:""};let n=i();const s=e.setInterval(()=>{const e=i();e!==n&&(n=e,t(e))},r);return()=>{null!=s&&e.clearInterval(s)}}let s=$t.get(e);if(!s){let t;const i=new Set,n=()=>{var t;return null!==(t=e.location.href)&&void 0!==t?t:""},r=()=>{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 r(),i};return t[qt]=!0,t},a=e.history;if(null==a?void 0:a.pushState){const e=Reflect.get(a,"pushState");e[qt]||(a.pushState=o(e))}if(null==a?void 0:a.replaceState){const e=Reflect.get(a,"replaceState");e[qt]||(a.replaceState=o(e))}s={callbacks:i,notify:r,onPopStateOrHashChange:()=>r(),listenersAttached:!1},$t.set(e,s)}const o=s;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 At(e={}){return{name:"amplitude/url-tracking@1",observer(t,i,n){var r,s,o;const a=Object.assign(Object.assign({},e),n),l=a.ugcFilterRules||[],c=null!==(r=a.enablePolling)&&void 0!==r&&r,d=null!==(s=a.pollingInterval)&&void 0!==s?s: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,r=g();let s="";return u&&(s=(null==n?void 0:n.title)||""),{href:l.length>0?Ce(r,l):r,title:s,viewportHeight:e,viewportWidth:t,type:"url-change-event"}})();t(n)}},f=Ut(i,()=>v(),c?{enablePolling:!0,pollingInterval:d}:{});return v(),()=>f()},options:e}}class Nt{constructor(){this.pendingLoadListeners=new Map}start(){var e;null===(e=this.mutationObserver)||void 0===e||e.disconnect();f()&&(this.sendToAllIframes({type:ce,action:"start"}),this.mutationObserver=new MutationObserver(e=>{for(const t of e){for(const e of Array.from(t.addedNodes))e instanceof HTMLIFrameElement?this.sendToIframeAfterLoad(e):e instanceof Element&&e.querySelectorAll("iframe").forEach(e=>{this.sendToIframeAfterLoad(e)});for(const e of Array.from(t.removedNodes))if(e instanceof HTMLIFrameElement){const t=this.pendingLoadListeners.get(e);t&&(e.removeEventListener("load",t),this.pendingLoadListeners.delete(e))}}}),this.mutationObserver.observe(document.documentElement,{childList:!0,subtree:!0}))}stop(){var e;null===(e=this.mutationObserver)||void 0===e||e.disconnect(),this.mutationObserver=void 0,this.pendingLoadListeners.forEach((e,t)=>{t.removeEventListener("load",e)}),this.pendingLoadListeners.clear(),this.sendToAllIframes({type:ce,action:"stop"})}sendToIframeAfterLoad(e){const t=()=>{this.pendingLoadListeners.delete(e),this.sendToIframe(e,{type:ce,action:"start"})};this.pendingLoadListeners.set(e,t),e.addEventListener("load",t,{once:!0})}sendToAllIframes(e){document.querySelectorAll("iframe").forEach(t=>this.sendToIframe(t,e))}sendToIframe(e,t){var i;try{null===(i=e.contentWindow)||void 0===i||i.postMessage(t,"*")}catch(e){}}}class Wt{constructor(){this.name="@amplitude/session-replay-browser",this.recordCancelCallback=null,this.eventCount=0,this.sessionTargetingMatch=!1,this.pageLeaveFns=[],this.recordFunction=null,this.recordEventsInFlight=!1,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=()=>{if(this.recordCancelCallback&&this.recordFunction)try{this.recordFunction.takeFullSnapshot(!0)}catch(e){this.loggerProvider.warn("Failed to take full snapshot on focus:",e)}else this.recordEventsInFlight||this.recordEvents(!1)},this.pageLeaveListener=e=>{this.pageLeaveFns.forEach(t=>{t(e)})},this.evaluateTargetingAndCapture=(e,t=!1,i=!1,r=!1)=>n(this,void 0,void 0,function*(){var s,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=r?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===(s=e.page)||void 0===s?void 0:s.url)&&void 0!==o?o:null===(l=null===(a=f())||void 0===a?void 0:a.location)||void 0===l?void 0:l.href)&&void 0!==c?c:"",v=null!==(u=e.page)&&void 0!==u?u:""!==g?{url:g}:void 0,p=yield(({sessionId:e,targetingConfig:t,loggerProvider:i,apiKey:r,targetingParams:s,urlChange:o=!1})=>n(void 0,void 0,void 0,function*(){if(yield Rt.clearStoreOfOldSessions({loggerProvider:i,apiKey:r,currentSessionId:e}),!0===(yield Rt.getTargetingMatchForSession({loggerProvider:i,apiKey:r,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({},s),{flag:t,sessionId:"string"==typeof e?parseInt(e,10):e,apiKey:r,loggerProvider:i}),l=yield o(a);l&&l.sr_targeting_config&&(n="on"===l.sr_targeting_config.key),Rt.storeTargetingMatchForSession({loggerProvider:i,apiKey:r,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:r});if(r&&void 0!==t&&t!==this.latestUrlChangeTargetingEvaluationId)return void this.loggerProvider.debug(`Ignoring stale URL-change targeting result #${t}; latest is #${this.latestUrlChangeTargetingEvaluationId}.`);this.sessionTargetingMatch=this.sessionTargetingMatch||p,this.loggerProvider.debug(JSON.stringify({name:"targeted replay capture config",sessionTargetingMatch:this.sessionTargetingMatch,event: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 r=this.config;if(r&&e!==de.METADATA&&(n={config:ke(r),version:qe},i)){const e=yield we();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 ue(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),r=Ut(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=()=>{r(),this.urlChangeCleanup=null}}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,r,s,o,a,l,c,d,u,h,g;return n(this,void 0,void 0,function*(){null===(i=this.urlChangeCleanup)||void 0===i||i.call(this),this.loggerProvider=new ue(t.loggerProvider||new S),Object.prototype.hasOwnProperty.call(t,"logLevel")&&this.loggerProvider.enable(t.logLevel),this.currentPageUrl=be(),this.identifiers=new Ot({sessionId:t.sessionId,deviceId:t.deviceId}),this.joinedConfigGenerator=yield((e,t)=>n(void 0,void 0,void 0,function*(){const i=new Ee(e,t),n=new z(e,i.loggerProvider,i.serverZone,t.configServerUrl);return new Te(n,i)}))(e,t);const{joinedConfig:v,localConfig:p,remoteConfig:m}=yield this.joinedConfigGenerator.generateJoinedConfig();if(this.config=v,this.setMetadata(t.sessionId,v,p,m,null===(r=t.version)||void 0===r?void 0:r.version,qe,null===(s=t.version)||void 0===s?void 0:s.type),this.pageLeaveFns=[],t.sessionId&&(null===(o=this.config.interactionConfig)||void 0===o?void 0:o.enabled)){const e=Et.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 Ct(this.loggerProvider,e)}const y=[];let b,I,{storeType:C}=this.config;"idb"!==C||(null===(a=f())||void 0===a?void 0:a.indexedDB)||(C="memory",this.loggerProvider.warn("Could not use preferred indexedDB storage, reverting to in memory option.")),this.loggerProvider.log(`Using ${C} for event storage.`);const w=f();if(this.config.useWebWorker&&w&&w.Worker){const{compressionScript:e,trackDestinationScript:t}=yield import("./worker-min.js");b=e,I=t}let k;try{k=yield Ge({config:this.config,type:"replay",storeType:C,trackDestinationWorkerScript:I}),y.push({name:"replay",manager:k})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating replay events manager: ${t.toString()}`)}if(null===(l=this.config.interactionConfig)||void 0===l?void 0:l.enabled){const e=this.config.interactionConfig.batch?It:St;try{const t=yield Ge({config:this.config,type:"interaction",minInterval:null!==(c=this.config.interactionConfig.trackEveryNms)&&void 0!==c?c:3e4,maxInterval:6e4,payloadBatcher:e,storeType:C,trackDestinationWorkerScript:I});y.push({name:"interaction",manager:t})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating interaction events manager: ${t.toString()}`)}}if(this.eventsManager=new Ze(...y),this.eventCompressor&&this.eventCompressor.terminate(),this.eventCompressor=new Fe(this.eventsManager,this.config,this.getDeviceId(),b,()=>this.sendEvents()),this.pageLeaveFns=[...this.pageLeaveFns,()=>{var e;if(!this.config||!(null===(e=this.identifiers)||void 0===e?void 0:e.sessionId)||!k)return;const t=k.getBeaconEvents();if(!t.length)return;const i=this.getDeviceId();i&&k.trackDestination.sendBeacon({events:t,sessionId:this.identifiers.sessionId,deviceId:i,apiKey:this.config.apiKey,serverZone:this.config.serverZone})}],yield this.initializeNetworkObservers(),null===(d=f())||void 0===d?void 0:d.opener){const e=X();!function(e,t){var i,n=e;if(!0!==n[V]){n[V]=!0;var r=null!==(i=null==t?void 0:t.scriptUrl)&&void 0!==i?i:"https://cdn.amplitude.com/libs/background-capture-1.0.0-alpha.3.js.gz",s=null,o=function(t,i){var n,r;"background-capture-complete"===t&&(null===(r=null===(n=e.logger)||void 0===n?void 0:n.debug)||void 0===r||r.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(r,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)"),s=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==s?void 0:s.close)||void 0===e||e.call(s),s=null})}}(e),e.setup(Object.assign({logger:this.loggerProvider},this.config.serverZone&&{endpoint:J[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!==(g=null===(h=null===(u=this.config.privacyConfig)||void 0===u?void 0:u.urlMaskLevels)||void 0===h?void 0:h.length)&&void 0!==g?g:0)>0)&&this.setupUrlChangeListener()})}setSessionId(e,t){return y(this.asyncSetSessionId(e,t))}asyncSetSessionId(e,t,i){var r;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 s=t||this.getDeviceId();if(this.identifiers=new Ot({sessionId:e,deviceId:s}),this.joinedConfigGenerator&&n){const{joinedConfig:e}=yield this.joinedConfigGenerator.generateJoinedConfig();this.config=e}(null===(r=this.config)||void 0===r?void 0:r.targetingConfig)?yield this.evaluateTargetingAndCapture({userProperties:null==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[re]=JSON.stringify({appHash:q(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;const i=e||(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId),n=this.getDeviceId();this.eventsManager&&i&&n&&this.eventsManager.sendCurrentSequenceEvents({sessionId:i,deviceId:n})}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),j.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,r=this.config.sampleRate,jt(n.toString())%1e6/1e6<r)?(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,r;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),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?fe(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 r=null==i?void 0:i.maskSelector;return r||void 0}getRecordingPlugins(e){var t,i,r,s,o,a;return n(this,void 0,void 0,function*(){const n=[];try{const e=At({ugcFilterRules:(null===(i=null===(t=this.config)||void 0===t?void 0:t.interactionConfig)||void 0===i?void 0:i.ugcFilterRules)||[],enablePolling:(null===(r=this.config)||void 0===r?void 0:r.enableUrlChangePolling)||!1,pollingInterval:null===(s=this.config)||void 0===s?void 0:s.urlChangePollingInterval,captureDocumentTitle:null===(o=this.config)||void 0===o?void 0:o.captureDocumentTitle});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,r,s,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=ge(n.serverZone,n.trackServerUrl),p=[oe,ae,le,v];null===(r=this.networkObservers)||void 0===r||r.start(e=>{p.some(t=>e.url.startsWith(t))||this.addCustomRRWebEvent(de.FETCH_REQUEST,e)},g);const{interactionConfig:m,loggingConfig:y}=n,b=(null==m?void 0:m.enabled)?{mouseInteraction:this.eventsManager&&(null===(s=this.clickHandler)||void 0===s?void 0:s.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),r=t&&function(){try{const e=f();return!!e&&e.parent!==e}catch(e){return!0}}();if(r&&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)===ce&&("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===Oe.Meta&&(e.data.href=Ce(e.data.href,S)),this.eventCompressor&&this.eventCompressor.enqueueEvent(e,u)},"Error while capturing replay: ")),{plugins:yield this.getRecordingPlugins(y),recordCrossOriginIframes:t})),t&&!r&&i&&(this.crossOriginIframeCoordinator||(this.crossOriginIframeCoordinator=new Nt),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){var r,s;const{privacyConfig:o}=e;return{emit:i,inlineStylesheet:e.shouldInlineStylesheet,hooks:t,maskAllInputs:!0,maskTextClass:se,blockClass:"amp-block",blockSelector:this.getBlockSelectors(),applyBackgroundColorToBlockedElements:e.applyBackgroundColorToBlockedElements,maskInputFn:me("input",o,()=>this.currentPageUrl),maskTextFn:me("text",o,()=>this.currentPageUrl),maskAttributeFn:ye(o,()=>this.currentPageUrl),maskTextSelector:this.getMaskTextSelectors(),recordCanvas:!1,captureAdoptedStyleSheets:e.captureAdoptedStyleSheets,slimDOMOptions:{script:null===(r=e.omitElementTags)||void 0===r?void 0:r.script,comment:null===(s=e.omitElementTags)||void 0===s?void 0:s.comment},errorHandler:e=>{const t=e;if(t.message.includes("insertRule")&&t.message.includes("CSSStyleSheet"))throw t;if(t._external_)throw t;return this.loggerProvider.warn(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,r,s,o){const a=(null==e?void 0:e.toString())?q(e.toString()):void 0;this.metadata={joinedConfig:t,localConfig:i,remoteConfig:n,sessionId:e,hashValue:a,sampleRate:t.sampleRate,replaySDKType:this.mapSDKType(o),replaySDKVersion:r,standaloneSDKType:"@amplitude/session-replay-browser",standaloneSDKVersion:s}}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 Bt=e=>()=>{const{config:t}=e,{loggerProvider:i,logLevel:n}=t||Pe();return{logger:i,logLevel:n}};var zt=(()=>{const e=new Wt;return{init:P(e.init.bind(e),"init",Bt(e)),evaluateTargetingAndCapture:P(e.evaluateTargetingAndCapture.bind(e),"evaluateTargetingAndRecord",Bt(e)),setSessionId:P(e.setSessionId.bind(e),"setSessionId",Bt(e)),getSessionId:P(e.getSessionId.bind(e),"getSessionId",Bt(e)),getSessionReplayProperties:P(e.getSessionReplayProperties.bind(e),"getSessionReplayProperties",Bt(e)),flush:P(e.flush.bind(e),"flush",Bt(e)),shutdown:P(e.shutdown.bind(e),"shutdown",Bt(e))}})();const{init:Ht,setSessionId:Kt,getSessionId:Jt,getSessionReplayProperties:Qt,flush:Gt,shutdown:Zt,evaluateTargetingAndCapture:Xt}=zt;export{ue as S,Jt as a,Qt as b,Zt as c,Xt as e,Gt as f,f as g,Ht as i,Kt as s};
2
2
  //# sourceMappingURL=index-min.js.map
Binary file