@kameleoon/javascript-sdk
Version:
Kameleoon JavaScript SDK
1 lines • 166 kB
JavaScript
var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function i(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var i=function e(){var i=!1;try{i=this instanceof e}catch{}return i?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};i.prototype=t.prototype}else i={};return Object.defineProperty(i,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var a=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(i,t,a.get?a:{enumerable:!0,get:function(){return e[t]}})}),i}var a,r,n,s={},o={},u=(r||(r=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Err=e.Ok=void 0;var t=function(){if(a)return o;function e(e){if(!this.ok){if("string"==typeof this.error||void 0===this.error)throw new Error(e||this.error||"There was an error! No specific error message was provided.");throw e&&(this.error.message=e),this.error}return this.data}function t(e){return this.ok?this.data:e(this.error)}function i(e){return this.ok?this.data:e}function r(e){return this.ok&&e(this.data),this}return a=1,Object.defineProperty(o,"__esModule",{value:!0}),o.Err=o.Ok=void 0,o.Ok=function(a){return{ok:!0,data:a,throw:e,else:t,or:i,and:r}},o.Err=function(a){return{ok:!1,error:a,throw:e,else:t,or:i,and:r}},o}();Object.defineProperty(e,"Ok",{enumerable:!0,get:function(){return t.Ok}}),Object.defineProperty(e,"Err",{enumerable:!0,get:function(){return t.Err}})}(s)),s);function d(e,t,i,a){return new(i||(i=Promise))(function(t,r){function n(e){try{o(a.next(e))}catch(e){r(e)}}function s(e){try{o(a.throw(e))}catch(e){r(e)}}function o(e){var a;e.done?t(e.value):(a=e.value,a instanceof i?a:new i(function(e){e(a)})).then(n,s)}o((a=a.apply(e,[])).next())})}"function"==typeof SuppressedError&&SuppressedError,function(e){e.Credentials="Credentials",e.EventSourceInitialization="EventSourceInitialization",e.FeatureFlagConfigurationNotFound="FeatureFlagConfigurationNotFound",e.FeatureFlagVariableNotFound="FeatureFlagVariableNotFound",e.FeatureFlagVariationNotFound="FeatureFlagVariationNotFound",e.FeatureFlagExperimentNotFound="FeatureFlagExperimentNotFound",e.FeatureFlagEnvironmentDisabled="FeatureFlagEnvironmentDisabled",e.VisitAmount="VisitAmount",e.VisitorCodeMaxLength="VisitorCodeMaxLength",e.VisitorCodeEmpty="VisitorCodeEmpty",e.StorageInitialization="StorageInitialization",e.StorageWrite="StorageWrite",e.StorageRead="StorageRead",e.StorageParse="StorageParse",e.StorageEmpty="StorageEmpty",e.ClientConfiguration="ClientConfiguration",e.TargetingCondition="TargetingCondition",e.AmongValuesCheck="AmongValuesCheck",e.RangeCheck="RangeCheck",e.Initialization="Initialization",e.JSONParse="JSONParse",e.NumberParse="NumberParse",e.VersionParse="VersionParse",e.CookieParse="CookieParse",e.SemanticVersionParse="SemanticVersionParse",e.RemoteData="RemoteData",e.MaximumRetriesReached="MaximumRetriesReached"}(n||(n={}));const l={[n.CookieParse]:e=>`Couldn't parse cookie string: ${e}`,[n.JSONParse]:e=>`Couldn't parse JSON variable: ${e}`,[n.NumberParse]:e=>`It's not possible to parse value ${e} to Number`,[n.VersionParse]:e=>`It's not possible to parse a version value ${e} to Number, version should be in format x.x`,[n.SemanticVersionParse]:e=>`It's not possible to parse a version value ${e} to Number, version should be in format x.x.x`,[n.Initialization]:()=>"It seems that the client wasn't properly initialized, make sure to run `initialize` method before invoking other methods",[n.Credentials]:()=>"KameleoonClient can not be created without credentials",[n.StorageInitialization]:()=>"There was an error while initializing React Native SDK storage, it seems that the storage library dependency wasn't installed",[n.EventSourceInitialization]:()=>"There was an error while initializing Real Time Update service, it seems that the event source library dependency wasn't installed",[n.FeatureFlagConfigurationNotFound]:e=>`No feature flag with key ${e} was found.`,[n.FeatureFlagEnvironmentDisabled]:(e,t)=>`Feature flag with key ${e} is disabled in ${t} environment.`,[n.FeatureFlagVariableNotFound]:(e,t)=>`No feature flag variable with key ${e} was found for ${t} visitorCode.`,[n.FeatureFlagVariationNotFound]:(e,t)=>`No feature flag variation with key ${e} was found for ${t} visitorCode.`,[n.FeatureFlagExperimentNotFound]:(e,t)=>`No feature flag experiment with id ${e} was found for ${t} visitorCode.`,[n.VisitAmount]:()=>"Visit amount must be a number between 1 and 25",[n.VisitorCodeMaxLength]:()=>"Visitor code can not be more than 255 characters long",[n.VisitorCodeEmpty]:()=>"Visitor code can not be empty",[n.StorageWrite]:e=>`Couldn't update storage for kameleoonClient: ${e}`,[n.StorageRead]:e=>`No data found in storage under ${e} key`,[n.StorageEmpty]:()=>"No data found in storage",[n.StorageParse]:(e,t)=>`Couldn't parse ${t} storage data, the data may be corrupted. Error: ${e}`,[n.ClientConfiguration]:e=>`Couldn't retrieve client configuration from Kameleoon Api. Error: ${e}`,[n.TargetingCondition]:e=>`${e} targeting condition is not yet supported.`,[n.AmongValuesCheck]:(e,t)=>`Couldn't parse value "${t}": ${e}`,[n.RangeCheck]:e=>`Couldn't parse value "${e}" as a range, value should be in format [x: number, y: number]`,[n.RemoteData]:e=>`Couldn't retrieve data from Kameleoon server. Error: ${e}`,[n.MaximumRetriesReached]:e=>`Maximum retries reached, request failed. Reason: ${e}`};function c(e){throw new Error(`Reaching an impossible state because of ${e}`)}class h extends Error{constructor(e,t,i){switch(super(`Error: ${e}`),this.name="KameleoonError",this.errorType=e,e){case n.Initialization:case n.Credentials:case n.VisitorCodeMaxLength:case n.VisitorCodeEmpty:case n.StorageInitialization:case n.VisitAmount:case n.EventSourceInitialization:case n.StorageEmpty:this.message=l[e]();break;case n.CookieParse:case n.FeatureFlagConfigurationNotFound:case n.NumberParse:case n.ClientConfiguration:case n.MaximumRetriesReached:case n.RemoteData:case n.VersionParse:case n.SemanticVersionParse:this.message=l[e](t);break;case n.FeatureFlagExperimentNotFound:case n.FeatureFlagVariationNotFound:case n.FeatureFlagVariableNotFound:this.message=l[e](t,i);break;case n.FeatureFlagEnvironmentDisabled:this.message=void 0!==i?l[e](t,i):t;break;case n.StorageWrite:case n.JSONParse:case n.StorageRead:this.message=l[e](t);break;case n.StorageParse:this.message=l[e](t,i);break;case n.TargetingCondition:this.message=l[e](t);break;case n.AmongValuesCheck:this.message=l[e](t,i);break;case n.RangeCheck:this.message=l[e](t);break;default:c(e)}}get type(){return this.errorType}}var g,v,p,f;!function(e){e.DataApi="dataApi",e.Events="events",e.ClientConfiguration="clientConfiguration"}(g||(g={})),function(e){e.Get="GET",e.Post="POST"}(v||(v={})),function(e){e[e.VisitEvent=0]="VisitEvent",e[e.VisitData=1]="VisitData",e[e.DataMap=2]="DataMap"}(p||(p={})),function(e){e.Configuration="configuration",e.Tracking="tracking",e.RemoteData="remoteData"}(f||(f={}));const m=1;var C;!function(e){e.UserAgent="User-Agent",e.ContentType="Content-Type",e.SdkVersion="X-Kameleoon-SDK-Version",e.SdkType="X-Kameleoon-SDK-Type",e.Authorization="Authorization",e.AcceptEncoding="Accept-Encoding",e.IfModifiedSince="If-Modified-Since",e.LastModified="Last-Modified"}(C||(C={}));const y="eventType=staticData",E="&browserIndex=",D="&browserVersion=",I="&deviceType=",k="&visitorCode=",T="&nonce=",V="&id=",R="&maxNumberPreviousVisits=",w="&os=",b="&osIndex=",S="&browser=",A="&mappingValue=",O="visit/",$={[g.DataApi]:"data.kameleoon.io",[g.Events]:"events.kameleoon.eu",[g.ClientConfiguration]:"sdk-config.kameleoon.eu"};var N;!function(e){e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARNING=2]="WARNING",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG"}(N||(N={}));const F={[N.NONE]:"NONE",[N.ERROR]:"ERROR",[N.WARNING]:"WARNING",[N.INFO]:"INFO",[N.DEBUG]:"DEBUG"},x=(e,t)=>"credentials"===e?{clientId:"****",clientSecret:"****"}:t instanceof Map?Array.from(t.entries()):t;class M{static setLogger(e){M.logger=e}static setLogLevel(e){M.logLevel=e}static log({level:e,strings:t,keys:i}){if(!M.checkLevel(e))return;let a;if("string"==typeof t)a=t;else if("function"==typeof t)try{a=t()}catch(e){a="Failed to log message"}else a=function(e,t){let i="";if(t)for(let a=0;a<t.length;a++){let r=t[a];if("object"==typeof r)try{i+=e[a]+JSON.stringify(r,x)}catch(t){i+=e[a]+"{object}"}else i+="string"==typeof r?e[a]+"'"+r+"'":e[a]+r}return i+=e[e.length-1],i}(t,i);M.writeMessage(e,a)}static info(e,...t){M.log({level:N.INFO,strings:e,keys:t})}static error(e,...t){M.log({level:N.ERROR,strings:e,keys:t})}static warning(e,...t){M.log({level:N.WARNING,strings:e,keys:t})}static debug(e,...t){M.log({level:N.DEBUG,strings:e,keys:t})}static checkLevel(e){return e<=M.logLevel&&e!==N.NONE}static writeMessage(e,t){M.logger.log(e,`Kameleoon [${F[e]}]: ${t}`)}}M.logger=new class{log(e,t){switch(e){case N.DEBUG:console.debug(t);break;case N.INFO:console.info(t);break;case N.WARNING:console.warn(t);break;case N.ERROR:console.error(t)}}},M.logLevel=N.WARNING;let _=class{constructor({urlProvider:e,packageInfo:t,externalRequester:i,requestTimeout:a,trackRetryDelay:r,useAbortController:n}){M.debug`CALL: new Requester(urlProvider, packageInfo: ${t}, externalRequester, requestTimeout: ${a}, trackRetryDelay: ${r}, useAbortController: ${n})`,this.urlProvider=e,this.useAbortController=n,this.externalRequester=i,this.trackRetryDelay=r,this.packageInfo=t,this.timeout=a,M.debug`RETURN: new Requester(urlProvider, packageInfo: ${t}, externalRequester, requestTimeout: ${a}, trackRetryDelay: ${r}, useAbortController: ${n})`}getClientConfiguration(e,t){return d(this,0,void 0,function*(){const i=this.urlProvider.getClientConfigurationUrl(e);let a=Object.assign({[C.SdkType]:this.packageInfo.type.toLowerCase(),[C.SdkVersion]:this.packageInfo.version},t&&{[C.IfModifiedSince]:t});try{let e={message:""};M.debug`Running configuration request Method: ${v.Get}, Url: ${i}, Headers: ${a}, with retry limit ${2}`;for(let t=0;t<2;t++){const r=yield this.sendRequest({url:i,requestType:f.Configuration,retryCount:t,parameters:{method:v.Get,headers:a}});if(r.ok){const e=yield r.json();this.logReceivedConfigurationResponse(r.status,i,a);const t=this.getLastModifiedHeader(r),n=e;return u.Ok({configuration:n,lastModified:t})}if(304===r.status)return this.logReceivedConfigurationResponse(r.status,i,a),u.Ok({});if(1===t){if(r.text){const t=yield r.text();e=JSON.parse(t)}M.error`Failed to get configuration response ${{status:r.status,message:e.message}} for request Method: ${v.Get}, Url: ${i}, Headers: ${a}`}else yield this.logRequestError({logLevel:N.WARNING,message:"Failed to get configuration response",response:r,method:v.Get,url:i})}return u.Err(new h(n.MaximumRetriesReached,e.message))}catch(e){return yield this.logRequestError({logLevel:N.ERROR,message:"Failed to get configuration response",error:e,method:v.Get,url:i,headers:a}),u.Err(new h(n.ClientConfiguration,e))}})}getRemoteData(e){var t;return d(this,0,void 0,function*(){const i=this.urlProvider.getRemoteDataUrl(e);M.debug`Running remote data request Method: ${v.Get}, Url: ${i}`;try{const e=yield this.sendRequest({url:i,requestType:f.RemoteData,retryCount:0,parameters:{method:v.Get}});if(!e.ok){if(yield this.logRequestError({logLevel:N.ERROR,message:"Failed to get remote data response",response:e,method:v.Get,url:i}),e.text){const i=yield e.text(),a=null===(t=JSON.parse(i))||void 0===t?void 0:t.message;return u.Err(new h(n.RemoteData,a))}return u.Err(new h(n.RemoteData,"Unknown Reason - no `text()` was found for a response"))}const a=yield e.json();return M.debug`Received remote data response: ${{status:e.status}} for request Method: ${v.Get}, Url: ${i}`,u.Ok(a)}catch(e){return yield this.logRequestError({logLevel:N.ERROR,message:"Failed to get remote data response",error:e,method:v.Get,url:i}),u.Err(new h(n.RemoteData,e))}})}getVisitorData({visitorCode:e,filters:t,isMappingIdentifier:i}){var a;return d(this,0,void 0,function*(){const r=this.urlProvider.getVisitorDataUrl({visitorCode:e,filters:t,isMappingIdentifier:i});M.debug`Running visitor data request Method: ${v.Get}, Url: ${r}`;try{const e=yield this.sendRequest({url:r,requestType:f.RemoteData,retryCount:0,parameters:{method:v.Get}});if(!e.ok){if(yield this.logRequestError({logLevel:N.ERROR,message:"Failed to get visitor data response",response:e,method:v.Get,url:r}),"function"==typeof e.text){const t=yield e.text();if(t){const e=null===(a=JSON.parse(t))||void 0===a?void 0:a.message;return u.Err(new h(n.RemoteData,e))}}return e.status?u.Err(new h(n.RemoteData,`No error message. Error status: ${e.status}`)):u.Err(new h(n.RemoteData,"Unknown Reason - no text message or error status was found for a response"))}const t=yield e.json();return M.debug`Received visitor data response: ${{status:e.status}} for request Method: ${v.Get}, Url: ${r}`,u.Ok(t)}catch(e){return yield this.logRequestError({logLevel:N.ERROR,message:"Failed to get visitor data response",error:e,method:v.Get,url:r}),u.Err(new h(n.RemoteData,e))}})}track(e,t){return d(this,0,void 0,function*(){const i=this.urlProvider.getTrackingUrl(t);M.debug`Running tracking request Method: ${v.Post}, Url: ${i}, Body: ${e}, with retry limit ${2}, retry delay ${this.trackRetryDelay} ms`;for(let t=0;t<2;t++){let a;try{if(a=yield this.sendRequest({url:i,retryCount:t,requestType:f.Tracking,parameters:{body:e,method:v.Post,headers:{[C.ContentType]:"*/*"}}}),a.ok)return M.debug`Received tracking response: ${{status:a.status}} for request Method: ${v.Post}, Url: ${i}, Body: ${e}`,u.Ok();yield this.logRequestError({logLevel:1==t?N.ERROR:N.WARNING,message:"Failed to get tracking response",response:a,method:v.Post,url:i})}catch(e){yield this.logRequestError({logLevel:1==t?N.ERROR:N.WARNING,message:"Failed to get tracking response",error:e,method:v.Post,url:i})}t<2&&(yield new Promise(e=>setTimeout(e,this.trackRetryDelay)))}return u.Err()})}sendRequest({url:e,requestType:t,retryCount:i,parameters:a}){return d(this,0,void 0,function*(){let r;if(this.useAbortController){const n=new AbortController,s=setTimeout(()=>n.abort(),this.timeout);r=yield this.externalRequester.sendRequest({url:e,retryCount:i,requestType:t,parameters:Object.assign(Object.assign({},a),{signal:n.signal})}),clearTimeout(s)}else r=yield this.externalRequester.sendRequest({url:e,retryCount:i,requestType:t,parameters:a});return r})}logRequestError({logLevel:e,message:t,error:i,method:a,url:r,response:n,headers:s}){return d(this,0,void 0,function*(){if(i){let n="Unknown error";i instanceof Error&&(n=i.message),M.log({level:e,strings:()=>`${t} with error: ${n} for request Method: ${a}, Url: ${r}`})}else if(n&&M.checkLevel(e)){const i=yield this.parseResponse(n);M.log({level:e,strings:()=>`${t} response: Status: '${i.status}' Message: '${i.message}' for request Method: ${a}, Url: '${r}'`+(s?`, Headers: ${s}`:"")})}})}parseResponse(e){return d(this,0,void 0,function*(){let t="";try{if("function"==typeof e.text){const i=yield e.text();i&&(t=i)}}catch(e){}return{status:e.status,message:t}})}getLastModifiedHeader(e){if(e.headers){const t=C.LastModified.toLowerCase();for(const[i,a]of e.headers)if(i.toLowerCase()===t)return a}}logReceivedConfigurationResponse(e,t,i){M.debug`Received configuration response: ${{status:e}} for request Method: ${v.Get}, Url: ${t}, Headers: ${i}`}};var U,L,P,K,G,B,z,j,q,H,W,Y;!function(e){e.Production="production",e.Staging="staging",e.Development="development"}(U||(U={}));class J{constructor(){this.ready=!1,this.isCustomDomain=!1,this.domains=$}initialize({domain:e,siteCode:t,packageInfo:i,environment:a}){this.siteCode=t,this.environment=a,this.packageInfo=i,this.ready=!0,this.setDomains(e)}set dataApiDomain(e){if(!this.isCustomDomain)return void(this.domains[g.DataApi]=e);const t=e.split(".")[0],i=this.domains[g.DataApi];this.domains[g.DataApi]=i.replace(/^[^.]+/,t)}get dataApiDomain(){return this.domains[g.DataApi]}getClientConfigurationUrl(e){this.isInitialized();const t=`https://${this.domains[g.ClientConfiguration]}/v3/`,i=this.environment===U.Production?"":"?environment="+encodeURIComponent(this.environment);let a="";return e&&(a=i?"&ts="+e:"?ts="+e),t+this.siteCode+i+a}getEventSourceUrl(){return this.isInitialized(),`https://${this.domains[g.Events]}:8110/sse?siteCode=${this.siteCode}`}getRemoteDataUrl(e){return this.isInitialized(),this.getDataApiUrl(p.DataMap)+this.siteCode+"&key="+encodeURI(e)}getVisitorDataUrl({visitorCode:e,filters:t,isMappingIdentifier:i}){this.isInitialized();const{customData:a,previousVisitAmount:r,currentVisit:n,conversions:s,geolocation:o,experiments:u,pageViews:d,device:l,browser:c,operatingSystem:h,kcs:g,personalization:v,visitorCode:f,cbs:m}=t,C=i?A:k,y=a||f?"&customData="+!0:"",E=s?"&conversion="+!0:"",D=o?"&geolocation="+!0:"",I=u?"&experiment="+!0:"",T=d?"&page="+!0:"",V="&staticData="+!0,w=n?"¤tVisit="+!0:"",b=g?"&kcs="+!0:"",S=v?"&personalization="+!0:"",O="number"!=typeof r?R+1:R+r,$=m?"&cbs="+!0:"";return this.getDataApiUrl(p.VisitData)+this.siteCode+C+e+O+y+E+D+I+T+V+w+b+S+$}getTrackingUrl(e){this.isInitialized();const{type:t,version:i}=this.packageInfo;let a=this.getDataApiUrl(p.VisitEvent)+this.siteCode+"&sdkName="+t.toLowerCase()+"&sdkVersion="+i;return e&&(a+="&bodyUa="+!0),a}isInitialized(){if(!this.ready)throw new Error("UrlProvider is not initialized")}getDataApiUrl(e){if(!this.domains[g.DataApi])throw new Error("Data API domain is not set");const t=`https://${this.domains[g.DataApi]}`;switch(e){case p.VisitEvent:return`${t}/${O+"events?siteCode="}`;case p.VisitData:return`${t}/${O+"visitor?siteCode="}`;case p.DataMap:return`${t}/map/map?siteCode=`}}setDomains(e){e&&(this.isCustomDomain=!0,this.domains[g.DataApi]="data."+e,this.domains[g.Events]="events."+e,this.domains[g.ClientConfiguration]="sdk-config."+e)}}!function(e){e.BOOLEAN="BOOLEAN",e.NUMBER="NUMBER",e.STRING="STRING",e.JSON="JSON",e.JS="JS",e.CSS="CSS"}(L||(L={})),function(e){e.Sent="sent",e.Unsent="unsent",e.Pending="pending"}(P||(P={})),function(e){e[e.Second=1e3]="Second",e[e.Minute=6e4]="Minute",e[e.Hour=36e5]="Hour",e[e.Day=864e5]="Day",e[e.Week=6048e5]="Week",e[e.Month=2592e6]="Month"}(K||(K={}));class X{constructor(e){this.cacheMap=new Map,this.intervalId=null,this.cleanupTimeout=e*K.Second}add({key:e,data:t,lifetime:i}){M.debug`CALL: CacheManager.add(key: ${e}, data: ${t}, lifetime: ${i})`,null===this.intervalId&&this.activate();const a=i*K.Second,r={data:t,expirationTime:Date.now()+a};this.cacheMap.set(e,r),M.debug`RETURN: CacheManager.add(key: ${e}, data: ${t}, lifetime: ${i})`}getAliveItem(e){M.debug`CALL: CacheManager.getAliveItem(key: ${e})`;const t=this.cacheMap.get(e);if(t&&t.expirationTime>=Date.now()){const i=t.data;return M.debug`RETURN: CacheManager.getAliveItem(key: ${e}) -> (item: ${i})`,i}return t&&this.cacheMap.delete(e),M.debug`RETURN: CacheManager.getAliveItem(key: ${e}) -> (item: null)`,null}activate(){this.intervalId=setInterval(()=>{const e=Date.now();for(const[t,i]of this.cacheMap)i.expirationTime<e&&this.cacheMap.delete(t);this.cacheMap.size||this.cleanupInterval()},this.cleanupTimeout)}cleanupInterval(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}}!function(e){e[e.Polling=0]="Polling",e[e.RealTime=1]="RealTime"}(G||(G={})),function(e){e.TARGETED_DELIVERY="TARGETED_DELIVERY",e.EXPERIMENTATION="EXPERIMENTATION"}(B||(B={})),function(e){e.ANDROID="ANDROID",e.SWIFT="SWIFT",e.JAVA="JAVA",e.CSHARP="CSHARP",e.NODEJS="NODEJS",e.PHP="PHP",e.RUBY="RUBY",e.GO="GO",e.FLUTTER="FLUTTER",e.REACTJS="REACTJS"}(z||(z={})),function(e){e.ACTIVATED="ACTIVATED",e.DEACTIVATED="DEACTIVATED",e.SCHEDULED="SCHEDULED"}(j||(j={})),function(e){e.Visit="VISIT",e.Visitor="VISITOR",e.Page="Page"}(q||(q={})),function(e){e.Required="REQUIRED",e.NotRequired="NOT_REQUIRED"}(H||(H={})),function(e){e.PartiallyBlocked="PARTIALLY_BLOCK",e.CompletelyBlocked="FULLY_BLOCK"}(W||(W={}));class Q{addEventHandler(e,t){this.eventHandlers||(this.eventHandlers=new Map),this.eventHandlers.set(e,t)}fireEvent(e,t){var i;const a=null===(i=this.eventHandlers)||void 0===i?void 0:i.get(e);a&&t&&a(t)}}!function(e){e.Evaluation="evaluation",e.ConfigurationUpdate="configurationUpdate"}(Y||(Y={}));const Z={customData:[],featureFlags:[],configuration:{realTimeUpdate:!1,consentType:H.NotRequired,dataApiDomain:"data.kameleoon.io",consentOptOutBehavior:W.PartiallyBlocked}};class ee{constructor(e){this._featureFlags=e.slice().sort((e,t)=>e.id-t.id)}getFeatureFlagByHash(e){let t=Math.floor(e*this._featureFlags.length);return t=Math.min(t,this._featureFlags.length-1),this._featureFlags[t]}get featureFlags(){return this._featureFlags}}class te{constructor({updateInterval:e,urlProvider:t,storage:i,requester:a,dataManager:r,eventSource:n,externalVisitorCodeManager:s,eventManager:o,externalPackageInfo:u,defaultDataFile:d}){this.updateConfigurationIntervalId=null,this.updateType=G.Polling,this.configurationData=Z,this.featureFlagsData=new Map,this.isTargetedDeliveryRule=null,this.segmentsData=null,this.holdoutData=null,this.meGroupsData=new Map,this.mappedRules=null,this.mappedExperiments=null,this.usedDefaultDataFile=!1,this.blockingBehaviourMode=W.PartiallyBlocked,this.CACHE_REVALIDATE_PERIOD=90*K.Minute,this.urlProvider=t,this.requester=a,this.updateInterval=e,this.lastUpdate=new Date,this.storage=i,this.dataManager=r,this.eventManager=o,this.visitorCodeManager=s,this.eventSource=n,this.externalPackageInfo=u,this.defaultDataFile=d}initialize(){return d(this,0,void 0,function*(){if(M.debug("CALL: ClientConfiguration.initialize()"),this.readStorageData(),this.checkShouldUpdate()){const e=yield this.updateClientConfiguration();if(!e.ok)return M.error("Error occurred during client configuration update"),e;if(e.data)return M.debug("RETURN: ClientConfiguration.initialize()"),u.Ok()}return this.updateType!==G.RealTime||this.eventSource.isOpen?(this.updateType===G.Polling&&this.handlePollingUpdates(),M.debug("RETURN: ClientConfiguration.initialize()"),u.Ok()):(this.handleRealTimeUpdates(),M.debug("RETURN: ClientConfiguration.initialize()"),u.Ok())})}cleanupHandlers(){this.eventSource.isOpen&&this.eventSource.close(),this.updateConfigurationIntervalId&&clearInterval(this.updateConfigurationIntervalId)}handleRealTimeUpdates(){this.cleanupHandlers(),this.eventSource.open(e=>{this.updateClientConfiguration(e).then(t=>{t.ok&&this.eventManager.fireEvent(Y.ConfigurationUpdate,{timestamp:e})})}),this.eventSource.onError(e=>{M.error`Error occurred during real-time update: ${e}. Switching to polling updates while the connection is not restored.`,this.updateType=G.Polling,this.handlePollingUpdates()})}handlePollingUpdates(){this.cleanupHandlers();try{const e=this.lastUpdate.getTime(),t=Date.now(),i=Math.max(this.updateInterval-(t-e),0);setTimeout(()=>d(this,0,void 0,function*(){yield this.updateClientConfiguration(),this.updateConfigurationIntervalId=setInterval(this.updateClientConfiguration.bind(this),this.updateInterval)}),i)}catch(e){throw this.updateConfigurationIntervalId&&clearInterval(this.updateConfigurationIntervalId),e}}get featureFlags(){return this.featureFlagsData}get configuration(){return this.configurationData.configuration}get segments(){if(this.segmentsData)return this.segmentsData;const e=new Map;return this.featureFlagsData.forEach(t=>{t.rules.forEach(t=>{t.segment&&!e.has(t.segment.id.toString())&&e.set(t.segment.id.toString(),t.segment)})}),this.segmentsData=e,e}get ruleMap(){var e;if(null===(e=this.mappedRules)||void 0===e?void 0:e.size)return this.mappedRules;const t=new Map;for(const e of this.featureFlags.values())for(const i of e.rules){const{id:a,experimentId:r,variationByExposition:n}=i,s=new Map;n.forEach(({variationKey:e,variationId:t})=>{"number"==typeof t&&s.set(e,t)}),t.set(a,{featureId:e.id,experimentId:r,variations:s})}return this.mappedRules=t,t}get experimentMap(){var e;if(null===(e=this.mappedExperiments)||void 0===e?void 0:e.size)return this.mappedExperiments;const t=new Map;for(const e of this.featureFlags.values())for(const i of e.rules){const{experimentId:e,variationByExposition:a}=i,r=new Map;a.forEach(({variationKey:e,variationId:t})=>{"number"==typeof t&&r.set(e,t)}),t.set(e,{type:i.type,variations:r})}return this.mappedExperiments=t,t}get holdout(){return this.holdoutData}get meGroups(){return this.meGroupsData}get isConsentRequired(){return this.configuration.consentType===H.Required}get consentBlockingBehaviour(){return this.blockingBehaviourMode}get hasAnyTargetedDeliveryRule(){if(null!==this.isTargetedDeliveryRule)return this.isTargetedDeliveryRule;for(const e of this.featureFlags.values())if(e.environmentEnabled&&e.rules.some(e=>e.type===B.TARGETED_DELIVERY))return!0;return!1}checkShouldUpdate(){const{configuration:e}=this.configurationData;return this.updateType=e.realTimeUpdate?G.RealTime:G.Polling,!this.featureFlags.size||this.lastUpdate.getTime()<Date.now()-this.updateInterval}readStorageData(){var e,t,i;M.debug("CALL: ClientConfiguration.readStorageData()");const a=this.storage.read();if(a.ok){let{data:r,lastUpdate:n,lastModified:s,requestTime:o}=a.data,u=!1;if(this.defaultDataFile)try{const a=JSON.parse(this.defaultDataFile);this.defaultDataFile=void 0,this.usedDefaultDataFile=!0;const n=null!==(t=null!==(e=r.dateModified)&&void 0!==e?e:o)&&void 0!==t?t:-1,s=null!==(i=a.dateModified)&&void 0!==i?i:0;(!o||s>n)&&(r=a,u=!0)}catch(e){M.error`Error parsing default data file: ${String(e)}`}this.updateConfigurationData(r,u),this.lastUpdate=this.usedDefaultDataFile?new Date(0):new Date(Date.parse(n)),this.lastModified=s,this.requestTime=o}M.debug`RETURN: ClientConfiguration.readStorageData() -> (result: ${a.ok})`}updateClientConfiguration(e){return d(this,0,void 0,function*(){const t=Date.now();if(this.usedDefaultDataFile)return this.updateClientConfigurationInBackground(),u.Ok(!1);if(this.requestTime&&!e&&!this.externalPackageInfo.isServer){if(t-this.requestTime<=this.CACHE_REVALIDATE_PERIOD)return this.updateClientConfigurationInBackground(),u.Ok(!1);M.debug`Cached configuration data has expired. Fetching fresh data.`}const i=yield this.requester.getClientConfiguration(e,this.lastModified);return this.applyNewConfigurationDataFromResponse(i)})}updateClientConfigurationInBackground(){setTimeout(()=>d(this,0,void 0,function*(){const e=yield this.requester.getClientConfiguration(void 0,this.lastModified);yield this.applyNewConfigurationDataFromResponse(e)}),0)}applyNewConfigurationDataFromResponse(e){var t,i;return d(this,0,void 0,function*(){if(this.requestTime=Date.now(),!e.ok)return this.featureFlags.size?(M.error("Error occurred while updating configuration. Existing configuration will be used as a fallback."),u.Ok(!0)):e;if(void 0===e.data.configuration)return this.updateStorageData(),u.Ok(!1);const a=e.data.configuration;this.updateConfigurationData(a,!0),this.dataManager.clearTrees(),null===(t=this.mappedRules)||void 0===t||t.clear(),null===(i=this.experimentMap)||void 0===i||i.clear(),this.isTargetedDeliveryRule=null,e.data.lastModified&&(this.lastModified=e.data.lastModified);const r=this.updateStorageData();if(!r.ok)return r;const n=a.configuration.realTimeUpdate?G.RealTime:G.Polling,s=n!==this.updateType;return s&&(this.updateType=n,M.info`Configuration update type was toggled to ${G[n]}`,yield this.initialize()),this.blockingBehaviourMode=this.consentBlockingBehaviourFromStr(a.configuration.consentOptOutBehavior),u.Ok(s)})}updateConfigurationData(e,t=!0){const{configuration:i,featureFlags:a,customData:r,holdout:n,segments:s,dateModified:o}=e;let u=s?new Map(s.map(e=>[e.id.toString(),e])):null,d=null;if(t&&(null==r?void 0:r.length)){d=new Map;for(let e of r){if(void 0===e.id){d=null;break}d.set(e.id,e.index)}}const l=new Map;for(const e of a)l.set(e.featureKey,e),t&&(this.updateFeatureFlagSegments(e,u),this.updateFeatureFlagBucketingCustomDataId(e,d));this.featureFlagsData=l,(null==r?void 0:r.length)&&(this.dataManager.customDataIndexes=r),this.meGroupsData=this.makeMEGroups(a),this.holdoutData=null!=n?n:null,this.configurationData={configuration:i,customData:r,holdout:n,dateModified:o},this.urlProvider.dataApiDomain=e.configuration.dataApiDomain,this.updateConsentRequired(),this.segmentsData=u}updateFeatureFlagSegments(e,t){null!==t&&e.rules.forEach(e=>{var i;const a=e.segmentId;e.segment=null!=a&&null!==(i=t.get(a.toString()))&&void 0!==i?i:null})}updateFeatureFlagBucketingCustomDataId(e,t){const i=e.bucketingCustomDataId;null!=i&&t&&(e.bucketingCustomDataIndex=t.get(i))}makeMEGroups(e){const t=new Map;e.forEach(e=>{const i=e.mutuallyExclusiveGroup;if(i){let a=t.get(i);a?a.push(e):t.set(i,[e])}});const i=new Map;return t.forEach((e,t)=>{i.set(t,new ee(e))}),i}updateStorageData(){this.lastUpdate=new Date;const e={data:Object.assign(Object.assign({},this.configurationData),{featureFlags:Array.from(this.featureFlags.values()),segments:this.segmentsData?Array.from(this.segmentsData.values()):void 0}),lastUpdate:this.lastUpdate.toString(),lastModified:this.lastModified,requestTime:this.requestTime};return this.storage.write(e)}updateConsentRequired(){this.visitorCodeManager.consentRequired=this.isConsentRequired&&!this.hasAnyTargetedDeliveryRule}consentBlockingBehaviourFromStr(e){return e===W.PartiallyBlocked||e===W.CompletelyBlocked?e:(M.error(`Unexpected consent blocking type '${e}'`),W.PartiallyBlocked)}}function ie(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e]))}var ae,re,ne,se;!function(e){e.UniqueIdentifier="uniqueIdentifier",e.CustomData="customData",e.PageView="pageView",e.GeolocationData="geolocation",e.Browser="browser",e.Conversion="conversion",e.Cookie="cookie",e.Device="device",e.OperatingSystem="operatingSystem",e.UserAgent="userAgent",e.ApplicationVersion="applicationVersion",e.VisitsData="visitsData",e.KameleoonConversionScore="kameleoonConversionScore",e.Personalization="personalization",e.CBScores="cbScores",e.TargetedSegment="targetedSegment"}(ae||(ae={})),function(e){e.Phone="PHONE",e.Tablet="TABLET",e.Desktop="DESKTOP"}(re||(re={})),function(e){e.WindowsPhone="WINDOWS_PHONE",e.Windows="WINDOWS",e.Android="ANDROID",e.Linux="LINUX",e.Mac="MAC",e.IOS="IOS"}(ne||(ne={})),function(e){e.Chrome="CHROME",e.InternetExplorer="IE",e.Firefox="FIREFOX",e.Safari="SAFARI",e.Opera="OPERA",e.Other="OTHER"}(se||(se={}));const oe={[ne.Windows]:0,[ne.Mac]:1,[ne.IOS]:2,[ne.Linux]:3,[ne.Android]:4,[ne.WindowsPhone]:5},ue=ie(oe),de={[se.Chrome]:0,[se.InternetExplorer]:1,[se.Firefox]:2,[se.Safari]:3,[se.Opera]:4,[se.Other]:5},le=ie(de),ce="off",he="warehouseAudiences";var ge;!function(e){e.ANDROID="ANDROID",e.IOS="IOS",e.JAVA="JAVA",e.CSHARP="CSHARP",e.NODEJS="NODEJS",e.PHP="PHP",e.RUBY="RUBY",e.GO="GO",e.FLUTTER="FLUTTER",e.REACT="REACT",e.PYTHON="PYTHON",e.JAVASCRIPT="JAVASCRIPT",e.RUST="RUST"}(ge||(ge={}));const ve={previousVisitAmount:1,currentVisit:!0,customData:!0,pageViews:!1,geolocation:!1,device:!1,browser:!1,operatingSystem:!1,conversions:!1,experiments:!1,kcs:!1,visitorCode:!0,personalization:!1};var pe,fe,me,Ce,ye,Ee,De,Ie,ke,Te,Ve,Re;!function(e){e.And="AND",e.Or="OR"}(pe||(pe={})),function(e){e.TRUE="TRUE",e.FALSE="FALSE",e.EXACT="EXACT",e.CONTAINS="CONTAINS",e.REGULAR_EXPRESSION="REGULAR_EXPRESSION",e.EQUAL="EQUAL",e.LOWER="LOWER",e.GREATER="GREATER",e.UNDEFINED="UNDEFINED",e.AMONG_VALUES="AMONG_VALUES",e.RANGE="RANGE"}(fe||(fe={})),function(e){e.NEW="NEW",e.RETURNING="RETURNING"}(me||(me={})),function(e){e.ANY="ANY",e.EXACT="EXACT"}(Ce||(Ce={})),function(e){e.ALL="ALL",e.TEST="TEST",e.PERSO="PERSO"}(ye||(ye={})),function(e){e.Experiment="EXPERIMENT",e.Personalization="PERSONALIZATION",e.Any="ANY"}(Ee||(Ee={})),function(e){e.EXACT="EXACT",e.CONTAINS="CONTAINS",e.REGULAR_EXPRESSION="REGULAR_EXPRESSION",e.GREATER="GREATER",e.EQUAL="EQUAL",e.LOWER="LOWER"}(De||(De={})),function(e){e.GREATER="GREATER",e.EQUAL="EQUAL",e.LOWER="LOWER"}(Ie||(Ie={})),function(e){e.EXACT="EXACT",e.CONTAINS="CONTAINS",e.REGULAR_EXPRESSION="REGULAR_EXPRESSION",e.OPTIONAL="OPTIONAL"}(ke||(ke={})),function(e){e.PAGE_URL="PAGE_URL",e.PAGE_TITLE="PAGE_TITLE",e.LANDING_PAGE="LANDING_PAGE",e.ORIGIN="ORIGIN",e.ORIGIN_TYPE="ORIGIN_TYPE",e.REFERRERS="REFERRERS",e.NEW_VISITORS="NEW_VISITORS",e.INTERESTS="INTERESTS",e.BROWSER_LANGUAGE="BROWSER_LANGUAGE",e.GEOLOCATION="GEOLOCATION",e.DEVICE_TYPE="DEVICE_TYPE",e.SCREEN_DIMENSION="SCREEN_DIMENSION",e.VISITOR_IP="VISITOR_IP",e.AD_BLOCKER="AD_BLOCKER",e.PREVIOUS_PAGE="PREVIOUS_PAGE",e.KEY_PAGES="KEY_PAGES",e.PAGE_VIEWS="PAGE_VIEWS",e.FIRST_VISIT="FIRST_VISIT",e.LAST_VISIT="LAST_VISIT",e.ACTIVE_SESSION="ACTIVE_SESSION",e.TIME_SINCE_PAGE_LOAD="TIME_SINCE_PAGE_LOAD",e.SAME_DAY_VISITS="SAME_DAY_VISITS",e.VISITS="VISITS",e.VISITS_BY_PAGE="VISITS_BY_PAGE",e.VISITOR_CODE="VISITOR_CODE",e.SDK_LANGUAGE="SDK_LANGUAGE",e.INTERNAL_SEARCH_KEYWORDS="INTERNAL_SEARCH_KEYWORDS",e.TABS_ON_SITE="TABS_ON_SITE",e.CONVERSION_PROBABILITY="CONVERSION_PROBABILITY",e.HEAT_SLICE="HEAT_SLICE",e.SKY_STATUS="SKY_STATUS",e.TEMPERATURE="TEMPERATURE",e.DAY_NIGHT="DAY_NIGHT",e.FORECAST_SKY_STATUS="FORECAST_SKY_STATUS",e.FORECAST_TEMPERATURE="FORECAST_TEMPERATURE",e.DAY_OF_WEEK="DAY_OF_WEEK",e.TIME_RANGE="TIME_RANGE",e.HOUR_MINUTE_RANGE="HOUR_MINUTE_RANGE",e.JS_CODE="JS_CODE",e.COOKIE="COOKIE",e.EVENT="EVENT",e.BROWSER="BROWSER",e.OPERATING_SYSTEM="OPERATING_SYSTEM",e.DOM_ELEMENT="DOM_ELEMENT",e.MOUSE_OUT="MOUSE_OUT",e.TARGET_EXPERIMENT="TARGET_EXPERIMENT",e.TARGET_FEATURE_FLAG="TARGET_FEATURE_FLAG",e.TARGET_PERSONALIZATION="TARGET_PERSONALIZATION",e.EXCLUSIVE_EXPERIMENT="EXCLUSIVE_EXPERIMENT",e.CONVERSIONS="CONVERSIONS",e.CUSTOM_DATUM="CUSTOM_DATUM",e.YSANCE_SEGMENT="YSANCE_SEGMENT",e.SEGMENT="SEGMENT",e.YSANCE_ATTRIBUT="YSANCE_ATTRIBUT",e.TEALIUM_BADGE="TEALIUM_BADGE",e.TEALIUM_AUDIENCE="TEALIUM_AUDIENCE",e.PRICE_OF_DISPLAYED_PAGE="PRICE_OF_DISPLAYED_PAGE",e.NUMBER_OF_VISITED_PAGES="NUMBER_OF_VISITED_PAGES",e.VISITED_PAGES="VISITED_PAGES",e.CUSTOM="CUSTOM",e.EXPLICIT_TRIGGER="EXPLICIT_TRIGGER",e.APPLICATION_VERSION="APPLICATION_VERSION"}(Te||(Te={})),function(e){e.Minute="MINUTE",e.Hour="HOUR",e.Day="DAY",e.Week="WEEK",e.Month="MONTH"}(Ve||(Ve={})),function(e){e.Ascending="asc",e.Descending="desc"}(Re||(Re={}));const we="localhost",be=/^(\.?(([a-zA-Z\d][a-zA-Z\d-]*[a-zA-Z\d])|[a-zA-Z\d]))(\.(([a-zA-Z\d][a-zA-Z\d-]*[a-zA-Z\d])|[a-zA-Z\d])){1,126}$/;class Se{static validateVersion(e){const t=e.split(".").map(e=>parseInt(e,10));for(;t.length<3;)t.push(0);return t.some(e=>isNaN(e))?u.Err(new h(n.SemanticVersionParse,e)):u.Ok(t.slice(0,3))}static validateDomain(e){return e?(e=Se.checkAndTrimProtocol(e.toLowerCase()),be.test(e)||e===we||M.error`The top-level domain ${e} is invalid. The value has been set as provided, but it does not meet the required format for proper SDK functionality. Please check the domain for correctness.`,u.Ok(e)):u.Err()}static validateNetworkDomain(e){return e?(e=(e=Se.checkAndTrimProtocol(e.toLowerCase())).replace(/^\.+|\.+$/g,""),be.test(e)||e===we?u.Ok(e):(M.error`The network domain ${e} is invalid.`,u.Err())):u.Err()}static checkAndTrimProtocol(e){const t=["http://","https://"];for(const i of t)if(e.startsWith(i)){e=e.substring(i.length),M.warning`The domain contains ${i}. Domain after protocol trimming: ${e}`;break}return e}}class Ae{static getNonce(e){let t="";for(let i=0;i<16;i++){const i=e.getRandomNumber(),a=Math.floor(16*i);t+="0123456789ABCDEF".charAt(a)}return t}static checkTargeting({segment:e,visitorCode:t,targetingData:i,experimentId:a,variationConfiguration:r,clientConfiguration:s,packageInfo:o,dataManager:d}){if(M.debug`CALL: checkTargeting(segment, visitorCode: ${t}, targetingData: ${i}, experimentId: ${a}, variationConfiguration, clientConfiguration, packageInfo, dataManager)`,!e||!e.conditionsData.firstLevel.length){const e=u.Ok(!0);return M.debug`RETURN checkTargeting(segment, visitorCode: ${t}, targetingData: ${i}, experimentId: ${a}, variationConfiguration, clientConfiguration, packageInfo, dataManager) -> (result: ${e})`,e}if(!r){const e=u.Err(new h(n.Initialization));return M.debug`RETURN checkTargeting(segment, visitorCode: ${t}, targetingData: ${i}, experimentId: ${a}, variationConfiguration, clientConfiguration, packageInfo, dataManager) -> (result: ${e})`,e}let l={};const c=r.getStoredVariations(t);c.ok&&(l=c.data);const g=d.getTree(e);let v,p,f;g.hasTargetingType(Te.SEGMENT)&&(v=d.trees,f=s.segments),g.hasTargetingType(Te.TARGET_FEATURE_FLAG)&&(p=s.ruleMap);const m=g.evaluate({variationData:l,sdkInfo:o,segments:f,ruleMap:p,trees:v,targetingData:i,experimentId:a,visitorCode:t});return M.debug`RETURN checkTargeting(segment, visitorCode: ${t}, targetingData: ${i}, experimentId: ${a}, variationConfiguration, clientConfiguration, packageInfo, dataManager) -> (result: ${m})`,m}static convertTimeUnit(e,t){return e/{[Ve.Minute]:K.Minute,[Ve.Hour]:K.Hour,[Ve.Day]:K.Day,[Ve.Week]:K.Week,[Ve.Month]:K.Month}[t]}static isCustomData(e){return e.data.type===ae.CustomData}static updateCache({hasJsCssVariables:e,cacheManager:t,visitorCode:i,experimentId:a,variationId:r}){const n=t.getAliveItem(i),s=n?Object.assign({},n):{};s[a]={variationId:r,hasJsCssVariables:e,expirationTime:Date.now()+5*K.Second},t.add({key:i,data:s,lifetime:5})}static getTrackingCode(e,t){let i="window.kameleoonQueue=window.kameleoonQueue||[];";const a=e.getAliveItem(t);if(!a)return i;const r={};return Object.entries(a).forEach(([e,{variationId:t,expirationTime:a,hasJsCssVariables:n}])=>{const s=!n;a>Date.now()&&(i+=`window.kameleoonQueue.push(['Experiments.assignVariation',${e},${t},true]);`,i+=`window.kameleoonQueue.push(['Experiments.trigger',${e},${s}]);`,r[Number(e)]={variationId:t,expirationTime:a,hasJsCssVariables:n})}),e.add({key:t,data:r,lifetime:5}),i}static compareSemVer({version:e,compareVersion:t,operator:i}){const a=Se.validateVersion(e),r=Se.validateVersion(t);if(!a.ok)return u.Err(a.error);if(!r.ok)return u.Err(r.error);const[n,s,o]=a.data,[d,l,h]=r.data,[g,v,p]=[n===d,s===l,o===h];switch(i){case Ie.EQUAL:return u.Ok(g&&v&&p);case Ie.GREATER:return u.Ok(n>d||g&&s>l||g&&v&&o>h);case Ie.LOWER:return u.Ok(n<d||g&&s<l||g&&v&&o<h);default:M.error`Unknown version match type: ${i}`,c(i)}}static getVariationByHash(e,t){let i=0;for(const a of e)if(i+=a.exposition,i>=t)return a;return null}}class Oe{static insertInOrderedListMutably({list:e,element:t,order:i}){if(e.includes(t))return;const a=e.findIndex(e=>i===Re.Ascending?e>=t:e<=t);-1===a?e.push(t):e.splice(a,0,t)}static insertVisitInOrderedListMutably({list:e,visit:t}){if(e.find(e=>"number"==typeof e?e===t.timeStarted:e.timeStarted===t.timeStarted))return;const i=e.findIndex(e=>"number"==typeof e?e>=t.timeStarted:e.timeStarted>=t.timeStarted);-1===i?e.push(t):e.splice(i,0,t),e.length>26&&e.splice(0,e.length-26)}}class $e{constructor({urlAddress:e,title:t,referrers:i}){this.urlAddress=e,this.title=t,this.referrers=i,this.timestamps=[{time:Date.now(),status:P.Unsent}]}get url(){var e;if(!this.urlAddress)return"";const t=this.title?"&title="+encodeURIComponent(this.title):"",i=(null===(e=this.referrers)||void 0===e?void 0:e.length)?"&referrersIndices="+JSON.stringify(this.referrers):"";return"eventType=page&href="+encodeURIComponent(this.urlAddress)+t+i}get status(){const{[P.Sent]:e,[P.Unsent]:t,[P.Pending]:i}=this.timestamps.reduce((e,{status:t})=>(e[t]=!0,e),{[P.Sent]:!1,[P.Unsent]:!1,[P.Pending]:!1});return!e||t||i?i&&!t?P.Pending:P.Unsent:P.Sent}set status(e){this.timestamps=this.timestamps.map(t=>Object.assign(Object.assign({},t),{status:e}))}set _nonce(e){this.nonce=e}get data(){return{urlAddress:this.urlAddress,title:this.title,referrers:this.referrers,type:ae.PageView,timestamps:this.timestamps,status:this.status,nonce:this.nonce}}static _fromRaw(e){const{urlAddress:t,title:i,referrers:a,timestamps:r,nonce:n}=e,s=new $e({urlAddress:t,title:i,referrers:a});return s.timestamps=r,n&&(s._nonce=n),s}static _updateFromVisit(e,t){const i=e.pageEvents;if(i)for(const e of i){let i=[];const{time:a}=e,{href:r,title:n,referrersIndices:s}=e.data;let o;if("number"==typeof s[0]&&(i=s),t.has(r)){const e=t.get(r).timestamps;o=new $e({urlAddress:r,title:n,referrers:i}),o.timestamps=[...e,{time:a,status:P.Sent}]}else o=new $e({urlAddress:r,title:n,referrers:i}),o.timestamps=[{time:a,status:P.Sent}];t.set(r,o)}}}let Ne=class e{constructor(t,i,...a){this._status=P.Unsent,this.isIdentifier=!1;const r="boolean"==typeof i;"number"==typeof t?this._index=t:(this._name=t,this._index=e.UNDEFINED_INDEX),this.overwrite=!r||i,this.value=r?a:[i,...a].filter(e=>null!=e)}get url(){if("number"!=typeof this._index)return"";const e=[...new Set(this.value)];let t={};e.forEach(e=>{t[e]=1});let i="";return this.isIdentifier&&(i="&mappingIdentifier="+String(!0)),"eventType=customData&index="+this._index+"&valuesCountMap="+encodeURIComponent(JSON.stringify(t))+"&overwrite="+String(this.overwrite)+i}get data(){return Object.assign(Object.assign({index:this._index},void 0!==this._name?{name:this._name}:{}),{value:this.value,type:ae.CustomData,isIdentifier:this.isIdentifier,status:this.status,overwrite:this.overwrite})}get status(){return this._isMappingIdentifier?P.Unsent:this._status}static _fromRaw(t){const{index:i,value:a,status:r,isIdentifier:n,name:s,overwrite:o}=t;let u;return s?(u=new e(s,null==o||o,...a),u.index=i):u=new e(i,null==o||o,...a),u.status=r,u._isMappingIdentifier=n,u}set _isMappingIdentifier(e){this.isIdentifier=e}set status(e){this._status=e}static _updateFromVisit(t,i){var a;if(null===(a=t.customDataEvents)||void 0===a?void 0:a.length)for(let a=t.customDataEvents.length-1;a>=0;a--){const{index:r,valuesCountMap:n}=t.customDataEvents[a].data;i.has(r)||i.set(r,new e(r,...Object.keys(n)))}}set index(e){this._index=e}get index(){return this._index}get name(){return this._name}get values(){return this.value}};Ne.UNDEFINED_INDEX=-1;let Fe=class e{constructor({goalId:e,revenue:t=0,negative:i=!1,metadata:a}){this.goalId=e,this.revenue=t,this.negative=i,this.status=P.Unsent,this.id=Math.floor(1e6*Math.random()),this._metadata=a}set _id(e){this.id=e}set _nonce(e){this.nonce=e}get url(){var e;return"eventType=conversion&goalId="+String(this.goalId)+"&revenue="+String(this.revenue)+"&negative="+String(this.negative)+((null===(e=this.metadata)||void 0===e?void 0:e.length)?"&metadata="+this._encodeMetadata():"")}get _metadata(){return this.metadata}set _metadata(e){this.metadata=e}get data(){var e;return{goalId:this.goalId,nonce:this.nonce,revenue:this.revenue,negative:this.negative,type:ae.Conversion,status:this.status,id:this.id,metadata:(null===(e=this.metadata)||void 0===e?void 0:e.map(e=>e.data))||void 0}}_encodeMetadata(){var e;if(!(null===(e=this.metadata)||void 0===e?void 0:e.length))return"";const t=new Set;return encodeURIComponent(JSON.stringify(this.metadata.reduce((e,i)=>(t.has(i.data.index)||(t.add(i.data.index),e[i.data.index]=i.data.value),e),{})))}static _fromRaw(t){const{goalId:i,revenue:a,negative:r,status:n,id:s,nonce:o,metadata:u}=t,d=new e({goalId:i,revenue:a,negative:r,metadata:e.parseMetadata(u)});return d._id=s,d.status=n,o&&(d._nonce=o),d}static parseMetadata(e){return(null==e?void 0:e.map(e=>Ne._fromRaw(e)))||void 0}static _listFromVisit(t){var i,a;const r=[];if(!(null===(i=t.conversionEvents)||void 0===i?void 0:i.length))return[];if(null===(a=t.conversionEvents)||void 0===a?void 0:a.length)for(const i of t.conversionEvents){const{goalId:t,revenue:a,negative:n}=i.data,s=new e({goalId:t,revenue:a,negative:n});s.status=P.Sent,r.push(s)}return r}static _updateFromVisit(t,i){var a;if(null===(a=t.conversionEvents)||void 0===a?void 0:a.length)for(const a of t.conversionEvents){const{goalId:t}=a.data;if(!i.has(t)){const a=new e({goalId:t});a.status=P.Sent,i.set(t,a)}}}},xe=class e{constructor(e,t){this.browser=e,this.version=t,this.status=P.Unsent}get url(){if(!this.browser)return"";const e=this.version?D+this.version:"";return y+S+this.browser+E+de[this.browser]+e}get data(){return{browser:this.browser,type:ae.Browser,version:this.version,status:this.status}}static _fromRaw(t){const{browser:i,version:a,status:r}=t,n=new e(i,a);return n.status=r,n}static _fromVisit(t){if(!t.staticDataEvent)return;const{browser:i,browserIndex:a,browserVersion:r}=t.staticDataEvent.data;if(i||"number"==typeof a){const t=null!=i?i:le[a];return r?new e(t,r):new e(t)}}},Me=class e{constructor(e){this.device=e,this.status=P.Unsent}get url(){return this.device?y+I+this.device:""}get data(){return{device:this.device,type:ae.Device,status:this.status}}static _fromRaw(t){const{device:i,status:a}=t,r=new e(i);return r.status=a,r}static _fromVisit(t){var i;if(null===(i=t.staticDataEvent)||void 0===i?void 0:i.data.deviceType)return new e(t.staticDataEvent.data.deviceType)}},_e=class e{constructor(e){this.operatingSystem=e,this.status=P.Unsent}get url(){return this.operatingSystem?y+w+this.operatingSystem+b+oe[this.operatingSystem]:""}get data(){return{operatingSystem:this.operatingSystem,type:ae.OperatingSystem,status:this.status}}static _fromRaw(t){const{operatingSystem:i,status:a}=t,r=new e(i);return r.status=a,r}static _fromVisit(t){if(!t.staticDataEvent)return;const{os:i,osIndex:a}=t.staticDataEvent.data;if(i||"number"==typeof a){const t=null!=i?i:ue[a];return new e(t)}}};class Ue{constructor({country:e,region:t,city:i,postalCode:a,coordinates:r}){this.country=e,this.region=t,this.city=i,this.postalCode=a,this.coordinates=r,this.status=P.Unsent}get url(){const e=this.region?"®ion="+encodeURIComponent(this.region):"",t=this.city?"&city="+encodeURIComponent(this.city):"",i=this.postalCode?"&postalCode="+encodeURIComponent(this.postalCode):"",a=this.coordinates?"&latitude="+this.coordinates[0]+"&longitude="+this.coordinates[1]:"";return"eventType=geolocation&country="+encodeURIComponent(this.country)+e+t+i+a}get data(){return{type:ae.GeolocationData,country:this.country,region:this.region,city:this.city,postalCode:this.postalCode,coordinates:this.coordinates,status:this.status}}static _fromRaw(e){const{country:t,region:i,city:a,postalCode:r,coordinates:n,status:s}=e,o=new Ue({country:t,region:i,city:a,postalCode:r,coordinates:n});return o.status=s,o}static _fromVisit(e){var t;if(!(null===(t=e.geolocationEvents)||void 0===t?void 0:t.length))return;let i;for(const t of e.geolocationEvents){const{data:e}=t;e.country&&(i=e)}const{country:a,region:r,city:n}=i||{};return a?new Ue(r&&n?{country:a,region:r,city:n}:r?{country:a,region:r}:{country:a}):void 0}}class Le{constructor(e){this.status=P.Sent,this.visits=e,this._visitNumber=e.length?e.length-1:0}get visitNumber(){return this._visitNumber}get url(){return""}get data(){return{visits:this.visits,visitNumber:this._visitNumber,type:ae.VisitsData,status:this.status}}get isSent(){return!0}set timestamp(e){Oe.insertVisitInOrderedListMutably({list:this.visits,visit:e}),this._visitNumber=this.visits.length?this.visits.length-1:0}updateVisitNumber(e){e>this._visitNumber&&(this._visitNumber=e)}}class Pe{constructor(e){this.kcs=e,this.status=P.Sent}get url(){return""}get data(){return{kcs:this.kcs,type:ae.KameleoonConversionScore,status:this.status}}}class Ke{constructor(e,t){this.id=e,this.variationId=t,this.status=P.Sent}get url(){return""}get data(){return{id:this.id,variationId:this.variationId,type:ae.Personalization,status:P.Sent}}static _fromRaw(e){return new Ke(e.id,e.variationId)}static _updateFromVisit(e,t){var i;if(null===(i=e.personalizationEvents)||void 0===i?void 0:i.length)for(const i of e.personalizationEvents){const{id:e,variationId:a}=i.data;if(!t.has(e)){const i=new Ke(e,a);t.set(e,i)}}}}class Ge{constructor(e){this.values=new Map(Object.entries(e).map(([e,t])=>[Number(e),this.extractVarIds(t)])),this.cbs=e,this.status=P.Sent}extractVarIds(e){const t=new Map;return Object.entries(e).forEach(([e,i])=>{t.has(i)||t.set(i,[]),t.get(i).push(Number(e))}),Array.from(t.entries()).sort(([e],[t])=>t-e).map(([,e])=>({ids:e.sort((e,t)=>e-t)}))}getValues(){return this.values}get url(){return""}get data(){return{cbs:this.cbs,type:ae.CBScores,status:this.status}}static _fromRaw(e){const t=new Ge(e.cbs);return t.status=e.status,t}}class Be{constructor({filters:e,dataManager:t,visitorCode:i}){this.visitsData=new Le([]),this.visitorData=[],this.storageVisitorData=[],this.experimentData={},this.singleDataTypes={[ae.Device]:null,[ae.Browser]:null,[ae.GeolocationData]:null,[ae.OperatingSystem]:null,[ae.KameleoonConversionScore]:null,[ae.CBScores]:null},this.multipleDataTypes={[ae.CustomData]:new Map,[ae.PageView]:new Map,[ae.Conversion]:new Map,[ae.Personalization]:new Map},this.filters=e,this.dataManager=t,this.visitorDataTypes=t.getVisitorStoredDataTypes(i)}get data(){return{visitorData:this.visitorData,storageVisitorData:this.storageVisitorData,visitsData:this.visitsData,experimentData:this.experimentData}}processVisit(e){this.processBrowser(e),this.processDevice(e),this.processOperatingSystem(e),this.processGeolocationData(e),this.processCustomData(e),this.processConversion(e),this.processPageView(e),this.processExperiments(e),this.processPersonalization(e)}processMultipleDataTypes(){for(const[e,t]of Object.entries(this.multipleDataTypes))if(t.size)switch(e){case ae.PageView:this.visitorData.push(...t.values()),this.storageVisitorData.push(...t.values());break;case ae.Personalization:case ae.Conversion:this.storageVisitorData.push(...t.values());break;case ae.CustomData:t.forEach(e=>{this.visitorData.push(e),this.dataManager.storedCustomDataIndexes.has(e.data.index)||this.storageVisitorData.push(e)})}}processKcs(e){if(this.filters.kcs&&e){const t=new Pe(e);this.storageVisitorData.push(t)}}processVisitsData(e){var t;this.visitsData.timestamp={timeStarted:e.timeStarted,timeLastActivity:null!==(t=e.timeLastEvent)&&void 0!==t?t:e.timeStarted}}processVisitNumber(e,t){var i,a,r;if(this.visitsData.visitNumber<=t&&(null===(i=e.staticDataEvent)||void 0===i?void 0:i.data.visitNumber)){const i=null!==(r=null===(a=e.st