@flagship.io/js-sdk
Version:
1 lines • 125 kB
JavaScript
import{createRequire as t}from"node:module";import*as i from"events";import*as e from"node-abort-controller";import*as s from"node-fetch";var a={611:i=>{i.exports=t(import.meta.url)("http")},692:i=>{i.exports=t(import.meta.url)("https")}},n={};function o(t){var i=n[t];if(void 0!==i)return i.exports;var e=n[t]={exports:{}};return a[t](e,e.exports,o),e.exports}o.d=(t,i)=>{for(var e in i)o.o(i,e)&&!o.o(t,e)&&Object.defineProperty(t,e,{enumerable:!0,get:i[e]})},o.o=(t,i)=>Object.prototype.hasOwnProperty.call(t,i);var r={};o.d(r,{ABTastyWebSDKPostMessageType:()=>kt,APP_VERSION_CODE:()=>Pi,APP_VERSION_NAME:()=>Li,CARRIER_NAME:()=>Vi,CacheStrategy:()=>At,DEVICE_LOCALE:()=>Ai,DEVICE_MODEL:()=>Ni,DEVICE_TYPE:()=>Si,DecisionApiConfig:()=>Zt,DecisionMode:()=>yt,EventCategory:()=>Ot,FLAGSHIP_CLIENT:()=>Ui,FLAGSHIP_CONTEXT:()=>qi,FLAGSHIP_VERSION:()=>Bi,FLAGSHIP_VISITOR:()=>Ki,FSFetchReasons:()=>Et,FSFetchStatus:()=>$i,FSFlag:()=>te,FSFlagCollection:()=>ie,FSFlagMetadata:()=>Qi,FSFlagStatus:()=>zi,FSSdkStatus:()=>mt,Flagship:()=>pe,HitType:()=>Dt,INTERFACE_NAME:()=>Gi,INTERNET_CONNECTION:()=>xi,IP:()=>Mi,LOCATION_CITY:()=>ki,LOCATION_COUNTRY:()=>Di,LOCATION_LAT:()=>Oi,LOCATION_LONG:()=>bi,LOCATION_REGION:()=>Ri,LogLevel:()=>Tt,OS_NAME:()=>Hi,OS_VERSION_CODE:()=>wi,OS_VERSION_NAME:()=>Fi,TroubleshootingLabel:()=>St,Visitor:()=>bt,VisitorCacheStatus:()=>Nt,default:()=>ve});const h=(_t={EventEmitter:()=>i.EventEmitter},Ct={},o.d(Ct,_t),Ct),c="5.1.2",g={name:"TypeScript",version:c},d=25e5,u="https://decision.flagship.io/v2/",l="https://events.flagship.io",f="https://events.flagship.io/troubleshooting",I="https://events.flagship.io/analytics",p="activate",v="fs_consent",_=144e5,C="ready",m="https://docs.developers.flagship.io/docs/js-v3",y=`Params 'envId' and 'apiKey' must not be null or empty.\n Learn more: ${m}#initialization`,T="{0} must be a {1}",E="Visitor {0}, method {1} is deactivated while SDK status is: {2}.",A="SEND BATCH",S="without calling `fetchFlags` method afterwards. So, the value of the flag `{1}` might be outdated",N=`You can't create a new visitor without first calling the "Flagship.start" method.\nLearn more: ${m}#initialization\n`,k="INITIALIZATION",R="UPDATE CONTEXT",D="NEW VISITOR",O="ADD HIT",b="batch",M="cid",H="cid",F="cuid",w="aid",V="vid",x="caid",L="vaid",P="ds",G="t",U="qt",B="APP",K="x-api-key",q="Content-Type",Q="x-sdk-client",$="x-sdk-version",z="application/json",W="BUCKETING",j=`Visitor {0}, the key '{1}' must be a non null String.\nLearn more: ${m}#updating-the-visitor-context`,J=`Visitor {0}, 'value' for key '{1}[], must be one of the following types : String, Number, Boolean\nLearn more: ${m}#updating-the-visitor-context`,Y=`visitor {0}, Predefined Context {0} must be of type {1}\nLearn more: ${m}#predefined-user-context-keys-`,Z="FETCH_FLAGS",X="FLAG_VALUE",tt="GET_FLAG",it="FLAG_VISITOR_EXPOSED",et="FLAG_METADATA",st="Visitor {0}, No Flags found for key {1}: Empty metadata object is returned",at=`Visitor {0}, Flag for key {1} Method Flag.metadata is deactivated while SDK status is NOT_READY: Empty metadata object is returned {2}\nLearn more: ${m}#getting-flags-campaigns-metadata`,nt="AUTHENTICATE",ot=`Visitor {0}, visitorId must not be null or empty\nLearn more: ${m}#authenticate`,rt="UNAUTHENTICATE",ht="ALLOCATION",ct=`lookupVisitor method has loaded a bad format version ({0}) for visitor {1}.\nLearn more: ${m}#managing-visitor-cache`,gt="CACHE",dt="visitor {0}. {1} threw an exception {2}",ut="{0} threw an exception {1}",lt="TRACKING_MANAGER",ft="{0} Unexpected Error occurred {1}",It="{0} has been sent : {1}",pt="ACTIVATE HIT",vt="BATCH HIT";var _t,Ct,mt,yt,Tt,Et,At,St,Nt,kt,Rt,Dt,Ot;class bt extends h.EventEmitter{visitorDelegate;_onReady;constructor(t){super(),this.visitorDelegate=t,this._onReady=t=>{this.emit(C,t)},this.visitorDelegate.on(C,this._onReady);const i=this;i.sendEaiVisitorEvent=t=>{this.visitorDelegate.sendEaiVisitorEvent(t)},i.sendEaiPageView=t=>{this.visitorDelegate.sendEaiPageView(t)},i.onEAICollectStatusChange=t=>{this.visitorDelegate.onEAICollectStatusChange(t)}}get visitorId(){return this.visitorDelegate.visitorId}set visitorId(t){this.visitorDelegate.visitorId=t}get anonymousId(){return this.visitorDelegate.anonymousId}get config(){return this.visitorDelegate.config}get context(){return this.visitorDelegate.context}get flagsStatus(){return this.visitorDelegate.flagsStatus}get hasConsented(){return this.visitorDelegate.hasConsented}setConsent(t){this.visitorDelegate.setConsent(t)}updateContext(t,i){this.visitorDelegate.updateContext(t,i)}clearContext(){this.visitorDelegate.clearContext()}getFlag(t){return this.visitorDelegate.getFlag(t)}getFlags(){return this.visitorDelegate.getFlags()}fetchFlags(){return this.visitorDelegate.fetchFlags()}sendHit(t){return this.visitorDelegate.sendHit(t)}sendHits(t){return this.visitorDelegate.sendHits(t)}authenticate(t){this.visitorDelegate.authenticate(t)}unauthenticate(){this.visitorDelegate.unauthenticate()}collectEAIEventsAsync(...t){let i;return t.length>0&&(i=t[0]),this.visitorDelegate.collectEAIEventsAsync(i)}cleanup(){this.visitorDelegate.cleanup(),this.visitorDelegate.off(C,this._onReady)}}function Mt(t,...i){let e=t;for(let t=0;t<i.length;t++){const s=i[t],a="string"==typeof s?s:JSON.stringify(s instanceof Map?Array.from(s.values()):s);e=e.replace(new RegExp(`\\{${t}\\}`,"g"),a)}return e}function Ht(t,i,e,...s){!t||!t.logLevel||t.logLevel<Tt.ERROR||Ft(t,Mt(e,...s),i)}function Ft(t,i,e){!t||!t.logLevel||t.logLevel<Tt.ERROR||("function"==typeof t.onLog&&t.onLog(Tt.ERROR,e,i),t.logManager&&"function"==typeof t.logManager.error&&t.logManager.error(i,e))}function wt(t,i,e,...s){!t||!t.logLevel||t.logLevel<Tt.WARNING||Vt(t,Mt(e,...s),i)}function Vt(t,i,e){!t||!t.logLevel||t.logLevel<Tt.WARNING||("function"==typeof t.onLog&&t.onLog(Tt.WARNING,e,i),t.logManager&&"function"==typeof t.logManager.warning&&t.logManager.warning(i,e))}function xt(t,i,e,...s){!t||!t.logLevel||t.logLevel<Tt.INFO||Lt(t,Mt(e,...s),i)}function Lt(t,i,e){!t||!t.logLevel||t.logLevel<Tt.INFO||("function"==typeof t.onLog&&t.onLog(Tt.INFO,e,i),t.logManager&&"function"==typeof t.logManager.info&&t.logManager.info(i,e))}function Pt(t,i,e,...s){!t||!t.logLevel||t.logLevel<Tt.DEBUG||Gt(t,Mt(e,...s),i)}function Gt(t,i,e){!t||!t.logLevel||t.logLevel<Tt.DEBUG||("function"==typeof t.onLog&&t.onLog(Tt.DEBUG,e,i),t.logManager&&"function"==typeof t.logManager.debug&&t.logManager.debug(i,e))}function Ut(){return"undefined"!=typeof window&&void 0!==window.document}function Bt(t,i){return typeof t==typeof i&&("object"!=typeof t||"object"!=typeof i||Array.isArray(t)===Array.isArray(i))}function Kt(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){const i=16*Math.random()|0;return("x"===t?i:3&i|8).toString(16)}))}function qt(t,i){return JSON.stringify({message:t,data:i})}function Qt(t){const i=JSON.stringify(t);return Array.from(i,(t=>t.charCodeAt(0).toString(16))).join("")}function $t(t,i){if("string"!=typeof t)return Ht(i,"hexToValue","Invalid hex string: {0}",t),null;let e="";for(let s=0;s<t.length;s+=2){const a=t.slice(s,s+2),n=parseInt(a,16);if(isNaN(n))return Ht(i,"hexToValue","Invalid hex character: {0}",a),null;e+=String.fromCharCode(n)}try{return JSON.parse(e)}catch(t){return Ht(i,"hexToValue","Error while parsing JSON: {0}",t),null}}function zt(t,i){if(t===i)return!0;if("object"!=typeof t||"object"!=typeof i||null==t||null==i)return!1;const e=Object.keys(t),s=Object.keys(i);if(e.length!==s.length)return!1;for(const a of e)if(!s.includes(a)||!zt(t[a],i[a]))return!1;return!0}function Wt(t,i,e){const s=new Date,a=t=>t.toString().padStart(2,"0");return`${{[Tt.EMERGENCY]:"[1;37;41m",[Tt.ALERT]:"[1;37;45m",[Tt.CRITICAL]:"[1;37;41m",[Tt.ERROR]:"[1;37;41m",[Tt.WARNING]:"[33;1m",[Tt.NOTICE]:"[36;1m",[Tt.INFO]:"[32;1m",[Tt.DEBUG]:"[90;1m",[Tt.NONE]:"",[Tt.ALL]:"[90;1m"}[t]||""}[${s.getFullYear()}-${a(s.getMonth()+1)}-${a(s.getDate())} ${a(s.getHours())}:${a(s.getMinutes())}:${a(s.getSeconds())}.${s.getMilliseconds().toString().padStart(3,"0")}] [Flagship SDK] [${Tt[t].padEnd(2)}] [${e}] ${i}[0m`}!function(t){t[t.SDK_NOT_INITIALIZED=0]="SDK_NOT_INITIALIZED",t[t.SDK_INITIALIZING=1]="SDK_INITIALIZING",t[t.SDK_PANIC=2]="SDK_PANIC",t[t.SDK_INITIALIZED=3]="SDK_INITIALIZED"}(mt||(mt={})),function(t){t.DECISION_API="DECISION-API",t.BUCKETING="BUCKETING",t.BUCKETING_EDGE="BUCKETING_EDGE"}(yt||(yt={})),function(t){t[t.NONE=0]="NONE",t[t.EMERGENCY=1]="EMERGENCY",t[t.ALERT=2]="ALERT",t[t.CRITICAL=3]="CRITICAL",t[t.ERROR=4]="ERROR",t[t.WARNING=5]="WARNING",t[t.NOTICE=6]="NOTICE",t[t.INFO=7]="INFO",t[t.DEBUG=8]="DEBUG",t[t.ALL=9]="ALL"}(Tt||(Tt={})),function(t){t.UPDATE_CONTEXT="UPDATE_CONTEXT",t.AUTHENTICATE="AUTHENTICATE",t.UNAUTHENTICATE="UNAUTHENTICATE",t.FLAGS_FETCHING_ERROR="FLAGS_FETCHING_ERROR",t.FLAGS_FETCHED_FROM_CACHE="FLAGS_FETCHED_FROM_CACHE",t.FLAGS_NEVER_FETCHED="FLAGS_NEVER_FETCHED",t.NONE="NONE"}(Et||(Et={})),function(t){t[t.CONTINUOUS_CACHING=0]="CONTINUOUS_CACHING",t[t.PERIODIC_CACHING=1]="PERIODIC_CACHING"}(At||(At={}));class jt{_batchIntervals;_poolMaxSize;_batchStrategy;constructor(t){this.batchIntervals=t?.batchIntervals,this.poolMaxSize=t?.poolMaxSize,this._batchStrategy=this.getCacheStrategy(t?.cacheStrategy)}getCacheStrategy(t){return"number"==typeof t?t:Ut()?At.CONTINUOUS_CACHING:At.PERIODIC_CACHING}get batchIntervals(){return this._batchIntervals}set batchIntervals(t){("number"!=typeof t||t<1||t>10800)&&(t=Ut()?5:10),this._batchIntervals=t}get poolMaxSize(){return this._poolMaxSize}set poolMaxSize(t){("number"!=typeof t||t<5)&&(t=Ut()?10:100),this._poolMaxSize=t}get cacheStrategy(){return this._batchStrategy}}class Jt{_envId;_apiKey;_decisionMode;_timeout;_logLevel;_onSdkStatusChanged;_logManager;_fetchNow;_pollingInterval;_onBucketingUpdated;_reuseVisitorIds;_initialBucketing;_decisionApiUrl;_hitDeduplicationTime;_visitorCacheImplementation;_hitCacheImplementation;_disableCache;_trackingManagerConfig;_onVisitorExposed;_fetchThirdPartyData;_nextFetchConfig;_fetchFlagsBufferingTime;_disableDeveloperUsageTracking;_onLog;_isQAModeEnabled;get isQAModeEnabled(){return this._isQAModeEnabled}set isQAModeEnabled(t){this._isQAModeEnabled=t}_enableAnalytics;get disableDeveloperUsageTracking(){return this._disableDeveloperUsageTracking}set disableDeveloperUsageTracking(t){this._disableDeveloperUsageTracking=t}get fetchFlagsBufferingTime(){return this._fetchFlagsBufferingTime}set fetchFlagsBufferingTime(t){this._fetchFlagsBufferingTime=t}get nextFetchConfig(){return this._nextFetchConfig}set nextFetchConfig(t){this._nextFetchConfig=t}get fetchThirdPartyData(){return this._fetchThirdPartyData}set fetchThirdPartyData(t){this._fetchThirdPartyData=t}get trackingManagerConfig(){return this._trackingManagerConfig}get onLog(){return this._onLog}set onLog(t){this._onLog=t}get onVisitorExposed(){return this._onVisitorExposed}constructor(t){const{envId:i,apiKey:e,timeout:s,logLevel:a,logManager:n,onSdkStatusChanged:o,fetchNow:r,decisionMode:h,reuseVisitorIds:c,initialBucketing:g,decisionApiUrl:d,hitDeduplicationTime:l,visitorCacheImplementation:f,hitCacheImplementation:I,disableCache:p,language:v,sdkVersion:_,trackingManagerConfig:C,onLog:m,onVisitorExposed:y,nextFetchConfig:T,fetchFlagsBufferingTime:E,disableDeveloperUsageTracking:A}=t;this.initQaMode(),this.initSDKInfo(v,_),n&&(this.logManager=n),this.fetchFlagsBufferingTime=E??2,this.nextFetchConfig=T||{revalidate:20},this._trackingManagerConfig=new jt(C||{}),this.onLog=m,this.decisionApiUrl=d||u,this._envId=i,this._apiKey=e,this.logLevel=a??Tt.INFO,this.timeout=s||2,this.fetchNow=void 0===r||r,this.reuseVisitorIds=void 0===c||c,this._decisionMode=h||yt.DECISION_API,this._initialBucketing=g,this.hitDeduplicationTime=l??2.5,this.disableCache=!!p,this.disableDeveloperUsageTracking=A||!1,f&&(this.visitorCacheImplementation=f),I&&(this.hitCacheImplementation=I),this.onSdkStatusChanged=o,this._onVisitorExposed=y}initQaMode(){}initSDKInfo(t,i){switch(t){case 1:g.name="ReactJS",g.version=i??c;break;case 2:g.name="React-Native",g.version=i??c;break;default:g.name="undefined"!=typeof window&&"Deno"in window?"Deno":"TypeScript",g.version=c}}get initialBucketing(){return this._initialBucketing}set initialBucketing(t){this._initialBucketing=t}get reuseVisitorIds(){return this._reuseVisitorIds}set reuseVisitorIds(t){this._reuseVisitorIds=t}get onBucketingUpdated(){return this._onBucketingUpdated}set onBucketingUpdated(t){this._onBucketingUpdated=t}set envId(t){this._envId=t}get envId(){return this._envId}set apiKey(t){this._apiKey=t}get apiKey(){return this._apiKey}get decisionMode(){return this._decisionMode}get timeout(){return this._timeout}set timeout(t){this._timeout=t}get logLevel(){return this._logLevel}set logLevel(t){this._logLevel=t}get fetchNow(){return this._fetchNow}set fetchNow(t){this._fetchNow=t}get pollingInterval(){return this._pollingInterval}set pollingInterval(t){this._pollingInterval=t}get hitDeduplicationTime(){return this._hitDeduplicationTime}set hitDeduplicationTime(t){"number"==typeof t?this._hitDeduplicationTime=t:Ft(this,Mt(T,"hitDeduplicationTime","number"),"hitDeduplicationTime")}get visitorCacheImplementation(){return this._visitorCacheImplementation}set visitorCacheImplementation(t){this._visitorCacheImplementation=t}get hitCacheImplementation(){return this._hitCacheImplementation}set hitCacheImplementation(t){this._hitCacheImplementation=t}get disableCache(){return this._disableCache}set disableCache(t){this._disableCache=t}get onSdkStatusChanged(){return this._onSdkStatusChanged}set onSdkStatusChanged(t){t&&"function"!=typeof t?Ft(this,"statusChangedCallback must be a function","onSdkStatusChanged"):this._onSdkStatusChanged=t}get logManager(){return this._logManager}set logManager(t){this._logManager=t}get decisionApiUrl(){return this._decisionApiUrl}set decisionApiUrl(t){"string"==typeof t?this._decisionApiUrl=t:Ft(this,Mt(T,"decisionApiUrl","string"),"decisionApiUrl")}}class Yt extends Jt{constructor(t){super({...t,decisionMode:yt.BUCKETING}),this.pollingInterval=t?.pollingInterval??5,this.onBucketingUpdated=t?.onBucketingUpdated,this.fetchThirdPartyData=t?.fetchThirdPartyData}}class Zt extends Jt{constructor(t){super({...t,decisionMode:yt.DECISION_API})}}class Xt{_config;_decisionManager;_trackingManager;_sharedActionTracking;constructor(t,i,e,s){this._config=t,this._decisionManager=i,this._trackingManager=e,this._sharedActionTracking=s}get config(){return this._config}set config(t){this._config=t}get decisionManager(){return this._decisionManager}set decisionManager(t){this._decisionManager=t}get trackingManager(){return this._trackingManager}set trackingManager(t){this._trackingManager=t}get sharedActionTracking(){return this._sharedActionTracking}}!function(t){t.VISITOR_SEND_HIT="VISITOR_SEND_HIT",t.VISITOR_FETCH_CAMPAIGNS_ERROR="VISITOR_FETCH_CAMPAIGNS_ERROR",t.VISITOR_FETCH_CAMPAIGNS="VISITOR_FETCH_CAMPAIGNS",t.VISITOR_AUTHENTICATE="VISITOR_AUTHENTICATE",t.VISITOR_UNAUTHENTICATE="VISITOR_UNAUTHENTICATE",t.VISITOR_EXPOSED_FLAG_NOT_FOUND="VISITOR_EXPOSED_FLAG_NOT_FOUND",t.FLAG_VALUE_NOT_CALLED="FLAG_VALUE_NOT_CALLED",t.GET_FLAG_VALUE_FLAG_NOT_FOUND="GET_FLAG_VALUE_FLAG_NOT_FOUND",t.GET_FLAG_METADATA_TYPE_WARNING="GET_FLAG_METADATA_TYPE_WARNING",t.GET_FLAG_VALUE_TYPE_WARNING="GET_FLAG_VALUE_TYPE_WARNING",t.VISITOR_EXPOSED_TYPE_WARNING="VISITOR_EXPOSED_TYPE_WARNING",t.VISITOR_SEND_ACTIVATE="VISITOR_SEND_ACTIVATE",t.GET_CAMPAIGNS_ROUTE_RESPONSE_ERROR="GET_CAMPAIGNS_ROUTE_RESPONSE_ERROR",t.GET_CAMPAIGNS_ROUTE_RESPONSE="GET_CAMPAIGNS_ROUTE_RESPONSE",t.SDK_BUCKETING_FILE="SDK_BUCKETING_FILE",t.SEND_ACTIVATE_HIT_ROUTE_ERROR="SEND_ACTIVATE_HIT_ROUTE_ERROR",t.SEND_BATCH_HIT_ROUTE_RESPONSE_ERROR="SEND_BATCH_HIT_ROUTE_RESPONSE_ERROR",t.SEND_HIT_ROUTE_ERROR="SEND_HIT_ROUTE_ERROR",t.SDK_BUCKETING_FILE_ERROR="SDK_BUCKETING_FILE_ERROR",t.SDK_CONFIG="SDK_CONFIG",t.ACCOUNT_SETTINGS="ACCOUNT_SETTINGS",t.ACCOUNT_SETTINGS_ERROR="ACCOUNT_SETTINGS_ERROR",t.EMOTION_AI_SCORE="EMOTION_EAI_SCORE",t.EMOTION_AI_SCORE_FROM_LOCAL_CACHE="EMOTION_AI_SCORE_FROM_LOCAL_CACHE",t.EMOTION_AI_SCORE_ERROR="EMOTION_EAI_SCORE_ERROR",t.EMOTION_AI_VISITOR_EVENT="EMOTION_AI_VISITOR_EVENT",t.EMOTION_AI_VISITOR_EVENT_ERROR="EMOTION_AI_VISITOR_EVENT_ERROR",t.EMOTION_AI_PAGE_VIEW="EMOTION_AI_PAGE_VIEW",t.EMOTION_AI_PAGE_VIEW_ERROR="EMOTION_AI_PAGE_VIEW_ERROR",t.EMOTION_AI_START_COLLECTING="EMOTION_AI_START_COLLECTING",t.EMOTION_AI_STOP_COLLECTING="EMOTION_AI_STOP_COLLECTING",t.EMOTION_AI_START_SCORING="EMOTION_AI_START_SCORING",t.EMOTION_AI_SCORING_FAILED="EMOTION_AI_SCORING_FAILED",t.EMOTION_AI_SCORING_SUCCESS="EMOTION_AI_SCORING_SUCCESS"}(St||(St={})),function(t){t.NONE="NONE",t.ANONYMOUS_ID_CACHE="ANONYMOUS_ID_CACHE",t.VISITOR_ID_CACHE="VISITOR_ID_CACHE",t.VISITOR_ID_CACHE_WITH_ANONYMOUS_ID_CACHE="VISITOR_ID_CACHE_WITH_ANONYMOUS_ID_CACHE"}(Nt||(Nt={})),function(t){t.AB_TASTY_WEB_SDK_INITIALIZED="AB_TASTY_WEB_SDK_INITIALIZED"}(kt||(kt={}));class ti{_visitorId;_config;_type;_ds;_anonymousId;_userIp;_screenResolution;_locale;_sessionNumber;_key;_createdAt;_qaMode;_isActionTrackingHit;get isActionTrackingHit(){return this._isActionTrackingHit}set isActionTrackingHit(t){this._isActionTrackingHit=t}get key(){return this._key}set key(t){this._key=t}get sessionNumber(){return this._sessionNumber}set sessionNumber(t){this._sessionNumber=t}get locale(){return this._locale}set locale(t){this._locale=t}get screenResolution(){return this._screenResolution}set screenResolution(t){this._screenResolution=t}get userIp(){return this._userIp}set userIp(t){this._userIp=t}get anonymousId(){return this._anonymousId}set anonymousId(t){this._anonymousId=t}get visitorId(){return this._visitorId}set visitorId(t){this._visitorId=t}get ds(){return this._ds}set ds(t){this._ds=t}get type(){return this._type}get config(){return this._config}set config(t){this._config=t}get createdAt(){return this._createdAt}set createdAt(t){this._createdAt=t}get qaMode(){return this._qaMode}set qaMode(t){this._qaMode=t}constructor(t){const{type:i,userIp:e,screenResolution:s,locale:a,sessionNumber:n,visitorId:o,anonymousId:r,ds:h,qaMode:c,isActionTrackingHit:g}=t;this._type=i,e&&(this.userIp=e),s&&(this.screenResolution=s),a&&(this.locale=a),n&&(this.sessionNumber=n),this.visitorId=o,this._anonymousId=r||null,this.createdAt=Date.now(),this.ds=h||B,this.qaMode=c,this.isActionTrackingHit=g}isNotEmptyString(t,i){return!(!t||"string"!=typeof t)||(Ft(this.config,Mt(T,i,"string"),i),!1)}isNumeric(t,i){return!(!t||"number"!=typeof t)||(Ft(this.config,Mt(T,i,"number"),i),!1)}isInteger(t,i){return!!Number.isInteger(t)||(Ft(this.config,Mt(T,i,"integer"),i),!1)}toApiKeys(){const t={[V]:this.visitorId,[P]:this.ds,[M]:`${this.config?.envId}`,[G]:this.type,[F]:null,[U]:Date.now()-this._createdAt};return this.qaMode&&(t.qa=!0),this.userIp&&(t.uip=this.userIp),this.screenResolution&&(t.sr=this.screenResolution),this.locale&&(t.ul=this.locale),this.sessionNumber&&(t.sn=this.sessionNumber),this.visitorId&&this.anonymousId&&(t[V]=this.anonymousId,t[F]=this.visitorId),t}toObject(){return{key:this.key,visitorId:this.visitorId,ds:this.ds,type:this.type,userIp:this.userIp,screenResolution:this.screenResolution,locale:this.locale,sessionNumber:this.sessionNumber,anonymousId:this.anonymousId,createdAt:this.createdAt,qaMode:this.qaMode}}isReady(t=!0){return!!(this.visitorId&&this.ds&&this.config&&this.config.envId&&this.type)}}!function(t){t[t.Timer=0]="Timer",t[t.BatchLength=1]="BatchLength",t[t.Flush=2]="Flush",t[t.ActivateLength=3]="ActivateLength",t[t.DirectHit=4]="DirectHit",t[t.DirectActivate=5]="DirectActivate"}(Rt||(Rt={}));class ii extends ti{data;_traffic;get traffic(){return this._traffic}set traffic(t){this._traffic=t}constructor(t){super({type:t.type,userIp:t.userIp,screenResolution:t.screenResolution,locale:t.locale,sessionNumber:t.sessionNumber,visitorId:t.visitorId,anonymousId:t.anonymousId}),this.data={...t,version:t.version||"1",stackType:t.stackType||"SDK",stackName:t.stackName||g.name,stackVersion:t.stackVersion||g.version,label:t.label,logLevel:t.logLevel,timestamp:t.timestamp||new Date(Date.now()).toISOString(),timeZone:this.getTimezone(),ds:B,envId:t.envId||t.config.envId},this._traffic=t.traffic,this.config=t.config}getTimezone(){return("object"==typeof Intl?Intl.DateTimeFormat()?.resolvedOptions()?.timeZone:void 0)||""+(new Date).getTimezoneOffset()/60}toApiKeys(){const t={[V]:this.visitorId,[P]:this.data.ds,[M]:`${this.data.config?.envId}`,[G]:this.type,cv:{}},i={version:`${this.data.version}`,logLevel:`${Tt[this.data.logLevel]}`,timestamp:`${this.data.timestamp}`,timeZone:`${this.data.timeZone}`,label:`${this.data.label}`,"stack.type":`${this.data.stackType}`,"stack.name":`${this.data.stackName}`,"stack.version":`${this.data.stackVersion}`};if(void 0!==this.data.lastBucketingTimestamp&&(i.lastBucketingTimestamp=`${this.data.lastBucketingTimestamp}`),void 0!==this.data.lastInitializationTimestamp&&(i.lastInitializationTimestamp=`${this.data.lastInitializationTimestamp}`),void 0!==this.data.flagshipInstanceId&&(i.flagshipInstanceId=`${this.data.flagshipInstanceId}`),this.data.accountId&&(i.accountId=`${this.data.accountId}`),this.data.envId&&(i.envId=`${this.data.envId}`),void 0!==this.data.sdkBucketingFile&&(i.sdkBucketingFile=JSON.stringify(this.data.sdkBucketingFile)),void 0!==this.data.stackOriginName&&(i["stack.origin.name"]=`${this.data.stackOriginName}`),void 0!==this.data.stackOriginVersion&&(i["stack.origin.version"]=`${this.data.stackOriginVersion}`),void 0!==this.data.sdkStatus&&(i["sdk.status"]=`${mt[this.data.sdkStatus]}`),void 0!==this.data.sdkConfigLogLevel&&(i["sdk.config.logLevel"]=`${Tt[this.data.sdkConfigLogLevel]}`),void 0!==this.data.sdkConfigMode&&(i["sdk.config.mode"]=`${this.data.sdkConfigMode}`),void 0!==this.data.sdkConfigCustomLogManager&&(i["sdk.config.customLogManager"]=`${this.data.sdkConfigCustomLogManager}`),void 0!==this.data.sdkConfigCustomCacheManager&&(i["sdk.config.customCacheManager"]=`${this.data.sdkConfigCustomCacheManager}`),void 0!==this.data.sdkConfigStatusListener&&(i["sdk.config.custom.StatusListener"]=`${this.data.sdkConfigStatusListener}`),void 0!==this.data.sdkConfigTimeout&&(i["sdk.config.timeout"]=""+1e3*this.data.sdkConfigTimeout),void 0!==this.data.sdkConfigPollingInterval&&(i["sdk.config.pollingTime"]=""+1e3*this.data.sdkConfigPollingInterval),void 0!==this.data.sdkConfigTrackingManagerStrategy&&(i["sdk.config.trackingManager.strategy"]=`${At[this.data.sdkConfigTrackingManagerStrategy]}`),void 0!==this.data.sdkConfigTrackingManagerBatchIntervals&&(i["sdk.config.trackingManager.batchIntervals"]=""+1e3*this.data.sdkConfigTrackingManagerBatchIntervals),void 0!==this.data.sdkConfigTrackingManagerPoolMaxSize&&(i["sdk.config.trackingManager.poolMaxSize"]=`${this.data.sdkConfigTrackingManagerPoolMaxSize}`),void 0!==this.data.sdkConfigFetchNow&&(i["sdk.config.fetchNow"]=`${this.data.sdkConfigFetchNow}`),void 0!==this.data.sdkConfigReuseVisitorIds&&(i["sdk.config.reuseVisitorIds"]=`${this.data.sdkConfigReuseVisitorIds}`),void 0!==this.data.sdkConfigInitialBucketing&&(i["sdk.config.initialBucketing"]=JSON.stringify(this.data.sdkConfigInitialBucketing)),void 0!==this.data.sdkConfigDecisionApiUrl&&(i["sdk.config.decisionApiUrl"]=`${this.data.sdkConfigDecisionApiUrl}`),void 0!==this.data.sdkConfigHitDeduplicationTime&&(i["sdk.config.hitDeduplicationTime"]=""+1e3*this.data.sdkConfigHitDeduplicationTime),void 0!==this.data.sdkConfigUsingCustomHitCache&&(i["sdk.config.usingCustomHitCache"]=JSON.stringify(this.data.sdkConfigUsingCustomHitCache)),void 0!==this.data.sdkConfigUsingCustomVisitorCache&&(i["sdk.config.usingCustomVisitorCache"]=JSON.stringify(this.data.sdkConfigUsingCustomVisitorCache)),void 0!==this.data.sdkConfigUsingOnVisitorExposed&&(i["sdk.config.usingOnVisitorExposed"]=JSON.stringify(this.data.sdkConfigUsingOnVisitorExposed)),void 0!==this.data.sdkConfigFetchThirdPartyData&&(i["sdk.config.fetchThirdPartyData"]=JSON.stringify(this.data.sdkConfigFetchThirdPartyData)),void 0!==this.data.sdkConfigFetchFlagsBufferingTime&&(i["sdk.config.fetchFlagsBufferingTime"]=JSON.stringify(1e3*this.data.sdkConfigFetchFlagsBufferingTime)),void 0!==this.data.sdkConfigNextFetchConfig&&(i["sdk.config.nextFetchConfig"]=JSON.stringify(this.data.sdkConfigNextFetchConfig)),void 0!==this.data.sdkConfigDisableDeveloperUsageTracking&&(i["sdk.config.disableDeveloperUsageTracking"]=JSON.stringify(this.data.sdkConfigDisableDeveloperUsageTracking)),void 0!==this.data.sdkConfigDisableCache&&(i["sdk.config.disableCache"]=JSON.stringify(this.data.sdkConfigDisableCache)),void 0!==this.data.httpRequestUrl&&(i["http.request.url"]=`${this.data.httpRequestUrl}`),void 0!==this.data.httpRequestMethod&&(i["http.request.method"]=`${this.data.httpRequestMethod}`),void 0!==this.data.httpRequestHeaders&&(i["http.request.headers"]=JSON.stringify(this.data.httpRequestHeaders)),void 0!==this.data.httpRequestBody&&(i["http.request.body"]=JSON.stringify(this.data.httpRequestBody)),void 0!==this.data.httpResponseUrl&&(i["http.response.url"]=`${this.data.httpResponseUrl}`),void 0!==this.data.httpResponseMethod&&(i["http.response.method"]=`${this.data.httpResponseMethod}`),void 0!==this.data.httpResponseHeaders&&(i["http.response.headers"]=JSON.stringify(this.data.httpResponseHeaders)),void 0!==this.data.httpResponseCode&&(i["http.response.code"]=`${this.data.httpResponseCode}`),void 0!==this.data.httpResponseBody&&(i["http.response.body"]=JSON.stringify(this.data.httpResponseBody)),void 0!==this.data.httpResponseTime&&(i["http.response.time"]=`${this.data.httpResponseTime}`),void 0!==this.visitorId&&(i["visitor.visitorId"]=`${this.visitorId}`),void 0!==this.anonymousId&&(i["visitor.anonymousId"]=`${this.anonymousId}`),void 0!==this.data.visitorSessionId&&(i["visitor.sessionId"]=`${this.data.visitorSessionId}`),void 0!==this.data.visitorStatus&&(i["visitor.status"]=`${this.data.visitorStatus}`),void 0!==this.data.visitorInstanceType&&(i["visitor.instanceType"]=`${this.data.visitorInstanceType}`),void 0!==this.data.visitorContext)for(const t in this.data.visitorContext){const e=this.data.visitorContext[t];i[`visitor.context.[${t}]`]=`${e}`}if(void 0!==this.data.visitorConsent&&(i["visitor.consent"]=`${this.data.visitorConsent}`),void 0!==this.data.visitorAssignmentHistory)for(const t in this.data.visitorAssignmentHistory){const e=this.data.visitorAssignmentHistory[t];i[`visitor.assignments.[${t}]`]=e}if(void 0!==this.data.visitorFlags&&this.data.visitorFlags.forEach(((t,e)=>{for(const s in t){const a=t[s],n="value"===s||"key"===s,o="string"==typeof a?a:JSON.stringify(a);i[`visitor.flags.[${e}]${n?"":".metadata"}.${s}`]=o}})),void 0!==this.data.visitorIsAuthenticated&&(i["visitor.isAuthenticated"]=`${this.data.visitorIsAuthenticated}`),void 0!==this.data.visitorInitialCampaigns&&(i["visitor.initialCampaigns"]=JSON.stringify(this.data.visitorInitialCampaigns)),void 0!==this.data.visitorInitialFlagsData&&(i["visitor.initialFlagsData"]=JSON.stringify(Array.isArray(this.data.visitorInitialFlagsData)?this.data.visitorInitialFlagsData:Array.from(this.data.visitorInitialFlagsData))),void 0!==this.data.visitorCampaigns&&(i["visitor.campaigns"]=JSON.stringify(this.data.visitorCampaigns)),void 0!==this.data.visitorCampaignFromCache&&(i["visitor.campaignFromCache"]=JSON.stringify(this.data.visitorCampaignFromCache)),void 0!==this.data.contextKey&&(i.contextKey=`${this.data.contextKey}`),void 0!==this.data.contextValue&&(i.contextValue=`${this.data.contextValue}`),void 0!==this.data.flagKey&&(i["flag.key"]=`${this.data.flagKey}`),void 0!==this.data.flagValue&&(i["flag.value"]=`${this.data.flagValue}`),void 0!==this.data.flagDefault&&(i["flag.default"]=JSON.stringify(this.data.flagDefault)),void 0!==this.data.flagMetadataCampaignId&&(i["flag.metadata.campaignId"]=`${this.data.flagMetadataCampaignId}`),void 0!==this.data.flagMetadataCampaignName&&(i["flag.metadata.campaignName"]=`${this.data.flagMetadataCampaignName}`),void 0!==this.data.flagMetadataVariationGroupId&&(i["flag.metadata.variationGroupId"]=`${this.data.flagMetadataVariationGroupId}`),void 0!==this.data.flagMetadataVariationGroupName&&(i["flag.metadata.variationGroupName"]=`${this.data.flagMetadataVariationGroupName}`),void 0!==this.data.flagMetadataVariationId&&(i["flag.metadata.variationId"]=`${this.data.flagMetadataVariationId}`),void 0!==this.data.flagMetadataVariationName&&(i["flag.metadata.variationName"]=`${this.data.flagMetadataVariationName}`),void 0!==this.data.flagMetadataCampaignSlug&&(i["flag.metadata.campaignSlug"]=`${this.data.flagMetadataCampaignSlug}`),void 0!==this.data.flagMetadataCampaignType&&(i["flag.metadata.campaignType"]=`${this.data.flagMetadataCampaignType}`),void 0!==this.data.flagMetadataCampaignIsReference&&(i["flag.metadata.isReference"]=`${this.data.flagMetadataCampaignIsReference}`),void 0!==this.data.hitContent)for(const t in this.data.hitContent){const e=this.data.hitContent[t];i[`hit.${t}`]="string"==typeof e?e:JSON.stringify(e)}if(void 0!==this.data.batchTriggeredBy&&(i.batchTriggeredBy=`${Rt[this.data.batchTriggeredBy]}`),void 0!==this.data.accountSettings)for(const t in this.data.accountSettings){const e=this.data.accountSettings[t];i[`accountSettings.${t}`]="string"==typeof e?e:JSON.stringify(e)}return void 0!==this.data.eAIScore&&(i["eAIScore.eai.eas"]=this.data.eAIScore.eai.eas),void 0!==this.data.isEAIScoreFromLocalCache&&(i.isEAIScoreFromLocalCache=`${this.data.isEAIScoreFromLocalCache}`),void 0!==this.data.eAIDataTimestamp&&(i.eAIDataTimestamp=`${this.data.eAIDataTimestamp}`),t.cv=i,t}isReady(t=!0){return!(t&&!super.isReady())}getErrorMessage(){return"event category and event action are required"}}class ei extends ii{constructor(t){super({...t,type:"TROUBLESHOOTING"})}}class si{_config;_panic=!1;_httpClient;_statusChangedCallback;_troubleshooting;_lastBucketingTimestamp;_trackingManager;_flagshipInstanceId;get trackingManager(){return this._trackingManager}set trackingManager(t){this._trackingManager=t}get flagshipInstanceId(){return this._flagshipInstanceId}set flagshipInstanceId(t){this._flagshipInstanceId=t}get lastBucketingTimestamp(){return this._lastBucketingTimestamp}get troubleshooting(){return this._troubleshooting}set troubleshooting(t){this._troubleshooting=t}get config(){return this._config}set panic(t){this.updateFlagshipStatus(t?mt.SDK_PANIC:mt.SDK_INITIALIZED),this._panic=t,t&&Gt(this.config,"Panic mode is enabled : all feature are disabled except fetchFlags.",Z)}statusChangedCallback(t){this._statusChangedCallback=t}constructor({httpClient:t,config:i,trackingManager:e,flagshipInstanceId:s}){this._config=i,this._httpClient=t,this._trackingManager=e,this._flagshipInstanceId=s||""}updateFlagshipStatus(t){"function"==typeof this._statusChangedCallback&&this._statusChangedCallback&&this._statusChangedCallback(t)}getModifications(t){const i=new Map;return t.forEach((t=>{const e=t.variation.modifications.value;for(const s in e){const a=e[s];i.set(s,{key:s,campaignId:t.id,campaignName:t.name||"",variationGroupId:t.variationGroupId,variationGroupName:t.variationGroupName||"",variationId:t.variation.id,variationName:t.variation.name||"",isReference:!!t.variation.reference,campaignType:t.type,slug:t.slug,value:a})}})),i}isPanic(){return this._panic}handleTroubleshootingError(t){const{error:i,visitor:e,requestBody:s,headers:a,url:n,now:o}=t,r=new ei({label:St.GET_CAMPAIGNS_ROUTE_RESPONSE_ERROR,logLevel:Tt.ERROR,visitorId:e.visitorId,flagshipInstanceId:this.flagshipInstanceId,anonymousId:e.anonymousId,visitorSessionId:e.instanceId,traffic:100,config:this.config,visitorContext:e.context,httpRequestBody:s,httpRequestHeaders:a,httpRequestMethod:"POST",httpRequestUrl:n,httpResponseBody:i?.message,httpResponseHeaders:i?.headers,httpResponseCode:i?.statusCode,httpResponseTime:Date.now()-o});this.trackingManager?.addTroubleshootingHit(r);const h=qt(i.message||i,{url:n,headers:a,body:s,duration:Date.now()-o});throw new Error(h)}async getDecisionApiCampaignsAsync(t){const i={[K]:`${this.config.apiKey}`,[Q]:g.name,[$]:g.version,[q]:z},e={visitorId:t.visitorId,anonymousId:t.anonymousId,trigger_hit:!1,context:t.context,visitor_consent:t.hasConsented},s=`${this.config.decisionApiUrl||u}${this.config.envId}/campaigns?exposeAllKeys=true&extras[]=accountSettings`,a=Date.now();try{const t=await this._httpClient.postAsync(s,{headers:i,timeout:this.config.timeout,body:e,nextFetchConfig:this.config.nextFetchConfig});this.panic=!!t?.body?.panic;let a=null;t?.body?.campaigns&&(a=t.body.campaigns);const n=t?.body?.extras?.accountSettings?.troubleshooting;return n&&(this.troubleshooting={startDate:new Date(n.startDate),endDate:new Date(n.endDate),timezone:n.timezone,traffic:n.traffic}),a}catch(n){this.handleTroubleshootingError({error:n,visitor:t,requestBody:e,headers:i,url:s,now:a})}}}class ai extends si{async getCampaignsAsync(t){return this.getDecisionApiCampaignsAsync(t)}}!function(t){t.PAGE_VIEW="PAGEVIEW",t.PAGE="PAGEVIEW",t.SCREEN_VIEW="SCREENVIEW",t.SCREEN="SCREENVIEW",t.TRANSACTION="TRANSACTION",t.ITEM="ITEM",t.EVENT="EVENT"}(Dt||(Dt={}));class ni extends ti{_context;get context(){return this._context}set context(t){this._context=t}constructor(t){super({type:"SEGMENT",userIp:t.userIp,screenResolution:t.screenResolution,locale:t.locale,sessionNumber:t.sessionNumber,visitorId:t.visitorId,anonymousId:t.anonymousId,qaMode:t.qaMode,isActionTrackingHit:t.isActionTrackingHit}),this.context=t.context}isReady(t=!0){return!(t&&!super.isReady()||!this.context)}toApiKeys(){const t=super.toApiKeys();return t.s=this.context,t}toObject(){return{...super.toObject(),context:this.context}}getErrorMessage(){return"data property is required"}}!function(t){t.ACTION_TRACKING="Action Tracking",t.USER_ENGAGEMENT="User Engagement"}(Ot||(Ot={}));class oi extends ti{_category;_action;_label;_value;get category(){return this._category}set category(t){Object.values(Ot).includes(t)?this._category=t:Ft(this.config,"The category value must be either EventCategory::ACTION_TRACKING or EventCategory::ACTION_TRACKING","category")}get action(){return this._action}set action(t){this.isNotEmptyString(t,"action")&&(this._action=t)}get label(){return this._label}set label(t){this.isNotEmptyString(t,"label")&&(this._label=t)}get value(){return this._value}set value(t){!Number.isInteger(t)||t<0?Ft(this.config,"value must be an integer and be >= 0","value"):this._value=t}constructor(t){super({type:Dt.EVENT,userIp:t.userIp,screenResolution:t.screenResolution,locale:t.locale,sessionNumber:t.sessionNumber,visitorId:t.visitorId,anonymousId:t.anonymousId,qaMode:t.qaMode,isActionTrackingHit:t.isActionTrackingHit});const{category:i,action:e,label:s,value:a}=t;this.category=i,this.action=e,s&&(this.label=s),a&&(this.value=a)}toApiKeys(){const t=super.toApiKeys();return t.ec=this.category,t.ea=this.action,this.label&&(t.el=this.label),this.value&&(t.ev=this.value),t}toObject(){return{...super.toObject(),category:this.category,action:this.action,label:this.label,value:this.value}}isReady(t=!0){return!(t&&!super.isReady()||!this.category||!this.action)}getErrorMessage(){return"event category and event action are required"}}class ri extends ti{_documentLocation;get documentLocation(){return this._documentLocation}set documentLocation(t){this.isNotEmptyString(t,"documentLocation")&&(this._documentLocation=t)}constructor(t){super({type:Dt.SCREEN_VIEW,userIp:t.userIp,screenResolution:t.screenResolution,locale:t.locale,sessionNumber:t.sessionNumber,visitorId:t.visitorId,anonymousId:t.anonymousId,qaMode:t.qaMode,isActionTrackingHit:t.isActionTrackingHit}),this.documentLocation=t.documentLocation}isReady(t=!0){return!(t&&!super.isReady()||!this.documentLocation)}toApiKeys(){const t=super.toApiKeys();return t.dl=this.documentLocation,t}toObject(){return{...super.toObject(),documentLocation:this.documentLocation}}getErrorMessage(){return"Screen name is required"}}class hi{_hits;_config;get hits(){return this._hits}get config(){return this._config}constructor(t,i){this._config=i,this._hits=t}toApiKeys(){return{[M]:`${this.config?.envId}`,[b]:this.hits.map((t=>{const i=t.toApiKeys();return delete i[M],i}))}}}class ci extends ti{_variationGroupId;_variationId;_flagKey;_flagValue;_flagDefaultValue;_flagMetadata;_visitorContext;constructor(t){super({type:"ACTIVATE",userIp:t.userIp,screenResolution:t.screenResolution,locale:t.locale,sessionNumber:t.sessionNumber,visitorId:t.visitorId,anonymousId:t.anonymousId,qaMode:t.qaMode});const{variationGroupId:i,variationId:e,flagKey:s,flagValue:a,flagDefaultValue:n,flagMetadata:o,visitorContext:r}=t;this.variationGroupId=i,this.variationId=e,this.flagKey=s,this.flagValue=a,this.flagDefaultValue=n,this.flagMetadata=o,this.visitorContext=r}get variationGroupId(){return this._variationGroupId}set variationGroupId(t){this._variationGroupId=t}get variationId(){return this._variationId}set variationId(t){this._variationId=t}get flagKey(){return this._flagKey}set flagKey(t){this._flagKey=t}get flagValue(){return this._flagValue}set flagValue(t){this._flagValue=t}get flagDefaultValue(){return this._flagDefaultValue}set flagDefaultValue(t){this._flagDefaultValue=t}get flagMetadata(){return this._flagMetadata}set flagMetadata(t){this._flagMetadata=t}get visitorContext(){return this._visitorContext}set visitorContext(t){this._visitorContext=t}isReady(t=!0){return!(t&&!super.isReady()||!this.variationGroupId||!this.variationId)}toApiKeys(){const t={[V]:this.anonymousId||this.visitorId,[L]:this.variationId,[x]:this.variationGroupId,[H]:this.config.envId,[w]:null,[U]:Date.now()-this.createdAt};return this.visitorId&&this.anonymousId&&(t[V]=this.visitorId,t.aid=this.anonymousId),this.qaMode&&(t.qa=this.qaMode),t}toObject(){return{...super.toObject(),variationGroupId:this.variationGroupId,variationId:this.variationId}}getErrorMessage(){return"variationGroupId and variationId are required"}}class gi extends ti{_hits;get hits(){return this._hits}set hits(t){this._hits=t}constructor(t){super({...t,visitorId:"",anonymousId:"",type:"BATCH"}),this.hits=t.hits}isReady(){return!!(super.isReady()&&this.hits&&this.hits.length>0&&this.hits.every((t=>t.isReady(!1))))}toApiKeys(){const t={[P]:this.ds,[M]:`${this.config?.envId}`,[G]:this.type,[U]:Date.now()-this.createdAt};return t.h=this.hits.map((t=>{const i=t.toApiKeys();return delete i[P],delete i[M],i})),t}getErrorMessage(){return"Please check required fields"}}class di{_config;_hitsPoolQueue;_activatePoolQueue;_httpClient;_troubleshootingQueue;_usageHitQueue;_flagshipInstanceId;_isUsageHitQueueSending;_isTroubleshootingQueueSending;_HitsToFsQa;_sendFsHitToQATimeoutId;_troubleshootingData;_initTroubleshootingHit;_hasInitTroubleshootingHitSent;_sharedActionTracking;get flagshipInstanceId(){return this._flagshipInstanceId}get troubleshootingData(){return this._troubleshootingData}set troubleshootingData(t){this._troubleshootingData=t}get config(){return this._config}get initTroubleshootingHit(){return this._initTroubleshootingHit}set initTroubleshootingHit(t){this._initTroubleshootingHit=t}constructor(t){const{config:i,hitsPoolQueue:e,httpClient:s,activatePoolQueue:a,troubleshootingQueue:n,flagshipInstanceId:o,analyticHitQueue:r,initTroubleshootingHit:h,sharedActionTracking:c}=t;this._HitsToFsQa=[],this._hasInitTroubleshootingHitSent=!1,this._config=i,this._hitsPoolQueue=e,this._httpClient=s,this._activatePoolQueue=a,this._troubleshootingQueue=n,this._flagshipInstanceId=o,this._usageHitQueue=r,this._isUsageHitQueueSending=!1,this._isTroubleshootingQueueSending=!1,this._initTroubleshootingHit=h,this._sharedActionTracking=c}dispatchHitsToTag(t){}sendHitsToFsQa(t){}async addHit(t){const i=`${t.visitorId}:${Kt()}`;t.key=i,await this.addHitInPoolQueue(t),t.type===Dt.EVENT&&t.action===v&&t.label===`${g.name}:false`&&await this.notConsent(t.visitorId),Pt(this.config,lt,"The HIT has been added into the pool queue : {0}",t.toApiKeys()),this.config.trackingManagerConfig?.poolMaxSize&&this._hitsPoolQueue.size>=this.config.trackingManagerConfig.poolMaxSize&&this.config.decisionMode!==yt.BUCKETING_EDGE&&this.sendBatch()}async activateFlag(t){const i=new ci(t);i.config=this.config;const e=`${i.visitorId}:${Kt()}`;if(i.key=e,this.config.decisionMode===yt.BUCKETING_EDGE)return await this.activateFlagEdgeMode(i),void Gt(this.config,Mt("The ACTIVATE has been added to the pool queue : {0}",JSON.stringify(i.toApiKeys())),"ADD ACTIVATE");let s=[];this._activatePoolQueue.size&&(s=Array.from(this._activatePoolQueue.values())),this._activatePoolQueue.clear(),await this.sendActivate({activateHitsPool:s,currentActivate:i,batchTriggeredBy:Rt.ActivateLength})}async activateFlagEdgeMode(t){this._activatePoolQueue.set(t.key,t),await this.cacheHit(new Map([[t.key,t]]))}onVisitorExposed(t){const i=this.config.onVisitorExposed;if("function"!=typeof i)return;const e={key:t.flagKey,value:t.flagValue,defaultValue:t.flagDefaultValue,metadata:t.flagMetadata};i({exposedVisitor:{id:t.visitorId,anonymousId:t.anonymousId,context:t.visitorContext},fromFlag:e})}async sendBatch(t=Rt.BatchLength){if(this._activatePoolQueue.size){const i=Array.from(this._activatePoolQueue.values());this._activatePoolQueue.clear(),await this.sendActivate({activateHitsPool:i,batchTriggeredBy:t})}const i=new gi({hits:[],ds:B});i.config=this.config;const e=[];for(const[t,s]of this._hitsPoolQueue)if(Date.now()-s.createdAt>=_)e.push(t);else{if(JSON.stringify(i).length>d)break;i.hits.push(s),e.push(t)}if(e.forEach((t=>{this._hitsPoolQueue.delete(t)})),!i.hits.length)return;const s={[q]:z},a=i.toApiKeys(),n=Date.now();try{await this._httpClient.postAsync(l,{headers:s,body:a,timeout:this.config.timeout,nextFetchConfig:this.config.nextFetchConfig}),Pt(this.config,lt,It,vt,{url:l,body:a,headers:s,nextFetchConfig:this.config.nextFetchConfig,duration:Date.now()-n,batchTriggeredBy:Rt[t]}),await this.flushHits(e),this.sendHitsToFsQa(i.hits),this.dispatchHitsToTag(i.hits)}catch(e){i.hits.forEach((t=>{this._hitsPoolQueue.set(t.key,t)})),Ht(this.config,lt,ft,vt,{httpRequestBody:a,httpRequestHeaders:s,httpRequestMethod:"POST",httpRequestUrl:l,httpResponseBody:e?.message,httpResponseHeaders:e?.headers,httpResponseCode:e?.statusCode,duration:Date.now()-n,batchTriggeredBy:Rt[t]});const o=new ei({label:St.SEND_BATCH_HIT_ROUTE_RESPONSE_ERROR,logLevel:Tt.ERROR,visitorId:`${this._flagshipInstanceId}`,flagshipInstanceId:this._flagshipInstanceId,traffic:0,config:this.config,httpRequestBody:i.hits,httpRequestHeaders:s,httpResponseBody:e?.message,httpResponseHeaders:e?.headers,httpResponseMethod:"POST",httpResponseUrl:l,httpResponseCode:e?.statusCode,httpResponseTime:Date.now()-n,batchTriggeredBy:t});this.sendTroubleshootingHit(o)}}async notConsent(t){const i=Array.from(this._hitsPoolQueue).filter((([,i])=>!(i?.type===Dt.EVENT&&i?.action===v||i.visitorId!==t&&i.anonymousId!==t))),e=Array.from(this._activatePoolQueue).filter((([,i])=>i.visitorId===t||i.anonymousId===t)),s=[];i.forEach((([t])=>{this._hitsPoolQueue.delete(t),s.push(t)})),e.forEach((([t])=>{this._activatePoolQueue.delete(t),s.push(t)})),s.length&&await this.flushHits(s)}async cacheHit(t){try{const i=this.config.hitCacheImplementation;if(this.config.disableCache||!i||"function"!=typeof i.cacheHit)return;const e={};t.forEach(((t,i)=>{const s={version:1,data:{visitorId:t.visitorId,anonymousId:t.anonymousId,type:t.type,content:t.toObject(),time:Date.now()}};e[i]=s})),await i.cacheHit(e),Pt(this.config,"CACHE HIT","Hit cache has been saved into database : {0}",e)}catch(t){Ht(this.config,gt,ut,"cacheHit",t.message||t)}}async flushHits(t){try{const i=this.config.hitCacheImplementation;if(this.config.disableCache||!i||"function"!=typeof i.flushHits)return;await i.flushHits(t),Pt(this.config,gt,"The following hit keys have been flushed from database : {0}",t)}catch(t){Ht(this.config,gt,ut,"flushHits",t.message||t)}}async flushAllHits(){try{const t=this.config.hitCacheImplementation;if(this.config.disableCache||!t||"function"!=typeof t.flushAllHits)return;await t.flushAllHits(),Gt(this.config,"All hits cache has been flushed from database","FLUSH HIT")}catch(t){Ht(this.config,gt,ut,"flushAllHits",t.message||t)}}isTroubleshootingActivated(){if(!this.troubleshootingData)return!1;const t=new Date;return t>=this.troubleshootingData.startDate&&!(t>this.troubleshootingData.endDate&&(this._hasInitTroubleshootingHitSent=!1,1))}async addTroubleshootingHit(t){if(!t.key){const i=`${t.visitorId}:${Kt()}`;t.key=i}this._troubleshootingQueue.set(t.key,t),Gt(this.config,Mt("The TROUBLESHOOTING HIT has been added to the pool queue : {0}",JSON.stringify(t.toApiKeys())),"ADD TROUBLESHOOTING HIT")}async sendTroubleshootingHit(t){if(!this.isTroubleshootingActivated()||void 0===t.traffic||this.troubleshootingData.traffic<t.traffic)return;const i=t.toApiKeys(),e=Date.now();try{await this._httpClient.postAsync(f,{body:i}),Gt(this.config,Mt("Troubleshooting hit has been sent : {0}",JSON.stringify({...i,duration:Date.now()-e})),"SEND TROUBLESHOOTING"),t.key&&(this._troubleshootingQueue.delete(t.key),await this.flushHits([t.key]))}catch(s){this.isTroubleshootingActivated()&&await this.addTroubleshootingHit(t),Ft(this.config,qt(s.message||s,{url:f,headers:{},body:i,duration:Date.now()-e}),A)}}async sendInitTroubleshootingHit(){this.isTroubleshootingActivated()&&this._initTroubleshootingHit&&!this._hasInitTroubleshootingHitSent&&(await this.sendTroubleshootingHit(this._initTroubleshootingHit),this._hasInitTroubleshootingHitSent=!0)}async sendTroubleshootingQueue(){if(await this.sendInitTroubleshootingHit(),this.isTroubleshootingActivated()&&!this._isTroubleshootingQueueSending&&0!==this._troubleshootingQueue.size){this._isTroubleshootingQueueSending=!0;for(const[t,i]of Array.from(this._troubleshootingQueue))await this.sendTroubleshootingHit(i);this._isTroubleshootingQueueSending=!1}}async addUsageHit(t){if(!t.key){const i=`${t.visitorId}:${Kt()}`;t.key=i}this._usageHitQueue.set(t.key,t),Gt(this.config,Mt("The USAGE HIT has been added to the pool queue : {0}",JSON.stringify(t.toApiKeys())),"ADD USAGE HIT")}async sendUsageHit(t){const i=t.toApiKeys(),e=Date.now();try{await this._httpClient.postAsync(I,{body:i}),Gt(this.config,Mt("Usage hit has been sent : {0}",JSON.stringify({...i,duration:Date.now()-e})),"SEND USAGE HIT"),t.key&&(this._usageHitQueue.delete(t.key),await this.flushHits([t.key]))}catch(s){await this.addUsageHit(t),Ft(this.config,qt(s.message||s,{url:I,headers:{},body:i,duration:Date.now()-e}),A)}}async sendUsageHitQueue(){if(!this._isUsageHitQueueSending&&0!==this._usageHitQueue.size){this._isUsageHitQueueSending=!0;for(const[,t]of Array.from(this._usageHitQueue))await this.sendUsageHit(t);this._isUsageHitQueueSending=!1}}}class ui extends di{async addHitInPoolQueue(t){this._hitsPoolQueue.set(t.key,t),await this.cacheHit(new Map([[t.key,t]]))}async sendActivateHitBatch(t,i,e){const s={[K]:this.config.apiKey,[Q]:g.name,[$]:g.version,[q]:z};e&&t.hits.push(e);const a=t.toApiKeys(),n=u+p,o=Date.now();try{await this._httpClient.postAsync(n,{headers:s,body:a,timeout:this.config.timeout,nextFetchConfig:this.config.nextFetchConfig}),Pt(this.config,lt,It,pt,{httpRequestBody:a,httpRequestHeaders:s,httpRequestMethod:"POST",httpRequestUrl:n,duration:Date.now()-o,batchTriggeredBy:Rt[i]});const r=t.hits.filter((t=>t.key!==e?.key)).map((t=>t.key));t.hits.forEach((t=>{this.onVisitorExposed(t)})),r.length&&await this.flushHits(r),this.sendHitsToFsQa(t.hits)}catch(r){t.hits.forEach((t=>{this._activatePoolQueue.set(t.key,t)})),e&&await this.cacheHit(new Map([[e.key,e]])),Ht(this.config,lt,ft,pt,{httpRequestBody:a,httpRequestHeaders:s,httpRequestMethod:"POST",httpRequestUrl:n,httpResponseBody:r?.message,httpResponseHeaders:r?.headers,httpResponseCode:r?.statusCode,duration:Date.now()-o,batchTriggeredBy:Rt[i]});const h=new ei({label:St.SEND_ACTIVATE_HIT_ROUTE_ERROR,logLevel:Tt.ERROR,visitorId:`${this._flagshipInstanceId}`,traffic:0,config:this.config,httpRequestBody:a,httpRequestHeaders:s,httpRequestMethod:"POST",httpRequestUrl:n,httpResponseBody:r?.message,httpResponseHeaders:r?.headers,httpResponseCode:r?.statusCode,httpResponseTime:Date.now()-o,batchTriggeredBy:i});this.sendTroubleshootingHit(h)}}async sendActivate({activateHitsPool:t,currentActivate:i,batchTriggeredBy:e}){const s=Array.from(t.filter((t=>Date.now()-t.createdAt<_)));if(s.length||!i)for(let t=0;t<s.length;t+=100){const a=new hi(s.slice(t,t+100),this.config);this.sendActivateHitBatch(a,e,0===t?i:void 0)}else{const t=new hi([],this.config);await this.sendActivateHitBatch(t,e,i)}}}class li extends di{async addHitInPoolQueue(t){this._hitsPoolQueue.set(t.key,t)}async sendActivate({activateHitsPool:t,currentActivate:i,batchTriggeredBy:e}){const s={[K]:this.config.apiKey,[Q]:g.name,[$]:g.version,[q]:z},a=new hi(Array.from(t.filter((t=>Date.now()-t.createdAt<_))),this.config);i&&a.hits.push(i);const n=a.toApiKeys(),o=u+p,r=Date.now();try{await this._httpClient.postAsync(o,{headers:s,body:n,timeout:this.config.timeout,nextFetchConfig:this.config.nextFetchConfig}),Pt(this.config,lt,It,pt,{httpRequestBody:n,httpRequestHeaders:s,httpRequestMethod:"POST",httpRequestUrl:o,duration:Date.now()-r,batchTriggeredBy:Rt[e]}),a.hits.forEach((t=>{this.onVisitorExposed(t)})),this.sendHitsToFsQa(a.hits)}catch(t){a.hits.forEach((t=>{this._activatePoolQueue.set(t.key,t)})),Ht(this.config,lt,ft,pt,{httpRequestBody:n,httpRequestHeaders:s,httpRequestMethod:"POST",httpRequestUrl:o,httpResponseBody:t?.message,httpResponseHeaders:t?.headers,httpResponseCode:t?.statusCode,duration:Date.now()-r,batchTriggeredBy:Rt[e]});const i=new ei({label:St.SEND_ACTIVATE_HIT_ROUTE_ERROR,logLevel:Tt.ERROR,visitorId:`${this._flagshipInstanceId}`,traffic:0,config:this.config,httpRequestBody:n,httpRequestHeaders:s,httpRequestMethod:"POST",httpRequestUrl:o,httpResponseBody:t?.message,httpResponseHeaders:t?.headers,httpResponseCode:t?.statusCode,httpResponseTime:Date.now()-r,batchTriggeredBy:e});this.sendTroubleshootingHit(i)}}async sendBatch(t=Rt.BatchLength){let i=!1