@amplitude/session-replay-browser 1.25.2-frustrationanalytics.0 → 1.25.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},e(t,n)};var t=function(){return t=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},t.apply(this,arguments)};function n(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{l(r.next(e))}catch(e){i(e)}}function a(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}l((r=r.apply(e,t||[])).next())}))}function r(e,t){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(l){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,r=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){i.label=a[1];break}if(6===a[0]&&i.label<o[1]){i.label=o[1],o=a;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(a);break}o[2]&&i.ops.pop(),i.trys.pop();continue}a=t.call(e,i)}catch(e){a=[6,e],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,l])}}}"function"==typeof SuppressedError&&SuppressedError;var o,i="".concat("AMP","_unsent"),s="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"}(o||(o={}));var a,l=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},c=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"}(a||(a={}));var u="Amplitude Logger ",d=function(){function e(){this.logLevel=a.None}return e.prototype.disable=function(){this.logLevel=a.None},e.prototype.enable=function(e){void 0===e&&(e=a.Warn),this.logLevel=e},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<a.Verbose||console.log("".concat(u,"[Log]: ").concat(e.join(" ")))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<a.Warn||console.warn("".concat(u,"[Warn]: ").concat(e.join(" ")))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<a.Error||console.error("".concat(u,"[Error]: ").concat(e.join(" ")))},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<a.Debug||console.log("".concat(u,"[Debug]: ").concat(e.join(" ")))},e}(),h=function(){return{flushMaxRetries:12,flushQueueSize:200,flushIntervalMillis:1e4,instanceName:"$default_instance",logLevel:a.Warn,loggerProvider:new d,offline:!1,optOut:!1,serverUrl:s,serverZone:"US",useBatch:!1}},f=function(){function e(e){var t,n,r,o;this._optOut=!1;var i=h();this.apiKey=e.apiKey,this.flushIntervalMillis=null!==(t=e.flushIntervalMillis)&&void 0!==t?t:i.flushIntervalMillis,this.flushMaxRetries=e.flushMaxRetries||i.flushMaxRetries,this.flushQueueSize=e.flushQueueSize||i.flushQueueSize,this.instanceName=e.instanceName||i.instanceName,this.loggerProvider=e.loggerProvider||i.loggerProvider,this.logLevel=null!==(n=e.logLevel)&&void 0!==n?n:i.logLevel,this.minIdLength=e.minIdLength,this.plan=e.plan,this.ingestionMetadata=e.ingestionMetadata,this.offline=void 0!==e.offline?e.offline:i.offline,this.optOut=null!==(r=e.optOut)&&void 0!==r?r:i.optOut,this.serverUrl=e.serverUrl,this.serverZone=e.serverZone||i.serverZone,this.storageProvider=e.storageProvider,this.transportProvider=e.transportProvider,this.useBatch=null!==(o=e.useBatch)&&void 0!==o?o:i.useBatch,this.loggerProvider.enable(this.logLevel);var s=g(e.serverUrl,e.serverZone,e.useBatch);this.serverZone=s.serverZone,this.serverUrl=s.serverUrl}return Object.defineProperty(e.prototype,"optOut",{get:function(){return this._optOut},set:function(e){this._optOut=e},enumerable:!1,configurable:!0}),e}(),v=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":s},g=function(e,t,n){if(void 0===e&&(e=""),void 0===t&&(t=h().serverZone),void 0===n&&(n=h().useBatch),e)return{serverUrl:e,serverZone:void 0};var r=["US","EU"].includes(t)?t:h().serverZone;return{serverZone:r,serverUrl:v(r,n)}},p=function(){function e(){}return e.prototype.getApplicationContext=function(){return{versionName:this.versionName,language:m(),platform:"Web",os:void 0,deviceModel:void 0}},e}(),m=function(){return"undefined"!=typeof navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||""},y=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}(),b=function(){return b=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},b.apply(this,arguments)};function S(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function w(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}"function"==typeof SuppressedError&&SuppressedError;var I=function(e,t){var n,r,o=typeof e;if(o!==typeof t)return!1;try{for(var i=S(["string","number","boolean","undefined"]),s=i.next();!s.done;s=i.next()){if(s.value===o)return e===t}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}if(null==e&&null==t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;var a=Array.isArray(e),l=Array.isArray(t);if(a!==l)return!1;if(!a||!l){var c=Object.keys(e).sort(),u=Object.keys(t).sort();if(!I(c,u))return!1;var d=!0;return Object.keys(e).forEach((function(n){I(e[n],t[n])||(d=!1)})),d}for(var h=0;h<e.length;h++)if(!I(e[h],t[h]))return!1;return!0};Object.entries||(Object.entries=function(e){for(var t=Object.keys(e),n=t.length,r=new Array(n);n--;)r[n]=[t[n],e[t[n]]];return r});var C,E=function(){function e(){this.identity={userProperties:{}},this.listeners=new Set}return e.prototype.editIdentity=function(){var e=this,t=b({},this.identity.userProperties),n=b(b({},this.identity),{userProperties:t});return{setUserId:function(e){return n.userId=e,this},setDeviceId:function(e){return n.deviceId=e,this},setUserProperties:function(e){return n.userProperties=e,this},setOptOut:function(e){return n.optOut=e,this},updateUserProperties:function(e){var t,r,o,i,s,a,l=n.userProperties||{};try{for(var c=S(Object.entries(e)),u=c.next();!u.done;u=c.next()){var d=w(u.value,2),h=d[0],f=d[1];switch(h){case"$set":try{for(var v=(o=void 0,S(Object.entries(f))),g=v.next();!g.done;g=v.next()){var p=w(g.value,2),m=p[0],y=p[1];l[m]=y}}catch(e){o={error:e}}finally{try{g&&!g.done&&(i=v.return)&&i.call(v)}finally{if(o)throw o.error}}break;case"$unset":try{for(var b=(s=void 0,S(Object.keys(f))),I=b.next();!I.done;I=b.next()){delete l[m=I.value]}}catch(e){s={error:e}}finally{try{I&&!I.done&&(a=b.return)&&a.call(b)}finally{if(s)throw s.error}}break;case"$clearAll":l={}}}}catch(e){t={error:e}}finally{try{u&&!u.done&&(r=c.return)&&r.call(c)}finally{if(t)throw t.error}}return n.userProperties=l,this},commit:function(){return e.setIdentity(n),this}}},e.prototype.getIdentity=function(){return b({},this.identity)},e.prototype.setIdentity=function(e){var t=b({},this.identity);this.identity=b({},e),I(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}(),k="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:self,x=function(){function e(){this.identityStore=new E,this.eventBridge=new y,this.applicationContextProvider=new p}return e.getInstance=function(t){return k.analyticsConnectorInstances||(k.analyticsConnectorInstances={}),k.analyticsConnectorInstances[t]||(k.analyticsConnectorInstances[t]=new e),k.analyticsConnectorInstances[t]},e}(),_=function(){function e(){}return e.prototype.send=function(e,t){return Promise.resolve(null)},e.prototype.buildResponse=function(e){var t,n,r,i,s,a,l,c,u,d,h,f,v,g,p,m,y,b,S,w,I,C;if("object"!=typeof e)return null;var E=e.code||0,k=this.buildStatus(E);switch(k){case o.Success:return{status:k,statusCode:E,body:{eventsIngested:null!==(t=e.events_ingested)&&void 0!==t?t:0,payloadSizeBytes:null!==(n=e.payload_size_bytes)&&void 0!==n?n:0,serverUploadTime:null!==(r=e.server_upload_time)&&void 0!==r?r:0}};case o.Invalid:return{status:k,statusCode:E,body:{error:null!==(i=e.error)&&void 0!==i?i:"",missingField:null!==(s=e.missing_field)&&void 0!==s?s:"",eventsWithInvalidFields:null!==(a=e.events_with_invalid_fields)&&void 0!==a?a:{},eventsWithMissingFields:null!==(l=e.events_with_missing_fields)&&void 0!==l?l:{},eventsWithInvalidIdLengths:null!==(c=e.events_with_invalid_id_lengths)&&void 0!==c?c:{},epsThreshold:null!==(u=e.eps_threshold)&&void 0!==u?u: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!==(f=e.silenced_events)&&void 0!==f?f:[],throttledDevices:null!==(v=e.throttled_devices)&&void 0!==v?v:{},throttledEvents:null!==(g=e.throttled_events)&&void 0!==g?g:[]}};case o.PayloadTooLarge:return{status:k,statusCode:E,body:{error:null!==(p=e.error)&&void 0!==p?p:""}};case o.RateLimit:return{status:k,statusCode:E,body:{error:null!==(m=e.error)&&void 0!==m?m:"",epsThreshold:null!==(y=e.eps_threshold)&&void 0!==y?y:0,throttledDevices:null!==(b=e.throttled_devices)&&void 0!==b?b:{},throttledUsers:null!==(S=e.throttled_users)&&void 0!==S?S:{},exceededDailyQuotaDevices:null!==(w=e.exceeded_daily_quota_devices)&&void 0!==w?w:{},exceededDailyQuotaUsers:null!==(I=e.exceeded_daily_quota_users)&&void 0!==I?I:{},throttledEvents:null!==(C=e.throttled_events)&&void 0!==C?C:[]}};case o.Timeout:default:return{status:k,statusCode:E}}},e.prototype.buildStatus=function(e){return e>=200&&e<300?o.Success:429===e?o.RateLimit:413===e?o.PayloadTooLarge:408===e?o.Timeout:e>=400&&e<500?o.Invalid:e>=500?o.Failed:o.Unknown},e}(),P=function(t){function o(){return null!==t&&t.apply(this,arguments)||this}return function(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}(o,t),o.prototype.send=function(e,t){return n(this,void 0,void 0,(function(){var n,o,i;return r(this,(function(r){switch(r.label){case 0:if("undefined"==typeof fetch)throw new Error("FetchTransport is not supported");return n={headers:{"Content-Type":"application/json",Accept:"*/*"},body:JSON.stringify(t),method:"POST"},[4,fetch(e,n)];case 1:return[4,(o=r.sent()).text()];case 2:i=r.sent();try{return[2,this.buildResponse(JSON.parse(i))]}catch(e){return[2,this.buildResponse({code:o.status})]}return[2]}}))}))},o}(_);!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}(C||(C={}));var O,R,T=(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))(T||{}),q=(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))(q||{});!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}(O||(O={})),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"}(R||(R={}));var M=function(){function e(){}return e.prototype.send=function(e,t){return Promise.resolve(null)},e.prototype.buildResponse=function(e){var t,n,r,o,i,s,a,l,c,u,d,h,f,v,g,p,m,y,b,S,w,I;if("object"!=typeof e)return null;var C=e.code||0,E=this.buildStatus(C);switch(E){case R.Success:return{status:E,statusCode:C,body:{eventsIngested:null!==(t=e.events_ingested)&&void 0!==t?t:0,payloadSizeBytes:null!==(n=e.payload_size_bytes)&&void 0!==n?n:0,serverUploadTime:null!==(r=e.server_upload_time)&&void 0!==r?r:0}};case R.Invalid:return{status:E,statusCode:C,body:{error:null!==(o=e.error)&&void 0!==o?o:"",missingField:null!==(i=e.missing_field)&&void 0!==i?i:"",eventsWithInvalidFields:null!==(s=e.events_with_invalid_fields)&&void 0!==s?s:{},eventsWithMissingFields:null!==(a=e.events_with_missing_fields)&&void 0!==a?a:{},eventsWithInvalidIdLengths:null!==(l=e.events_with_invalid_id_lengths)&&void 0!==l?l:{},epsThreshold:null!==(c=e.eps_threshold)&&void 0!==c?c:0,exceededDailyQuotaDevices:null!==(u=e.exceeded_daily_quota_devices)&&void 0!==u?u:{},silencedDevices:null!==(d=e.silenced_devices)&&void 0!==d?d:[],silencedEvents:null!==(h=e.silenced_events)&&void 0!==h?h:[],throttledDevices:null!==(f=e.throttled_devices)&&void 0!==f?f:{},throttledEvents:null!==(v=e.throttled_events)&&void 0!==v?v:[]}};case R.PayloadTooLarge:return{status:E,statusCode:C,body:{error:null!==(g=e.error)&&void 0!==g?g:""}};case R.RateLimit:return{status:E,statusCode:C,body:{error:null!==(p=e.error)&&void 0!==p?p:"",epsThreshold:null!==(m=e.eps_threshold)&&void 0!==m?m:0,throttledDevices:null!==(y=e.throttled_devices)&&void 0!==y?y:{},throttledUsers:null!==(b=e.throttled_users)&&void 0!==b?b:{},exceededDailyQuotaDevices:null!==(S=e.exceeded_daily_quota_devices)&&void 0!==S?S:{},exceededDailyQuotaUsers:null!==(w=e.exceeded_daily_quota_users)&&void 0!==w?w:{},throttledEvents:null!==(I=e.throttled_events)&&void 0!==I?I:[]}};case R.Timeout:default:return{status:E,statusCode:C}}},e.prototype.buildStatus=function(e){return e>=200&&e<300?R.Success:429===e?R.RateLimit:413===e?R.PayloadTooLarge:408===e?R.Timeout:e>=400&&e<500?R.Invalid:e>=500?R.Failed:R.Unknown},e}(),L="Remote config fetch rejected due to timeout after 5 seconds",D="Unexpected error occurred",j=function(){function e(e){var o=e.localConfig,i=e.configKeys,s=this;this.retryTimeout=1e3,this.attempts=0,this.sessionTargetingMatch=!1,this.metrics={},this.getRemoteConfig=function(e,t,o){return n(s,void 0,void 0,(function(){var n,i,s;return r(this,(function(r){switch(r.label){case 0:return n=Date.now(),[4,this.fetchWithTimeout(o)];case 1:return(i=r.sent())&&(s=i.configs&&i.configs[e])?(this.metrics.fetchTimeAPISuccess=Date.now()-n,[2,s[t]]):(this.metrics.fetchTimeAPIFail=Date.now()-n,[2,void 0])}}))}))},this.fetchWithTimeout=function(e){return n(s,void 0,void 0,(function(){var t,n,o;return r(this,(function(r){switch(r.label){case 0:return t=new AbortController,n=setTimeout((function(){return t.abort()}),5e3),[4,this.fetchRemoteConfig(t.signal,e)];case 1:return o=r.sent(),clearTimeout(n),[2,o]}}))}))},this.fetchRemoteConfig=function(e,o){return n(s,void 0,void 0,(function(){var n,i,s,a,l,c,u,d,h,f,v,g;return r(this,(function(r){switch(r.label){case 0:if(o===this.lastFetchedSessionId&&this.attempts>=this.localConfig.flushMaxRetries)return[2,this.completeRequest({err:"Remote config fetch rejected due to exceeded retry count"})];if(e.aborted)return[2,this.completeRequest({err:L})];o!==this.lastFetchedSessionId&&(this.lastFetchedSessionId=o,this.attempts=0),r.label=1;case 1:r.trys.push([1,3,,4]),n=new URLSearchParams({api_key:this.localConfig.apiKey});try{for(i=function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(this.configKeys),s=i.next();!s.done;s=i.next())a=s.value,n.append("config_keys",a)}catch(e){f={error:e}}finally{try{s&&!s.done&&(v=i.return)&&v.call(i)}finally{if(f)throw f.error}}return o&&n.set("session_id",String(o)),l={headers:{Accept:"*/*"},method:"GET"},c="".concat(this.getServerUrl(),"?").concat(n.toString()),this.attempts+=1,[4,fetch(c,t(t({},l),{signal:e}))];case 2:if(null===(u=r.sent()))return[2,this.completeRequest({err:D})];switch((new M).buildStatus(u.status)){case R.Success:return this.attempts=0,[2,this.parseAndStoreConfig(u)];case R.Failed:return[2,this.retryFetch(e,o)];default:return[2,this.completeRequest({err:"Network error occurred, remote config fetch failed"})]}case 3:return d=r.sent(),h=d,e.aborted?[2,this.completeRequest({err:L})]:[2,this.completeRequest({err:null!==(g=h.message)&&void 0!==g?g:D})];case 4:return[2]}}))}))},this.retryFetch=function(e,t){return n(s,void 0,void 0,(function(){var n=this;return r(this,(function(r){switch(r.label){case 0:return[4,new Promise((function(e){return setTimeout(e,n.attempts*n.retryTimeout)}))];case 1:return r.sent(),[2,this.fetchRemoteConfig(e,t)]}}))}))},this.parseAndStoreConfig=function(e){return n(s,void 0,void 0,(function(){var t;return r(this,(function(n){switch(n.label){case 0:return[4,e.json()];case 1:return t=n.sent(),this.completeRequest({success:"Remote config successfully fetched"}),[2,t]}}))}))},this.localConfig=o,this.configKeys=i}return e.prototype.getServerUrl=function(){return this.localConfig.configServerUrl?this.localConfig.configServerUrl:this.localConfig.serverZone===O.STAGING?"https://sr-client-cfg.stag2.amplitude.com/config":this.localConfig.serverZone===O.EU?"https://sr-client-cfg.eu.amplitude.com/config":"https://sr-client-cfg.amplitude.com/config"},e.prototype.completeRequest=function(e){var t=e.err,n=e.success;if(t)throw new Error(t);n&&this.localConfig.loggerProvider.log(n)},e}(),N=function(e){var t=e.localConfig,o=e.configKeys;return n(void 0,void 0,void 0,(function(){return r(this,(function(e){return[2,new j({localConfig:t,configKeys:o})]}))}))};const $="medium",U="[Amplitude]",B=`${U} Session Replay ID`,F=C.US,A=`${U} Session Replay Debug`,K="amp-mask";var W;!function(e){e.GET_SR_PROPS="get-sr-props",e.DEBUG_INFO="debug-info",e.FETCH_REQUEST="fetch-request",e.METADATA="metadata"}(W||(W={}));const z=(e,t,n)=>{switch(t){case"light":{if("input"!==e)return!0;const t=n?function(e){const t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?t.toLowerCase():null}(n):"";return!!t&&(!!["password","hidden","email","tel"].includes(t)||!!n.autocomplete.startsWith("cc-"))}case"medium":case"conservative":return!0;default:return z(e,$,n)}},G=(e,t)=>(n,r)=>((e,t={defaultMaskLevel:$},n)=>{var r,o,i;if(n){if(n.closest("."+K))return!0;const e=(null!==(r=t.maskSelector)&&void 0!==r?r:[]).some((e=>n.closest(e)));if(e)return!0;if(n.closest(".amp-unmask"))return!1;const i=(null!==(o=t.unmaskSelector)&&void 0!==o?o:[]).some((e=>n.closest(e)));if(i)return!1}return z(e,null!==(i=t.defaultMaskLevel)&&void 0!==i?i:$,n)})(e,t,r)?n.replace(/[^\s]/g,"*"):n,Q=function(e){let t=0;if(0===e.length)return t;for(let n=0;n<e.length;n++){t=(t<<5)-t+e.charCodeAt(n),t|=0}return t},H=(e,t)=>t||(e===C.STAGING?"https://api-sr.stag2.amplitude.com/sessions/v2/track":e===C.EU?"https://api-sr.eu.amplitude.com/sessions/v2/track":"https://api-sr.amplitude.com/sessions/v2/track"),J=e=>{const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${t}$`)},V=(e,t)=>{for(const n of t){const t=J(n.selector);if(t.test(e))return e.replace(t,n.replacement)}return e},Z=()=>n(void 0,void 0,void 0,(function*(){try{const e=l();if(e){const{usage:t,quota:n,usageDetails:r}=yield e.navigator.storage.estimate(),o=t?Math.round(t/1024):0;return{totalStorageSize:o,percentOfQuota:t&&n?Math.round(1e3*(t/n+Number.EPSILON))/1e3:0,usageDetails:JSON.stringify(r)}}}catch(e){}return{totalStorageSize:0,percentOfQuota:0,usageDetails:""}})),X=e=>{const t=Object.assign({},e),{apiKey:n}=t;return t.apiKey=`****${n.substring(n.length-4)}`,t};class Y{constructor(e){this.logger=e,this.log=this.getSafeMethod("log"),this.warn=this.getSafeMethod("warn"),this.error=this.getSafeMethod("error"),this.debug=this.getSafeMethod("debug")}getSafeMethod(e){var t;if(!this.logger)return()=>{};const n=this.logger[e];if("function"==typeof n){return(null!==(t=n.__rrweb_original__)&&void 0!==t?t:n).bind(this.logger)}return()=>{}}enable(e){this.logger.enable(e)}disable(){this.logger.disable()}}class ee extends f{constructor(e,t){var n,r;const o={flushMaxRetries:2,logLevel:a.Warn,loggerProvider:new d,transportProvider:new P};super(Object.assign(Object.assign({transportProvider:o.transportProvider,loggerProvider:new Y(t.loggerProvider||o.loggerProvider)},t),{apiKey:e})),this.flushMaxRetries=void 0!==t.flushMaxRetries&&t.flushMaxRetries<=o.flushMaxRetries?t.flushMaxRetries:o.flushMaxRetries,this.apiKey=e,this.sampleRate=t.sampleRate||0,this.serverZone=t.serverZone||F,this.configServerUrl=t.configServerUrl,this.trackServerUrl=t.trackServerUrl,this.shouldInlineStylesheet=t.shouldInlineStylesheet,this.version=t.version,this.performanceConfig=t.performanceConfig,this.storeType=null!==(n=t.storeType)&&void 0!==n?n:"idb",this.applyBackgroundColorToBlockedElements=null!==(r=t.applyBackgroundColorToBlockedElements)&&void 0!==r&&r,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),t.experimental&&(this.experimental=t.experimental)}}class te{constructor(e,t){this.localConfig=t,this.remoteConfigFetch=e}generateJoinedConfig(e){var t,r,o,i;return n(this,void 0,void 0,(function*(){const n=Object.assign({},this.localConfig);let s;n.optOut=this.localConfig.optOut,n.captureEnabled=!0;try{const r=yield this.remoteConfigFetch.getRemoteConfig("sessionReplay","sr_sampling_config",e),o=yield this.remoteConfigFetch.getRemoteConfig("sessionReplay","sr_privacy_config",e),i=null===(t=n.interactionConfig)||void 0===t?void 0:t.ugcFilterRules;n.interactionConfig=yield this.remoteConfigFetch.getRemoteConfig("sessionReplay","sr_interaction_config",e),n.interactionConfig&&i&&(n.interactionConfig.ugcFilterRules=i),n.loggingConfig=yield this.remoteConfigFetch.getRemoteConfig("sessionReplay","sr_logging_config",e),(r||o)&&(s={},r&&(s.sr_sampling_config=r),o&&(s.sr_privacy_config=o))}catch(e){const t=e;this.localConfig.loggerProvider.warn(t.message),n.captureEnabled=!1}if(!s)return{localConfig:this.localConfig,joinedConfig:n,remoteConfig:s};const{sr_sampling_config:a,sr_privacy_config:l}=s;if(a&&Object.keys(a).length>0?(Object.prototype.hasOwnProperty.call(a,"capture_enabled")?n.captureEnabled=a.capture_enabled:n.captureEnabled=!1,Object.prototype.hasOwnProperty.call(a,"sample_rate")&&(n.sampleRate=a.sample_rate)):(n.captureEnabled=!0,this.localConfig.loggerProvider.debug("Remote config successfully fetched, but no values set for project, Session Replay capture enabled.")),l){const e=null!==(r=n.privacyConfig)&&void 0!==r?r:{},t={defaultMaskLevel:null!==(i=null!==(o=l.defaultMaskLevel)&&void 0!==o?o:e.defaultMaskLevel)&&void 0!==i?i:"medium",blockSelector:[],maskSelector:[],unmaskSelector:[]},s=e=>{var t,n,r;const o={};"string"==typeof e.blockSelector&&(e.blockSelector=[e.blockSelector]);for(const n of null!==(t=e.blockSelector)&&void 0!==t?t:[])o[n]="block";for(const t of null!==(n=e.maskSelector)&&void 0!==n?n:[])o[t]="mask";for(const t of null!==(r=e.unmaskSelector)&&void 0!==r?r:[])o[t]="unmask";return o},a=Object.assign(Object.assign({},s(e)),s(l));for(const[e,n]of Object.entries(a))"mask"===n?t.maskSelector.push(e):"block"===n?t.blockSelector.push(e):"unmask"===n&&t.unmaskSelector.push(e);n.privacyConfig=((e,t)=>{const n=document.createDocumentFragment(),r=(e=[])=>{if("string"==typeof e&&(e=[e]),e=e.filter((e=>{try{n.querySelector(e)}catch(n){return t.warn(`[session-replay-browser] omitting selector "${e}" because it is invalid`),!1}return!0})),0!==e.length)return e};return e.blockSelector=r(e.blockSelector),e.maskSelector=r(e.maskSelector),e.unmaskSelector=r(e.unmaskSelector),e})(t,this.localConfig.loggerProvider)}return this.localConfig.loggerProvider.debug(JSON.stringify({name:"session replay joined config",config:X(n)},null,2)),{localConfig:this.localConfig,joinedConfig:n,remoteConfig:s}}))}}const ne="Failed to store session replay events in IndexedDB",re="1.25.2-frustrationanalytics.0";class oe{constructor({trackServerUrl:e,loggerProvider:t,payloadBatcher:n}){this.storageKey="",this.retryTimeout=1e3,this.scheduled=null,this.queue=[],this.loggerProvider=t,this.payloadBatcher=n||(e=>e),this.trackServerUrl=e}sendEventsList(e){this.addToQueue(Object.assign(Object.assign({},e),{attempts:0,timeout:0}))}addToQueue(...e){e.filter((e=>e.attempts<(e.flushMaxRetries||0)?(e.attempts+=1,!0):(this.completeRequest({context:e,err:"Session replay event batch rejected due to exceeded retry count"}),!1))).forEach((e=>{this.queue=this.queue.concat(e),0!==e.timeout?setTimeout((()=>{e.timeout=0,this.schedule(0)}),e.timeout):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=[],n=[];this.queue.forEach((e=>0===e.timeout?t.push(e):n.push(e))),this.queue=n,this.scheduled&&(clearTimeout(this.scheduled),this.scheduled=null),yield Promise.all(t.map((t=>this.send(t,e))))}))}send(e,t=!0){var r,o;return n(this,void 0,void 0,(function*(){const n=e.apiKey;if(!n)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing api key"});const i=e.deviceId;if(!i)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing device ID"});const s=(()=>{const e=l();return(null==e?void 0:e.location)?e.location.href:""})(),a=re,c=e.sampleRate,u=new URLSearchParams({device_id:i,session_id:`${e.sessionId}`,type:`${e.type}`}),d=`${(null===(r=e.version)||void 0===r?void 0:r.type)||"standalone"}/${(null===(o=e.version)||void 0===o?void 0:o.version)||a}`,h=this.payloadBatcher({version:1,events:e.events});if(0!==h.events.length)try{const r={headers:{"Content-Type":"application/json",Accept:"*/*",Authorization:`Bearer ${n}`,"X-Client-Version":a,"X-Client-Library":d,"X-Client-Url":s.substring(0,1e3),"X-Client-Sample-Rate":`${c}`},body:JSON.stringify(h),method:"POST"},o=`${H(e.serverZone,this.trackServerUrl)}?${u.toString()}`,i=yield fetch(o,r);if(null===i)return void this.completeRequest({context:e,err:"Unexpected error occurred"});if(t)this.handleReponse(i.status,e);else{let t="";try{t=JSON.stringify(i.body,null,2)}catch(e){}this.completeRequest({context:e,success:`${i.status}: ${t}`})}}catch(t){this.completeRequest({context:e,err:t})}else this.completeRequest({context:e})}))}handleReponse(e,t){switch((new _).buildStatus(e)){case o.Success:this.handleSuccessResponse(t);break;case o.Failed:this.handleOtherResponse(t);break;default: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){this.addToQueue(Object.assign(Object.assign({},e),{timeout:e.attempts*this.retryTimeout}))}completeRequest({context:e,err:t,success:n}){e.onComplete(),t?this.loggerProvider.warn(t):n&&this.loggerProvider.log(n)}}const ie=(e,t)=>t.some((t=>e instanceof t));let se,ae;const le=new WeakMap,ce=new WeakMap,ue=new WeakMap;let de={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return le.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return ge(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function he(e){de=e(de)}function fe(e){return(ae||(ae=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(pe(this),t),ge(this.request)}:function(...t){return ge(e.apply(pe(this),t))}}function ve(e){return"function"==typeof e?fe(e):(e instanceof IDBTransaction&&function(e){if(le.has(e))return;const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("complete",o),e.removeEventListener("error",i),e.removeEventListener("abort",i)},o=()=>{t(),r()},i=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",o),e.addEventListener("error",i),e.addEventListener("abort",i)}));le.set(e,t)}(e),ie(e,se||(se=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,de):e)}function ge(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("success",o),e.removeEventListener("error",i)},o=()=>{t(ge(e.result)),r()},i=()=>{n(e.error),r()};e.addEventListener("success",o),e.addEventListener("error",i)}));return ue.set(t,e),t}(e);if(ce.has(e))return ce.get(e);const t=ve(e);return t!==e&&(ce.set(e,t),ue.set(t,e)),t}const pe=e=>ue.get(e);const me=["get","getKey","getAll","getAllKeys","count"],ye=["put","add","delete","clear"],be=new Map;function Se(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(be.get(t))return be.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,o=ye.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!o&&!me.includes(n))return;const i=async function(e,...t){const i=this.transaction(e,o?"readwrite":"readonly");let s=i.store;return r&&(s=s.index(t.shift())),(await Promise.all([s[n](...t),o&&i.done]))[0]};return be.set(t,i),i}he((e=>({...e,get:(t,n,r)=>Se(t,n)||e.get(t,n,r),has:(t,n)=>!!Se(t,n)||e.has(t,n)})));const we=["continue","continuePrimaryKey","advance"],Ie={},Ce=new WeakMap,Ee=new WeakMap,ke={get(e,t){if(!we.includes(t))return e[t];let n=Ie[t];return n||(n=Ie[t]=function(...e){Ce.set(this,Ee.get(this)[t](...e))}),n}};async function*xe(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const n=new Proxy(t,ke);for(Ee.set(n,t),ue.set(n,pe(t));t;)yield n,t=await(Ce.get(n)||t.continue()),Ce.delete(n)}function _e(e,t){return t===Symbol.asyncIterator&&ie(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&ie(e,[IDBIndex,IDBObjectStore])}he((e=>({...e,get:(t,n,r)=>_e(t,n)?xe:e.get(t,n,r),has:(t,n)=>_e(t,n)||e.has(t,n)})));class Pe{get timeAtLastSplit(){return this._timeAtLastSplit}constructor(e){var t,n,r;this.minInterval=500,this.maxInterval=1e4,this.maxPersistedEventsSize=1e6,this.interval=this.minInterval,this._timeAtLastSplit=Date.now(),this.shouldSplitEventsList=(e,t)=>{const n=new Blob([t]).size;return new Blob(e).size+n>=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!==(n=e.maxInterval)&&void 0!==n?n:this.maxInterval,this.maxPersistedEventsSize=null!==(r=e.maxPersistedEventsSize)&&void 0!==r?r:this.maxPersistedEventsSize}}var Oe;!function(e){e.RECORDING="recording",e.SENT="sent"}(Oe||(Oe={}));const Re="sessionCurrentSequence",Te="sequencesToSend",qe=e=>n(void 0,void 0,void 0,(function*(){for(;e.length>0;){const t=10,n=e.splice(0,t);yield Promise.all(n)}})),Me=e=>{let t,n;return e.objectStoreNames.contains(Re)||(n=e.createObjectStore(Re,{keyPath:"sessionId"})),e.objectStoreNames.contains(Te)||(t=e.createObjectStore(Te,{keyPath:"sequenceId",autoIncrement:!0}),t.createIndex("sessionId","sessionId")),{sequencesStore:t,currentSequenceStore:n}},Le=e=>n(void 0,void 0,void 0,(function*(){return yield function(e,t,{blocked:n,upgrade:r,blocking:o,terminated:i}={}){const s=indexedDB.open(e,t),a=ge(s);return r&&s.addEventListener("upgradeneeded",(e=>{r(ge(s.result),e.oldVersion,e.newVersion,ge(s.transaction),e)})),n&&s.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),a.then((e=>{i&&e.addEventListener("close",(()=>i())),o&&e.addEventListener("versionchange",(e=>o(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),a}(e,1,{upgrade:Me})}));class De extends Pe{constructor(e){super(e),this.getSequencesToSend=()=>n(this,void 0,void 0,(function*(){try{const e=[];let t=yield this.db.transaction("sequencesToSend").store.openCursor();for(;t;){const{sessionId:n,events:r}=t.value;e.push({events:r,sequenceId:t.key,sessionId:n}),t=yield t.continue()}return e}catch(e){this.loggerProvider.warn(`${ne}: ${e}`)}})),this.storeCurrentSequence=e=>n(this,void 0,void 0,(function*(){try{const t=yield this.db.get(Re,e);if(!t)return;const n=yield this.db.put(Te,{sessionId:e,events:t.events});return yield this.db.put(Re,{sessionId:e,events:[]}),Object.assign(Object.assign({},t),{sessionId:e,sequenceId:n})}catch(e){this.loggerProvider.warn(`${ne}: ${e}`)}})),this.addEventToCurrentSequence=(e,t)=>n(this,void 0,void 0,(function*(){try{const n=this.db.transaction(Re,"readwrite"),r=yield n.store.get(e);if(!r)return void(yield n.store.put({sessionId:e,events:[t]}));let o;if(this.shouldSplitEventsList(r.events,t))o=r.events,yield n.store.put({sessionId:e,events:[t]});else{const o=r.events.concat(t);yield n.store.put({sessionId:e,events:o})}if(yield n.done,!o)return;const i=yield this.storeSendingEvents(e,o);if(!i)return;return{events:o,sessionId:e,sequenceId:i}}catch(e){this.loggerProvider.warn(`${ne}: ${e}`)}})),this.storeSendingEvents=(e,t)=>n(this,void 0,void 0,(function*(){try{return yield this.db.put(Te,{sessionId:e,events:t})}catch(e){this.loggerProvider.warn(`${ne}: ${e}`)}})),this.cleanUpSessionEventsStore=(e,t)=>n(this,void 0,void 0,(function*(){if(t)try{yield this.db.delete(Te,t)}catch(e){this.loggerProvider.warn(`${ne}: ${e}`)}})),this.transitionFromKeyValStore=e=>n(this,void 0,void 0,(function*(){try{const t=yield function(){const e=l();return new Promise(((t,n)=>{if(!e)return n(new Error("Global scope not found"));if(!e.indexedDB)return n(new Error("Session Replay: cannot find indexedDB"));try{const r=e.indexedDB.open("keyval-store");r.onupgradeneeded=function(){1===r.result.version&&(r.result.close(),r.transaction&&r.transaction.abort(),e.indexedDB.deleteDatabase("keyval-store"),t())},r.onsuccess=function(){t(r.result)},r.onerror=function(){n(r.error)}}catch(e){n(e)}}))}();if(!t)return;const r=(e,t)=>n(this,void 0,void 0,(function*(){const r=t.sessionSequences,o=[];Object.keys(r).forEach((i=>{const s=parseInt(i,10),a=r[s];if(s===t.currentSequenceId){const t=a.events.map((t=>n(this,void 0,void 0,(function*(){return this.addEventToCurrentSequence(e,t)}))));o.push(...t)}else a.status!==Oe.SENT&&o.push(this.storeSendingEvents(e,a.events))})),yield qe(o)})),o=`${i}_${this.apiKey.substring(0,10)}`;try{const i=t.transaction("keyval").objectStore("keyval").getAll(o),s=new Promise((t=>{i.onsuccess=o=>n(this,void 0,void 0,(function*(){const n=o&&o.target.result,i=n&&n[0];if(i){const t=[];Object.keys(i).forEach((n=>{const o=parseInt(n,10),s=i[o];if(e===o)t.push(r(o,s));else{const e=s.sessionSequences;Object.keys(e).forEach((n=>{const r=parseInt(n,10);e[r].status!==Oe.SENT&&t.push(this.storeSendingEvents(o,e[r].events))}))}})),yield qe(t)}t()}))}));yield s;const a=l();a&&a.indexedDB.deleteDatabase("keyval-store")}catch(e){this.loggerProvider.warn(`Failed to transition session replay events from keyval to new store: ${e}`)}}catch(e){this.loggerProvider.warn(`Failed to access keyval store: ${e}. For more information, visit: https://www.docs.developers.amplitude.com/session-replay/sdks/standalone/#indexeddb-best-practices`)}})),this.apiKey=e.apiKey,this.db=e.db}static new(e,t,r){return n(this,void 0,void 0,(function*(){try{const n="replay"===e?"":`_${e}`,o=`${t.apiKey.substring(0,10)}_amp_session_replay_events${n}`,i=yield Le(o),s=new De(Object.assign(Object.assign({},t),{db:i}));return yield s.transitionFromKeyValStore(r),s}catch(e){t.loggerProvider.warn(`${ne}: ${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 je extends Pe{constructor(){super(...arguments),this.finalizedSequences={},this.sequences={},this.sequenceId=0}resetCurrentSequence(e){this.sequences[e]=[]}addSequence(e){const t=this.sequenceId++,n=[...this.sequences[e]];return this.finalizedSequences[t]={sessionId:e,events:n},this.resetCurrentSequence(e),{sequenceId:t,events:n,sessionId:e}}getSequencesToSend(){return n(this,void 0,void 0,(function*(){return Object.entries(this.finalizedSequences).map((([e,{sessionId:t,events:n}])=>({sequenceId:Number(e),sessionId:t,events:n})))}))}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 n;return this.sequences[e]||this.resetCurrentSequence(e),this.shouldSplitEventsList(this.sequences[e],t)&&(n=this.addSequence(e)),this.sequences[e].push(t),n}))}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 Ne=({config:e,sessionId:t,minInterval:r,maxInterval:o,type:i,payloadBatcher:s,storeType:a})=>n(void 0,void 0,void 0,(function*(){const l=new oe(Object.assign(Object.assign({},e),{loggerProvider:e.loggerProvider,payloadBatcher:s})),c=()=>new je({loggerProvider:e.loggerProvider,maxInterval:o,minInterval:r}),u="idb"===a?yield n(void 0,void 0,void 0,(function*(){const n=yield De.new(i,{loggerProvider:e.loggerProvider,minInterval:r,maxInterval:o,apiKey:e.apiKey},t);return e.loggerProvider.log("Failed to initialize idb store, falling back to memory store."),null!=n?n:c()})):c(),d=({events:t,sessionId:r,deviceId:o,sequenceId:s})=>{e.debugMode&&Z().then((({totalStorageSize:t,percentOfQuota:n,usageDetails:r})=>{e.loggerProvider.debug(`Total storage size: ${t} KB, percentage of quota: ${n}%, usage details: ${r}`)})).catch((()=>{})),l.sendEventsList({events:t,sessionId:r,flushMaxRetries:e.flushMaxRetries,apiKey:e.apiKey,deviceId:o,sampleRate:e.sampleRate,serverZone:e.serverZone,version:e.version,type:i,onComplete:()=>n(void 0,void 0,void 0,(function*(){yield u.cleanUpSessionEventsStore(r,s)}))})};return{sendCurrentSequenceEvents:({sessionId:t,deviceId:n})=>{u.storeCurrentSequence(t).then((e=>{e&&d({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:n})})).catch((t=>{e.loggerProvider.warn("Failed to get current sequence of session replay events for session:",t)}))},addEvent:({event:t,sessionId:n,deviceId:r})=>{u.addEventToCurrentSequence(n,t.data).then((e=>e&&d({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:r}))).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*(){const t=yield u.getSequencesToSend();t&&t.forEach((t=>{d({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)}))}}}));class $e{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((n=>{t.push(n.sendStoredEvents(e))})),yield Promise.all(t)}))}addEvent({sessionId:e,event:t,deviceId:n}){var r;null===(r=this.managers.get(t.type))||void 0===r||r.addEvent({sessionId:e,event:t,deviceId:n})}sendCurrentSequenceEvents({sessionId:e,deviceId:t}){this.managers.forEach((n=>{n.sendCurrentSequenceEvents({sessionId:e,deviceId:t})}))}flush(e){return n(this,void 0,void 0,(function*(){const t=[];this.managers.forEach((n=>{t.push(n.flush(e))})),yield Promise.all(t)}))}}const Ue={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},Be={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},Fe={};function Ae(e){if(Fe[e])return Fe[e];const t=globalThis[e],n=t.prototype,r=e in Ue?Ue[e]:void 0,o=Boolean(r&&r.every((e=>{var t,r;return Boolean(null==(r=null==(t=Object.getOwnPropertyDescriptor(n,e))?void 0:t.get)?void 0:r.toString().includes("[native code]"))}))),i=e in Be?Be[e]:void 0,s=Boolean(i&&i.every((e=>{var t;return"function"==typeof n[e]&&(null==(t=n[e])?void 0:t.toString().includes("[native code]"))})));if(o&&s&&!globalThis.Zone)return Fe[e]=t.prototype,t.prototype;try{const r=document.createElement("iframe");document.body.appendChild(r);const o=r.contentWindow;if(!o)return t.prototype;const i=o[e].prototype;return document.body.removeChild(r),i?Fe[e]=i:n}catch{return n}}const Ke={};function We(e,t,n){var r;const o=`${e}.${String(n)}`;if(Ke[o])return Ke[o].call(t);const i=Ae(e),s=null==(r=Object.getOwnPropertyDescriptor(i,n))?void 0:r.get;return s?(Ke[o]=s,s.call(t)):t[n]}const ze={};function Ge(e,t,n){const r=`${e}.${String(n)}`;if(ze[r])return ze[r].bind(t);const o=Ae(e)[n];return"function"!=typeof o?t[n]:(ze[r]=o,o.bind(t))}const Qe={childNodes:function(e){return We("Node",e,"childNodes")},parentNode:function(e){return We("Node",e,"parentNode")},parentElement:function(e){return We("Node",e,"parentElement")},textContent:function(e){return We("Node",e,"textContent")},contains:function(e,t){return Ge("Node",e,"contains")(t)},getRootNode:function(e){return Ge("Node",e,"getRootNode")()},host:function(e){return e&&"host"in e?We("ShadowRoot",e,"host"):null},styleSheets:function(e){return e.styleSheets},shadowRoot:function(e){return e&&"shadowRoot"in e?We("Element",e,"shadowRoot"):null},querySelector:function(e,t){return We("Element",e,"querySelector")(t)},querySelectorAll:function(e,t){return We("Element",e,"querySelectorAll")(t)},mutationObserver:function(){return Ae("MutationObserver").constructor}};function He(){const e=l();return(null==e?void 0:e.innerHeight)||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight||0}function Je(){const e=l();return(null==e?void 0:e.innerWidth)||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth||0}let Ve,Ze,Xe;function Ye(e,t){if(Xe=new Date,e.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if("html"===e.tagName.toLowerCase())return"html";const n={root:document.body,idName:e=>!0,className:e=>!0,tagName:e=>!0,attr:(e,t)=>!1,seedMinLength:1,optimizedMinLength:2,threshold:1e3,maxNumberOfTries:1e4,timeoutMs:void 0};Ve=Object.assign(Object.assign({},n),t),Ze=function(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return e;if(e===t.root)return e.ownerDocument;return e}(Ve.root,n);let r=et(e,"all",(()=>et(e,"two",(()=>et(e,"one",(()=>et(e,"none")))))));if(r){const t=gt(pt(r,e));return t.length>0&&(r=t[0]),nt(r)}throw new Error("Selector was not found.")}function et(e,t,n){let r=null,o=[],i=e,s=0;for(;i;){const e=(new Date).getTime()-Xe.getTime();if(void 0!==Ve.timeoutMs&&e>Ve.timeoutMs)throw new Error(`Timeout: Can't find a unique selector after ${e}ms`);let a=ht(it(i))||ht(...st(i))||ht(...at(i))||ht(lt(i))||[{name:"*",penalty:3}];const l=ct(i);if("all"==t)l&&(a=a.concat(a.filter(dt).map((e=>ut(e,l)))));else if("two"==t)a=a.slice(0,1),l&&(a=a.concat(a.filter(dt).map((e=>ut(e,l)))));else if("one"==t){const[e]=a=a.slice(0,1);l&&dt(e)&&(a=[ut(e,l)])}else"none"==t&&(a=[{name:"*",penalty:3}],l&&(a=[ut(a[0],l)]));for(let e of a)e.level=s;if(o.push(a),o.length>=Ve.seedMinLength&&(r=tt(o,n),r))break;i=i.parentElement,s++}return r||(r=tt(o,n)),!r&&n?n():r}function tt(e,t){const n=gt(vt(e));if(n.length>Ve.threshold)return t?t():null;for(let e of n)if(ot(e))return e;return null}function nt(e){let t=e[0],n=t.name;for(let r=1;r<e.length;r++){const o=e[r].level||0;n=t.level===o-1?`${e[r].name} > ${n}`:`${e[r].name} ${n}`,t=e[r]}return n}function rt(e){return e.map((e=>e.penalty)).reduce(((e,t)=>e+t),0)}function ot(e){const t=nt(e);switch(Ze.querySelectorAll(t).length){case 0:throw new Error(`Can't select any node with this selector: ${t}`);case 1:return!0;default:return!1}}function it(e){const t=e.getAttribute("id");return t&&Ve.idName(t)?{name:"#"+CSS.escape(t),penalty:0}:null}function st(e){const t=Array.from(e.attributes).filter((e=>Ve.attr(e.name,e.value)));return t.map((e=>({name:`[${CSS.escape(e.name)}="${CSS.escape(e.value)}"]`,penalty:.5})))}function at(e){return Array.from(e.classList).filter(Ve.className).map((e=>({name:"."+CSS.escape(e),penalty:1})))}function lt(e){const t=e.tagName.toLowerCase();return Ve.tagName(t)?{name:t,penalty:2}:null}function ct(e){const t=e.parentNode;if(!t)return null;let n=t.firstChild;if(!n)return null;let r=0;for(;n&&(n.nodeType===Node.ELEMENT_NODE&&r++,n!==e);)n=n.nextSibling;return r}function ut(e,t){return{name:e.name+`:nth-child(${t})`,penalty:e.penalty+1}}function dt(e){return"html"!==e.name&&!e.name.startsWith("#")}function ht(...e){const t=e.filter(ft);return t.length>0?t:null}function ft(e){return null!=e}function*vt(e,t=[]){if(e.length>0)for(let n of e[0])yield*vt(e.slice(1,e.length),t.concat(n));else yield t}function gt(e){return[...e].sort(((e,t)=>rt(e)-rt(t)))}function*pt(e,t,n={counter:0,visited:new Map}){if(e.length>2&&e.length>Ve.optimizedMinLength)for(let r=1;r<e.length-1;r++){if(n.counter>Ve.maxNumberOfTries)return;n.counter+=1;const o=[...e];o.splice(r,1);const i=nt(o);if(n.visited.has(i))return;ot(o)&&mt(o,t)&&(yield o,n.visited.set(i,!0),yield*pt(o,t,n))}}function mt(e,t){return Ze.querySelector(nt(e))===t}const yt=({version:e,events:t})=>{const n=[];return t.forEach((e=>{const t=JSON.parse(e);t.count=1,"click"===t.type&&n.push(t)})),{version:e,events:n}},bt=({version:e,events:t})=>{const n=[];t.forEach((e=>{const t=JSON.parse(e);"click"===t.type&&n.push(t)}));const r=n.reduce(((e,t)=>{const{x:n,y:r,selector:o,timestamp:i}=t,s=i-i%36e5,a=`${n}:${r}:${null!=o?o:""}:${s}`;return e[a]?e[a].count+=1:e[a]=Object.assign(Object.assign({},t),{timestamp:s,count:1}),e}),{});return{version:e,events:Object.values(r)}},St=(e,{eventsManager:t,sessionId:n,deviceIdFn:r,mirror:o,ugcFilterRules:i})=>s=>{if(s.type!==q.Click)return;const a=l();if(!a)return;const{location:c,innerHeight:u,innerWidth:d}=a;if(!c)return;const{x:h,y:f}=s;if(void 0===h||void 0===f)return;const v=o.getNode(s.id);let g;if(v)try{g=Ye(v)}catch(t){e.debug("error resolving selector from finder")}const{left:p,top:m}=function(e){var t,n,r,o;const i=e.document;return{left:i.scrollingElement?i.scrollingElement.scrollLeft:void 0!==e.pageXOffset?e.pageXOffset:i.documentElement.scrollLeft||(null==i?void 0:i.body)&&(null===(t=Qe.parentElement(i.body))||void 0===t?void 0:t.scrollLeft)||(null===(n=null==i?void 0:i.body)||void 0===n?void 0:n.scrollLeft)||0,top:i.scrollingElement?i.scrollingElement.scrollTop:void 0!==e.pageYOffset?e.pageYOffset:(null==i?void 0:i.documentElement.scrollTop)||(null==i?void 0:i.body)&&(null===(r=Qe.parentElement(i.body))||void 0===r?void 0:r.scrollTop)||(null===(o=null==i?void 0:i.body)||void 0===o?void 0:o.scrollTop)||0}}(a),y={x:h+p,y:f+m,selector:g,viewportHeight:u,viewportWidth:d,pageUrl:V(c.href,i),timestamp:Date.now(),type:"click"},b=r();b&&t.addEvent({sessionId:n,event:{type:"interaction",data:JSON.stringify(y)},deviceId:b})};class wt{constructor(e,t){const n=l();n&&n.navigator&&"function"==typeof n.navigator.sendBeacon?this.sendBeacon=(e,t)=>{try{if(n.navigator.sendBeacon(e,JSON.stringify(t)))return!0}catch(e){}return!1}:this.sendBeacon=()=>!1,this.sendXhr=(e,t)=>{const n=new XMLHttpRequest;return n.open("POST",e,!0),n.setRequestHeader("Accept","*/*"),n.send(JSON.stringify(t)),!0},this.basePageUrl=H(t.serverZone,t.trackServerUrl),this.apiKey=t.apiKey,this.context=e}send(e,t){const{sessionId:n,type:r}=this.context,o=new URLSearchParams({device_id:e,session_id:String(n),type:String(r),api_key:this.apiKey}),i=`${this.basePageUrl}?${o.toString()}`;this.sendBeacon(i,t)||this.sendXhr(i,t)}}class It{static default(e,t){return new It(new wt(e,t),t)}constructor(e,t){this.timestamp=Date.now(),this.hook=e=>{this.update(e)},this.send=e=>t=>{var n,r;const o=e(),i=l();i&&o&&this.transport.send(o,{version:1,events:[{maxScrollX:this._maxScrollX,maxScrollY:this._maxScrollY,maxScrollWidth:this._maxScrollWidth,maxScrollHeight:this._maxScrollHeight,viewportHeight:He(),viewportWidth:Je(),pageUrl:V(i.location.href,null!==(r=null===(n=this.config.interactionConfig)||void 0===n?void 0:n.ugcFilterRules)&&void 0!==r?r:[]),timestamp:this.timestamp,type:"scroll"}]})},this._maxScrollX=0,this._maxScrollY=0,this._maxScrollWidth=Je(),this._maxScrollHeight=He(),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}update(e){const t=Date.now();if(e.x>this._maxScrollX){const n=Je();this._maxScrollX=e.x;const r=e.x+n;r>this._maxScrollWidth&&(this._maxScrollWidth=r),this.timestamp=t}if(e.y>this._maxScrollY){const n=He();this._maxScrollY=e.y;const r=e.y+n;r>this._maxScrollHeight&&(this._maxScrollHeight=r),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))}}var Et=Uint8Array,kt=Uint16Array,xt=Uint32Array,_t=new Et([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Pt=new Et([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Ot=new Et([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Rt=function(e,t){for(var n=new kt(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];var o=new xt(n[30]);for(r=1;r<30;++r)for(var i=n[r];i<n[r+1];++i)o[i]=i-n[r]<<5|r;return[n,o]},Tt=Rt(_t,2),qt=Tt[0],Mt=Tt[1];qt[28]=258,Mt[258]=28;for(var Lt=Rt(Pt,0)[1],Dt=new kt(32768),jt=0;jt<32768;++jt){var Nt=(43690&jt)>>>1|(21845&jt)<<1;Nt=(61680&(Nt=(52428&Nt)>>>2|(13107&Nt)<<2))>>>4|(3855&Nt)<<4,Dt[jt]=((65280&Nt)>>>8|(255&Nt)<<8)>>>1}var $t=function(e,t,n){for(var r=e.length,o=0,i=new kt(t);o<r;++o)++i[e[o]-1];var s,a=new kt(t);for(o=0;o<t;++o)a[o]=a[o-1]+i[o-1]<<1;if(n){s=new kt(1<<t);var l=15-t;for(o=0;o<r;++o)if(e[o])for(var c=o<<4|e[o],u=t-e[o],d=a[e[o]-1]++<<u,h=d|(1<<u)-1;d<=h;++d)s[Dt[d]>>>l]=c}else for(s=new kt(r),o=0;o<r;++o)s[o]=Dt[a[e[o]-1]++]>>>15-e[o];return s},Ut=new Et(288);for(jt=0;jt<144;++jt)Ut[jt]=8;for(jt=144;jt<256;++jt)Ut[jt]=9;for(jt=256;jt<280;++jt)Ut[jt]=7;for(jt=280;jt<288;++jt)Ut[jt]=8;var Bt=new Et(32);for(jt=0;jt<32;++jt)Bt[jt]=5;var Ft=$t(Ut,9,0),At=$t(Bt,5,0),Kt=function(e){return(e/8|0)+(7&e&&1)},Wt=function(e,t,n){(null==n||n>e.length)&&(n=e.length);var r=new(e instanceof kt?kt:e instanceof xt?xt:Et)(n-t);return r.set(e.subarray(t,n)),r},zt=function(e,t,n){n<<=7&t;var r=t/8|0;e[r]|=n,e[r+1]|=n>>>8},Gt=function(e,t,n){n<<=7&t;var r=t/8|0;e[r]|=n,e[r+1]|=n>>>8,e[r+2]|=n>>>16},Qt=function(e,t){for(var n=[],r=0;r<e.length;++r)e[r]&&n.push({s:r,f:e[r]});var o=n.length,i=n.slice();if(!o)return[new Et(0),0];if(1==o){var s=new Et(n[0].s+1);return s[n[0].s]=1,[s,1]}n.sort((function(e,t){return e.f-t.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],c=0,u=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};u!=o-1;)a=n[n[c].f<n[d].f?c++:d++],l=n[c!=u&&n[c].f<n[d].f?c++:d++],n[u++]={s:-1,f:a.f+l.f,l:a,r:l};var h=i[0].s;for(r=1;r<o;++r)i[r].s>h&&(h=i[r].s);var f=new kt(h+1),v=Ht(n[u-1],f,0);if(v>t){r=0;var g=0,p=v-t,m=1<<p;for(i.sort((function(e,t){return f[t.s]-f[e.s]||e.f-t.f}));r<o;++r){var y=i[r].s;if(!(f[y]>t))break;g+=m-(1<<v-f[y]),f[y]=t}for(g>>>=p;g>0;){var b=i[r].s;f[b]<t?g-=1<<t-f[b]++-1:++r}for(;r>=0&&g;--r){var S=i[r].s;f[S]==t&&(--f[S],++g)}v=t}return[new Et(f),v]},Ht=function(e,t,n){return-1==e.s?Math.max(Ht(e.l,t,n+1),Ht(e.r,t,n+1)):t[e.s]=n},Jt=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new kt(++t),r=0,o=e[0],i=1,s=function(e){n[r++]=e},a=1;a<=t;++a)if(e[a]==o&&a!=t)++i;else{if(!o&&i>2){for(;i>138;i-=138)s(32754);i>2&&(s(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(s(o),--i;i>6;i-=6)s(8304);i>2&&(s(i-3<<5|8208),i=0)}for(;i--;)s(o);i=1,o=e[a]}return[n.subarray(0,r),t]},Vt=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},Zt=function(e,t,n){var r=n.length,o=Kt(t+2);e[o]=255&r,e[o+1]=r>>>8,e[o+2]=255^e[o],e[o+3]=255^e[o+1];for(var i=0;i<r;++i)e[o+i+4]=n[i];return 8*(o+4+r)},Xt=function(e,t,n,r,o,i,s,a,l,c,u){zt(t,u++,n),++o[256];for(var d=Qt(o,15),h=d[0],f=d[1],v=Qt(i,15),g=v[0],p=v[1],m=Jt(h),y=m[0],b=m[1],S=Jt(g),w=S[0],I=S[1],C=new kt(19),E=0;E<y.length;++E)C[31&y[E]]++;for(E=0;E<w.length;++E)C[31&w[E]]++;for(var k=Qt(C,7),x=k[0],_=k[1],P=19;P>4&&!x[Ot[P-1]];--P);var O,R,T,q,M=c+5<<3,L=Vt(o,Ut)+Vt(i,Bt)+s,D=Vt(o,h)+Vt(i,g)+s+14+3*P+Vt(C,x)+(2*C[16]+3*C[17]+7*C[18]);if(M<=L&&M<=D)return Zt(t,u,e.subarray(l,l+c));if(zt(t,u,1+(D<L)),u+=2,D<L){O=$t(h,f,0),R=h,T=$t(g,p,0),q=g;var j=$t(x,_,0);zt(t,u,b-257),zt(t,u+5,I-1),zt(t,u+10,P-4),u+=14;for(E=0;E<P;++E)zt(t,u+3*E,x[Ot[E]]);u+=3*P;for(var N=[y,w],$=0;$<2;++$){var U=N[$];for(E=0;E<U.length;++E){var B=31&U[E];zt(t,u,j[B]),u+=x[B],B>15&&(zt(t,u,U[E]>>>5&127),u+=U[E]>>>12)}}}else O=Ft,R=Ut,T=At,q=Bt;for(E=0;E<a;++E)if(r[E]>255){B=r[E]>>>18&31;Gt(t,u,O[B+257]),u+=R[B+257],B>7&&(zt(t,u,r[E]>>>23&31),u+=_t[B]);var F=31&r[E];Gt(t,u,T[F]),u+=q[F],F>3&&(Gt(t,u,r[E]>>>5&8191),u+=Pt[F])}else Gt(t,u,O[r[E]]),u+=R[r[E]];return Gt(t,u,O[256]),u+R[256]},Yt=new xt([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),en=function(e,t,n,r,o){return function(e,t,n,r,o,i){var s=e.length,a=new Et(r+s+5*(1+Math.floor(s/7e3))+o),l=a.subarray(r,a.length-o),c=0;if(!t||s<8)for(var u=0;u<=s;u+=65535){var d=u+65535;d<s?c=Zt(l,c,e.subarray(u,d)):(l[u]=i,c=Zt(l,c,e.subarray(u,s)))}else{for(var h=Yt[t-1],f=h>>>13,v=8191&h,g=(1<<n)-1,p=new kt(32768),m=new kt(g+1),y=Math.ceil(n/3),b=2*y,S=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<b)&g},w=new xt(25e3),I=new kt(288),C=new kt(32),E=0,k=0,x=(u=0,0),_=0,P=0;u<s;++u){var O=S(u),R=32767&u,T=m[O];if(p[R]=T,m[O]=R,_<=u){var q=s-u;if((E>7e3||x>24576)&&q>423){c=Xt(e,l,0,w,I,C,k,x,P,u-P,c),x=E=k=0,P=u;for(var M=0;M<286;++M)I[M]=0;for(M=0;M<30;++M)C[M]=0}var L=2,D=0,j=v,N=R-T&32767;if(q>2&&O==S(u-N))for(var $=Math.min(f,q)-1,U=Math.min(32767,u),B=Math.min(258,q);N<=U&&--j&&R!=T;){if(e[u+L]==e[u+L-N]){for(var F=0;F<B&&e[u+F]==e[u+F-N];++F);if(F>L){if(L=F,D=N,F>$)break;var A=Math.min(N,F-2),K=0;for(M=0;M<A;++M){var W=u-N+M+32768&32767,z=W-p[W]+32768&32767;z>K&&(K=z,T=W)}}}N+=(R=T)-(T=p[R])+32768&32767}if(D){w[x++]=268435456|Mt[L]<<18|Lt[D];var G=31&Mt[L],Q=31&Lt[D];k+=_t[G]+Pt[Q],++I[257+G],++C[Q],_=u+L,++E}else w[x++]=e[u],++I[e[u]]}}c=Xt(e,l,i,w,I,C,k,x,P,u-P,c)}return Wt(a,0,r+Kt(c)+o)}(e,null==t.level?6:t.level,null==t.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):12+t.mem,n,r,!o)};function tn(e,t){void 0===t&&(t={});var n=function(){var e=1,t=0;return{p:function(n){for(var r=e,o=t,i=n.length,s=0;s!=i;){for(var a=Math.min(s+5552,i);s<a;++s)o+=r+=n[s];r%=65521,o%=65521}e=r,t=o},d:function(){return(e>>>8<<16|(255&t)<<8|t>>>8)+2*((255&e)<<23)}}}();n.p(e);var r,o,i,s=en(e,t,2,4);return r=s,o=t.level,i=0==o?0:o<6?1:9==o?3:2,r[0]=120,r[1]=i<<6|(i?32-2*i:1),function(e,t,n){for(;n;++t)e[t]=n,n>>>=8}(s,s.length-4,n.d()),s}const nn=e=>{const t={...e,v:"v1"};return function(e,t){var n="";if(!t&&"undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);for(var r=0;r<e.length;){var o=e[r++];o<128||t?n+=String.fromCharCode(o):o<224?n+=String.fromCharCode((31&o)<<6|63&e[r++]):o<240?n+=String.fromCharCode((15&o)<<12|(63&e[r++])<<6|63&e[r++]):(o=((15&o)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536,n+=String.fromCharCode(55296|o>>10,56320|1023&o))}return n}(tn(function(e,t){var n=e.length;if(!t&&"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);for(var r=new Et(e.length+(e.length>>>1)),o=0,i=function(e){r[o++]=e},s=0;s<n;++s){if(o+5>r.length){var a=new Et(o+8+(n-s<<1));a.set(r),r=a}var l=e.charCodeAt(s);l<128||t?i(l):l<2048?(i(192|l>>>6),i(128|63&l)):l>55295&&l<57344?(i(240|(l=65536+(1047552&l)|1023&e.charCodeAt(++s))>>>18),i(128|l>>>12&63),i(128|l>>>6&63),i(128|63&l)):(i(224|l>>>12),i(128|l>>>6&63),i(128|63&l))}return Wt(r,0,o)}(JSON.stringify(t))),!0)};class rn{constructor(e,t,n,r){var o,i,s;this.taskQueue=[],this.isProcessing=!1,this.compressEvent=e=>{const t=nn(e);return JSON.stringify(t)},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)this.worker.postMessage({event:e,sessionId:t});else{const n=this.compressEvent(e);this.addCompressedEventToManager(n,t)}},this.terminate=()=>{var e;null===(e=this.worker)||void 0===e||e.terminate()};const a=l();this.canUseIdleCallback=a&&"requestIdleCallback"in a,this.eventsManager=e,this.config=t,this.deviceId=n,this.timeout=(null===(o=t.performanceConfig)||void 0===o?void 0:o.timeout)||2e3;const c=null!==(i='var WebWorker=function(r){"use strict";var n=Uint8Array,e=Uint16Array,f=Uint32Array,t=new n([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),o=new n([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),a=new n([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),i=function(r,n){for(var t=new e(31),o=0;o<31;++o)t[o]=n+=1<<r[o-1];var a=new f(t[30]);for(o=1;o<30;++o)for(var i=t[o];i<t[o+1];++i)a[i]=i-t[o]<<5|o;return[t,a]},v=i(t,2),u=v[0],s=v[1];u[28]=258,s[258]=28;for(var l=i(o,0)[1],c=new e(32768),h=0;h<32768;++h){var g=(43690&h)>>>1|(21845&h)<<1;g=(61680&(g=(52428&g)>>>2|(13107&g)<<2))>>>4|(3855&g)<<4,c[h]=((65280&g)>>>8|(255&g)<<8)>>>1}var w=function(r,n,f){for(var t=r.length,o=0,a=new e(n);o<t;++o)++a[r[o]-1];var i,v=new e(n);for(o=0;o<n;++o)v[o]=v[o-1]+a[o-1]<<1;if(f){i=new e(1<<n);var u=15-n;for(o=0;o<t;++o)if(r[o])for(var s=o<<4|r[o],l=n-r[o],h=v[r[o]-1]++<<l,g=h|(1<<l)-1;h<=g;++h)i[c[h]>>>u]=s}else for(i=new e(t),o=0;o<t;++o)i[o]=c[v[r[o]-1]++]>>>15-r[o];return i},d=new n(288);for(h=0;h<144;++h)d[h]=8;for(h=144;h<256;++h)d[h]=9;for(h=256;h<280;++h)d[h]=7;for(h=280;h<288;++h)d[h]=8;var m=new n(32);for(h=0;h<32;++h)m[h]=5;var M=w(d,9,0),y=w(m,5,0),b=function(r){return(r/8|0)+(7&r&&1)},p=function(r,t,o){(null==o||o>r.length)&&(o=r.length);var a=new(r instanceof e?e:r instanceof f?f:n)(o-t);return a.set(r.subarray(t,o)),a},C=function(r,n,e){e<<=7&n;var f=n/8|0;r[f]|=e,r[f+1]|=e>>>8},x=function(r,n,e){e<<=7&n;var f=n/8|0;r[f]|=e,r[f+1]|=e>>>8,r[f+2]|=e>>>16},S=function(r,f){for(var t=[],o=0;o<r.length;++o)r[o]&&t.push({s:o,f:r[o]});var a=t.length,i=t.slice();if(!a)return[new n(0),0];if(1==a){var v=new n(t[0].s+1);return v[t[0].s]=1,[v,1]}t.sort((function(r,n){return r.f-n.f})),t.push({s:-1,f:25001});var u=t[0],s=t[1],l=0,c=1,h=2;for(t[0]={s:-1,f:u.f+s.f,l:u,r:s};c!=a-1;)u=t[t[l].f<t[h].f?l++:h++],s=t[l!=c&&t[l].f<t[h].f?l++:h++],t[c++]={s:-1,f:u.f+s.f,l:u,r:s};var g=i[0].s;for(o=1;o<a;++o)i[o].s>g&&(g=i[o].s);var w=new e(g+1),d=A(t[c-1],w,0);if(d>f){o=0;var m=0,M=d-f,y=1<<M;for(i.sort((function(r,n){return w[n.s]-w[r.s]||r.f-n.f}));o<a;++o){var b=i[o].s;if(!(w[b]>f))break;m+=y-(1<<d-w[b]),w[b]=f}for(m>>>=M;m>0;){var p=i[o].s;w[p]<f?m-=1<<f-w[p]++-1:++o}for(;o>=0&&m;--o){var C=i[o].s;w[C]==f&&(--w[C],++m)}d=f}return[new n(w),d]},A=function(r,n,e){return-1==r.s?Math.max(A(r.l,n,e+1),A(r.r,n,e+1)):n[r.s]=e},O=function(r){for(var n=r.length;n&&!r[--n];);for(var f=new e(++n),t=0,o=r[0],a=1,i=function(r){f[t++]=r},v=1;v<=n;++v)if(r[v]==o&&v!=n)++a;else{if(!o&&a>2){for(;a>138;a-=138)i(32754);a>2&&(i(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(i(o),--a;a>6;a-=6)i(8304);a>2&&(i(a-3<<5|8208),a=0)}for(;a--;)i(o);a=1,o=r[v]}return[f.subarray(0,t),n]},T=function(r,n){for(var e=0,f=0;f<n.length;++f)e+=r[f]*n[f];return e},k=function(r,n,e){var f=e.length,t=b(n+2);r[t]=255&f,r[t+1]=f>>>8,r[t+2]=255^r[t],r[t+3]=255^r[t+1];for(var o=0;o<f;++o)r[t+o+4]=e[o];return 8*(t+4+f)},E=function(r,n,f,i,v,u,s,l,c,h,g){C(n,g++,f),++v[256];for(var b=S(v,15),p=b[0],A=b[1],E=S(u,15),U=E[0],D=E[1],I=O(p),J=I[0],N=I[1],W=O(U),_=W[0],j=W[1],P=new e(19),q=0;q<J.length;++q)P[31&J[q]]++;for(q=0;q<_.length;++q)P[31&_[q]]++;for(var z=S(P,7),B=z[0],F=z[1],G=19;G>4&&!B[a[G-1]];--G);var H,K,L,Q,R=h+5<<3,V=T(v,d)+T(u,m)+s,X=T(v,p)+T(u,U)+s+14+3*G+T(P,B)+(2*P[16]+3*P[17]+7*P[18]);if(R<=V&&R<=X)return k(n,g,r.subarray(c,c+h));if(C(n,g,1+(X<V)),g+=2,X<V){H=w(p,A,0),K=p,L=w(U,D,0),Q=U;var Y=w(B,F,0);C(n,g,N-257),C(n,g+5,j-1),C(n,g+10,G-4),g+=14;for(q=0;q<G;++q)C(n,g+3*q,B[a[q]]);g+=3*G;for(var Z=[J,_],$=0;$<2;++$){var rr=Z[$];for(q=0;q<rr.length;++q){var nr=31&rr[q];C(n,g,Y[nr]),g+=B[nr],nr>15&&(C(n,g,rr[q]>>>5&127),g+=rr[q]>>>12)}}}else H=M,K=d,L=y,Q=m;for(q=0;q<l;++q)if(i[q]>255){nr=i[q]>>>18&31;x(n,g,H[nr+257]),g+=K[nr+257],nr>7&&(C(n,g,i[q]>>>23&31),g+=t[nr]);var er=31&i[q];x(n,g,L[er]),g+=Q[er],er>3&&(x(n,g,i[q]>>>5&8191),g+=o[er])}else x(n,g,H[i[q]]),g+=K[i[q]];return x(n,g,H[256]),g+K[256]},U=new f([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),D=function(r,a,i,v,u){return function(r,a,i,v,u,c){var h=r.length,g=new n(v+h+5*(1+Math.floor(h/7e3))+u),w=g.subarray(v,g.length-u),d=0;if(!a||h<8)for(var m=0;m<=h;m+=65535){var M=m+65535;M<h?d=k(w,d,r.subarray(m,M)):(w[m]=c,d=k(w,d,r.subarray(m,h)))}else{for(var y=U[a-1],C=y>>>13,x=8191&y,S=(1<<i)-1,A=new e(32768),O=new e(S+1),T=Math.ceil(i/3),D=2*T,I=function(n){return(r[n]^r[n+1]<<T^r[n+2]<<D)&S},J=new f(25e3),N=new e(288),W=new e(32),_=0,j=0,P=(m=0,0),q=0,z=0;m<h;++m){var B=I(m),F=32767&m,G=O[B];if(A[F]=G,O[B]=F,q<=m){var H=h-m;if((_>7e3||P>24576)&&H>423){d=E(r,w,0,J,N,W,j,P,z,m-z,d),P=_=j=0,z=m;for(var K=0;K<286;++K)N[K]=0;for(K=0;K<30;++K)W[K]=0}var L=2,Q=0,R=x,V=F-G&32767;if(H>2&&B==I(m-V))for(var X=Math.min(C,H)-1,Y=Math.min(32767,m),Z=Math.min(258,H);V<=Y&&--R&&F!=G;){if(r[m+L]==r[m+L-V]){for(var $=0;$<Z&&r[m+$]==r[m+$-V];++$);if($>L){if(L=$,Q=V,$>X)break;var rr=Math.min(V,$-2),nr=0;for(K=0;K<rr;++K){var er=m-V+K+32768&32767,fr=er-A[er]+32768&32767;fr>nr&&(nr=fr,G=er)}}}V+=(F=G)-(G=A[F])+32768&32767}if(Q){J[P++]=268435456|s[L]<<18|l[Q];var tr=31&s[L],or=31&l[Q];j+=t[tr]+o[or],++N[257+tr],++W[or],q=m+L,++_}else J[P++]=r[m],++N[r[m]]}}d=E(r,w,c,J,N,W,j,P,z,m-z,d)}return p(g,0,v+b(d)+u)}(r,null==a.level?6:a.level,null==a.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.length)))):12+a.mem,i,v,!u)};function I(r,n){void 0===n&&(n={});var e=function(){var r=1,n=0;return{p:function(e){for(var f=r,t=n,o=e.length,a=0;a!=o;){for(var i=Math.min(a+5552,o);a<i;++a)t+=f+=e[a];f%=65521,t%=65521}r=f,n=t},d:function(){return(r>>>8<<16|(255&n)<<8|n>>>8)+2*((255&r)<<23)}}}();e.p(r);var f,t,o,a=D(r,n,2,4);return f=a,t=n.level,o=0==t?0:t<6?1:9==t?3:2,f[0]=120,f[1]=o<<6|(o?32-2*o:1),function(r,n,e){for(;e;++n)r[n]=e,e>>>=8}(a,a.length-4,e.d()),a}const J=r=>{const e={...r,v:"v1"};return function(r,n){var e="";if(!n&&"undefined"!=typeof TextDecoder)return(new TextDecoder).decode(r);for(var f=0;f<r.length;){var t=r[f++];t<128||n?e+=String.fromCharCode(t):t<224?e+=String.fromCharCode((31&t)<<6|63&r[f++]):t<240?e+=String.fromCharCode((15&t)<<12|(63&r[f++])<<6|63&r[f++]):(t=((15&t)<<18|(63&r[f++])<<12|(63&r[f++])<<6|63&r[f++])-65536,e+=String.fromCharCode(55296|t>>10,56320|1023&t))}return e}(I(function(r,e){var f=r.length;if(!e&&"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(r);for(var t=new n(r.length+(r.length>>>1)),o=0,a=function(r){t[o++]=r},i=0;i<f;++i){if(o+5>t.length){var v=new n(o+8+(f-i<<1));v.set(t),t=v}var u=r.charCodeAt(i);u<128||e?a(u):u<2048?(a(192|u>>>6),a(128|63&u)):u>55295&&u<57344?(a(240|(u=65536+(1047552&u)|1023&r.charCodeAt(++i))>>>18),a(128|u>>>12&63),a(128|u>>>6&63),a(128|63&u)):(a(224|u>>>12),a(128|u>>>6&63),a(128|63&u))}return p(t,0,o)}(JSON.stringify(e))),!0)};onmessage=r=>{const{event:n,sessionId:e}=r.data,f=JSON.stringify(J(n));postMessage({compressedEvent:f,sessionId:e})};const N=onmessage;return r.compressionOnMessage=N,Object.defineProperty(r,"__esModule",{value:!0}),r}({});\n')?i:r;if((null===(s=this.config.experimental)||void 0===s?void 0:s.useWebWorker)&&a&&a.Worker&&c){t.loggerProvider.log("[Experimental] Enabling web worker for compression");const e=new Worker(URL.createObjectURL(new Blob([c],{type:"application/javascript"})));e.onerror=e=>{t.loggerProvider.error(e)},e.onmessage=e=>{const{compressedEvent:t,sessionId:n}=e.data;this.addCompressedEventToManager(t,n)},this.worker=e}}scheduleIdleProcessing(){this.isProcessing||(this.isProcessing=!0,requestIdleCallback((e=>{this.processQueue(e)}),{timeout:this.timeout}))}enqueueEvent(e,t){var n;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.taskQueue.push({event:e,sessionId:t}),this.scheduleIdleProcessing()):(this.config.loggerProvider.debug("Processing event without idle callback."),this.addCompressedEvent(e,t))}processQueue(e){for(;this.taskQueue.length>0&&(e.timeRemaining()>0||e.didTimeout);){const e=this.taskQueue.shift();if(e){const{event:t,sessionId:n}=e;this.addCompressedEvent(t,n)}}this.taskQueue.length>0?requestIdleCallback((e=>{this.processQueue(e)}),{timeout:this.timeout}):this.isProcessing=!1}}class on{constructor(){this.name="@amplitude/session-replay-browser",this.recordCancelCallback=null,this.eventCount=0,this.pageLeaveFns=[],this.recordFunction=null,this.teardownEventListeners=e=>{const t=l();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=()=>{this.recordEvents(!1)},this.pageLeaveListener=e=>{this.pageLeaveFns.forEach((t=>{t(e)}))},this.addCustomRRWebEvent=(e,t={},r=!0)=>n(this,void 0,void 0,(function*(){try{let n;const o=this.config;if(o&&e!==W.METADATA&&(n={config:X(o),version:re},r)){const e=yield Z();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 Y(new d)}init(e,t){return c(this._init(e,t))}_init(e,t){var r,o,i,s,a,c;return n(this,void 0,void 0,(function*(){this.loggerProvider=new Y(t.loggerProvider||new d),Object.prototype.hasOwnProperty.call(t,"logLevel")&&this.loggerProvider.enable(t.logLevel),this.identifiers=new Ct({sessionId:t.sessionId,deviceId:t.deviceId}),this.joinedConfigGenerator=yield((e,t)=>n(void 0,void 0,void 0,(function*(){const n=new ee(e,t),r=yield N({localConfig:n,configKeys:["sessionReplay"]});return new te(r,n)})))(e,t);const{joinedConfig:u,localConfig:h,remoteConfig:f}=yield this.joinedConfigGenerator.generateJoinedConfig(this.identifiers.sessionId);if(this.config=u,this.setMetadata(t.sessionId,u,h,f,null===(r=t.version)||void 0===r?void 0:r.version,re,null===(o=t.version)||void 0===o?void 0:o.type),t.sessionId&&(null===(i=this.config.interactionConfig)||void 0===i?void 0:i.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)}const v=[];let{storeType:g}=this.config;"idb"!==g||(null===(s=l())||void 0===s?void 0:s.indexedDB)||(g="memory",this.loggerProvider.warn("Could not use preferred indexedDB storage, reverting to in memory option.")),this.loggerProvider.log(`Using ${g} for event storage.`);try{const e=yield Ne({config:this.config,sessionId:this.identifiers.sessionId,type:"replay",storeType:g});v.push({name:"replay",manager:e})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating replay events manager: ${t.toString()}`)}if(null===(a=this.config.interactionConfig)||void 0===a?void 0:a.enabled){const e=this.config.interactionConfig.batch?bt:yt;try{const t=yield Ne({config:this.config,sessionId:this.identifiers.sessionId,type:"interaction",minInterval:null!==(c=this.config.interactionConfig.trackEveryNms)&&void 0!==c?c:3e4,maxInterval:6e4,payloadBatcher:e,storeType:g});v.push({name:"interaction",manager:t})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating interaction events manager: ${t.toString()}`)}}this.eventsManager=new $e(...v),this.eventCompressor&&this.eventCompressor.terminate(),this.eventCompressor=new rn(this.eventsManager,this.config,this.getDeviceId()),yield this.initializeNetworkObservers(),this.loggerProvider.log("Installing @amplitude/session-replay-browser."),this.teardownEventListeners(!1),this.initialize(!0)}))}setSessionId(e,t){return c(this.asyncSetSessionId(e,t))}asyncSetSessionId(e,t){return n(this,void 0,void 0,(function*(){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.identifiers.sessionId);this.config=e}this.recordEvents()}))}getSessionReplayProperties(){const e=this.config,t=this.identifiers;if(!e||!t)return this.loggerProvider.warn("Session replay init has not been called, cannot get session replay properties."),{};const n=this.getShouldRecord();let r={};return n&&(r={[B]:t.sessionReplayId?t.sessionReplayId:null},e.debugMode&&(r[A]=JSON.stringify({appHash:Q(e.apiKey).toString()}))),this.addCustomRRWebEvent(W.GET_SR_PROPS,{shouldRecord:n,eventProperties:r},10===this.eventCount),10===this.eventCount&&(this.eventCount=0),this.eventCount++,r}sendEvents(e){var t;const n=e||(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId),r=this.getDeviceId();this.eventsManager&&n&&r&&this.eventsManager.sendCurrentSequenceEvents({sessionId:n,deviceId:r})}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 n=this.getDeviceId();return n?(this.eventsManager&&e&&this.eventsManager.sendStoredEvents({deviceId:n}),this.recordEvents()):(this.loggerProvider.log("Session is not being recorded due to lack of device id."),Promise.resolve())}))}shouldOptOut(){var e,t;let n;if(null===(e=this.config)||void 0===e?void 0:e.instanceName){n=(r=this.config.instanceName,void 0===r&&(r="$default_instance"),x.getInstance(r)).identityStore.getIdentity().optOut}var r;return void 0!==n?n:null===(t=this.config)||void 0===t?void 0:t.optOut}getShouldRecord(){if(!this.identifiers||!this.config||!this.identifiers.sessionId)return this.loggerProvider.warn("Session is not being recorded due to lack of config, please call sessionReplay.init."),!1;if(!this.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;const e=function(e,t){const n=Q(e.toString());return 31*Math.abs(n)%1e6/1e6<t}(this.identifiers.sessionId,this.config.sampleRate);return e||this.loggerProvider.log(`Opting session ${this.identifiers.sessionId} out of recording due to sample rate.`),e}getBlockSelectors(){var e,t,n;const r=null!==(n=null===(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)||void 0===t?void 0:t.blockSelector)&&void 0!==n?n:[];if(0!==r.length)return r}getMaskTextSelectors(){var e,t,n,r;if("conservative"===(null===(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)||void 0===t?void 0:t.defaultMaskLevel))return"*";const o=null===(r=null===(n=this.config)||void 0===n?void 0:n.privacyConfig)||void 0===r?void 0:r.maskSelector;return o||void 0}getRecordingPlugins(e){var t;return n(this,void 0,void 0,(function*(){const n=[];if(null===(t=null==e?void 0:e.console)||void 0===t?void 0:t.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){var t,r,o;return n(this,void 0,void 0,(function*(){const n=this.config,i=this.getShouldRecord(),s=null===(t=this.identifiers)||void 0===t?void 0:t.sessionId;if(!i||!s||!n)return;this.stopRecordingEvents();const a=yield this.getRecordFunction();if(!a)return;yield this.initializeNetworkObservers(),null===(r=this.networkObservers)||void 0===r||r.start((e=>{this.addCustomRRWebEvent(W.FETCH_REQUEST,e)}));const{privacyConfig:l,interactionConfig:c,loggingConfig:u}=n,d=(null==c?void 0:c.enabled)?{mouseInteraction:this.eventsManager&&St(this.loggerProvider,{eventsManager:this.eventsManager,sessionId:s,deviceIdFn:this.getDeviceId.bind(this),mirror:a.mirror,ugcFilterRules:null!==(o=c.ugcFilterRules)&&void 0!==o?o:[]}),scroll:this.scrollHook}:{},h=(null==c?void 0:c.enabled)&&c.ugcFilterRules?c.ugcFilterRules:[];this.loggerProvider.log(`Session Replay capture beginning for ${s}.`);try{this.recordCancelCallback=a({emit:e=>{if(this.shouldOptOut())return this.loggerProvider.log(`Opting session ${s} out of recording due to optOut config.`),this.stopRecordingEvents(),void this.sendEvents();e.type===T.Meta&&(e.data.href=V(e.data.href,h)),this.eventCompressor&&this.eventCompressor.enqueueEvent(e,s)},inlineStylesheet:n.shouldInlineStylesheet,hooks:d,maskAllInputs:!0,maskTextClass:K,blockClass:"amp-block",blockSelector:this.getBlockSelectors(),applyBackgroundColorToBlockedElements:n.applyBackgroundColorToBlockedElements,maskInputFn:G("input",l),maskTextFn:G("text",l),maskTextSelector:this.getMaskTextSelectors(),recordCanvas:!1,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(u)}),this.addCustomRRWebEvent(W.DEBUG_INFO),e&&this.addCustomRRWebEvent(W.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(){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,n,r,o,i,s){const a=(null==e?void 0:e.toString())?Q(e.toString()):void 0;this.metadata={joinedConfig:t,localConfig:n,remoteConfig:r,sessionId:e,hashValue:a,sampleRate:t.sampleRate,replaySDKType:this.mapSDKType(s),replaySDKVersion:o,standaloneSDKType:"@amplitude/session-replay-browser",standaloneSDKVersion:i}}initializeNetworkObservers(){var e,t,r;return n(this,void 0,void 0,(function*(){if((null===(r=null===(t=null===(e=this.config)||void 0===e?void 0:e.loggingConfig)||void 0===t?void 0:t.network)||void 0===r?void 0:r.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)}}))}}export{on as S,n as _,l as g};
1
+ var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},e(t,n)};var t=function(){return t=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},t.apply(this,arguments)};function n(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{l(r.next(e))}catch(e){i(e)}}function a(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}l((r=r.apply(e,t||[])).next())}))}function r(e,t){var n,r,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(l){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(i=0)),i;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,r=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){i.label=a[1];break}if(6===a[0]&&i.label<o[1]){i.label=o[1],o=a;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(a);break}o[2]&&i.ops.pop(),i.trys.pop();continue}a=t.call(e,i)}catch(e){a=[6,e],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,l])}}}"function"==typeof SuppressedError&&SuppressedError;var o,i="".concat("AMP","_unsent"),s="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"}(o||(o={}));var a,l=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},c=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"}(a||(a={}));var u="Amplitude Logger ",d=function(){function e(){this.logLevel=a.None}return e.prototype.disable=function(){this.logLevel=a.None},e.prototype.enable=function(e){void 0===e&&(e=a.Warn),this.logLevel=e},e.prototype.log=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<a.Verbose||console.log("".concat(u,"[Log]: ").concat(e.join(" ")))},e.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<a.Warn||console.warn("".concat(u,"[Warn]: ").concat(e.join(" ")))},e.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<a.Error||console.error("".concat(u,"[Error]: ").concat(e.join(" ")))},e.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this.logLevel<a.Debug||console.log("".concat(u,"[Debug]: ").concat(e.join(" ")))},e}(),h=function(){return{flushMaxRetries:12,flushQueueSize:200,flushIntervalMillis:1e4,instanceName:"$default_instance",logLevel:a.Warn,loggerProvider:new d,offline:!1,optOut:!1,serverUrl:s,serverZone:"US",useBatch:!1}},f=function(){function e(e){var t,n,r,o;this._optOut=!1;var i=h();this.apiKey=e.apiKey,this.flushIntervalMillis=null!==(t=e.flushIntervalMillis)&&void 0!==t?t:i.flushIntervalMillis,this.flushMaxRetries=e.flushMaxRetries||i.flushMaxRetries,this.flushQueueSize=e.flushQueueSize||i.flushQueueSize,this.instanceName=e.instanceName||i.instanceName,this.loggerProvider=e.loggerProvider||i.loggerProvider,this.logLevel=null!==(n=e.logLevel)&&void 0!==n?n:i.logLevel,this.minIdLength=e.minIdLength,this.plan=e.plan,this.ingestionMetadata=e.ingestionMetadata,this.offline=void 0!==e.offline?e.offline:i.offline,this.optOut=null!==(r=e.optOut)&&void 0!==r?r:i.optOut,this.serverUrl=e.serverUrl,this.serverZone=e.serverZone||i.serverZone,this.storageProvider=e.storageProvider,this.transportProvider=e.transportProvider,this.useBatch=null!==(o=e.useBatch)&&void 0!==o?o:i.useBatch,this.loggerProvider.enable(this.logLevel);var s=g(e.serverUrl,e.serverZone,e.useBatch);this.serverZone=s.serverZone,this.serverUrl=s.serverUrl}return Object.defineProperty(e.prototype,"optOut",{get:function(){return this._optOut},set:function(e){this._optOut=e},enumerable:!1,configurable:!0}),e}(),v=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":s},g=function(e,t,n){if(void 0===e&&(e=""),void 0===t&&(t=h().serverZone),void 0===n&&(n=h().useBatch),e)return{serverUrl:e,serverZone:void 0};var r=["US","EU"].includes(t)?t:h().serverZone;return{serverZone:r,serverUrl:v(r,n)}},p=function(){function e(){}return e.prototype.getApplicationContext=function(){return{versionName:this.versionName,language:m(),platform:"Web",os:void 0,deviceModel:void 0}},e}(),m=function(){return"undefined"!=typeof navigator&&(navigator.languages&&navigator.languages[0]||navigator.language)||""},y=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}(),b=function(){return b=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},b.apply(this,arguments)};function S(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function w(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}"function"==typeof SuppressedError&&SuppressedError;var I=function(e,t){var n,r,o=typeof e;if(o!==typeof t)return!1;try{for(var i=S(["string","number","boolean","undefined"]),s=i.next();!s.done;s=i.next()){if(s.value===o)return e===t}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}if(null==e&&null==t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;var a=Array.isArray(e),l=Array.isArray(t);if(a!==l)return!1;if(!a||!l){var c=Object.keys(e).sort(),u=Object.keys(t).sort();if(!I(c,u))return!1;var d=!0;return Object.keys(e).forEach((function(n){I(e[n],t[n])||(d=!1)})),d}for(var h=0;h<e.length;h++)if(!I(e[h],t[h]))return!1;return!0};Object.entries||(Object.entries=function(e){for(var t=Object.keys(e),n=t.length,r=new Array(n);n--;)r[n]=[t[n],e[t[n]]];return r});var C,E=function(){function e(){this.identity={userProperties:{}},this.listeners=new Set}return e.prototype.editIdentity=function(){var e=this,t=b({},this.identity.userProperties),n=b(b({},this.identity),{userProperties:t});return{setUserId:function(e){return n.userId=e,this},setDeviceId:function(e){return n.deviceId=e,this},setUserProperties:function(e){return n.userProperties=e,this},setOptOut:function(e){return n.optOut=e,this},updateUserProperties:function(e){var t,r,o,i,s,a,l=n.userProperties||{};try{for(var c=S(Object.entries(e)),u=c.next();!u.done;u=c.next()){var d=w(u.value,2),h=d[0],f=d[1];switch(h){case"$set":try{for(var v=(o=void 0,S(Object.entries(f))),g=v.next();!g.done;g=v.next()){var p=w(g.value,2),m=p[0],y=p[1];l[m]=y}}catch(e){o={error:e}}finally{try{g&&!g.done&&(i=v.return)&&i.call(v)}finally{if(o)throw o.error}}break;case"$unset":try{for(var b=(s=void 0,S(Object.keys(f))),I=b.next();!I.done;I=b.next()){delete l[m=I.value]}}catch(e){s={error:e}}finally{try{I&&!I.done&&(a=b.return)&&a.call(b)}finally{if(s)throw s.error}}break;case"$clearAll":l={}}}}catch(e){t={error:e}}finally{try{u&&!u.done&&(r=c.return)&&r.call(c)}finally{if(t)throw t.error}}return n.userProperties=l,this},commit:function(){return e.setIdentity(n),this}}},e.prototype.getIdentity=function(){return b({},this.identity)},e.prototype.setIdentity=function(e){var t=b({},this.identity);this.identity=b({},e),I(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}(),k="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:self,x=function(){function e(){this.identityStore=new E,this.eventBridge=new y,this.applicationContextProvider=new p}return e.getInstance=function(t){return k.analyticsConnectorInstances||(k.analyticsConnectorInstances={}),k.analyticsConnectorInstances[t]||(k.analyticsConnectorInstances[t]=new e),k.analyticsConnectorInstances[t]},e}(),_=function(){function e(){}return e.prototype.send=function(e,t){return Promise.resolve(null)},e.prototype.buildResponse=function(e){var t,n,r,i,s,a,l,c,u,d,h,f,v,g,p,m,y,b,S,w,I,C;if("object"!=typeof e)return null;var E=e.code||0,k=this.buildStatus(E);switch(k){case o.Success:return{status:k,statusCode:E,body:{eventsIngested:null!==(t=e.events_ingested)&&void 0!==t?t:0,payloadSizeBytes:null!==(n=e.payload_size_bytes)&&void 0!==n?n:0,serverUploadTime:null!==(r=e.server_upload_time)&&void 0!==r?r:0}};case o.Invalid:return{status:k,statusCode:E,body:{error:null!==(i=e.error)&&void 0!==i?i:"",missingField:null!==(s=e.missing_field)&&void 0!==s?s:"",eventsWithInvalidFields:null!==(a=e.events_with_invalid_fields)&&void 0!==a?a:{},eventsWithMissingFields:null!==(l=e.events_with_missing_fields)&&void 0!==l?l:{},eventsWithInvalidIdLengths:null!==(c=e.events_with_invalid_id_lengths)&&void 0!==c?c:{},epsThreshold:null!==(u=e.eps_threshold)&&void 0!==u?u: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!==(f=e.silenced_events)&&void 0!==f?f:[],throttledDevices:null!==(v=e.throttled_devices)&&void 0!==v?v:{},throttledEvents:null!==(g=e.throttled_events)&&void 0!==g?g:[]}};case o.PayloadTooLarge:return{status:k,statusCode:E,body:{error:null!==(p=e.error)&&void 0!==p?p:""}};case o.RateLimit:return{status:k,statusCode:E,body:{error:null!==(m=e.error)&&void 0!==m?m:"",epsThreshold:null!==(y=e.eps_threshold)&&void 0!==y?y:0,throttledDevices:null!==(b=e.throttled_devices)&&void 0!==b?b:{},throttledUsers:null!==(S=e.throttled_users)&&void 0!==S?S:{},exceededDailyQuotaDevices:null!==(w=e.exceeded_daily_quota_devices)&&void 0!==w?w:{},exceededDailyQuotaUsers:null!==(I=e.exceeded_daily_quota_users)&&void 0!==I?I:{},throttledEvents:null!==(C=e.throttled_events)&&void 0!==C?C:[]}};case o.Timeout:default:return{status:k,statusCode:E}}},e.prototype.buildStatus=function(e){return e>=200&&e<300?o.Success:429===e?o.RateLimit:413===e?o.PayloadTooLarge:408===e?o.Timeout:e>=400&&e<500?o.Invalid:e>=500?o.Failed:o.Unknown},e}(),P=function(t){function o(){return null!==t&&t.apply(this,arguments)||this}return function(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}(o,t),o.prototype.send=function(e,t){return n(this,void 0,void 0,(function(){var n,o,i;return r(this,(function(r){switch(r.label){case 0:if("undefined"==typeof fetch)throw new Error("FetchTransport is not supported");return n={headers:{"Content-Type":"application/json",Accept:"*/*"},body:JSON.stringify(t),method:"POST"},[4,fetch(e,n)];case 1:return[4,(o=r.sent()).text()];case 2:i=r.sent();try{return[2,this.buildResponse(JSON.parse(i))]}catch(e){return[2,this.buildResponse({code:o.status})]}return[2]}}))}))},o}(_);!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}(C||(C={}));var O,T,R=(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))(R||{}),q=(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))(q||{});!function(e){e.US="US",e.EU="EU",e.STAGING="STAGING"}(O||(O={})),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"}(T||(T={}));var M=function(){function e(){}return e.prototype.send=function(e,t){return Promise.resolve(null)},e.prototype.buildResponse=function(e){var t,n,r,o,i,s,a,l,c,u,d,h,f,v,g,p,m,y,b,S,w,I;if("object"!=typeof e)return null;var C=e.code||0,E=this.buildStatus(C);switch(E){case T.Success:return{status:E,statusCode:C,body:{eventsIngested:null!==(t=e.events_ingested)&&void 0!==t?t:0,payloadSizeBytes:null!==(n=e.payload_size_bytes)&&void 0!==n?n:0,serverUploadTime:null!==(r=e.server_upload_time)&&void 0!==r?r:0}};case T.Invalid:return{status:E,statusCode:C,body:{error:null!==(o=e.error)&&void 0!==o?o:"",missingField:null!==(i=e.missing_field)&&void 0!==i?i:"",eventsWithInvalidFields:null!==(s=e.events_with_invalid_fields)&&void 0!==s?s:{},eventsWithMissingFields:null!==(a=e.events_with_missing_fields)&&void 0!==a?a:{},eventsWithInvalidIdLengths:null!==(l=e.events_with_invalid_id_lengths)&&void 0!==l?l:{},epsThreshold:null!==(c=e.eps_threshold)&&void 0!==c?c:0,exceededDailyQuotaDevices:null!==(u=e.exceeded_daily_quota_devices)&&void 0!==u?u:{},silencedDevices:null!==(d=e.silenced_devices)&&void 0!==d?d:[],silencedEvents:null!==(h=e.silenced_events)&&void 0!==h?h:[],throttledDevices:null!==(f=e.throttled_devices)&&void 0!==f?f:{},throttledEvents:null!==(v=e.throttled_events)&&void 0!==v?v:[]}};case T.PayloadTooLarge:return{status:E,statusCode:C,body:{error:null!==(g=e.error)&&void 0!==g?g:""}};case T.RateLimit:return{status:E,statusCode:C,body:{error:null!==(p=e.error)&&void 0!==p?p:"",epsThreshold:null!==(m=e.eps_threshold)&&void 0!==m?m:0,throttledDevices:null!==(y=e.throttled_devices)&&void 0!==y?y:{},throttledUsers:null!==(b=e.throttled_users)&&void 0!==b?b:{},exceededDailyQuotaDevices:null!==(S=e.exceeded_daily_quota_devices)&&void 0!==S?S:{},exceededDailyQuotaUsers:null!==(w=e.exceeded_daily_quota_users)&&void 0!==w?w:{},throttledEvents:null!==(I=e.throttled_events)&&void 0!==I?I:[]}};case T.Timeout:default:return{status:E,statusCode:C}}},e.prototype.buildStatus=function(e){return e>=200&&e<300?T.Success:429===e?T.RateLimit:413===e?T.PayloadTooLarge:408===e?T.Timeout:e>=400&&e<500?T.Invalid:e>=500?T.Failed:T.Unknown},e}(),L="Remote config fetch rejected due to timeout after 5 seconds",D="Unexpected error occurred",j=function(){function e(e){var o=e.localConfig,i=e.configKeys,s=this;this.retryTimeout=1e3,this.attempts=0,this.sessionTargetingMatch=!1,this.metrics={},this.getRemoteNamespaceConfig=function(e,t){return n(s,void 0,void 0,(function(){var n,o,i;return r(this,(function(r){switch(r.label){case 0:return n=Date.now(),[4,this.fetchWithTimeout(t)];case 1:return(o=r.sent())&&(i=o.configs&&o.configs[e])?(this.metrics.fetchTimeAPISuccess=Date.now()-n,[2,i]):(this.metrics.fetchTimeAPIFail=Date.now()-n,[2,void 0])}}))}))},this.getRemoteConfig=function(e,t,o){return n(s,void 0,void 0,(function(){var n;return r(this,(function(r){switch(r.label){case 0:return[4,this.getRemoteNamespaceConfig(e,o)];case 1:return[2,null==(n=r.sent())?void 0:n[t]]}}))}))},this.fetchWithTimeout=function(e){return n(s,void 0,void 0,(function(){var t,n,o;return r(this,(function(r){switch(r.label){case 0:return t=new AbortController,n=setTimeout((function(){return t.abort()}),5e3),[4,this.fetchRemoteConfig(t.signal,e)];case 1:return o=r.sent(),clearTimeout(n),[2,o]}}))}))},this.fetchRemoteConfig=function(e,o){return n(s,void 0,void 0,(function(){var n,i,s,a,l,c,u,d,h,f,v,g;return r(this,(function(r){switch(r.label){case 0:if(o===this.lastFetchedSessionId&&this.attempts>=this.localConfig.flushMaxRetries)return[2,this.completeRequest({err:"Remote config fetch rejected due to exceeded retry count"})];if(e.aborted)return[2,this.completeRequest({err:L})];o!==this.lastFetchedSessionId&&(this.lastFetchedSessionId=o,this.attempts=0),r.label=1;case 1:r.trys.push([1,3,,4]),n=new URLSearchParams({api_key:this.localConfig.apiKey});try{for(i=function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(this.configKeys),s=i.next();!s.done;s=i.next())a=s.value,n.append("config_keys",a)}catch(e){f={error:e}}finally{try{s&&!s.done&&(v=i.return)&&v.call(i)}finally{if(f)throw f.error}}return o&&n.set("session_id",String(o)),l={headers:{Accept:"*/*"},method:"GET"},c="".concat(this.getServerUrl(),"?").concat(n.toString()),this.attempts+=1,[4,fetch(c,t(t({},l),{signal:e}))];case 2:if(null===(u=r.sent()))return[2,this.completeRequest({err:D})];switch((new M).buildStatus(u.status)){case T.Success:return this.attempts=0,[2,this.parseAndStoreConfig(u)];case T.Failed:return[2,this.retryFetch(e,o)];default:return[2,this.completeRequest({err:"Network error occurred, remote config fetch failed"})]}case 3:return d=r.sent(),h=d,e.aborted?[2,this.completeRequest({err:L})]:[2,this.completeRequest({err:null!==(g=h.message)&&void 0!==g?g:D})];case 4:return[2]}}))}))},this.retryFetch=function(e,t){return n(s,void 0,void 0,(function(){var n=this;return r(this,(function(r){switch(r.label){case 0:return[4,new Promise((function(e){return setTimeout(e,n.attempts*n.retryTimeout)}))];case 1:return r.sent(),[2,this.fetchRemoteConfig(e,t)]}}))}))},this.parseAndStoreConfig=function(e){return n(s,void 0,void 0,(function(){var t;return r(this,(function(n){switch(n.label){case 0:return[4,e.json()];case 1:return t=n.sent(),this.completeRequest({success:"Remote config successfully fetched"}),[2,t]}}))}))},this.localConfig=o,this.configKeys=i}return e.prototype.getServerUrl=function(){return this.localConfig.configServerUrl?this.localConfig.configServerUrl:this.localConfig.serverZone===O.STAGING?"https://sr-client-cfg.stag2.amplitude.com/config":this.localConfig.serverZone===O.EU?"https://sr-client-cfg.eu.amplitude.com/config":"https://sr-client-cfg.amplitude.com/config"},e.prototype.completeRequest=function(e){var t=e.err,n=e.success;if(t)throw new Error(t);n&&this.localConfig.loggerProvider.log(n)},e}(),N=function(e){var t=e.localConfig,o=e.configKeys;return n(void 0,void 0,void 0,(function(){return r(this,(function(e){return[2,new j({localConfig:t,configKeys:o})]}))}))};const $="medium",U="[Amplitude]",B=`${U} Session Replay ID`,F=C.US,A=`${U} Session Replay Debug`,K="amp-mask";var W;!function(e){e.GET_SR_PROPS="get-sr-props",e.DEBUG_INFO="debug-info",e.FETCH_REQUEST="fetch-request",e.METADATA="metadata"}(W||(W={}));const z=(e,t,n)=>{switch(t){case"light":{if("input"!==e)return!0;const t=n?function(e){const t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?t.toLowerCase():null}(n):"";return!!t&&(!!["password","hidden","email","tel"].includes(t)||!!n.autocomplete.startsWith("cc-"))}case"medium":case"conservative":return!0;default:return z(e,$,n)}},G=(e,t)=>(n,r)=>((e,t={defaultMaskLevel:$},n)=>{var r,o,i;if(n){if(n.closest("."+K))return!0;const e=(null!==(r=t.maskSelector)&&void 0!==r?r:[]).some((e=>n.closest(e)));if(e)return!0;if(n.closest(".amp-unmask"))return!1;const i=(null!==(o=t.unmaskSelector)&&void 0!==o?o:[]).some((e=>n.closest(e)));if(i)return!1}return z(e,null!==(i=t.defaultMaskLevel)&&void 0!==i?i:$,n)})(e,t,r)?n.replace(/[^\s]/g,"*"):n,Q=function(e){let t=0;if(0===e.length)return t;for(let n=0;n<e.length;n++){t=(t<<5)-t+e.charCodeAt(n),t|=0}return t},H=(e,t)=>t||(e===C.STAGING?"https://api-sr.stag2.amplitude.com/sessions/v2/track":e===C.EU?"https://api-sr.eu.amplitude.com/sessions/v2/track":"https://api-sr.amplitude.com/sessions/v2/track"),J=e=>{const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${t}$`)},V=(e,t)=>{for(const n of t){const t=J(n.selector);if(t.test(e))return e.replace(t,n.replacement)}return e},Z=()=>n(void 0,void 0,void 0,(function*(){try{const e=l();if(e){const{usage:t,quota:n,usageDetails:r}=yield e.navigator.storage.estimate(),o=t?Math.round(t/1024):0;return{totalStorageSize:o,percentOfQuota:t&&n?Math.round(1e3*(t/n+Number.EPSILON))/1e3:0,usageDetails:JSON.stringify(r)}}}catch(e){}return{totalStorageSize:0,percentOfQuota:0,usageDetails:""}})),X=e=>{const t=Object.assign({},e),{apiKey:n}=t;return t.apiKey=`****${n.substring(n.length-4)}`,t};class Y{constructor(e){this.logger=e,this.log=this.getSafeMethod("log"),this.warn=this.getSafeMethod("warn"),this.error=this.getSafeMethod("error"),this.debug=this.getSafeMethod("debug")}getSafeMethod(e){var t;if(!this.logger)return()=>{};const n=this.logger[e];if("function"==typeof n){return(null!==(t=n.__rrweb_original__)&&void 0!==t?t:n).bind(this.logger)}return()=>{}}enable(e){this.logger.enable(e)}disable(){this.logger.disable()}}class ee extends f{constructor(e,t){var n,r;const o={flushMaxRetries:2,logLevel:a.Warn,loggerProvider:new d,transportProvider:new P};super(Object.assign(Object.assign({transportProvider:o.transportProvider,loggerProvider:new Y(t.loggerProvider||o.loggerProvider)},t),{apiKey:e})),this.flushMaxRetries=void 0!==t.flushMaxRetries&&t.flushMaxRetries<=o.flushMaxRetries?t.flushMaxRetries:o.flushMaxRetries,this.apiKey=e,this.sampleRate=t.sampleRate||0,this.serverZone=t.serverZone||F,this.configServerUrl=t.configServerUrl,this.trackServerUrl=t.trackServerUrl,this.shouldInlineStylesheet=t.shouldInlineStylesheet,this.version=t.version,this.performanceConfig=t.performanceConfig,this.storeType=null!==(n=t.storeType)&&void 0!==n?n:"idb",this.applyBackgroundColorToBlockedElements=null!==(r=t.applyBackgroundColorToBlockedElements)&&void 0!==r&&r,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),t.experimental&&(this.experimental=t.experimental)}}class te{constructor(e,t){this.localConfig=t,this.remoteConfigFetch=e}generateJoinedConfig(e){var t,r,o,i;return n(this,void 0,void 0,(function*(){const n=Object.assign({},this.localConfig);let s;n.optOut=this.localConfig.optOut,n.captureEnabled=!0;try{const r=yield this.remoteConfigFetch.getRemoteNamespaceConfig("sessionReplay",e);if(r){const e=r.sr_sampling_config,o=r.sr_privacy_config,i=null===(t=n.interactionConfig)||void 0===t?void 0:t.ugcFilterRules;n.interactionConfig=r.sr_interaction_config,n.interactionConfig&&i&&(n.interactionConfig.ugcFilterRules=i),n.loggingConfig=r.sr_logging_config,(e||o)&&(s={},e&&(s.sr_sampling_config=e),o&&(s.sr_privacy_config=o))}}catch(e){const t=e;this.localConfig.loggerProvider.warn(t.message),n.captureEnabled=!1}if(!s)return{localConfig:this.localConfig,joinedConfig:n,remoteConfig:s};const{sr_sampling_config:a,sr_privacy_config:l}=s;if(a&&Object.keys(a).length>0?(Object.prototype.hasOwnProperty.call(a,"capture_enabled")?n.captureEnabled=a.capture_enabled:n.captureEnabled=!1,Object.prototype.hasOwnProperty.call(a,"sample_rate")&&(n.sampleRate=a.sample_rate)):(n.captureEnabled=!0,this.localConfig.loggerProvider.debug("Remote config successfully fetched, but no values set for project, Session Replay capture enabled.")),l){const e=null!==(r=n.privacyConfig)&&void 0!==r?r:{},t={defaultMaskLevel:null!==(i=null!==(o=l.defaultMaskLevel)&&void 0!==o?o:e.defaultMaskLevel)&&void 0!==i?i:"medium",blockSelector:[],maskSelector:[],unmaskSelector:[]},s=e=>{var t,n,r;const o={};"string"==typeof e.blockSelector&&(e.blockSelector=[e.blockSelector]);for(const n of null!==(t=e.blockSelector)&&void 0!==t?t:[])o[n]="block";for(const t of null!==(n=e.maskSelector)&&void 0!==n?n:[])o[t]="mask";for(const t of null!==(r=e.unmaskSelector)&&void 0!==r?r:[])o[t]="unmask";return o},a=Object.assign(Object.assign({},s(e)),s(l));for(const[e,n]of Object.entries(a))"mask"===n?t.maskSelector.push(e):"block"===n?t.blockSelector.push(e):"unmask"===n&&t.unmaskSelector.push(e);n.privacyConfig=((e,t)=>{const n=document.createDocumentFragment(),r=(e=[])=>{if("string"==typeof e&&(e=[e]),e=e.filter((e=>{try{n.querySelector(e)}catch(n){return t.warn(`[session-replay-browser] omitting selector "${e}" because it is invalid`),!1}return!0})),0!==e.length)return e};return e.blockSelector=r(e.blockSelector),e.maskSelector=r(e.maskSelector),e.unmaskSelector=r(e.unmaskSelector),e})(t,this.localConfig.loggerProvider)}return this.localConfig.loggerProvider.debug(JSON.stringify({name:"session replay joined config",config:X(n)},null,2)),{localConfig:this.localConfig,joinedConfig:n,remoteConfig:s}}))}}const ne="Failed to store session replay events in IndexedDB",re="1.25.3";class oe{constructor({trackServerUrl:e,loggerProvider:t,payloadBatcher:n}){this.storageKey="",this.retryTimeout=1e3,this.scheduled=null,this.queue=[],this.loggerProvider=t,this.payloadBatcher=n||(e=>e),this.trackServerUrl=e}sendEventsList(e){this.addToQueue(Object.assign(Object.assign({},e),{attempts:0,timeout:0}))}addToQueue(...e){e.filter((e=>e.attempts<(e.flushMaxRetries||0)?(e.attempts+=1,!0):(this.completeRequest({context:e,err:"Session replay event batch rejected due to exceeded retry count"}),!1))).forEach((e=>{this.queue=this.queue.concat(e),0!==e.timeout?setTimeout((()=>{e.timeout=0,this.schedule(0)}),e.timeout):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=[],n=[];this.queue.forEach((e=>0===e.timeout?t.push(e):n.push(e))),this.queue=n,this.scheduled&&(clearTimeout(this.scheduled),this.scheduled=null),yield Promise.all(t.map((t=>this.send(t,e))))}))}send(e,t=!0){var r,o;return n(this,void 0,void 0,(function*(){const n=e.apiKey;if(!n)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing api key"});const i=e.deviceId;if(!i)return this.completeRequest({context:e,err:"Session replay event batch not sent due to missing device ID"});const s=(()=>{const e=l();return(null==e?void 0:e.location)?e.location.href:""})(),a=re,c=e.sampleRate,u=new URLSearchParams({device_id:i,session_id:`${e.sessionId}`,type:`${e.type}`}),d=`${(null===(r=e.version)||void 0===r?void 0:r.type)||"standalone"}/${(null===(o=e.version)||void 0===o?void 0:o.version)||a}`,h=this.payloadBatcher({version:1,events:e.events});if(0!==h.events.length)try{const r={headers:{"Content-Type":"application/json",Accept:"*/*",Authorization:`Bearer ${n}`,"X-Client-Version":a,"X-Client-Library":d,"X-Client-Url":s.substring(0,1e3),"X-Client-Sample-Rate":`${c}`},body:JSON.stringify(h),method:"POST"},o=`${H(e.serverZone,this.trackServerUrl)}?${u.toString()}`,i=yield fetch(o,r);if(null===i)return void this.completeRequest({context:e,err:"Unexpected error occurred"});if(t)this.handleReponse(i.status,e);else{let t="";try{t=JSON.stringify(i.body,null,2)}catch(e){}this.completeRequest({context:e,success:`${i.status}: ${t}`})}}catch(t){this.completeRequest({context:e,err:t})}else this.completeRequest({context:e})}))}handleReponse(e,t){switch((new _).buildStatus(e)){case o.Success:this.handleSuccessResponse(t);break;case o.Failed:this.handleOtherResponse(t);break;default: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){this.addToQueue(Object.assign(Object.assign({},e),{timeout:e.attempts*this.retryTimeout}))}completeRequest({context:e,err:t,success:n}){e.onComplete(),t?this.loggerProvider.warn(t):n&&this.loggerProvider.log(n)}}const ie=(e,t)=>t.some((t=>e instanceof t));let se,ae;const le=new WeakMap,ce=new WeakMap,ue=new WeakMap;let de={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return le.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return ge(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function he(e){de=e(de)}function fe(e){return(ae||(ae=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(pe(this),t),ge(this.request)}:function(...t){return ge(e.apply(pe(this),t))}}function ve(e){return"function"==typeof e?fe(e):(e instanceof IDBTransaction&&function(e){if(le.has(e))return;const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("complete",o),e.removeEventListener("error",i),e.removeEventListener("abort",i)},o=()=>{t(),r()},i=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",o),e.addEventListener("error",i),e.addEventListener("abort",i)}));le.set(e,t)}(e),ie(e,se||(se=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,de):e)}function ge(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("success",o),e.removeEventListener("error",i)},o=()=>{t(ge(e.result)),r()},i=()=>{n(e.error),r()};e.addEventListener("success",o),e.addEventListener("error",i)}));return ue.set(t,e),t}(e);if(ce.has(e))return ce.get(e);const t=ve(e);return t!==e&&(ce.set(e,t),ue.set(t,e)),t}const pe=e=>ue.get(e);const me=["get","getKey","getAll","getAllKeys","count"],ye=["put","add","delete","clear"],be=new Map;function Se(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(be.get(t))return be.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,o=ye.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!o&&!me.includes(n))return;const i=async function(e,...t){const i=this.transaction(e,o?"readwrite":"readonly");let s=i.store;return r&&(s=s.index(t.shift())),(await Promise.all([s[n](...t),o&&i.done]))[0]};return be.set(t,i),i}he((e=>({...e,get:(t,n,r)=>Se(t,n)||e.get(t,n,r),has:(t,n)=>!!Se(t,n)||e.has(t,n)})));const we=["continue","continuePrimaryKey","advance"],Ie={},Ce=new WeakMap,Ee=new WeakMap,ke={get(e,t){if(!we.includes(t))return e[t];let n=Ie[t];return n||(n=Ie[t]=function(...e){Ce.set(this,Ee.get(this)[t](...e))}),n}};async function*xe(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const n=new Proxy(t,ke);for(Ee.set(n,t),ue.set(n,pe(t));t;)yield n,t=await(Ce.get(n)||t.continue()),Ce.delete(n)}function _e(e,t){return t===Symbol.asyncIterator&&ie(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&ie(e,[IDBIndex,IDBObjectStore])}he((e=>({...e,get:(t,n,r)=>_e(t,n)?xe:e.get(t,n,r),has:(t,n)=>_e(t,n)||e.has(t,n)})));class Pe{get timeAtLastSplit(){return this._timeAtLastSplit}constructor(e){var t,n,r;this.minInterval=500,this.maxInterval=1e4,this.maxPersistedEventsSize=1e6,this.interval=this.minInterval,this._timeAtLastSplit=Date.now(),this.shouldSplitEventsList=(e,t)=>{const n=new Blob([t]).size;return new Blob(e).size+n>=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!==(n=e.maxInterval)&&void 0!==n?n:this.maxInterval,this.maxPersistedEventsSize=null!==(r=e.maxPersistedEventsSize)&&void 0!==r?r:this.maxPersistedEventsSize}}var Oe;!function(e){e.RECORDING="recording",e.SENT="sent"}(Oe||(Oe={}));const Te="sessionCurrentSequence",Re="sequencesToSend",qe=e=>n(void 0,void 0,void 0,(function*(){for(;e.length>0;){const t=10,n=e.splice(0,t);yield Promise.all(n)}})),Me=e=>{let t,n;return e.objectStoreNames.contains(Te)||(n=e.createObjectStore(Te,{keyPath:"sessionId"})),e.objectStoreNames.contains(Re)||(t=e.createObjectStore(Re,{keyPath:"sequenceId",autoIncrement:!0}),t.createIndex("sessionId","sessionId")),{sequencesStore:t,currentSequenceStore:n}},Le=e=>n(void 0,void 0,void 0,(function*(){return yield function(e,t,{blocked:n,upgrade:r,blocking:o,terminated:i}={}){const s=indexedDB.open(e,t),a=ge(s);return r&&s.addEventListener("upgradeneeded",(e=>{r(ge(s.result),e.oldVersion,e.newVersion,ge(s.transaction),e)})),n&&s.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),a.then((e=>{i&&e.addEventListener("close",(()=>i())),o&&e.addEventListener("versionchange",(e=>o(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),a}(e,1,{upgrade:Me})}));class De extends Pe{constructor(e){super(e),this.getSequencesToSend=()=>n(this,void 0,void 0,(function*(){try{const e=[];let t=yield this.db.transaction("sequencesToSend").store.openCursor();for(;t;){const{sessionId:n,events:r}=t.value;e.push({events:r,sequenceId:t.key,sessionId:n}),t=yield t.continue()}return e}catch(e){this.loggerProvider.warn(`${ne}: ${e}`)}})),this.storeCurrentSequence=e=>n(this,void 0,void 0,(function*(){try{const t=yield this.db.get(Te,e);if(!t)return;const n=yield this.db.put(Re,{sessionId:e,events:t.events});return yield this.db.put(Te,{sessionId:e,events:[]}),Object.assign(Object.assign({},t),{sessionId:e,sequenceId:n})}catch(e){this.loggerProvider.warn(`${ne}: ${e}`)}})),this.addEventToCurrentSequence=(e,t)=>n(this,void 0,void 0,(function*(){try{const n=this.db.transaction(Te,"readwrite"),r=yield n.store.get(e);if(!r)return void(yield n.store.put({sessionId:e,events:[t]}));let o;if(this.shouldSplitEventsList(r.events,t))o=r.events,yield n.store.put({sessionId:e,events:[t]});else{const o=r.events.concat(t);yield n.store.put({sessionId:e,events:o})}if(yield n.done,!o)return;const i=yield this.storeSendingEvents(e,o);if(!i)return;return{events:o,sessionId:e,sequenceId:i}}catch(e){this.loggerProvider.warn(`${ne}: ${e}`)}})),this.storeSendingEvents=(e,t)=>n(this,void 0,void 0,(function*(){try{return yield this.db.put(Re,{sessionId:e,events:t})}catch(e){this.loggerProvider.warn(`${ne}: ${e}`)}})),this.cleanUpSessionEventsStore=(e,t)=>n(this,void 0,void 0,(function*(){if(t)try{yield this.db.delete(Re,t)}catch(e){this.loggerProvider.warn(`${ne}: ${e}`)}})),this.transitionFromKeyValStore=e=>n(this,void 0,void 0,(function*(){try{const t=yield function(){const e=l();return new Promise(((t,n)=>{if(!e)return n(new Error("Global scope not found"));if(!e.indexedDB)return n(new Error("Session Replay: cannot find indexedDB"));try{const r=e.indexedDB.open("keyval-store");r.onupgradeneeded=function(){1===r.result.version&&(r.result.close(),r.transaction&&r.transaction.abort(),e.indexedDB.deleteDatabase("keyval-store"),t())},r.onsuccess=function(){t(r.result)},r.onerror=function(){n(r.error)}}catch(e){n(e)}}))}();if(!t)return;const r=(e,t)=>n(this,void 0,void 0,(function*(){const r=t.sessionSequences,o=[];Object.keys(r).forEach((i=>{const s=parseInt(i,10),a=r[s];if(s===t.currentSequenceId){const t=a.events.map((t=>n(this,void 0,void 0,(function*(){return this.addEventToCurrentSequence(e,t)}))));o.push(...t)}else a.status!==Oe.SENT&&o.push(this.storeSendingEvents(e,a.events))})),yield qe(o)})),o=`${i}_${this.apiKey.substring(0,10)}`;try{const i=t.transaction("keyval").objectStore("keyval").getAll(o),s=new Promise((t=>{i.onsuccess=o=>n(this,void 0,void 0,(function*(){const n=o&&o.target.result,i=n&&n[0];if(i){const t=[];Object.keys(i).forEach((n=>{const o=parseInt(n,10),s=i[o];if(e===o)t.push(r(o,s));else{const e=s.sessionSequences;Object.keys(e).forEach((n=>{const r=parseInt(n,10);e[r].status!==Oe.SENT&&t.push(this.storeSendingEvents(o,e[r].events))}))}})),yield qe(t)}t()}))}));yield s;const a=l();a&&a.indexedDB.deleteDatabase("keyval-store")}catch(e){this.loggerProvider.warn(`Failed to transition session replay events from keyval to new store: ${e}`)}}catch(e){this.loggerProvider.warn(`Failed to access keyval store: ${e}. For more information, visit: https://www.docs.developers.amplitude.com/session-replay/sdks/standalone/#indexeddb-best-practices`)}})),this.apiKey=e.apiKey,this.db=e.db}static new(e,t,r){return n(this,void 0,void 0,(function*(){try{const n="replay"===e?"":`_${e}`,o=`${t.apiKey.substring(0,10)}_amp_session_replay_events${n}`,i=yield Le(o),s=new De(Object.assign(Object.assign({},t),{db:i}));return yield s.transitionFromKeyValStore(r),s}catch(e){t.loggerProvider.warn(`${ne}: ${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 je extends Pe{constructor(){super(...arguments),this.finalizedSequences={},this.sequences={},this.sequenceId=0}resetCurrentSequence(e){this.sequences[e]=[]}addSequence(e){const t=this.sequenceId++,n=[...this.sequences[e]];return this.finalizedSequences[t]={sessionId:e,events:n},this.resetCurrentSequence(e),{sequenceId:t,events:n,sessionId:e}}getSequencesToSend(){return n(this,void 0,void 0,(function*(){return Object.entries(this.finalizedSequences).map((([e,{sessionId:t,events:n}])=>({sequenceId:Number(e),sessionId:t,events:n})))}))}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 n;return this.sequences[e]||this.resetCurrentSequence(e),this.shouldSplitEventsList(this.sequences[e],t)&&(n=this.addSequence(e)),this.sequences[e].push(t),n}))}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 Ne=({config:e,sessionId:t,minInterval:r,maxInterval:o,type:i,payloadBatcher:s,storeType:a})=>n(void 0,void 0,void 0,(function*(){const l=new oe(Object.assign(Object.assign({},e),{loggerProvider:e.loggerProvider,payloadBatcher:s})),c=()=>new je({loggerProvider:e.loggerProvider,maxInterval:o,minInterval:r}),u="idb"===a?yield n(void 0,void 0,void 0,(function*(){const n=yield De.new(i,{loggerProvider:e.loggerProvider,minInterval:r,maxInterval:o,apiKey:e.apiKey},t);return e.loggerProvider.log("Failed to initialize idb store, falling back to memory store."),null!=n?n:c()})):c(),d=({events:t,sessionId:r,deviceId:o,sequenceId:s})=>{e.debugMode&&Z().then((({totalStorageSize:t,percentOfQuota:n,usageDetails:r})=>{e.loggerProvider.debug(`Total storage size: ${t} KB, percentage of quota: ${n}%, usage details: ${r}`)})).catch((()=>{})),l.sendEventsList({events:t,sessionId:r,flushMaxRetries:e.flushMaxRetries,apiKey:e.apiKey,deviceId:o,sampleRate:e.sampleRate,serverZone:e.serverZone,version:e.version,type:i,onComplete:()=>n(void 0,void 0,void 0,(function*(){yield u.cleanUpSessionEventsStore(r,s)}))})};return{sendCurrentSequenceEvents:({sessionId:t,deviceId:n})=>{u.storeCurrentSequence(t).then((e=>{e&&d({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:n})})).catch((t=>{e.loggerProvider.warn("Failed to get current sequence of session replay events for session:",t)}))},addEvent:({event:t,sessionId:n,deviceId:r})=>{u.addEventToCurrentSequence(n,t.data).then((e=>e&&d({sequenceId:e.sequenceId,events:e.events,sessionId:e.sessionId,deviceId:r}))).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*(){const t=yield u.getSequencesToSend();t&&t.forEach((t=>{d({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)}))}}}));class $e{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((n=>{t.push(n.sendStoredEvents(e))})),yield Promise.all(t)}))}addEvent({sessionId:e,event:t,deviceId:n}){var r;null===(r=this.managers.get(t.type))||void 0===r||r.addEvent({sessionId:e,event:t,deviceId:n})}sendCurrentSequenceEvents({sessionId:e,deviceId:t}){this.managers.forEach((n=>{n.sendCurrentSequenceEvents({sessionId:e,deviceId:t})}))}flush(e){return n(this,void 0,void 0,(function*(){const t=[];this.managers.forEach((n=>{t.push(n.flush(e))})),yield Promise.all(t)}))}}const Ue={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},Be={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},Fe={};function Ae(e){if(Fe[e])return Fe[e];const t=globalThis[e],n=t.prototype,r=e in Ue?Ue[e]:void 0,o=Boolean(r&&r.every((e=>{var t,r;return Boolean(null==(r=null==(t=Object.getOwnPropertyDescriptor(n,e))?void 0:t.get)?void 0:r.toString().includes("[native code]"))}))),i=e in Be?Be[e]:void 0,s=Boolean(i&&i.every((e=>{var t;return"function"==typeof n[e]&&(null==(t=n[e])?void 0:t.toString().includes("[native code]"))})));if(o&&s&&!globalThis.Zone)return Fe[e]=t.prototype,t.prototype;try{const r=document.createElement("iframe");document.body.appendChild(r);const o=r.contentWindow;if(!o)return t.prototype;const i=o[e].prototype;return document.body.removeChild(r),i?Fe[e]=i:n}catch{return n}}const Ke={};function We(e,t,n){var r;const o=`${e}.${String(n)}`;if(Ke[o])return Ke[o].call(t);const i=Ae(e),s=null==(r=Object.getOwnPropertyDescriptor(i,n))?void 0:r.get;return s?(Ke[o]=s,s.call(t)):t[n]}const ze={};function Ge(e,t,n){const r=`${e}.${String(n)}`;if(ze[r])return ze[r].bind(t);const o=Ae(e)[n];return"function"!=typeof o?t[n]:(ze[r]=o,o.bind(t))}const Qe={childNodes:function(e){return We("Node",e,"childNodes")},parentNode:function(e){return We("Node",e,"parentNode")},parentElement:function(e){return We("Node",e,"parentElement")},textContent:function(e){return We("Node",e,"textContent")},contains:function(e,t){return Ge("Node",e,"contains")(t)},getRootNode:function(e){return Ge("Node",e,"getRootNode")()},host:function(e){return e&&"host"in e?We("ShadowRoot",e,"host"):null},styleSheets:function(e){return e.styleSheets},shadowRoot:function(e){return e&&"shadowRoot"in e?We("Element",e,"shadowRoot"):null},querySelector:function(e,t){return We("Element",e,"querySelector")(t)},querySelectorAll:function(e,t){return We("Element",e,"querySelectorAll")(t)},mutationObserver:function(){return Ae("MutationObserver").constructor}};function He(){const e=l();return(null==e?void 0:e.innerHeight)||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight||0}function Je(){const e=l();return(null==e?void 0:e.innerWidth)||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth||0}let Ve,Ze,Xe;function Ye(e,t){if(Xe=new Date,e.nodeType!==Node.ELEMENT_NODE)throw new Error("Can't generate CSS selector for non-element node type.");if("html"===e.tagName.toLowerCase())return"html";const n={root:document.body,idName:e=>!0,className:e=>!0,tagName:e=>!0,attr:(e,t)=>!1,seedMinLength:1,optimizedMinLength:2,threshold:1e3,maxNumberOfTries:1e4,timeoutMs:void 0};Ve=Object.assign(Object.assign({},n),t),Ze=function(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return e;if(e===t.root)return e.ownerDocument;return e}(Ve.root,n);let r=et(e,"all",(()=>et(e,"two",(()=>et(e,"one",(()=>et(e,"none")))))));if(r){const t=gt(pt(r,e));return t.length>0&&(r=t[0]),nt(r)}throw new Error("Selector was not found.")}function et(e,t,n){let r=null,o=[],i=e,s=0;for(;i;){const e=(new Date).getTime()-Xe.getTime();if(void 0!==Ve.timeoutMs&&e>Ve.timeoutMs)throw new Error(`Timeout: Can't find a unique selector after ${e}ms`);let a=ht(it(i))||ht(...st(i))||ht(...at(i))||ht(lt(i))||[{name:"*",penalty:3}];const l=ct(i);if("all"==t)l&&(a=a.concat(a.filter(dt).map((e=>ut(e,l)))));else if("two"==t)a=a.slice(0,1),l&&(a=a.concat(a.filter(dt).map((e=>ut(e,l)))));else if("one"==t){const[e]=a=a.slice(0,1);l&&dt(e)&&(a=[ut(e,l)])}else"none"==t&&(a=[{name:"*",penalty:3}],l&&(a=[ut(a[0],l)]));for(let e of a)e.level=s;if(o.push(a),o.length>=Ve.seedMinLength&&(r=tt(o,n),r))break;i=i.parentElement,s++}return r||(r=tt(o,n)),!r&&n?n():r}function tt(e,t){const n=gt(vt(e));if(n.length>Ve.threshold)return t?t():null;for(let e of n)if(ot(e))return e;return null}function nt(e){let t=e[0],n=t.name;for(let r=1;r<e.length;r++){const o=e[r].level||0;n=t.level===o-1?`${e[r].name} > ${n}`:`${e[r].name} ${n}`,t=e[r]}return n}function rt(e){return e.map((e=>e.penalty)).reduce(((e,t)=>e+t),0)}function ot(e){const t=nt(e);switch(Ze.querySelectorAll(t).length){case 0:throw new Error(`Can't select any node with this selector: ${t}`);case 1:return!0;default:return!1}}function it(e){const t=e.getAttribute("id");return t&&Ve.idName(t)?{name:"#"+CSS.escape(t),penalty:0}:null}function st(e){const t=Array.from(e.attributes).filter((e=>Ve.attr(e.name,e.value)));return t.map((e=>({name:`[${CSS.escape(e.name)}="${CSS.escape(e.value)}"]`,penalty:.5})))}function at(e){return Array.from(e.classList).filter(Ve.className).map((e=>({name:"."+CSS.escape(e),penalty:1})))}function lt(e){const t=e.tagName.toLowerCase();return Ve.tagName(t)?{name:t,penalty:2}:null}function ct(e){const t=e.parentNode;if(!t)return null;let n=t.firstChild;if(!n)return null;let r=0;for(;n&&(n.nodeType===Node.ELEMENT_NODE&&r++,n!==e);)n=n.nextSibling;return r}function ut(e,t){return{name:e.name+`:nth-child(${t})`,penalty:e.penalty+1}}function dt(e){return"html"!==e.name&&!e.name.startsWith("#")}function ht(...e){const t=e.filter(ft);return t.length>0?t:null}function ft(e){return null!=e}function*vt(e,t=[]){if(e.length>0)for(let n of e[0])yield*vt(e.slice(1,e.length),t.concat(n));else yield t}function gt(e){return[...e].sort(((e,t)=>rt(e)-rt(t)))}function*pt(e,t,n={counter:0,visited:new Map}){if(e.length>2&&e.length>Ve.optimizedMinLength)for(let r=1;r<e.length-1;r++){if(n.counter>Ve.maxNumberOfTries)return;n.counter+=1;const o=[...e];o.splice(r,1);const i=nt(o);if(n.visited.has(i))return;ot(o)&&mt(o,t)&&(yield o,n.visited.set(i,!0),yield*pt(o,t,n))}}function mt(e,t){return Ze.querySelector(nt(e))===t}const yt=({version:e,events:t})=>{const n=[];return t.forEach((e=>{const t=JSON.parse(e);t.count=1,"click"===t.type&&n.push(t)})),{version:e,events:n}},bt=({version:e,events:t})=>{const n=[];t.forEach((e=>{const t=JSON.parse(e);"click"===t.type&&n.push(t)}));const r=n.reduce(((e,t)=>{const{x:n,y:r,selector:o,timestamp:i}=t,s=i-i%36e5,a=`${n}:${r}:${null!=o?o:""}:${s}`;return e[a]?e[a].count+=1:e[a]=Object.assign(Object.assign({},t),{timestamp:s,count:1}),e}),{});return{version:e,events:Object.values(r)}},St=(e,{eventsManager:t,sessionId:n,deviceIdFn:r,mirror:o,ugcFilterRules:i})=>s=>{if(s.type!==q.Click)return;const a=l();if(!a)return;const{location:c,innerHeight:u,innerWidth:d}=a;if(!c)return;const{x:h,y:f}=s;if(void 0===h||void 0===f)return;const v=o.getNode(s.id);let g;if(v)try{g=Ye(v)}catch(t){e.debug("error resolving selector from finder")}const{left:p,top:m}=function(e){var t,n,r,o;const i=e.document;return{left:i.scrollingElement?i.scrollingElement.scrollLeft:void 0!==e.pageXOffset?e.pageXOffset:i.documentElement.scrollLeft||(null==i?void 0:i.body)&&(null===(t=Qe.parentElement(i.body))||void 0===t?void 0:t.scrollLeft)||(null===(n=null==i?void 0:i.body)||void 0===n?void 0:n.scrollLeft)||0,top:i.scrollingElement?i.scrollingElement.scrollTop:void 0!==e.pageYOffset?e.pageYOffset:(null==i?void 0:i.documentElement.scrollTop)||(null==i?void 0:i.body)&&(null===(r=Qe.parentElement(i.body))||void 0===r?void 0:r.scrollTop)||(null===(o=null==i?void 0:i.body)||void 0===o?void 0:o.scrollTop)||0}}(a),y={x:h+p,y:f+m,selector:g,viewportHeight:u,viewportWidth:d,pageUrl:V(c.href,i),timestamp:Date.now(),type:"click"},b=r();b&&t.addEvent({sessionId:n,event:{type:"interaction",data:JSON.stringify(y)},deviceId:b})};class wt{constructor(e,t){const n=l();n&&n.navigator&&"function"==typeof n.navigator.sendBeacon?this.sendBeacon=(e,t)=>{try{if(n.navigator.sendBeacon(e,JSON.stringify(t)))return!0}catch(e){}return!1}:this.sendBeacon=()=>!1,this.sendXhr=(e,t)=>{const n=new XMLHttpRequest;return n.open("POST",e,!0),n.setRequestHeader("Accept","*/*"),n.send(JSON.stringify(t)),!0},this.basePageUrl=H(t.serverZone,t.trackServerUrl),this.apiKey=t.apiKey,this.context=e}send(e,t){const{sessionId:n,type:r}=this.context,o=new URLSearchParams({device_id:e,session_id:String(n),type:String(r),api_key:this.apiKey}),i=`${this.basePageUrl}?${o.toString()}`;this.sendBeacon(i,t)||this.sendXhr(i,t)}}class It{static default(e,t){return new It(new wt(e,t),t)}constructor(e,t){this.timestamp=Date.now(),this.hook=e=>{this.update(e)},this.send=e=>t=>{var n,r;const o=e(),i=l();i&&o&&this.transport.send(o,{version:1,events:[{maxScrollX:this._maxScrollX,maxScrollY:this._maxScrollY,maxScrollWidth:this._maxScrollWidth,maxScrollHeight:this._maxScrollHeight,viewportHeight:He(),viewportWidth:Je(),pageUrl:V(i.location.href,null!==(r=null===(n=this.config.interactionConfig)||void 0===n?void 0:n.ugcFilterRules)&&void 0!==r?r:[]),timestamp:this.timestamp,type:"scroll"}]})},this._maxScrollX=0,this._maxScrollY=0,this._maxScrollWidth=Je(),this._maxScrollHeight=He(),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}update(e){const t=Date.now();if(e.x>this._maxScrollX){const n=Je();this._maxScrollX=e.x;const r=e.x+n;r>this._maxScrollWidth&&(this._maxScrollWidth=r),this.timestamp=t}if(e.y>this._maxScrollY){const n=He();this._maxScrollY=e.y;const r=e.y+n;r>this._maxScrollHeight&&(this._maxScrollHeight=r),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))}}var Et=Uint8Array,kt=Uint16Array,xt=Uint32Array,_t=new Et([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Pt=new Et([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Ot=new Et([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Tt=function(e,t){for(var n=new kt(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];var o=new xt(n[30]);for(r=1;r<30;++r)for(var i=n[r];i<n[r+1];++i)o[i]=i-n[r]<<5|r;return[n,o]},Rt=Tt(_t,2),qt=Rt[0],Mt=Rt[1];qt[28]=258,Mt[258]=28;for(var Lt=Tt(Pt,0)[1],Dt=new kt(32768),jt=0;jt<32768;++jt){var Nt=(43690&jt)>>>1|(21845&jt)<<1;Nt=(61680&(Nt=(52428&Nt)>>>2|(13107&Nt)<<2))>>>4|(3855&Nt)<<4,Dt[jt]=((65280&Nt)>>>8|(255&Nt)<<8)>>>1}var $t=function(e,t,n){for(var r=e.length,o=0,i=new kt(t);o<r;++o)++i[e[o]-1];var s,a=new kt(t);for(o=0;o<t;++o)a[o]=a[o-1]+i[o-1]<<1;if(n){s=new kt(1<<t);var l=15-t;for(o=0;o<r;++o)if(e[o])for(var c=o<<4|e[o],u=t-e[o],d=a[e[o]-1]++<<u,h=d|(1<<u)-1;d<=h;++d)s[Dt[d]>>>l]=c}else for(s=new kt(r),o=0;o<r;++o)s[o]=Dt[a[e[o]-1]++]>>>15-e[o];return s},Ut=new Et(288);for(jt=0;jt<144;++jt)Ut[jt]=8;for(jt=144;jt<256;++jt)Ut[jt]=9;for(jt=256;jt<280;++jt)Ut[jt]=7;for(jt=280;jt<288;++jt)Ut[jt]=8;var Bt=new Et(32);for(jt=0;jt<32;++jt)Bt[jt]=5;var Ft=$t(Ut,9,0),At=$t(Bt,5,0),Kt=function(e){return(e/8|0)+(7&e&&1)},Wt=function(e,t,n){(null==n||n>e.length)&&(n=e.length);var r=new(e instanceof kt?kt:e instanceof xt?xt:Et)(n-t);return r.set(e.subarray(t,n)),r},zt=function(e,t,n){n<<=7&t;var r=t/8|0;e[r]|=n,e[r+1]|=n>>>8},Gt=function(e,t,n){n<<=7&t;var r=t/8|0;e[r]|=n,e[r+1]|=n>>>8,e[r+2]|=n>>>16},Qt=function(e,t){for(var n=[],r=0;r<e.length;++r)e[r]&&n.push({s:r,f:e[r]});var o=n.length,i=n.slice();if(!o)return[new Et(0),0];if(1==o){var s=new Et(n[0].s+1);return s[n[0].s]=1,[s,1]}n.sort((function(e,t){return e.f-t.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],c=0,u=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};u!=o-1;)a=n[n[c].f<n[d].f?c++:d++],l=n[c!=u&&n[c].f<n[d].f?c++:d++],n[u++]={s:-1,f:a.f+l.f,l:a,r:l};var h=i[0].s;for(r=1;r<o;++r)i[r].s>h&&(h=i[r].s);var f=new kt(h+1),v=Ht(n[u-1],f,0);if(v>t){r=0;var g=0,p=v-t,m=1<<p;for(i.sort((function(e,t){return f[t.s]-f[e.s]||e.f-t.f}));r<o;++r){var y=i[r].s;if(!(f[y]>t))break;g+=m-(1<<v-f[y]),f[y]=t}for(g>>>=p;g>0;){var b=i[r].s;f[b]<t?g-=1<<t-f[b]++-1:++r}for(;r>=0&&g;--r){var S=i[r].s;f[S]==t&&(--f[S],++g)}v=t}return[new Et(f),v]},Ht=function(e,t,n){return-1==e.s?Math.max(Ht(e.l,t,n+1),Ht(e.r,t,n+1)):t[e.s]=n},Jt=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new kt(++t),r=0,o=e[0],i=1,s=function(e){n[r++]=e},a=1;a<=t;++a)if(e[a]==o&&a!=t)++i;else{if(!o&&i>2){for(;i>138;i-=138)s(32754);i>2&&(s(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(s(o),--i;i>6;i-=6)s(8304);i>2&&(s(i-3<<5|8208),i=0)}for(;i--;)s(o);i=1,o=e[a]}return[n.subarray(0,r),t]},Vt=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},Zt=function(e,t,n){var r=n.length,o=Kt(t+2);e[o]=255&r,e[o+1]=r>>>8,e[o+2]=255^e[o],e[o+3]=255^e[o+1];for(var i=0;i<r;++i)e[o+i+4]=n[i];return 8*(o+4+r)},Xt=function(e,t,n,r,o,i,s,a,l,c,u){zt(t,u++,n),++o[256];for(var d=Qt(o,15),h=d[0],f=d[1],v=Qt(i,15),g=v[0],p=v[1],m=Jt(h),y=m[0],b=m[1],S=Jt(g),w=S[0],I=S[1],C=new kt(19),E=0;E<y.length;++E)C[31&y[E]]++;for(E=0;E<w.length;++E)C[31&w[E]]++;for(var k=Qt(C,7),x=k[0],_=k[1],P=19;P>4&&!x[Ot[P-1]];--P);var O,T,R,q,M=c+5<<3,L=Vt(o,Ut)+Vt(i,Bt)+s,D=Vt(o,h)+Vt(i,g)+s+14+3*P+Vt(C,x)+(2*C[16]+3*C[17]+7*C[18]);if(M<=L&&M<=D)return Zt(t,u,e.subarray(l,l+c));if(zt(t,u,1+(D<L)),u+=2,D<L){O=$t(h,f,0),T=h,R=$t(g,p,0),q=g;var j=$t(x,_,0);zt(t,u,b-257),zt(t,u+5,I-1),zt(t,u+10,P-4),u+=14;for(E=0;E<P;++E)zt(t,u+3*E,x[Ot[E]]);u+=3*P;for(var N=[y,w],$=0;$<2;++$){var U=N[$];for(E=0;E<U.length;++E){var B=31&U[E];zt(t,u,j[B]),u+=x[B],B>15&&(zt(t,u,U[E]>>>5&127),u+=U[E]>>>12)}}}else O=Ft,T=Ut,R=At,q=Bt;for(E=0;E<a;++E)if(r[E]>255){B=r[E]>>>18&31;Gt(t,u,O[B+257]),u+=T[B+257],B>7&&(zt(t,u,r[E]>>>23&31),u+=_t[B]);var F=31&r[E];Gt(t,u,R[F]),u+=q[F],F>3&&(Gt(t,u,r[E]>>>5&8191),u+=Pt[F])}else Gt(t,u,O[r[E]]),u+=T[r[E]];return Gt(t,u,O[256]),u+T[256]},Yt=new xt([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),en=function(e,t,n,r,o){return function(e,t,n,r,o,i){var s=e.length,a=new Et(r+s+5*(1+Math.floor(s/7e3))+o),l=a.subarray(r,a.length-o),c=0;if(!t||s<8)for(var u=0;u<=s;u+=65535){var d=u+65535;d<s?c=Zt(l,c,e.subarray(u,d)):(l[u]=i,c=Zt(l,c,e.subarray(u,s)))}else{for(var h=Yt[t-1],f=h>>>13,v=8191&h,g=(1<<n)-1,p=new kt(32768),m=new kt(g+1),y=Math.ceil(n/3),b=2*y,S=function(t){return(e[t]^e[t+1]<<y^e[t+2]<<b)&g},w=new xt(25e3),I=new kt(288),C=new kt(32),E=0,k=0,x=(u=0,0),_=0,P=0;u<s;++u){var O=S(u),T=32767&u,R=m[O];if(p[T]=R,m[O]=T,_<=u){var q=s-u;if((E>7e3||x>24576)&&q>423){c=Xt(e,l,0,w,I,C,k,x,P,u-P,c),x=E=k=0,P=u;for(var M=0;M<286;++M)I[M]=0;for(M=0;M<30;++M)C[M]=0}var L=2,D=0,j=v,N=T-R&32767;if(q>2&&O==S(u-N))for(var $=Math.min(f,q)-1,U=Math.min(32767,u),B=Math.min(258,q);N<=U&&--j&&T!=R;){if(e[u+L]==e[u+L-N]){for(var F=0;F<B&&e[u+F]==e[u+F-N];++F);if(F>L){if(L=F,D=N,F>$)break;var A=Math.min(N,F-2),K=0;for(M=0;M<A;++M){var W=u-N+M+32768&32767,z=W-p[W]+32768&32767;z>K&&(K=z,R=W)}}}N+=(T=R)-(R=p[T])+32768&32767}if(D){w[x++]=268435456|Mt[L]<<18|Lt[D];var G=31&Mt[L],Q=31&Lt[D];k+=_t[G]+Pt[Q],++I[257+G],++C[Q],_=u+L,++E}else w[x++]=e[u],++I[e[u]]}}c=Xt(e,l,i,w,I,C,k,x,P,u-P,c)}return Wt(a,0,r+Kt(c)+o)}(e,null==t.level?6:t.level,null==t.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):12+t.mem,n,r,!o)};function tn(e,t){void 0===t&&(t={});var n=function(){var e=1,t=0;return{p:function(n){for(var r=e,o=t,i=n.length,s=0;s!=i;){for(var a=Math.min(s+5552,i);s<a;++s)o+=r+=n[s];r%=65521,o%=65521}e=r,t=o},d:function(){return(e>>>8<<16|(255&t)<<8|t>>>8)+2*((255&e)<<23)}}}();n.p(e);var r,o,i,s=en(e,t,2,4);return r=s,o=t.level,i=0==o?0:o<6?1:9==o?3:2,r[0]=120,r[1]=i<<6|(i?32-2*i:1),function(e,t,n){for(;n;++t)e[t]=n,n>>>=8}(s,s.length-4,n.d()),s}const nn=e=>{const t={...e,v:"v1"};return function(e,t){var n="";if(!t&&"undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);for(var r=0;r<e.length;){var o=e[r++];o<128||t?n+=String.fromCharCode(o):o<224?n+=String.fromCharCode((31&o)<<6|63&e[r++]):o<240?n+=String.fromCharCode((15&o)<<12|(63&e[r++])<<6|63&e[r++]):(o=((15&o)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536,n+=String.fromCharCode(55296|o>>10,56320|1023&o))}return n}(tn(function(e,t){var n=e.length;if(!t&&"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);for(var r=new Et(e.length+(e.length>>>1)),o=0,i=function(e){r[o++]=e},s=0;s<n;++s){if(o+5>r.length){var a=new Et(o+8+(n-s<<1));a.set(r),r=a}var l=e.charCodeAt(s);l<128||t?i(l):l<2048?(i(192|l>>>6),i(128|63&l)):l>55295&&l<57344?(i(240|(l=65536+(1047552&l)|1023&e.charCodeAt(++s))>>>18),i(128|l>>>12&63),i(128|l>>>6&63),i(128|63&l)):(i(224|l>>>12),i(128|l>>>6&63),i(128|63&l))}return Wt(r,0,o)}(JSON.stringify(t))),!0)};class rn{constructor(e,t,n,r){var o,i,s;this.taskQueue=[],this.isProcessing=!1,this.compressEvent=e=>{const t=nn(e);return JSON.stringify(t)},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)this.worker.postMessage({event:e,sessionId:t});else{const n=this.compressEvent(e);this.addCompressedEventToManager(n,t)}},this.terminate=()=>{var e;null===(e=this.worker)||void 0===e||e.terminate()};const a=l();this.canUseIdleCallback=a&&"requestIdleCallback"in a,this.eventsManager=e,this.config=t,this.deviceId=n,this.timeout=(null===(o=t.performanceConfig)||void 0===o?void 0:o.timeout)||2e3;const c=null!==(i='var WebWorker=function(r){"use strict";var n=Uint8Array,e=Uint16Array,f=Uint32Array,t=new n([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),o=new n([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),a=new n([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),i=function(r,n){for(var t=new e(31),o=0;o<31;++o)t[o]=n+=1<<r[o-1];var a=new f(t[30]);for(o=1;o<30;++o)for(var i=t[o];i<t[o+1];++i)a[i]=i-t[o]<<5|o;return[t,a]},v=i(t,2),u=v[0],s=v[1];u[28]=258,s[258]=28;for(var l=i(o,0)[1],c=new e(32768),h=0;h<32768;++h){var g=(43690&h)>>>1|(21845&h)<<1;g=(61680&(g=(52428&g)>>>2|(13107&g)<<2))>>>4|(3855&g)<<4,c[h]=((65280&g)>>>8|(255&g)<<8)>>>1}var w=function(r,n,f){for(var t=r.length,o=0,a=new e(n);o<t;++o)++a[r[o]-1];var i,v=new e(n);for(o=0;o<n;++o)v[o]=v[o-1]+a[o-1]<<1;if(f){i=new e(1<<n);var u=15-n;for(o=0;o<t;++o)if(r[o])for(var s=o<<4|r[o],l=n-r[o],h=v[r[o]-1]++<<l,g=h|(1<<l)-1;h<=g;++h)i[c[h]>>>u]=s}else for(i=new e(t),o=0;o<t;++o)i[o]=c[v[r[o]-1]++]>>>15-r[o];return i},d=new n(288);for(h=0;h<144;++h)d[h]=8;for(h=144;h<256;++h)d[h]=9;for(h=256;h<280;++h)d[h]=7;for(h=280;h<288;++h)d[h]=8;var m=new n(32);for(h=0;h<32;++h)m[h]=5;var M=w(d,9,0),y=w(m,5,0),b=function(r){return(r/8|0)+(7&r&&1)},p=function(r,t,o){(null==o||o>r.length)&&(o=r.length);var a=new(r instanceof e?e:r instanceof f?f:n)(o-t);return a.set(r.subarray(t,o)),a},C=function(r,n,e){e<<=7&n;var f=n/8|0;r[f]|=e,r[f+1]|=e>>>8},x=function(r,n,e){e<<=7&n;var f=n/8|0;r[f]|=e,r[f+1]|=e>>>8,r[f+2]|=e>>>16},S=function(r,f){for(var t=[],o=0;o<r.length;++o)r[o]&&t.push({s:o,f:r[o]});var a=t.length,i=t.slice();if(!a)return[new n(0),0];if(1==a){var v=new n(t[0].s+1);return v[t[0].s]=1,[v,1]}t.sort((function(r,n){return r.f-n.f})),t.push({s:-1,f:25001});var u=t[0],s=t[1],l=0,c=1,h=2;for(t[0]={s:-1,f:u.f+s.f,l:u,r:s};c!=a-1;)u=t[t[l].f<t[h].f?l++:h++],s=t[l!=c&&t[l].f<t[h].f?l++:h++],t[c++]={s:-1,f:u.f+s.f,l:u,r:s};var g=i[0].s;for(o=1;o<a;++o)i[o].s>g&&(g=i[o].s);var w=new e(g+1),d=A(t[c-1],w,0);if(d>f){o=0;var m=0,M=d-f,y=1<<M;for(i.sort((function(r,n){return w[n.s]-w[r.s]||r.f-n.f}));o<a;++o){var b=i[o].s;if(!(w[b]>f))break;m+=y-(1<<d-w[b]),w[b]=f}for(m>>>=M;m>0;){var p=i[o].s;w[p]<f?m-=1<<f-w[p]++-1:++o}for(;o>=0&&m;--o){var C=i[o].s;w[C]==f&&(--w[C],++m)}d=f}return[new n(w),d]},A=function(r,n,e){return-1==r.s?Math.max(A(r.l,n,e+1),A(r.r,n,e+1)):n[r.s]=e},O=function(r){for(var n=r.length;n&&!r[--n];);for(var f=new e(++n),t=0,o=r[0],a=1,i=function(r){f[t++]=r},v=1;v<=n;++v)if(r[v]==o&&v!=n)++a;else{if(!o&&a>2){for(;a>138;a-=138)i(32754);a>2&&(i(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(i(o),--a;a>6;a-=6)i(8304);a>2&&(i(a-3<<5|8208),a=0)}for(;a--;)i(o);a=1,o=r[v]}return[f.subarray(0,t),n]},T=function(r,n){for(var e=0,f=0;f<n.length;++f)e+=r[f]*n[f];return e},k=function(r,n,e){var f=e.length,t=b(n+2);r[t]=255&f,r[t+1]=f>>>8,r[t+2]=255^r[t],r[t+3]=255^r[t+1];for(var o=0;o<f;++o)r[t+o+4]=e[o];return 8*(t+4+f)},E=function(r,n,f,i,v,u,s,l,c,h,g){C(n,g++,f),++v[256];for(var b=S(v,15),p=b[0],A=b[1],E=S(u,15),U=E[0],D=E[1],I=O(p),J=I[0],N=I[1],W=O(U),_=W[0],j=W[1],P=new e(19),q=0;q<J.length;++q)P[31&J[q]]++;for(q=0;q<_.length;++q)P[31&_[q]]++;for(var z=S(P,7),B=z[0],F=z[1],G=19;G>4&&!B[a[G-1]];--G);var H,K,L,Q,R=h+5<<3,V=T(v,d)+T(u,m)+s,X=T(v,p)+T(u,U)+s+14+3*G+T(P,B)+(2*P[16]+3*P[17]+7*P[18]);if(R<=V&&R<=X)return k(n,g,r.subarray(c,c+h));if(C(n,g,1+(X<V)),g+=2,X<V){H=w(p,A,0),K=p,L=w(U,D,0),Q=U;var Y=w(B,F,0);C(n,g,N-257),C(n,g+5,j-1),C(n,g+10,G-4),g+=14;for(q=0;q<G;++q)C(n,g+3*q,B[a[q]]);g+=3*G;for(var Z=[J,_],$=0;$<2;++$){var rr=Z[$];for(q=0;q<rr.length;++q){var nr=31&rr[q];C(n,g,Y[nr]),g+=B[nr],nr>15&&(C(n,g,rr[q]>>>5&127),g+=rr[q]>>>12)}}}else H=M,K=d,L=y,Q=m;for(q=0;q<l;++q)if(i[q]>255){nr=i[q]>>>18&31;x(n,g,H[nr+257]),g+=K[nr+257],nr>7&&(C(n,g,i[q]>>>23&31),g+=t[nr]);var er=31&i[q];x(n,g,L[er]),g+=Q[er],er>3&&(x(n,g,i[q]>>>5&8191),g+=o[er])}else x(n,g,H[i[q]]),g+=K[i[q]];return x(n,g,H[256]),g+K[256]},U=new f([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),D=function(r,a,i,v,u){return function(r,a,i,v,u,c){var h=r.length,g=new n(v+h+5*(1+Math.floor(h/7e3))+u),w=g.subarray(v,g.length-u),d=0;if(!a||h<8)for(var m=0;m<=h;m+=65535){var M=m+65535;M<h?d=k(w,d,r.subarray(m,M)):(w[m]=c,d=k(w,d,r.subarray(m,h)))}else{for(var y=U[a-1],C=y>>>13,x=8191&y,S=(1<<i)-1,A=new e(32768),O=new e(S+1),T=Math.ceil(i/3),D=2*T,I=function(n){return(r[n]^r[n+1]<<T^r[n+2]<<D)&S},J=new f(25e3),N=new e(288),W=new e(32),_=0,j=0,P=(m=0,0),q=0,z=0;m<h;++m){var B=I(m),F=32767&m,G=O[B];if(A[F]=G,O[B]=F,q<=m){var H=h-m;if((_>7e3||P>24576)&&H>423){d=E(r,w,0,J,N,W,j,P,z,m-z,d),P=_=j=0,z=m;for(var K=0;K<286;++K)N[K]=0;for(K=0;K<30;++K)W[K]=0}var L=2,Q=0,R=x,V=F-G&32767;if(H>2&&B==I(m-V))for(var X=Math.min(C,H)-1,Y=Math.min(32767,m),Z=Math.min(258,H);V<=Y&&--R&&F!=G;){if(r[m+L]==r[m+L-V]){for(var $=0;$<Z&&r[m+$]==r[m+$-V];++$);if($>L){if(L=$,Q=V,$>X)break;var rr=Math.min(V,$-2),nr=0;for(K=0;K<rr;++K){var er=m-V+K+32768&32767,fr=er-A[er]+32768&32767;fr>nr&&(nr=fr,G=er)}}}V+=(F=G)-(G=A[F])+32768&32767}if(Q){J[P++]=268435456|s[L]<<18|l[Q];var tr=31&s[L],or=31&l[Q];j+=t[tr]+o[or],++N[257+tr],++W[or],q=m+L,++_}else J[P++]=r[m],++N[r[m]]}}d=E(r,w,c,J,N,W,j,P,z,m-z,d)}return p(g,0,v+b(d)+u)}(r,null==a.level?6:a.level,null==a.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.length)))):12+a.mem,i,v,!u)};function I(r,n){void 0===n&&(n={});var e=function(){var r=1,n=0;return{p:function(e){for(var f=r,t=n,o=e.length,a=0;a!=o;){for(var i=Math.min(a+5552,o);a<i;++a)t+=f+=e[a];f%=65521,t%=65521}r=f,n=t},d:function(){return(r>>>8<<16|(255&n)<<8|n>>>8)+2*((255&r)<<23)}}}();e.p(r);var f,t,o,a=D(r,n,2,4);return f=a,t=n.level,o=0==t?0:t<6?1:9==t?3:2,f[0]=120,f[1]=o<<6|(o?32-2*o:1),function(r,n,e){for(;e;++n)r[n]=e,e>>>=8}(a,a.length-4,e.d()),a}const J=r=>{const e={...r,v:"v1"};return function(r,n){var e="";if(!n&&"undefined"!=typeof TextDecoder)return(new TextDecoder).decode(r);for(var f=0;f<r.length;){var t=r[f++];t<128||n?e+=String.fromCharCode(t):t<224?e+=String.fromCharCode((31&t)<<6|63&r[f++]):t<240?e+=String.fromCharCode((15&t)<<12|(63&r[f++])<<6|63&r[f++]):(t=((15&t)<<18|(63&r[f++])<<12|(63&r[f++])<<6|63&r[f++])-65536,e+=String.fromCharCode(55296|t>>10,56320|1023&t))}return e}(I(function(r,e){var f=r.length;if(!e&&"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(r);for(var t=new n(r.length+(r.length>>>1)),o=0,a=function(r){t[o++]=r},i=0;i<f;++i){if(o+5>t.length){var v=new n(o+8+(f-i<<1));v.set(t),t=v}var u=r.charCodeAt(i);u<128||e?a(u):u<2048?(a(192|u>>>6),a(128|63&u)):u>55295&&u<57344?(a(240|(u=65536+(1047552&u)|1023&r.charCodeAt(++i))>>>18),a(128|u>>>12&63),a(128|u>>>6&63),a(128|63&u)):(a(224|u>>>12),a(128|u>>>6&63),a(128|63&u))}return p(t,0,o)}(JSON.stringify(e))),!0)};onmessage=r=>{const{event:n,sessionId:e}=r.data,f=JSON.stringify(J(n));postMessage({compressedEvent:f,sessionId:e})};const N=onmessage;return r.compressionOnMessage=N,Object.defineProperty(r,"__esModule",{value:!0}),r}({});\n')?i:r;if((null===(s=this.config.experimental)||void 0===s?void 0:s.useWebWorker)&&a&&a.Worker&&c){t.loggerProvider.log("[Experimental] Enabling web worker for compression");const e=new Worker(URL.createObjectURL(new Blob([c],{type:"application/javascript"})));e.onerror=e=>{t.loggerProvider.error(e)},e.onmessage=e=>{const{compressedEvent:t,sessionId:n}=e.data;this.addCompressedEventToManager(t,n)},this.worker=e}}scheduleIdleProcessing(){this.isProcessing||(this.isProcessing=!0,requestIdleCallback((e=>{this.processQueue(e)}),{timeout:this.timeout}))}enqueueEvent(e,t){var n;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.taskQueue.push({event:e,sessionId:t}),this.scheduleIdleProcessing()):(this.config.loggerProvider.debug("Processing event without idle callback."),this.addCompressedEvent(e,t))}processQueue(e){for(;this.taskQueue.length>0&&(e.timeRemaining()>0||e.didTimeout);){const e=this.taskQueue.shift();if(e){const{event:t,sessionId:n}=e;this.addCompressedEvent(t,n)}}this.taskQueue.length>0?requestIdleCallback((e=>{this.processQueue(e)}),{timeout:this.timeout}):this.isProcessing=!1}}class on{constructor(){this.name="@amplitude/session-replay-browser",this.recordCancelCallback=null,this.eventCount=0,this.pageLeaveFns=[],this.recordFunction=null,this.teardownEventListeners=e=>{const t=l();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=()=>{this.recordEvents(!1)},this.pageLeaveListener=e=>{this.pageLeaveFns.forEach((t=>{t(e)}))},this.addCustomRRWebEvent=(e,t={},r=!0)=>n(this,void 0,void 0,(function*(){try{let n;const o=this.config;if(o&&e!==W.METADATA&&(n={config:X(o),version:re},r)){const e=yield Z();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 Y(new d)}init(e,t){return c(this._init(e,t))}_init(e,t){var r,o,i,s,a,c;return n(this,void 0,void 0,(function*(){this.loggerProvider=new Y(t.loggerProvider||new d),Object.prototype.hasOwnProperty.call(t,"logLevel")&&this.loggerProvider.enable(t.logLevel),this.identifiers=new Ct({sessionId:t.sessionId,deviceId:t.deviceId}),this.joinedConfigGenerator=yield((e,t)=>n(void 0,void 0,void 0,(function*(){const n=new ee(e,t),r=yield N({localConfig:n,configKeys:["sessionReplay"]});return new te(r,n)})))(e,t);const{joinedConfig:u,localConfig:h,remoteConfig:f}=yield this.joinedConfigGenerator.generateJoinedConfig(this.identifiers.sessionId);if(this.config=u,this.setMetadata(t.sessionId,u,h,f,null===(r=t.version)||void 0===r?void 0:r.version,re,null===(o=t.version)||void 0===o?void 0:o.type),t.sessionId&&(null===(i=this.config.interactionConfig)||void 0===i?void 0:i.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)}const v=[];let{storeType:g}=this.config;"idb"!==g||(null===(s=l())||void 0===s?void 0:s.indexedDB)||(g="memory",this.loggerProvider.warn("Could not use preferred indexedDB storage, reverting to in memory option.")),this.loggerProvider.log(`Using ${g} for event storage.`);try{const e=yield Ne({config:this.config,sessionId:this.identifiers.sessionId,type:"replay",storeType:g});v.push({name:"replay",manager:e})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating replay events manager: ${t.toString()}`)}if(null===(a=this.config.interactionConfig)||void 0===a?void 0:a.enabled){const e=this.config.interactionConfig.batch?bt:yt;try{const t=yield Ne({config:this.config,sessionId:this.identifiers.sessionId,type:"interaction",minInterval:null!==(c=this.config.interactionConfig.trackEveryNms)&&void 0!==c?c:3e4,maxInterval:6e4,payloadBatcher:e,storeType:g});v.push({name:"interaction",manager:t})}catch(e){const t=e;this.loggerProvider.warn(`Error occurred while creating interaction events manager: ${t.toString()}`)}}this.eventsManager=new $e(...v),this.eventCompressor&&this.eventCompressor.terminate(),this.eventCompressor=new rn(this.eventsManager,this.config,this.getDeviceId()),yield this.initializeNetworkObservers(),this.loggerProvider.log("Installing @amplitude/session-replay-browser."),this.teardownEventListeners(!1),this.initialize(!0)}))}setSessionId(e,t){return c(this.asyncSetSessionId(e,t))}asyncSetSessionId(e,t){return n(this,void 0,void 0,(function*(){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.identifiers.sessionId);this.config=e}this.recordEvents()}))}getSessionReplayProperties(){const e=this.config,t=this.identifiers;if(!e||!t)return this.loggerProvider.warn("Session replay init has not been called, cannot get session replay properties."),{};const n=this.getShouldRecord();let r={};return n&&(r={[B]:t.sessionReplayId?t.sessionReplayId:null},e.debugMode&&(r[A]=JSON.stringify({appHash:Q(e.apiKey).toString()}))),this.addCustomRRWebEvent(W.GET_SR_PROPS,{shouldRecord:n,eventProperties:r},10===this.eventCount),10===this.eventCount&&(this.eventCount=0),this.eventCount++,r}sendEvents(e){var t;const n=e||(null===(t=this.identifiers)||void 0===t?void 0:t.sessionId),r=this.getDeviceId();this.eventsManager&&n&&r&&this.eventsManager.sendCurrentSequenceEvents({sessionId:n,deviceId:r})}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 n=this.getDeviceId();return n?(this.eventsManager&&e&&this.eventsManager.sendStoredEvents({deviceId:n}),this.recordEvents()):(this.loggerProvider.log("Session is not being recorded due to lack of device id."),Promise.resolve())}))}shouldOptOut(){var e,t;let n;if(null===(e=this.config)||void 0===e?void 0:e.instanceName){n=(r=this.config.instanceName,void 0===r&&(r="$default_instance"),x.getInstance(r)).identityStore.getIdentity().optOut}var r;return void 0!==n?n:null===(t=this.config)||void 0===t?void 0:t.optOut}getShouldRecord(){if(!this.identifiers||!this.config||!this.identifiers.sessionId)return this.loggerProvider.warn("Session is not being recorded due to lack of config, please call sessionReplay.init."),!1;if(!this.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;const e=function(e,t){const n=Q(e.toString());return 31*Math.abs(n)%1e6/1e6<t}(this.identifiers.sessionId,this.config.sampleRate);return e||this.loggerProvider.log(`Opting session ${this.identifiers.sessionId} out of recording due to sample rate.`),e}getBlockSelectors(){var e,t,n;const r=null!==(n=null===(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)||void 0===t?void 0:t.blockSelector)&&void 0!==n?n:[];if(0!==r.length)return r}getMaskTextSelectors(){var e,t,n,r;if("conservative"===(null===(t=null===(e=this.config)||void 0===e?void 0:e.privacyConfig)||void 0===t?void 0:t.defaultMaskLevel))return"*";const o=null===(r=null===(n=this.config)||void 0===n?void 0:n.privacyConfig)||void 0===r?void 0:r.maskSelector;return o||void 0}getRecordingPlugins(e){var t;return n(this,void 0,void 0,(function*(){const n=[];if(null===(t=null==e?void 0:e.console)||void 0===t?void 0:t.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){var t,r,o;return n(this,void 0,void 0,(function*(){const n=this.config,i=this.getShouldRecord(),s=null===(t=this.identifiers)||void 0===t?void 0:t.sessionId;if(!i||!s||!n)return;this.stopRecordingEvents();const a=yield this.getRecordFunction();if(!a)return;yield this.initializeNetworkObservers(),null===(r=this.networkObservers)||void 0===r||r.start((e=>{this.addCustomRRWebEvent(W.FETCH_REQUEST,e)}));const{privacyConfig:l,interactionConfig:c,loggingConfig:u}=n,d=(null==c?void 0:c.enabled)?{mouseInteraction:this.eventsManager&&St(this.loggerProvider,{eventsManager:this.eventsManager,sessionId:s,deviceIdFn:this.getDeviceId.bind(this),mirror:a.mirror,ugcFilterRules:null!==(o=c.ugcFilterRules)&&void 0!==o?o:[]}),scroll:this.scrollHook}:{},h=(null==c?void 0:c.enabled)&&c.ugcFilterRules?c.ugcFilterRules:[];this.loggerProvider.log(`Session Replay capture beginning for ${s}.`);try{this.recordCancelCallback=a({emit:e=>{if(this.shouldOptOut())return this.loggerProvider.log(`Opting session ${s} out of recording due to optOut config.`),this.stopRecordingEvents(),void this.sendEvents();e.type===R.Meta&&(e.data.href=V(e.data.href,h)),this.eventCompressor&&this.eventCompressor.enqueueEvent(e,s)},inlineStylesheet:n.shouldInlineStylesheet,hooks:d,maskAllInputs:!0,maskTextClass:K,blockClass:"amp-block",blockSelector:this.getBlockSelectors(),applyBackgroundColorToBlockedElements:n.applyBackgroundColorToBlockedElements,maskInputFn:G("input",l),maskTextFn:G("text",l),maskTextSelector:this.getMaskTextSelectors(),recordCanvas:!1,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(u)}),this.addCustomRRWebEvent(W.DEBUG_INFO),e&&this.addCustomRRWebEvent(W.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(){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,n,r,o,i,s){const a=(null==e?void 0:e.toString())?Q(e.toString()):void 0;this.metadata={joinedConfig:t,localConfig:n,remoteConfig:r,sessionId:e,hashValue:a,sampleRate:t.sampleRate,replaySDKType:this.mapSDKType(s),replaySDKVersion:o,standaloneSDKType:"@amplitude/session-replay-browser",standaloneSDKVersion:i}}initializeNetworkObservers(){var e,t,r;return n(this,void 0,void 0,(function*(){if((null===(r=null===(t=null===(e=this.config)||void 0===e?void 0:e.loggingConfig)||void 0===t?void 0:t.network)||void 0===r?void 0:r.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)}}))}}export{on as S,n as _,l as g};
2
2
  //# sourceMappingURL=session-replay-min.js.map