@kameleoon/javascript-sdk-core 5.10.0 → 5.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Change Log
|
|
2
2
|
|
|
3
|
+
## 5.10.1 (2025-06-26)
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Fixed a potential error: `Cannot read property 'createCondition' of undefined`, which could occur due to differences in how various JavaScript bundlers or module loaders handle dependency initialization timing (for JS / React SDKs).
|
|
8
|
+
|
|
3
9
|
## 5.10.0 (2025-05-26)
|
|
4
10
|
|
|
5
11
|
### Features
|
package/dist/kameleoonClient.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.KameleoonClient=void 0;var _tsRes=require("ts-res"),_cacheManager=require("./cacheManager"),_clientConfiguration=require("./clientConfiguration"),_clientSettings=require("./clientSettings"),_constants=require("./constants"),_kameleoonData=require("./kameleoonData"),_kameleoonError=require("./kameleoonError"),_requester=require("./requester"),_storage=require("./storage"),_types=require("./types"),_utilities=require("./utilities"),_variationConfiguration=require("./variationConfiguration"),_eventSource=require("./eventSource"),_visitorCodeManager=require("./visitorCodeManager"),_eventManager=require("./eventManager"),_tracking=require("./tracking"),_logging=require("./logging"),_hasher=require("./hasher");function _defineProperty(a,b,c){return(b=_toPropertyKey(b))in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}function _toPropertyKey(a){var b=_toPrimitive(a,"string");return"symbol"==typeof b?b:b+""}function _toPrimitive(a,b){if("object"!=typeof a||!a)return a;var c=a[Symbol.toPrimitive];if(void 0!==c){var d=c.call(a,b||"default");if("object"!=typeof d)return d;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===b?String:Number)(a)}class KameleoonClient{constructor(a){var b;let{siteCode:c,dependencies:d,configuration:e,internalConfiguration:f,stubMode:g}=a;if(_defineProperty(this,"variationConfiguration",void 0),_defineProperty(this,"clientConfiguration",void 0),_defineProperty(this,"dataManager",void 0),_defineProperty(this,"consentDataStorage",void 0),_defineProperty(this,"trackingCache",void 0),_defineProperty(this,"requester",void 0),_defineProperty(this,"externalPackageInfo",void 0),_defineProperty(this,"initialized",!1),_defineProperty(this,"visitorCodeManager",void 0),_defineProperty(this,"eventManager",void 0),_defineProperty(this,"tracker",void 0),_defineProperty(this,"environment",void 0),_defineProperty(this,"stubMode",void 0),this.stubMode=g,g)return this.variationConfiguration={},this.clientConfiguration={},this.dataManager={},this.consentDataStorage={},this.trackingCache={},this.requester={},this.externalPackageInfo={},this.visitorCodeManager={},this.eventManager={},this.tracker={},void(this.environment="");const h=null===f||void 0===f?void 0:f.externals.externalLogger;h&&_logging.KameleoonLogger.setLogger(h),_logging.KameleoonLogger.debug`CALL: new KameleoonClient(siteCode: ${c}, dependencies: ${d}, configuration: ${e})`;const{settings:i}=new _clientSettings.ClientSettings(c,e);this.environment=i.environment;const{externalStorage:j,externalEventSource:k,externalPackageInfo:l,externalVisitorCodeManager:m,externalRequester:n,externalPRNG:o,customDataManager:p}=f.externals,{useAbortController:q}=f.settings,r=new _cacheManager.CacheManager(_constants.CACHE_CLEANUP_TIMEOUT),s=new _storage.DataStorage(j,_storage.KameleoonStorageKey.ClientData),t=new _storage.DataStorage(j,_storage.KameleoonStorageKey.VariationData),u=new _storage.DataStorage(j,_storage.KameleoonStorageKey.ForcedExperimentVariation),v=new _storage.DataStorage(j,_storage.KameleoonStorageKey.ForcedFeatureVariation),w=new _storage.DataStorage(j,_storage.KameleoonStorageKey.ConsentData),x=new _storage.DataStorage(j,_storage.KameleoonStorageKey.TrackingData);let y=p;if(!y){const a=new _storage.DataStorage(j,_storage.KameleoonStorageKey.TargetingData),b=new _storage.DataStorage(j,_storage.KameleoonStorageKey.DataInfo);y=new _kameleoonData.DataManager({dataStorage:a,infoStorage:b,cleanupInterval:i.cleanupInterval,packageInfo:l})}const z=null!==(b=null===d||void 0===d?void 0:d.urlProvider)&&void 0!==b?b:new _requester.UrlProvider;z.initialize({domain:i.networkDomain,siteCode:i.siteCode,packageInfo:l,environment:i.environment});const A=new _requester.Requester({urlProvider:z,useAbortController:q,packageInfo:l,externalRequester:n,requestTimeout:i.requestTimeout,trackRetryDelay:i.trackRetryDelay}),B=new _eventSource.KameleoonEventSource({siteCode:i.siteCode,externalEventSource:k,urlProvider:z}),C=new _eventManager.EventManager,D=new _clientConfiguration.ClientConfiguration({urlProvider:z,storage:s,updateInterval:i.updateInterval,dataManager:y,eventManager:C,requester:A,eventSource:B,externalVisitorCodeManager:m}),E=new _variationConfiguration.VariationConfiguration(t,u,v,m,D),F=new _tracking.Tracker({dataManager:y,trackingStorage:x,variationConfiguration:E,requester:A,trackingInterval:i.trackingInterval,prng:o});this.tracker=F,this.variationConfiguration=E,this.requester=A,this.trackingCache=r,this.dataManager=y,this.clientConfiguration=D,this.externalPackageInfo=l,this.consentDataStorage=w,this.visitorCodeManager=m,this.eventManager=C,null!==i.cleanupInterval&&new _storage.StorageCleanupManager(j,i.cleanupInterval),_logging.KameleoonLogger.debug`RETURN: new KameleoonClient(siteCode: ${c}, dependencies: ${d}, configuration: ${e})`}async initialize(){if(this.stubMode)return!1;_logging.KameleoonLogger.info("CALL: KameleoonClient.initialize()");const a=await this.clientConfiguration.initialize();return a.throw(),this.initialized=!0,_logging.KameleoonLogger.info`RETURN: KameleoonClient.initialize() -> (result: ${a.ok})`,a.ok}addData(a){if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);for(var b=arguments.length,c=Array(1<b?b-1:0),d=1;d<b;d++)c[d-1]=arguments[d];if(_logging.KameleoonLogger.info`CALL: KameleoonClient.addData(visitorCode: ${a}, data: ${c})`,this.visitorCodeManager.validateVisitorCode(a).throw(),!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);this.dataManager.storeData(a,...c).throw(),_logging.KameleoonLogger.info`RETURN: KameleoonClient.addData(visitorCode: ${a}, data: ${c})`}async getRemoteVisitorData(a){let{visitorCode:b,shouldAddData:c=!0,filters:d=_constants.DEFAULT_VISITOR_DATA_FILTERS}=a;if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);if(_logging.KameleoonLogger.info`CALL: KameleoonClient.getRemoteVisitorData(visitorCode: ${b}, shouldAddData: ${c}, filters: ${d})`,!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);this.visitorCodeManager.validateVisitorCode(b).throw();const{previousVisitAmount:e}=d;if("number"==typeof e&&(1>e||25<e))throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.VisitAmount);const f=this.dataManager.isUniqueIdentifier(b),g=await this.requester.getVisitorData({visitorCode:b,filters:d,isMappingIdentifier:f}),h=g.throw(),{visitorData:i,storageVisitorData:j,visitsData:k,mappingIdentifier:l}=_utilities.Parser.parseVisitorData({data:h,filters:d,visitorCode:b,dataManager:this.dataManager,variationConfiguration:this.variationConfiguration});for(const d of j)(c||this.dataManager.isPersistentCustomData(d))&&this.addData(b,d);return k&&c&&this.addData(b,k),null!==d&&void 0!==d&&d.visitorCode&&l&&this.dataManager.setMappingIdentifier(b,l),_logging.KameleoonLogger.info`RETURN: KameleoonClient.getRemoteVisitorData(visitorCode: ${b}, shouldAddData: ${c}, filters: ${d}) -> (visitorData: ${i})`,i}trackConversion(a){let{visitorCode:b,goalId:c,negative:d,revenue:e,metadata:f}=a;this.stubMode||(_logging.KameleoonLogger.info`CALL: KameleoonClient.trackConversion(visitorCode: ${b}, goalId: ${c}, negative: ${d}, revenue: ${e}, metadata: ${f})`,this.addData(b,new _kameleoonData.Conversion({goalId:c,revenue:e,negative:d,metadata:f})),this.flush(b),_logging.KameleoonLogger.info`RETURN: KameleoonClient.trackConversion(visitorCode: ${b}, goalId: ${c}, negative: ${d}, revenue: ${e}, metadata: ${f})`)}flush(a){if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);if(_logging.KameleoonLogger.info`CALL: KameleoonClient.flush(visitorCode: ${a})`,!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);if("string"==typeof a)return this.visitorCodeManager.validateVisitorCode(a).throw(),this.tracker.scheduleVisitor(a,this._isConsentProvided(a)),void _logging.KameleoonLogger.info`RETURN: KameleoonClient.flush(visitorCode: ${a})`;for(const b of this.dataManager.unsentDataVisitors)this.tracker.scheduleVisitor(b,this._isConsentProvided(b));_logging.KameleoonLogger.info`RETURN: KameleoonClient.flush(visitorCode: ${a})`}getFeatureFlags(){if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);if(_logging.KameleoonLogger.info("CALL: KameleoonClient.getFeatureFlags()"),!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);const a=this.clientConfiguration.featureFlags,b=[];return a.forEach(a=>{let{id:c,featureKey:d}=a;b.push({id:c,key:d})}),_logging.KameleoonLogger.info`RETURN: KameleoonClient.getFeatureFlags() -> (FeatureFlags: ${b})`,b}getVisitorFeatureFlags(a){if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);if(_logging.KameleoonLogger.info`CALL: KameleoonClient.getVisitorFeatureFlags(visitorCode: ${a})`,!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);this.visitorCodeManager.validateVisitorCode(a).throw();const b=this._getActiveFeatureVariations(a),c=[];return b.forEach(a=>{let{featureFlagId:b,featureKey:d}=a;c.push({id:b,key:d})}),_logging.KameleoonLogger.info`RETURN: KameleoonClient.getVisitorFeatureFlags(visitorCode: ${a}) -> (FeatureFlags: ${c})`,c}getVariation(a){let{visitorCode:b,featureKey:c,track:d=!0}=a;if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);_logging.KameleoonLogger.info`CALL: KameleoonClient.getVariation(visitorCode: ${b}, featureKey: ${c}, track: ${d})`,this.visitorCodeManager.validateVisitorCode(b).throw();const e=this._getFeatureVariation({visitorCode:b,featureKey:c,track:d}).throw();return _logging.KameleoonLogger.info`RETURN: KameleoonClient.getVariation(visitorCode: ${b}, featureKey: ${c}, track: ${d}) -> (variation: ${e})`,e}getVariations(a){let{visitorCode:b,onlyActive:c=!1,track:d=!0}=a;if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);_logging.KameleoonLogger.info`CALL: KameleoonClient.getVariations(visitorCode: ${b}, onlyActive: ${c}, track: ${d})`,this.visitorCodeManager.validateVisitorCode(b).throw();const e=new Map,f=this.clientConfiguration.featureFlags;for(const g of f.values()){const a=this._getFeatureVariation({visitorCode:b,featureKey:g.featureKey,track:d});a.ok&&(!c||a.data.key!==_constants.OFF_VARIATION_KEY)&&e.set(g.featureKey,a.data)}return _logging.KameleoonLogger.info`RETURN: KameleoonClient.getVariations(visitorCode: ${b}, onlyActive: ${c}, track: ${d}) -> (variations: ${e})`,e}getActiveFeatureFlags(a){if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);if(_logging.KameleoonLogger.info`CALL: KameleoonClient.getActiveFeatureFlags(visitorCode: ${a})`,!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);this.visitorCodeManager.validateVisitorCode(a).throw();const b=this._getActiveFeatureVariations(a),c=new Map;return b.forEach(b=>{const{variationKey:d,featureKey:e,variationId:f,experimentId:g}=b;let h=[];null!==f&&null!==g&&(h=this._getFeatureVariables({visitorCode:a,featureKey:e,variationKey:d}));const i=h.map(a=>_utilities.Parser.parseFeatureVariable(a).throw());c.set(b.featureKey,{key:d,id:f,experimentId:g,variables:i})}),_logging.KameleoonLogger.info`RETURN: KameleoonClient.getActiveFeatureFlags(visitorCode: ${a}) -> (FeatureFlags: ${c})`,c}getFeatureFlagVariationKey(a,b){if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);_logging.KameleoonLogger.info`CALL: KameleoonClient.getFeatureFlagVariationKey(visitorCode: ${a}, featureKey: ${b})`,this.visitorCodeManager.validateVisitorCode(a).throw();const{key:c}=this._getFeatureVariation({visitorCode:a,featureKey:b,track:!0}).throw();return _logging.KameleoonLogger.info`RETURN: KameleoonClient.getFeatureFlagVariationKey(visitorCode: ${a}, featureKey: ${b}) -> (variationKey: ${c})`,c}getFeatureFlagVariable(a){let{visitorCode:b,featureKey:c,variableKey:d}=a;if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);_logging.KameleoonLogger.info`CALL: KameleoonClient.getFeatureFlagVariable(visitorCode: ${b}, featureKey: ${c}, variableKey: ${d})`,this.visitorCodeManager.validateVisitorCode(b).throw();const{key:e}=this._getFeatureVariation({visitorCode:b,featureKey:c,track:!0}).throw(),f=this._getFeatureVariables({visitorCode:b,featureKey:c,variationKey:e}),g=f.find(a=>a.key===d);if(!g)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagVariableNotFound,d,b);const{type:h,value:i}=_utilities.Parser.parseFeatureVariable(g).throw(),j={type:h,value:i};return _logging.KameleoonLogger.info`RETURN: KameleoonClient.getFeatureFlagVariable(visitorCode: ${b}, featureKey: ${c}, variableKey: ${d}) -> (FeatureFlagVariable: ${j})`,j}getFeatureFlagVariables(a,b){if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);_logging.KameleoonLogger.info`CALL: KameleoonClient.getFeatureFlagVariables(visitorCode: ${a}, featureKey: ${b})`,this.visitorCodeManager.validateVisitorCode(a).throw();const{key:c}=this._getFeatureVariation({visitorCode:a,featureKey:b,track:!0}).throw(),d=this._getFeatureVariables({visitorCode:a,featureKey:b,variationKey:c}),e=[];for(const c of d){const a=_utilities.Parser.parseFeatureVariable(c).throw();e.push(a)}return _logging.KameleoonLogger.info`RETURN: KameleoonClient.getFeatureFlagVariables(visitorCode: ${a}, featureKey: ${b}) -> (FeatureFlagVariables: ${e})`,e}isFeatureFlagActive(a,b){if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);let[c,d,e]=["","",!0];"string"==typeof a?(c=a,d=b):([c,d]=[a.visitorCode,a.featureKey],a.track!==void 0&&(e=a.track)),_logging.KameleoonLogger.info`CALL: KameleoonClient.isFeatureFlagActive(visitorCode: ${c}, featureKey: ${d}, track ${e})`,this.visitorCodeManager.validateVisitorCode(c).throw();try{const{key:a}=this._getFeatureVariation({visitorCode:c,featureKey:d,track:e}).throw(),b=a!==_constants.OFF_VARIATION_KEY;return _logging.KameleoonLogger.info`RETURN: KameleoonClient.isFeatureFlagActive(visitorCode: ${c}, featureKey: ${d}, track: ${e}) -> (isActive: ${b})`,b}catch(a){if(a instanceof _kameleoonError.KameleoonError&&a.type===_kameleoonError.KameleoonException.FeatureFlagEnvironmentDisabled)return _logging.KameleoonLogger.info`RETURN: KameleoonClient.isFeatureFlagActive(visitorCode: ${c}, featureKey: ${d}, track: ${e}) -> (isActive: false)`,!1;throw a}}async getRemoteData(a){if(this.stubMode)return null;_logging.KameleoonLogger.info`CALL: KameleoonClient.getRemoteData(key: ${a})`;const b=await this.requester.getRemoteData(a);return _logging.KameleoonLogger.info`RETURN: KameleoonClient.getRemoteData(key: ${a}) -> (remoteData: ${b})`,b.throw()}async getVisitorWarehouseAudience(a){let{visitorCode:b,customDataIndex:c,warehouseKey:d}=a;if(this.stubMode)return null;_logging.KameleoonLogger.info`CALL: KameleoonClient.getVisitorWarehouseAudience(visitorCode: ${b}, customDataIndex: ${c}, warehouseKey: ${d})`,this.visitorCodeManager.validateVisitorCode(b).throw();const e=await this.getRemoteData(d||b);if(!e)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,`No data found for ${d||b} key`);if(!e[_constants.WAREHOUSE_AUDIENCE_KEY]||0===Object.keys(e[_constants.WAREHOUSE_AUDIENCE_KEY]).length)return _logging.KameleoonLogger.info`RETURN: KameleoonClient.getVisitorWarehouseAudience(visitorCode: ${b}, customDataIndex: ${c}, warehouseKey: ${d}) -> (customData: null)`,null;const f=new _kameleoonData.CustomData(c,...Object.keys(e[_constants.WAREHOUSE_AUDIENCE_KEY]));return this.dataManager.storeData(b,f),_logging.KameleoonLogger.info`RETURN: KameleoonClient.getVisitorWarehouseAudience(visitorCode: ${b}, customDataIndex: ${c}, warehouseKey: ${d}) -> (customData: ${f})`,f}onEvent(a,b){if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);if(_logging.KameleoonLogger.info`CALL: KameleoonClient.onEvent(event: ${a}, callback)`,!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);this.eventManager.addEventHandler(a,b),_logging.KameleoonLogger.info`RETURN: KameleoonClient.onEvent(event: ${a}, callback)`}getEngineTrackingCode(a){if(this.stubMode)return"";_logging.KameleoonLogger.info`CALL: KameleoonClient.getEngineTrackingCode(visitorCode: ${a})`,this.visitorCodeManager.validateVisitorCode(a).throw();const b=_utilities.Utilities.getTrackingCode(this.trackingCache,a);return _logging.KameleoonLogger.info`RETURN: KameleoonClient.getEngineTrackingCode(visitorCode: ${a}) -> (trackingCode: ${b})`,b}isInitialized(){return _logging.KameleoonLogger.debug`CALL/RETURN: KameleoonClient.isInitialized() -> (initialized: ${this.initialized})`,this.initialized}setLogLevel(a){_logging.KameleoonLogger.setLogLevel(a)}setForcedVariation(a){let{visitorCode:b,experimentId:c,variationKey:d,forceTargeting:e=!0}=a;this.stubMode||(_logging.KameleoonLogger.info`CALL: KameleoonClient.setForcedVariation(visitorCode: '${b}', experimentId: ${c}, variationKey: '${d}', forceTargeting: ${e})`,this.visitorCodeManager.validateVisitorCode(b).throw(),this._setForcedVariation({visitorCode:b,experimentId:c,variationKey:d,forceTargeting:e}).throw(),_logging.KameleoonLogger.info`RETURN: KameleoonClient.setForcedVariation(visitorCode: '${b}', experimentId: ${c}, variationKey: '${d}', forceTargeting: ${e})`)}setUserConsent(a){let{visitorCode:b,consent:c,setData:d}=a;this.stubMode||(_logging.KameleoonLogger.info`CALL: KameleoonClient.setUserConsent(visitorCode: ${b}, consent: ${c}, setData: ${d})`,this.visitorCodeManager.validateVisitorCode(b).throw(),this.updateConsentData(b,c),c?d({visitorCode:b,key:_storage.KameleoonStorageKey.VisitorCode,maxAge:_visitorCodeManager.DEFAULT_MAX_AGE,path:_visitorCodeManager.PATH}):this.visitorCodeManager.consentRequired&&d({visitorCode:"",key:_storage.KameleoonStorageKey.VisitorCode,maxAge:_visitorCodeManager.ZERO_MAX_AGE,path:_visitorCodeManager.PATH}),_logging.KameleoonLogger.info`RETURN: KameleoonClient.setUserConsent(visitorCode: ${b}, consent: ${c}, setData: ${d})`)}updateConsentData(a,b){const c=this.consentDataStorage.read();if(!c.ok)return void(c.error.type===_kameleoonError.KameleoonException.StorageEmpty&&this.consentDataStorage.write({[a]:{consent:b}}));const d=c.data;d[a]={consent:b},this.consentDataStorage.write(d)}_isConsentProvided(a){_logging.KameleoonLogger.debug`CALL: KameleoonClient._isConsentProvided(visitorCode: ${a})`;const{isConsentRequired:b}=this.clientConfiguration,c=this.consentDataStorage.read();let d=!1;if(!b)d=!0;else if(c.ok){const b=c.data[a];d="boolean"==typeof b?b:b&&b.consent}return _logging.KameleoonLogger.debug`RETURN: KameleoonClient._isConsentProvided(visitorCode: ${a}) -> (isConsentProvided: ${d})`,d}_getFeatureVariables(a){let{visitorCode:b,featureKey:c,variationKey:d}=a;_logging.KameleoonLogger.debug`CALL: KameleoonClient._getFeatureVariables(visitorCode: ${b}, featureKey: ${c}, variationKey: ${d})`;const e=this.clientConfiguration.featureFlags,f=e.get(c);if(!f)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagConfigurationNotFound,c);const g=f.variations.find(a=>a.key===d);if(!g)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagVariationNotFound,d,b);return _logging.KameleoonLogger.debug`RETURN: KameleoonClient._getFeatureVariables(visitorCode: ${b}, featureKey: ${c}, variationKey: ${d}) -> (variables: ${g.variables})`,g.variables}_getActiveFeatureVariations(a){_logging.KameleoonLogger.debug`CALL: KameleoonClient._getActiveFeatureVariations(visitorCode: ${a})`;const b=this.clientConfiguration.featureFlags,c=[];for(const d of b.values()){if(!d.environmentEnabled)continue;const b=this._evaluate({visitorCode:a,featureFlag:d,track:!1,save:!1});b.variationKey!==_constants.OFF_VARIATION_KEY&&c.push({variationKey:b.variationKey,variationId:b.variationId,experimentId:b.experimentId,featureFlagId:d.id,featureKey:d.featureKey,rule:null,isTargetedRule:b.ruleType===_clientConfiguration.RuleType.TARGETED_DELIVERY})}return _logging.KameleoonLogger.debug`RETURN: KameleoonClient._getActiveFeatureVariations(visitorCode: ${a}) -> (activeVariations: ${c})`,c}_evaluate(a){let{visitorCode:b,featureFlag:c,track:d,save:e}=a;_logging.KameleoonLogger.debug`CALL: KameleoonClient._evaluate(visitorCode: ${b}, featureFlag: ${c}, track: ${d}, save: ${e})`;let f,g=null;const h=this.variationConfiguration.getForcedFeatureVariation(b,c.featureKey);if(h.ok&&(g=h.data),g)f=KameleoonClient.EvaluatedExperiment.fromForcedFeatureVariation(c.defaultVariationKey,g);else if(this._isVisitorNotInHoldout(b,d,e)&&this._isFFUnrestrictedByMEGroup(b,c)){const a=this.dataManager.getVisitorData(b),g=this.dataManager.getVisitorIdentifier(b),h=this.variationConfiguration.getVariation({visitorCode:b,visitorIdentifier:g,featureFlag:c,track:d,withAssignment:e,targetingData:a,clientConfiguration:this.clientConfiguration,dataManager:this.dataManager,packageInfo:this.externalPackageInfo}).throw();f=KameleoonClient.EvaluatedExperiment.fromVariationData(h)}else f=KameleoonClient.EvaluatedExperiment.fromDefaultVariationKey(c.defaultVariationKey);return e&&!f.isSimulated&&null!==f.experimentId&&null!==f.variationId&&this.variationConfiguration.updateStoredVariations(b,{[f.experimentId]:{variationId:f.variationId,isTargetedRule:f.ruleType===_clientConfiguration.RuleType.TARGETED_DELIVERY,status:d?_types.TrackingStatus.Unsent:_types.TrackingStatus.Sent}}),this.eventManager.fireEvent(_eventManager.EventType.Evaluation,{featureKey:c.featureKey,variation:{key:f.variationKey,experimentId:f.experimentId,id:f.variationId}}),_logging.KameleoonLogger.debug`RETURN: KameleoonClient._evaluate(visitorCode: ${b}, featureFlag: ${c}, track: ${d}, save: ${e}) -> (evalExp: ${f})`,f}_isFFUnrestrictedByMEGroup(a,b){const c=b.mutuallyExclusiveGroup;if(!c)return!0;_logging.KameleoonLogger.debug`CALL: KameleoonClient._isFFUnrestrictedByMEGroup(visitorCode: ${a}, featureFlag: ${b})`;let d=!0;const e=this.clientConfiguration.meGroups.get(c);if(e){const f=this.dataManager.getVisitorIdentifier(a),g=_hasher.Hasher.getHashDoubleForMEGroup(f,c);_logging.KameleoonLogger.debug`Calculated meGroup hash ${g} for code: '${f}', meGroup: '${c}'`,d=e.getFeatureFlagByHash(g)===b}return _logging.KameleoonLogger.debug`RETURN: KameleoonClient._isFFUnrestrictedByMEGroup(visitorCode: '${a}', featureFlag: ${b}) -> (selected: ${d})`,d}_getFeatureVariation(a){let{visitorCode:b,featureKey:c,track:d}=a;if(_logging.KameleoonLogger.debug`CALL: KameleoonClient._getFeatureVariation(visitorCode: ${b}, featureKey: ${c}, track: ${d})`,!this.initialized)return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization));const e=this.clientConfiguration.featureFlags,f=e.get(c);if(!f)return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagConfigurationNotFound,c));if(!f.environmentEnabled)return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagEnvironmentDisabled,f.featureKey,this.environment));const g=this._evaluate({visitorCode:b,featureFlag:f,track:d,save:!0}),{experimentId:h,variationId:i,variationKey:j,isSimulated:k}=g;let l=new Map,m=!1;try{const a=this._getFeatureVariables({visitorCode:b,featureKey:c,variationKey:j});a.forEach(a=>{m||a.type!==_types.VariableType.JS&&a.type!==_types.VariableType.CSS||(m=!0);const b=_utilities.Parser.parseFeatureVariable(a).throw();l.set(a.key,b)})}catch(_){}h&&"number"==typeof i&&!k&&_utilities.Utilities.updateCache({cacheManager:this.trackingCache,hasJsCssVariables:m,visitorCode:b,experimentId:h,variationId:i}),d&&!k&&this.tracker.scheduleVisitor(b,this._isConsentProvided(b));const n={key:j,id:i,experimentId:h,variables:l};return _logging.KameleoonLogger.debug`RETURN: KameleoonClient._getFeatureVariation(visitorCode: ${b}, featureKey: ${c}, track: ${d}) -> (variation: ${n})`,(0,_tsRes.Ok)(n)}_isVisitorNotInHoldout(a,b,c){const d=this.clientConfiguration.holdout;if(!d)return!0;_logging.KameleoonLogger.debug`CALL: KameleoonClient._isVisitorNotInHoldout(visitorCode: ${a}, track: ${b}, save: ${c})`;let e=!0;const f=this.dataManager.getVisitorIdentifier(a),g=_hasher.Hasher.getHashDouble({visitorIdentifier:f,respoolTime:null,id:d.experimentId+""});_logging.KameleoonLogger.debug`Calculated holdoutHash: ${g} for visitorCode: ${f}`;let h=_utilities.Utilities.getVariationByHash(d.variationByExposition,g);return null!==h&&(e=h.variationKey!==_constants.IN_HOLDOUT_VARIATION_KEY,c&&this.variationConfiguration.updateStoredVariations(a,{[d.experimentId]:{variationId:h.variationId,isTargetedRule:!1,status:b?_types.TrackingStatus.Unsent:_types.TrackingStatus.Sent}})),_logging.KameleoonLogger.debug`RETURN: KameleoonClient._isVisitorNotInHoldout(visitorCode: ${a}, track: ${b}, save: ${c}) -> (isNotInHoldout: ${e})`,e}_setForcedVariation(a){let{visitorCode:b,experimentId:c,variationKey:d,forceTargeting:e=!0}=a;if(_logging.KameleoonLogger.debug`CALL: KameleoonClient._setForcedVariation(visitorCode: '${b}', experimentId: ${c}, variationKey: '${d}', forceTargeting: ${e})`,null===d){const a=this.variationConfiguration.updateForcedExperimentVariation(b,c,null);return _logging.KameleoonLogger.debug`RETURN: KameleoonClient._setForcedVariation(visitorCode: '${b}', experimentId: ${c}, variationKey: '${d}', forceTargeting: ${e}) -> (writeResult: ${a})`,a}let f=null,g=null;if(f=this.clientConfiguration.experimentMap.get(c),!f)return _logging.KameleoonLogger.error`Experiment with id ${c} not found for visitor ${b}`,(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagExperimentNotFound,c,b));if(g=f.variations.get(d),void 0===g)return _logging.KameleoonLogger.error`Variation with key ${d} not found in experiment ${f} for visitor ${b}`,(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagVariationNotFound,d,b));f={type:f.type,experimentId:c},g={variationKey:d,variationId:g};const h=this.variationConfiguration.updateForcedExperimentVariation(b,c,{rule:f,varByExp:g,forceTargeting:e});return _logging.KameleoonLogger.debug`RETURN: KameleoonClient._setForcedVariation(visitorCode: '${b}', experimentId: ${c}, variationKey: '${d}', forceTargeting: ${e}) -> (writeResult: ${h})`,h}}exports.KameleoonClient=KameleoonClient,_defineProperty(KameleoonClient,"EvaluatedExperiment",class{static fromForcedFeatureVariation(a,b){var c,d,e;let f=a;return b.varByExp?f=b.varByExp.variationKey:b.rule&&b.rule.type===_clientConfiguration.RuleType.EXPERIMENTATION&&(f=_constants.OFF_VARIATION_KEY),{variationKey:f,variationId:(null===(c=b.varByExp)||void 0===c?void 0:c.variationId)||null,experimentId:(null===(d=b.rule)||void 0===d?void 0:d.experimentId)||null,ruleType:(null===(e=b.rule)||void 0===e?void 0:e.type)||null,isSimulated:b.simulated}}static fromVariationData(a){var b,c;return{variationKey:a.variationKey,variationId:a.variationId,experimentId:a.experimentId,ruleType:null!==(b=null===(c=a.rule)||void 0===c?void 0:c.type)&&void 0!==b?b:null,isSimulated:!1}}static fromDefaultVariationKey(a){return{variationKey:a,variationId:null,experimentId:null,ruleType:null,isSimulated:!1}}});
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.KameleoonClient=void 0;var _tsRes=require("ts-res"),_cacheManager=require("./cacheManager"),_clientConfiguration=require("./clientConfiguration"),_clientSettings=require("./clientSettings"),_constants=require("./constants"),_kameleoonData=require("./kameleoonData"),_kameleoonError=require("./kameleoonError"),_requester=require("./requester"),_storage=require("./storage"),_types=require("./types"),_utilities=require("./utilities"),_variationConfiguration=require("./variationConfiguration"),_targeting=require("./targeting"),_eventSource=require("./eventSource"),_visitorCodeManager=require("./visitorCodeManager"),_eventManager=require("./eventManager"),_tracking=require("./tracking"),_logging=require("./logging"),_hasher=require("./hasher"),_conditionFactoryInstance=require("./targeting/conditions/conditionFactoryInstance");function _defineProperty(a,b,c){return(b=_toPropertyKey(b))in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}function _toPropertyKey(a){var b=_toPrimitive(a,"string");return"symbol"==typeof b?b:b+""}function _toPrimitive(a,b){if("object"!=typeof a||!a)return a;var c=a[Symbol.toPrimitive];if(void 0!==c){var d=c.call(a,b||"default");if("object"!=typeof d)return d;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===b?String:Number)(a)}class KameleoonClient{constructor(a){var b;let{siteCode:c,dependencies:d,configuration:e,internalConfiguration:f,stubMode:g}=a;if(_defineProperty(this,"variationConfiguration",void 0),_defineProperty(this,"clientConfiguration",void 0),_defineProperty(this,"dataManager",void 0),_defineProperty(this,"consentDataStorage",void 0),_defineProperty(this,"trackingCache",void 0),_defineProperty(this,"requester",void 0),_defineProperty(this,"externalPackageInfo",void 0),_defineProperty(this,"initialized",!1),_defineProperty(this,"visitorCodeManager",void 0),_defineProperty(this,"eventManager",void 0),_defineProperty(this,"tracker",void 0),_defineProperty(this,"environment",void 0),_defineProperty(this,"stubMode",void 0),this.stubMode=g,g)return this.variationConfiguration={},this.clientConfiguration={},this.dataManager={},this.consentDataStorage={},this.trackingCache={},this.requester={},this.externalPackageInfo={},this.visitorCodeManager={},this.eventManager={},this.tracker={},void(this.environment="");const h=null===f||void 0===f?void 0:f.externals.externalLogger;h&&_logging.KameleoonLogger.setLogger(h),_conditionFactoryInstance.ConditionFactoryInstance.setConditionFactoryInstance(new _targeting.ConditionFactory),_logging.KameleoonLogger.debug`CALL: new KameleoonClient(siteCode: ${c}, dependencies: ${d}, configuration: ${e})`;const{settings:i}=new _clientSettings.ClientSettings(c,e);this.environment=i.environment;const{externalStorage:j,externalEventSource:k,externalPackageInfo:l,externalVisitorCodeManager:m,externalRequester:n,externalPRNG:o,customDataManager:p}=f.externals,{useAbortController:q}=f.settings,r=new _cacheManager.CacheManager(_constants.CACHE_CLEANUP_TIMEOUT),s=new _storage.DataStorage(j,_storage.KameleoonStorageKey.ClientData),t=new _storage.DataStorage(j,_storage.KameleoonStorageKey.VariationData),u=new _storage.DataStorage(j,_storage.KameleoonStorageKey.ForcedExperimentVariation),v=new _storage.DataStorage(j,_storage.KameleoonStorageKey.ForcedFeatureVariation),w=new _storage.DataStorage(j,_storage.KameleoonStorageKey.ConsentData),x=new _storage.DataStorage(j,_storage.KameleoonStorageKey.TrackingData);let y=p;if(!y){const a=new _storage.DataStorage(j,_storage.KameleoonStorageKey.TargetingData),b=new _storage.DataStorage(j,_storage.KameleoonStorageKey.DataInfo);y=new _kameleoonData.DataManager({dataStorage:a,infoStorage:b,cleanupInterval:i.cleanupInterval,packageInfo:l})}const z=null!==(b=null===d||void 0===d?void 0:d.urlProvider)&&void 0!==b?b:new _requester.UrlProvider;z.initialize({domain:i.networkDomain,siteCode:i.siteCode,packageInfo:l,environment:i.environment});const A=new _requester.Requester({urlProvider:z,useAbortController:q,packageInfo:l,externalRequester:n,requestTimeout:i.requestTimeout,trackRetryDelay:i.trackRetryDelay}),B=new _eventSource.KameleoonEventSource({siteCode:i.siteCode,externalEventSource:k,urlProvider:z}),C=new _eventManager.EventManager,D=new _clientConfiguration.ClientConfiguration({urlProvider:z,storage:s,updateInterval:i.updateInterval,dataManager:y,eventManager:C,requester:A,eventSource:B,externalVisitorCodeManager:m}),E=new _variationConfiguration.VariationConfiguration(t,u,v,m,D),F=new _tracking.Tracker({dataManager:y,trackingStorage:x,variationConfiguration:E,requester:A,trackingInterval:i.trackingInterval,prng:o});this.tracker=F,this.variationConfiguration=E,this.requester=A,this.trackingCache=r,this.dataManager=y,this.clientConfiguration=D,this.externalPackageInfo=l,this.consentDataStorage=w,this.visitorCodeManager=m,this.eventManager=C,null!==i.cleanupInterval&&new _storage.StorageCleanupManager(j,i.cleanupInterval),_logging.KameleoonLogger.debug`RETURN: new KameleoonClient(siteCode: ${c}, dependencies: ${d}, configuration: ${e})`}async initialize(){if(this.stubMode)return!1;_logging.KameleoonLogger.info("CALL: KameleoonClient.initialize()");const a=await this.clientConfiguration.initialize();return a.throw(),this.initialized=!0,_logging.KameleoonLogger.info`RETURN: KameleoonClient.initialize() -> (result: ${a.ok})`,a.ok}addData(a){if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);for(var b=arguments.length,c=Array(1<b?b-1:0),d=1;d<b;d++)c[d-1]=arguments[d];if(_logging.KameleoonLogger.info`CALL: KameleoonClient.addData(visitorCode: ${a}, data: ${c})`,this.visitorCodeManager.validateVisitorCode(a).throw(),!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);this.dataManager.storeData(a,...c).throw(),_logging.KameleoonLogger.info`RETURN: KameleoonClient.addData(visitorCode: ${a}, data: ${c})`}async getRemoteVisitorData(a){let{visitorCode:b,shouldAddData:c=!0,filters:d=_constants.DEFAULT_VISITOR_DATA_FILTERS}=a;if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);if(_logging.KameleoonLogger.info`CALL: KameleoonClient.getRemoteVisitorData(visitorCode: ${b}, shouldAddData: ${c}, filters: ${d})`,!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);this.visitorCodeManager.validateVisitorCode(b).throw();const{previousVisitAmount:e}=d;if("number"==typeof e&&(1>e||25<e))throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.VisitAmount);const f=this.dataManager.isUniqueIdentifier(b),g=await this.requester.getVisitorData({visitorCode:b,filters:d,isMappingIdentifier:f}),h=g.throw(),{visitorData:i,storageVisitorData:j,visitsData:k,mappingIdentifier:l}=_utilities.Parser.parseVisitorData({data:h,filters:d,visitorCode:b,dataManager:this.dataManager,variationConfiguration:this.variationConfiguration});for(const d of j)(c||this.dataManager.isPersistentCustomData(d))&&this.addData(b,d);return k&&c&&this.addData(b,k),null!==d&&void 0!==d&&d.visitorCode&&l&&this.dataManager.setMappingIdentifier(b,l),_logging.KameleoonLogger.info`RETURN: KameleoonClient.getRemoteVisitorData(visitorCode: ${b}, shouldAddData: ${c}, filters: ${d}) -> (visitorData: ${i})`,i}trackConversion(a){let{visitorCode:b,goalId:c,negative:d,revenue:e,metadata:f}=a;this.stubMode||(_logging.KameleoonLogger.info`CALL: KameleoonClient.trackConversion(visitorCode: ${b}, goalId: ${c}, negative: ${d}, revenue: ${e}, metadata: ${f})`,this.addData(b,new _kameleoonData.Conversion({goalId:c,revenue:e,negative:d,metadata:f})),this.flush(b),_logging.KameleoonLogger.info`RETURN: KameleoonClient.trackConversion(visitorCode: ${b}, goalId: ${c}, negative: ${d}, revenue: ${e}, metadata: ${f})`)}flush(a){if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);if(_logging.KameleoonLogger.info`CALL: KameleoonClient.flush(visitorCode: ${a})`,!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);if("string"==typeof a)return this.visitorCodeManager.validateVisitorCode(a).throw(),this.tracker.scheduleVisitor(a,this._isConsentProvided(a)),void _logging.KameleoonLogger.info`RETURN: KameleoonClient.flush(visitorCode: ${a})`;for(const b of this.dataManager.unsentDataVisitors)this.tracker.scheduleVisitor(b,this._isConsentProvided(b));_logging.KameleoonLogger.info`RETURN: KameleoonClient.flush(visitorCode: ${a})`}getFeatureFlags(){if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);if(_logging.KameleoonLogger.info("CALL: KameleoonClient.getFeatureFlags()"),!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);const a=this.clientConfiguration.featureFlags,b=[];return a.forEach(a=>{let{id:c,featureKey:d}=a;b.push({id:c,key:d})}),_logging.KameleoonLogger.info`RETURN: KameleoonClient.getFeatureFlags() -> (FeatureFlags: ${b})`,b}getVisitorFeatureFlags(a){if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);if(_logging.KameleoonLogger.info`CALL: KameleoonClient.getVisitorFeatureFlags(visitorCode: ${a})`,!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);this.visitorCodeManager.validateVisitorCode(a).throw();const b=this._getActiveFeatureVariations(a),c=[];return b.forEach(a=>{let{featureFlagId:b,featureKey:d}=a;c.push({id:b,key:d})}),_logging.KameleoonLogger.info`RETURN: KameleoonClient.getVisitorFeatureFlags(visitorCode: ${a}) -> (FeatureFlags: ${c})`,c}getVariation(a){let{visitorCode:b,featureKey:c,track:d=!0}=a;if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);_logging.KameleoonLogger.info`CALL: KameleoonClient.getVariation(visitorCode: ${b}, featureKey: ${c}, track: ${d})`,this.visitorCodeManager.validateVisitorCode(b).throw();const e=this._getFeatureVariation({visitorCode:b,featureKey:c,track:d}).throw();return _logging.KameleoonLogger.info`RETURN: KameleoonClient.getVariation(visitorCode: ${b}, featureKey: ${c}, track: ${d}) -> (variation: ${e})`,e}getVariations(a){let{visitorCode:b,onlyActive:c=!1,track:d=!0}=a;if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);_logging.KameleoonLogger.info`CALL: KameleoonClient.getVariations(visitorCode: ${b}, onlyActive: ${c}, track: ${d})`,this.visitorCodeManager.validateVisitorCode(b).throw();const e=new Map,f=this.clientConfiguration.featureFlags;for(const g of f.values()){const a=this._getFeatureVariation({visitorCode:b,featureKey:g.featureKey,track:d});a.ok&&(!c||a.data.key!==_constants.OFF_VARIATION_KEY)&&e.set(g.featureKey,a.data)}return _logging.KameleoonLogger.info`RETURN: KameleoonClient.getVariations(visitorCode: ${b}, onlyActive: ${c}, track: ${d}) -> (variations: ${e})`,e}getActiveFeatureFlags(a){if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);if(_logging.KameleoonLogger.info`CALL: KameleoonClient.getActiveFeatureFlags(visitorCode: ${a})`,!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);this.visitorCodeManager.validateVisitorCode(a).throw();const b=this._getActiveFeatureVariations(a),c=new Map;return b.forEach(b=>{const{variationKey:d,featureKey:e,variationId:f,experimentId:g}=b;let h=[];null!==f&&null!==g&&(h=this._getFeatureVariables({visitorCode:a,featureKey:e,variationKey:d}));const i=h.map(a=>_utilities.Parser.parseFeatureVariable(a).throw());c.set(b.featureKey,{key:d,id:f,experimentId:g,variables:i})}),_logging.KameleoonLogger.info`RETURN: KameleoonClient.getActiveFeatureFlags(visitorCode: ${a}) -> (FeatureFlags: ${c})`,c}getFeatureFlagVariationKey(a,b){if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);_logging.KameleoonLogger.info`CALL: KameleoonClient.getFeatureFlagVariationKey(visitorCode: ${a}, featureKey: ${b})`,this.visitorCodeManager.validateVisitorCode(a).throw();const{key:c}=this._getFeatureVariation({visitorCode:a,featureKey:b,track:!0}).throw();return _logging.KameleoonLogger.info`RETURN: KameleoonClient.getFeatureFlagVariationKey(visitorCode: ${a}, featureKey: ${b}) -> (variationKey: ${c})`,c}getFeatureFlagVariable(a){let{visitorCode:b,featureKey:c,variableKey:d}=a;if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);_logging.KameleoonLogger.info`CALL: KameleoonClient.getFeatureFlagVariable(visitorCode: ${b}, featureKey: ${c}, variableKey: ${d})`,this.visitorCodeManager.validateVisitorCode(b).throw();const{key:e}=this._getFeatureVariation({visitorCode:b,featureKey:c,track:!0}).throw(),f=this._getFeatureVariables({visitorCode:b,featureKey:c,variationKey:e}),g=f.find(a=>a.key===d);if(!g)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagVariableNotFound,d,b);const{type:h,value:i}=_utilities.Parser.parseFeatureVariable(g).throw(),j={type:h,value:i};return _logging.KameleoonLogger.info`RETURN: KameleoonClient.getFeatureFlagVariable(visitorCode: ${b}, featureKey: ${c}, variableKey: ${d}) -> (FeatureFlagVariable: ${j})`,j}getFeatureFlagVariables(a,b){if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);_logging.KameleoonLogger.info`CALL: KameleoonClient.getFeatureFlagVariables(visitorCode: ${a}, featureKey: ${b})`,this.visitorCodeManager.validateVisitorCode(a).throw();const{key:c}=this._getFeatureVariation({visitorCode:a,featureKey:b,track:!0}).throw(),d=this._getFeatureVariables({visitorCode:a,featureKey:b,variationKey:c}),e=[];for(const c of d){const a=_utilities.Parser.parseFeatureVariable(c).throw();e.push(a)}return _logging.KameleoonLogger.info`RETURN: KameleoonClient.getFeatureFlagVariables(visitorCode: ${a}, featureKey: ${b}) -> (FeatureFlagVariables: ${e})`,e}isFeatureFlagActive(a,b){if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);let[c,d,e]=["","",!0];"string"==typeof a?(c=a,d=b):([c,d]=[a.visitorCode,a.featureKey],a.track!==void 0&&(e=a.track)),_logging.KameleoonLogger.info`CALL: KameleoonClient.isFeatureFlagActive(visitorCode: ${c}, featureKey: ${d}, track ${e})`,this.visitorCodeManager.validateVisitorCode(c).throw();try{const{key:a}=this._getFeatureVariation({visitorCode:c,featureKey:d,track:e}).throw(),b=a!==_constants.OFF_VARIATION_KEY;return _logging.KameleoonLogger.info`RETURN: KameleoonClient.isFeatureFlagActive(visitorCode: ${c}, featureKey: ${d}, track: ${e}) -> (isActive: ${b})`,b}catch(a){if(a instanceof _kameleoonError.KameleoonError&&a.type===_kameleoonError.KameleoonException.FeatureFlagEnvironmentDisabled)return _logging.KameleoonLogger.info`RETURN: KameleoonClient.isFeatureFlagActive(visitorCode: ${c}, featureKey: ${d}, track: ${e}) -> (isActive: false)`,!1;throw a}}async getRemoteData(a){if(this.stubMode)return null;_logging.KameleoonLogger.info`CALL: KameleoonClient.getRemoteData(key: ${a})`;const b=await this.requester.getRemoteData(a);return _logging.KameleoonLogger.info`RETURN: KameleoonClient.getRemoteData(key: ${a}) -> (remoteData: ${b})`,b.throw()}async getVisitorWarehouseAudience(a){let{visitorCode:b,customDataIndex:c,warehouseKey:d}=a;if(this.stubMode)return null;_logging.KameleoonLogger.info`CALL: KameleoonClient.getVisitorWarehouseAudience(visitorCode: ${b}, customDataIndex: ${c}, warehouseKey: ${d})`,this.visitorCodeManager.validateVisitorCode(b).throw();const e=await this.getRemoteData(d||b);if(!e)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,`No data found for ${d||b} key`);if(!e[_constants.WAREHOUSE_AUDIENCE_KEY]||0===Object.keys(e[_constants.WAREHOUSE_AUDIENCE_KEY]).length)return _logging.KameleoonLogger.info`RETURN: KameleoonClient.getVisitorWarehouseAudience(visitorCode: ${b}, customDataIndex: ${c}, warehouseKey: ${d}) -> (customData: null)`,null;const f=new _kameleoonData.CustomData(c,...Object.keys(e[_constants.WAREHOUSE_AUDIENCE_KEY]));return this.dataManager.storeData(b,f),_logging.KameleoonLogger.info`RETURN: KameleoonClient.getVisitorWarehouseAudience(visitorCode: ${b}, customDataIndex: ${c}, warehouseKey: ${d}) -> (customData: ${f})`,f}onEvent(a,b){if(this.stubMode)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);if(_logging.KameleoonLogger.info`CALL: KameleoonClient.onEvent(event: ${a}, callback)`,!this.initialized)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization);this.eventManager.addEventHandler(a,b),_logging.KameleoonLogger.info`RETURN: KameleoonClient.onEvent(event: ${a}, callback)`}getEngineTrackingCode(a){if(this.stubMode)return"";_logging.KameleoonLogger.info`CALL: KameleoonClient.getEngineTrackingCode(visitorCode: ${a})`,this.visitorCodeManager.validateVisitorCode(a).throw();const b=_utilities.Utilities.getTrackingCode(this.trackingCache,a);return _logging.KameleoonLogger.info`RETURN: KameleoonClient.getEngineTrackingCode(visitorCode: ${a}) -> (trackingCode: ${b})`,b}isInitialized(){return _logging.KameleoonLogger.debug`CALL/RETURN: KameleoonClient.isInitialized() -> (initialized: ${this.initialized})`,this.initialized}setLogLevel(a){_logging.KameleoonLogger.setLogLevel(a)}setForcedVariation(a){let{visitorCode:b,experimentId:c,variationKey:d,forceTargeting:e=!0}=a;this.stubMode||(_logging.KameleoonLogger.info`CALL: KameleoonClient.setForcedVariation(visitorCode: '${b}', experimentId: ${c}, variationKey: '${d}', forceTargeting: ${e})`,this.visitorCodeManager.validateVisitorCode(b).throw(),this._setForcedVariation({visitorCode:b,experimentId:c,variationKey:d,forceTargeting:e}).throw(),_logging.KameleoonLogger.info`RETURN: KameleoonClient.setForcedVariation(visitorCode: '${b}', experimentId: ${c}, variationKey: '${d}', forceTargeting: ${e})`)}setUserConsent(a){let{visitorCode:b,consent:c,setData:d}=a;this.stubMode||(_logging.KameleoonLogger.info`CALL: KameleoonClient.setUserConsent(visitorCode: ${b}, consent: ${c}, setData: ${d})`,this.visitorCodeManager.validateVisitorCode(b).throw(),this.updateConsentData(b,c),c?d({visitorCode:b,key:_storage.KameleoonStorageKey.VisitorCode,maxAge:_visitorCodeManager.DEFAULT_MAX_AGE,path:_visitorCodeManager.PATH}):this.visitorCodeManager.consentRequired&&d({visitorCode:"",key:_storage.KameleoonStorageKey.VisitorCode,maxAge:_visitorCodeManager.ZERO_MAX_AGE,path:_visitorCodeManager.PATH}),_logging.KameleoonLogger.info`RETURN: KameleoonClient.setUserConsent(visitorCode: ${b}, consent: ${c}, setData: ${d})`)}updateConsentData(a,b){const c=this.consentDataStorage.read();if(!c.ok)return void(c.error.type===_kameleoonError.KameleoonException.StorageEmpty&&this.consentDataStorage.write({[a]:{consent:b}}));const d=c.data;d[a]={consent:b},this.consentDataStorage.write(d)}_isConsentProvided(a){_logging.KameleoonLogger.debug`CALL: KameleoonClient._isConsentProvided(visitorCode: ${a})`;const{isConsentRequired:b}=this.clientConfiguration,c=this.consentDataStorage.read();let d=!1;if(!b)d=!0;else if(c.ok){const b=c.data[a];d="boolean"==typeof b?b:b&&b.consent}return _logging.KameleoonLogger.debug`RETURN: KameleoonClient._isConsentProvided(visitorCode: ${a}) -> (isConsentProvided: ${d})`,d}_getFeatureVariables(a){let{visitorCode:b,featureKey:c,variationKey:d}=a;_logging.KameleoonLogger.debug`CALL: KameleoonClient._getFeatureVariables(visitorCode: ${b}, featureKey: ${c}, variationKey: ${d})`;const e=this.clientConfiguration.featureFlags,f=e.get(c);if(!f)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagConfigurationNotFound,c);const g=f.variations.find(a=>a.key===d);if(!g)throw new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagVariationNotFound,d,b);return _logging.KameleoonLogger.debug`RETURN: KameleoonClient._getFeatureVariables(visitorCode: ${b}, featureKey: ${c}, variationKey: ${d}) -> (variables: ${g.variables})`,g.variables}_getActiveFeatureVariations(a){_logging.KameleoonLogger.debug`CALL: KameleoonClient._getActiveFeatureVariations(visitorCode: ${a})`;const b=this.clientConfiguration.featureFlags,c=[];for(const d of b.values()){if(!d.environmentEnabled)continue;const b=this._evaluate({visitorCode:a,featureFlag:d,track:!1,save:!1});b.variationKey!==_constants.OFF_VARIATION_KEY&&c.push({variationKey:b.variationKey,variationId:b.variationId,experimentId:b.experimentId,featureFlagId:d.id,featureKey:d.featureKey,rule:null,isTargetedRule:b.ruleType===_clientConfiguration.RuleType.TARGETED_DELIVERY})}return _logging.KameleoonLogger.debug`RETURN: KameleoonClient._getActiveFeatureVariations(visitorCode: ${a}) -> (activeVariations: ${c})`,c}_evaluate(a){let{visitorCode:b,featureFlag:c,track:d,save:e}=a;_logging.KameleoonLogger.debug`CALL: KameleoonClient._evaluate(visitorCode: ${b}, featureFlag: ${c}, track: ${d}, save: ${e})`;let f,g=null;const h=this.variationConfiguration.getForcedFeatureVariation(b,c.featureKey);if(h.ok&&(g=h.data),g)f=KameleoonClient.EvaluatedExperiment.fromForcedFeatureVariation(c.defaultVariationKey,g);else if(this._isVisitorNotInHoldout(b,d,e)&&this._isFFUnrestrictedByMEGroup(b,c)){const a=this.dataManager.getVisitorData(b),g=this.dataManager.getVisitorIdentifier(b),h=this.variationConfiguration.getVariation({visitorCode:b,visitorIdentifier:g,featureFlag:c,track:d,withAssignment:e,targetingData:a,clientConfiguration:this.clientConfiguration,dataManager:this.dataManager,packageInfo:this.externalPackageInfo}).throw();f=KameleoonClient.EvaluatedExperiment.fromVariationData(h)}else f=KameleoonClient.EvaluatedExperiment.fromDefaultVariationKey(c.defaultVariationKey);return e&&!f.isSimulated&&null!==f.experimentId&&null!==f.variationId&&this.variationConfiguration.updateStoredVariations(b,{[f.experimentId]:{variationId:f.variationId,isTargetedRule:f.ruleType===_clientConfiguration.RuleType.TARGETED_DELIVERY,status:d?_types.TrackingStatus.Unsent:_types.TrackingStatus.Sent}}),this.eventManager.fireEvent(_eventManager.EventType.Evaluation,{featureKey:c.featureKey,variation:{key:f.variationKey,experimentId:f.experimentId,id:f.variationId}}),_logging.KameleoonLogger.debug`RETURN: KameleoonClient._evaluate(visitorCode: ${b}, featureFlag: ${c}, track: ${d}, save: ${e}) -> (evalExp: ${f})`,f}_isFFUnrestrictedByMEGroup(a,b){const c=b.mutuallyExclusiveGroup;if(!c)return!0;_logging.KameleoonLogger.debug`CALL: KameleoonClient._isFFUnrestrictedByMEGroup(visitorCode: ${a}, featureFlag: ${b})`;let d=!0;const e=this.clientConfiguration.meGroups.get(c);if(e){const f=this.dataManager.getVisitorIdentifier(a),g=_hasher.Hasher.getHashDoubleForMEGroup(f,c);_logging.KameleoonLogger.debug`Calculated meGroup hash ${g} for code: '${f}', meGroup: '${c}'`,d=e.getFeatureFlagByHash(g)===b}return _logging.KameleoonLogger.debug`RETURN: KameleoonClient._isFFUnrestrictedByMEGroup(visitorCode: '${a}', featureFlag: ${b}) -> (selected: ${d})`,d}_getFeatureVariation(a){let{visitorCode:b,featureKey:c,track:d}=a;if(_logging.KameleoonLogger.debug`CALL: KameleoonClient._getFeatureVariation(visitorCode: ${b}, featureKey: ${c}, track: ${d})`,!this.initialized)return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.Initialization));const e=this.clientConfiguration.featureFlags,f=e.get(c);if(!f)return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagConfigurationNotFound,c));if(!f.environmentEnabled)return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagEnvironmentDisabled,f.featureKey,this.environment));const g=this._evaluate({visitorCode:b,featureFlag:f,track:d,save:!0}),{experimentId:h,variationId:i,variationKey:j,isSimulated:k}=g;let l=new Map,m=!1;try{const a=this._getFeatureVariables({visitorCode:b,featureKey:c,variationKey:j});a.forEach(a=>{m||a.type!==_types.VariableType.JS&&a.type!==_types.VariableType.CSS||(m=!0);const b=_utilities.Parser.parseFeatureVariable(a).throw();l.set(a.key,b)})}catch(_){}h&&"number"==typeof i&&!k&&_utilities.Utilities.updateCache({cacheManager:this.trackingCache,hasJsCssVariables:m,visitorCode:b,experimentId:h,variationId:i}),d&&!k&&this.tracker.scheduleVisitor(b,this._isConsentProvided(b));const n={key:j,id:i,experimentId:h,variables:l};return _logging.KameleoonLogger.debug`RETURN: KameleoonClient._getFeatureVariation(visitorCode: ${b}, featureKey: ${c}, track: ${d}) -> (variation: ${n})`,(0,_tsRes.Ok)(n)}_isVisitorNotInHoldout(a,b,c){const d=this.clientConfiguration.holdout;if(!d)return!0;_logging.KameleoonLogger.debug`CALL: KameleoonClient._isVisitorNotInHoldout(visitorCode: ${a}, track: ${b}, save: ${c})`;let e=!0;const f=this.dataManager.getVisitorIdentifier(a),g=_hasher.Hasher.getHashDouble({visitorIdentifier:f,respoolTime:null,id:d.experimentId+""});_logging.KameleoonLogger.debug`Calculated holdoutHash: ${g} for visitorCode: ${f}`;let h=_utilities.Utilities.getVariationByHash(d.variationByExposition,g);return null!==h&&(e=h.variationKey!==_constants.IN_HOLDOUT_VARIATION_KEY,c&&this.variationConfiguration.updateStoredVariations(a,{[d.experimentId]:{variationId:h.variationId,isTargetedRule:!1,status:b?_types.TrackingStatus.Unsent:_types.TrackingStatus.Sent}})),_logging.KameleoonLogger.debug`RETURN: KameleoonClient._isVisitorNotInHoldout(visitorCode: ${a}, track: ${b}, save: ${c}) -> (isNotInHoldout: ${e})`,e}_setForcedVariation(a){let{visitorCode:b,experimentId:c,variationKey:d,forceTargeting:e=!0}=a;if(_logging.KameleoonLogger.debug`CALL: KameleoonClient._setForcedVariation(visitorCode: '${b}', experimentId: ${c}, variationKey: '${d}', forceTargeting: ${e})`,null===d){const a=this.variationConfiguration.updateForcedExperimentVariation(b,c,null);return _logging.KameleoonLogger.debug`RETURN: KameleoonClient._setForcedVariation(visitorCode: '${b}', experimentId: ${c}, variationKey: '${d}', forceTargeting: ${e}) -> (writeResult: ${a})`,a}let f=null,g=null;if(f=this.clientConfiguration.experimentMap.get(c),!f)return _logging.KameleoonLogger.error`Experiment with id ${c} not found for visitor ${b}`,(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagExperimentNotFound,c,b));if(g=f.variations.get(d),void 0===g)return _logging.KameleoonLogger.error`Variation with key ${d} not found in experiment ${f} for visitor ${b}`,(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.FeatureFlagVariationNotFound,d,b));f={type:f.type,experimentId:c},g={variationKey:d,variationId:g};const h=this.variationConfiguration.updateForcedExperimentVariation(b,c,{rule:f,varByExp:g,forceTargeting:e});return _logging.KameleoonLogger.debug`RETURN: KameleoonClient._setForcedVariation(visitorCode: '${b}', experimentId: ${c}, variationKey: '${d}', forceTargeting: ${e}) -> (writeResult: ${h})`,h}}exports.KameleoonClient=KameleoonClient,_defineProperty(KameleoonClient,"EvaluatedExperiment",class{static fromForcedFeatureVariation(a,b){var c,d,e;let f=a;return b.varByExp?f=b.varByExp.variationKey:b.rule&&b.rule.type===_clientConfiguration.RuleType.EXPERIMENTATION&&(f=_constants.OFF_VARIATION_KEY),{variationKey:f,variationId:(null===(c=b.varByExp)||void 0===c?void 0:c.variationId)||null,experimentId:(null===(d=b.rule)||void 0===d?void 0:d.experimentId)||null,ruleType:(null===(e=b.rule)||void 0===e?void 0:e.type)||null,isSimulated:b.simulated}}static fromVariationData(a){var b,c;return{variationKey:a.variationKey,variationId:a.variationId,experimentId:a.experimentId,ruleType:null!==(b=null===(c=a.rule)||void 0===c?void 0:c.type)&&void 0!==b?b:null,isSimulated:!1}}static fromDefaultVariationKey(a){return{variationKey:a,variationId:null,experimentId:null,ruleType:null,isSimulated:!1}}});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Requester=void 0;var _tsRes=require("ts-res"),_kameleoonError=require("../kameleoonError"),_constants=require("./constants"),_types=require("./types"),_logging=require("../logging");function ownKeys(a,b){var c=Object.keys(a);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(a);b&&(d=d.filter(function(b){return Object.getOwnPropertyDescriptor(a,b).enumerable})),c.push.apply(c,d)}return c}function _objectSpread(a){for(var b,c=1;c<arguments.length;c++)b=null==arguments[c]?{}:arguments[c],c%2?ownKeys(Object(b),!0).forEach(function(c){_defineProperty(a,c,b[c])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(b)):ownKeys(Object(b)).forEach(function(c){Object.defineProperty(a,c,Object.getOwnPropertyDescriptor(b,c))});return a}function _defineProperty(a,b,c){return(b=_toPropertyKey(b))in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}function _toPropertyKey(a){var b=_toPrimitive(a,"string");return"symbol"==typeof b?b:b+""}function _toPrimitive(a,b){if("object"!=typeof a||!a)return a;var c=a[Symbol.toPrimitive];if(void 0!==c){var d=c.call(a,b||"default");if("object"!=typeof d)return d;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===b?String:Number)(a)}class Requester{constructor(a){let{urlProvider:b,packageInfo:c,externalRequester:d,requestTimeout:e,trackRetryDelay:f,useAbortController:g}=a;_defineProperty(this,"externalRequester",void 0),_defineProperty(this,"urlProvider",void 0),_defineProperty(this,"packageInfo",void 0),_defineProperty(this,"trackRetryDelay",void 0),_defineProperty(this,"useAbortController",void 0),_defineProperty(this,"timeout",void 0),_logging.KameleoonLogger.debug`CALL: new Requester(urlProvider, packageInfo: ${c}, externalRequester, requestTimeout: ${e}, trackRetryDelay: ${f}, useAbortController: ${g})`,this.urlProvider=b,this.useAbortController=g,this.externalRequester=d,this.trackRetryDelay=f,this.packageInfo=c,this.timeout=e,_logging.KameleoonLogger.debug`RETURN: new Requester(urlProvider, packageInfo: ${c}, externalRequester, requestTimeout: ${e}, trackRetryDelay: ${f}, useAbortController: ${g})`}async getClientConfiguration(a){const b=this.urlProvider.getClientConfigurationUrl(a),c={[_constants.Header.SdkType]:this.packageInfo.type.toLowerCase(),[_constants.Header.SdkVersion]:this.packageInfo.version},d=_constants.NUMBER_OF_RETRIES+1;try{let a={message:""};_logging.KameleoonLogger.debug`Running configuration request Method: ${_types.HttpMethod.Get}, Url: ${b}, Headers: ${c}, with retry limit ${d}`;for(let e=0;e<d;e++){const d=await this.sendRequest({url:b,requestType:_types.RequestType.Configuration,retryCount:e,parameters:{method:_types.HttpMethod.Get,headers:c}});if(d.ok){const a=await d.json();return _logging.KameleoonLogger.debug`Received configuration response: ${{status:d.status}} for request Method: ${_types.HttpMethod.Get}, Url: ${b}, Headers: ${c}`,(0,_tsRes.Ok)(a)}if(e===_constants.NUMBER_OF_RETRIES){if(d.text){const b=await d.text();a=JSON.parse(b)}_logging.KameleoonLogger.error`Failed to get configuration response ${{status:d.status,message:a.message}} for request Method: ${_types.HttpMethod.Get}, Url: ${b}, Headers: ${c}`}else await this.logRequestError({logLevel:_logging.LogLevel.WARNING,message:"Failed to get configuration response",response:d,method:_types.HttpMethod.Get,url:b})}return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.MaximumRetriesReached,a.message))}catch(a){return await this.logRequestError({logLevel:_logging.LogLevel.ERROR,message:"Failed to get configuration response",error:a,method:_types.HttpMethod.Get,url:b,headers:c}),(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.ClientConfiguration,a))}}async getRemoteData(a){const b=this.urlProvider.getRemoteDataUrl(a);_logging.KameleoonLogger.debug`Running remote data request Method: ${_types.HttpMethod.Get}, Url: ${b}`;try{const a=await this.sendRequest({url:b,requestType:_types.RequestType.RemoteData,retryCount:0,parameters:{method:_types.HttpMethod.Get}});if(!a.ok){if(await this.logRequestError({logLevel:_logging.LogLevel.ERROR,message:"Failed to get remote data response",response:a,method:_types.HttpMethod.Get,url:b}),a.text){var c;const b=await a.text(),d=null===(c=JSON.parse(b))||void 0===c?void 0:c.message;return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,d))}return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,"Unknown Reason - no `text()` was found for a response"))}const d=await a.json();return _logging.KameleoonLogger.debug`Received remote data response: ${{status:a.status}} for request Method: ${_types.HttpMethod.Get}, Url: ${b}`,(0,_tsRes.Ok)(d)}catch(a){return await this.logRequestError({logLevel:_logging.LogLevel.ERROR,message:"Failed to get remote data response",error:a,method:_types.HttpMethod.Get,url:b}),(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,a))}}async getVisitorData(a){let{visitorCode:b,filters:c,isMappingIdentifier:d}=a;const e=this.urlProvider.getVisitorDataUrl({visitorCode:b,filters:c,isMappingIdentifier:d});_logging.KameleoonLogger.debug`Running visitor data request Method: ${_types.HttpMethod.Get}, Url: ${e}`;try{const a=await this.sendRequest({url:e,requestType:_types.RequestType.RemoteData,retryCount:0,parameters:{method:_types.HttpMethod.Get}});if(!a.ok){if(await this.logRequestError({logLevel:_logging.LogLevel.ERROR,message:"Failed to get visitor data response",response:a,method:_types.HttpMethod.Get,url:e}),"function"==typeof a.text){const b=await a.text();if(b){var f;const a=null===(f=JSON.parse(b))||void 0===f?void 0:f.message;return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,a))}}return a.status?(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,`No error message. Error status: ${a.status}`)):(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,"Unknown Reason - no text message or error status was found for a response"))}const b=await a.json();return _logging.KameleoonLogger.debug`Received visitor data response: ${{status:a.status}} for request Method: ${_types.HttpMethod.Get}, Url: ${e}`,(0,_tsRes.Ok)(b)}catch(a){return await this.logRequestError({logLevel:_logging.LogLevel.ERROR,message:"Failed to get visitor data response",error:a,method:_types.HttpMethod.Get,url:e}),(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,a))}}async track(a,b){const c=_constants.NUMBER_OF_RETRIES+1,d=this.urlProvider.getTrackingUrl(b);_logging.KameleoonLogger.debug`Running tracking request Method: ${_types.HttpMethod.Post}, Url: ${d}, Body: ${a}, with retry limit ${c}, retry delay ${this.trackRetryDelay} ms`;for(let e=0;e<c;e++){let b;try{if(b=await this.sendRequest({url:d,retryCount:e,requestType:_types.RequestType.Tracking,parameters:{body:a,method:_types.HttpMethod.Post}}),b.ok)return _logging.KameleoonLogger.debug`Received tracking response: ${{status:b.status}} for request Method: ${_types.HttpMethod.Post}, Url: ${d}, Body: ${a}`,(0,_tsRes.Ok)();await this.logRequestError({logLevel:e==_constants.NUMBER_OF_RETRIES?_logging.LogLevel.ERROR:_logging.LogLevel.WARNING,message:"Failed to get tracking response",response:b,method:_types.HttpMethod.Post,url:d})}catch(a){await this.logRequestError({logLevel:e==_constants.NUMBER_OF_RETRIES?_logging.LogLevel.ERROR:_logging.LogLevel.WARNING,message:"Failed to get tracking response",error:a,method:_types.HttpMethod.Post,url:d})}e<c&&(await new Promise(a=>setTimeout(a,this.trackRetryDelay)))}return(0,_tsRes.Err)()}async sendRequest(a){let b,{url:c,requestType:d,retryCount:e,parameters:f}=a;if(this.useAbortController){const a=new AbortController,g=setTimeout(()=>a.abort(),this.timeout);b=await this.externalRequester.sendRequest({url:c,retryCount:e,requestType:d,parameters:_objectSpread(_objectSpread({},f),{},{signal:a.signal})}),clearTimeout(g)}else b=await this.externalRequester.sendRequest({url:c,retryCount:e,requestType:d,parameters:f});return b}async logRequestError(a){let{logLevel:b,message:c,error:d,method:e,url:f,response:g,headers:h}=a;if(d){let a="Unknown error";d instanceof Error&&(a=d.message),_logging.KameleoonLogger.log({level:b,strings:()=>`${c} with error: ${a} for request Method: ${e}, Url: ${f}`})}else if(g&&_logging.KameleoonLogger.checkLevel(b)){const a=await this.parseResponse(g);_logging.KameleoonLogger.log({level:b,strings:()=>`${c} response: Status: '${a.status}' Message: '${a.message}' for request Method: ${e}, Url: '${f}'`+(h?`, Headers: ${h}`:"")})}}async parseResponse(a){let b="";try{if("function"==typeof a.text){const c=await a.text();c&&(b=c)}}catch(a){}return{status:a.status,message:b}}}exports.Requester=Requester;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Requester=void 0;var _tsRes=require("ts-res"),_kameleoonError=require("../kameleoonError"),_constants=require("./constants"),_types=require("./types"),_logging=require("../logging");function ownKeys(a,b){var c=Object.keys(a);if(Object.getOwnPropertySymbols){var d=Object.getOwnPropertySymbols(a);b&&(d=d.filter(function(b){return Object.getOwnPropertyDescriptor(a,b).enumerable})),c.push.apply(c,d)}return c}function _objectSpread(a){for(var b,c=1;c<arguments.length;c++)b=null==arguments[c]?{}:arguments[c],c%2?ownKeys(Object(b),!0).forEach(function(c){_defineProperty(a,c,b[c])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(b)):ownKeys(Object(b)).forEach(function(c){Object.defineProperty(a,c,Object.getOwnPropertyDescriptor(b,c))});return a}function _defineProperty(a,b,c){return(b=_toPropertyKey(b))in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}function _toPropertyKey(a){var b=_toPrimitive(a,"string");return"symbol"==typeof b?b:b+""}function _toPrimitive(a,b){if("object"!=typeof a||!a)return a;var c=a[Symbol.toPrimitive];if(void 0!==c){var d=c.call(a,b||"default");if("object"!=typeof d)return d;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===b?String:Number)(a)}class Requester{constructor(a){let{urlProvider:b,packageInfo:c,externalRequester:d,requestTimeout:e,trackRetryDelay:f,useAbortController:g}=a;_defineProperty(this,"externalRequester",void 0),_defineProperty(this,"urlProvider",void 0),_defineProperty(this,"packageInfo",void 0),_defineProperty(this,"trackRetryDelay",void 0),_defineProperty(this,"useAbortController",void 0),_defineProperty(this,"timeout",void 0),_logging.KameleoonLogger.debug`CALL: new Requester(urlProvider, packageInfo: ${c}, externalRequester, requestTimeout: ${e}, trackRetryDelay: ${f}, useAbortController: ${g})`,this.urlProvider=b,this.useAbortController=g,this.externalRequester=d,this.trackRetryDelay=f,this.packageInfo=c,this.timeout=e,_logging.KameleoonLogger.debug`RETURN: new Requester(urlProvider, packageInfo: ${c}, externalRequester, requestTimeout: ${e}, trackRetryDelay: ${f}, useAbortController: ${g})`}async getClientConfiguration(a){const b=this.urlProvider.getClientConfigurationUrl(a),c={[_constants.Header.SdkType]:this.packageInfo.type.toLowerCase(),[_constants.Header.SdkVersion]:this.packageInfo.version},d=_constants.NUMBER_OF_RETRIES+1;try{let a={message:""};_logging.KameleoonLogger.debug`Running configuration request Method: ${_types.HttpMethod.Get}, Url: ${b}, Headers: ${c}, with retry limit ${d}`;for(let e=0;e<d;e++){const d=await this.sendRequest({url:b,requestType:_types.RequestType.Configuration,retryCount:e,parameters:{method:_types.HttpMethod.Get,headers:c}});if(d.ok){const a=await d.json();return _logging.KameleoonLogger.debug`Received configuration response: ${{status:d.status}} for request Method: ${_types.HttpMethod.Get}, Url: ${b}, Headers: ${c}`,(0,_tsRes.Ok)(a)}if(e===_constants.NUMBER_OF_RETRIES){if(d.text){const b=await d.text();a=JSON.parse(b)}_logging.KameleoonLogger.error`Failed to get configuration response ${{status:d.status,message:a.message}} for request Method: ${_types.HttpMethod.Get}, Url: ${b}, Headers: ${c}`}else await this.logRequestError({logLevel:_logging.LogLevel.WARNING,message:"Failed to get configuration response",response:d,method:_types.HttpMethod.Get,url:b})}return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.MaximumRetriesReached,a.message))}catch(a){return await this.logRequestError({logLevel:_logging.LogLevel.ERROR,message:"Failed to get configuration response",error:a,method:_types.HttpMethod.Get,url:b,headers:c}),(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.ClientConfiguration,a))}}async getRemoteData(a){const b=this.urlProvider.getRemoteDataUrl(a);_logging.KameleoonLogger.debug`Running remote data request Method: ${_types.HttpMethod.Get}, Url: ${b}`;try{const a=await this.sendRequest({url:b,requestType:_types.RequestType.RemoteData,retryCount:0,parameters:{method:_types.HttpMethod.Get}});if(!a.ok){if(await this.logRequestError({logLevel:_logging.LogLevel.ERROR,message:"Failed to get remote data response",response:a,method:_types.HttpMethod.Get,url:b}),a.text){var c;const b=await a.text(),d=null===(c=JSON.parse(b))||void 0===c?void 0:c.message;return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,d))}return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,"Unknown Reason - no `text()` was found for a response"))}const d=await a.json();return _logging.KameleoonLogger.debug`Received remote data response: ${{status:a.status}} for request Method: ${_types.HttpMethod.Get}, Url: ${b}`,(0,_tsRes.Ok)(d)}catch(a){return await this.logRequestError({logLevel:_logging.LogLevel.ERROR,message:"Failed to get remote data response",error:a,method:_types.HttpMethod.Get,url:b}),(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,a))}}async getVisitorData(a){let{visitorCode:b,filters:c,isMappingIdentifier:d}=a;const e=this.urlProvider.getVisitorDataUrl({visitorCode:b,filters:c,isMappingIdentifier:d});_logging.KameleoonLogger.debug`Running visitor data request Method: ${_types.HttpMethod.Get}, Url: ${e}`;try{const a=await this.sendRequest({url:e,requestType:_types.RequestType.RemoteData,retryCount:0,parameters:{method:_types.HttpMethod.Get}});if(!a.ok){if(await this.logRequestError({logLevel:_logging.LogLevel.ERROR,message:"Failed to get visitor data response",response:a,method:_types.HttpMethod.Get,url:e}),"function"==typeof a.text){const b=await a.text();if(b){var f;const a=null===(f=JSON.parse(b))||void 0===f?void 0:f.message;return(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,a))}}return a.status?(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,`No error message. Error status: ${a.status}`)):(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,"Unknown Reason - no text message or error status was found for a response"))}const b=await a.json();return _logging.KameleoonLogger.debug`Received visitor data response: ${{status:a.status}} for request Method: ${_types.HttpMethod.Get}, Url: ${e}`,(0,_tsRes.Ok)(b)}catch(a){return await this.logRequestError({logLevel:_logging.LogLevel.ERROR,message:"Failed to get visitor data response",error:a,method:_types.HttpMethod.Get,url:e}),(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData,a))}}async track(a,b){const c=_constants.NUMBER_OF_RETRIES+1,d=this.urlProvider.getTrackingUrl(b);_logging.KameleoonLogger.debug`Running tracking request Method: ${_types.HttpMethod.Post}, Url: ${d}, Body: ${a}, with retry limit ${c}, retry delay ${this.trackRetryDelay} ms`;for(let e=0;e<c;e++){let b;try{if(b=await this.sendRequest({url:d,retryCount:e,requestType:_types.RequestType.Tracking,parameters:{body:a,method:_types.HttpMethod.Post,headers:{[_constants.Header.ContentType]:"*/*"}}}),b.ok)return _logging.KameleoonLogger.debug`Received tracking response: ${{status:b.status}} for request Method: ${_types.HttpMethod.Post}, Url: ${d}, Body: ${a}`,(0,_tsRes.Ok)();await this.logRequestError({logLevel:e==_constants.NUMBER_OF_RETRIES?_logging.LogLevel.ERROR:_logging.LogLevel.WARNING,message:"Failed to get tracking response",response:b,method:_types.HttpMethod.Post,url:d})}catch(a){await this.logRequestError({logLevel:e==_constants.NUMBER_OF_RETRIES?_logging.LogLevel.ERROR:_logging.LogLevel.WARNING,message:"Failed to get tracking response",error:a,method:_types.HttpMethod.Post,url:d})}e<c&&(await new Promise(a=>setTimeout(a,this.trackRetryDelay)))}return(0,_tsRes.Err)()}async sendRequest(a){let b,{url:c,requestType:d,retryCount:e,parameters:f}=a;if(this.useAbortController){const a=new AbortController,g=setTimeout(()=>a.abort(),this.timeout);b=await this.externalRequester.sendRequest({url:c,retryCount:e,requestType:d,parameters:_objectSpread(_objectSpread({},f),{},{signal:a.signal})}),clearTimeout(g)}else b=await this.externalRequester.sendRequest({url:c,retryCount:e,requestType:d,parameters:f});return b}async logRequestError(a){let{logLevel:b,message:c,error:d,method:e,url:f,response:g,headers:h}=a;if(d){let a="Unknown error";d instanceof Error&&(a=d.message),_logging.KameleoonLogger.log({level:b,strings:()=>`${c} with error: ${a} for request Method: ${e}, Url: ${f}`})}else if(g&&_logging.KameleoonLogger.checkLevel(b)){const a=await this.parseResponse(g);_logging.KameleoonLogger.log({level:b,strings:()=>`${c} response: Status: '${a.status}' Message: '${a.message}' for request Method: ${e}, Url: '${f}'`+(h?`, Headers: ${h}`:"")})}}async parseResponse(a){let b="";try{if("function"==typeof a.text){const c=await a.text();c&&(b=c)}}catch(a){}return{status:a.status,message:b}}}exports.Requester=Requester;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ConditionFactory=void 0;var _tsRes=require("ts-res"),_kameleoonError=require("../../kameleoonError"),_types=require("../types"),_browser=require("./browser"),_conversion=require("./conversion"),_customData=require("./customData"),_device=require("./device"),_pageTitle=require("./pageTitle"),_pageUrl=require("./pageUrl"),_sdkLanguage=require("./sdkLanguage"),_visitorCode=require("./visitorCode"),_cookie=require("./cookie"),_operatingSystem=require("./operatingSystem"),_geolocation=require("./geolocation"),_segment=require("./segment"),_targetFeatureFlag=require("./targetFeatureFlag"),_previousPage=require("./previousPage"),_visitedPages=require("./visitedPages"),_firstVisit=require("./firstVisit"),_lastVisit=require("./lastVisit"),_sameDayVisits=require("./sameDayVisits"),_visits=require("./visits"),_newVisitor=require("./newVisitor"),_applicationVersion=require("./applicationVersion"),_conversionLikelihood=require("./conversionLikelihood"),_logging=require("../../logging"),_exclusiveExperiment=require("./exclusiveExperiment"),_targetExperiment=require("./targetExperiment"),_targetPersonalization=require("./targetPersonalization")
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ConditionFactory=void 0;var _tsRes=require("ts-res"),_kameleoonError=require("../../kameleoonError"),_types=require("../types"),_browser=require("./browser"),_conversion=require("./conversion"),_customData=require("./customData"),_device=require("./device"),_pageTitle=require("./pageTitle"),_pageUrl=require("./pageUrl"),_sdkLanguage=require("./sdkLanguage"),_visitorCode=require("./visitorCode"),_cookie=require("./cookie"),_operatingSystem=require("./operatingSystem"),_geolocation=require("./geolocation"),_segment=require("./segment"),_targetFeatureFlag=require("./targetFeatureFlag"),_previousPage=require("./previousPage"),_visitedPages=require("./visitedPages"),_firstVisit=require("./firstVisit"),_lastVisit=require("./lastVisit"),_sameDayVisits=require("./sameDayVisits"),_visits=require("./visits"),_newVisitor=require("./newVisitor"),_applicationVersion=require("./applicationVersion"),_conversionLikelihood=require("./conversionLikelihood"),_logging=require("../../logging"),_exclusiveExperiment=require("./exclusiveExperiment"),_targetExperiment=require("./targetExperiment"),_targetPersonalization=require("./targetPersonalization");class ConditionFactory{createCondition(a){const{targetingType:b}=a;return b===_types.TargetingType.CUSTOM_DATUM?(0,_tsRes.Ok)(new _customData.CustomData(a)):b===_types.TargetingType.EXCLUSIVE_EXPERIMENT?(0,_tsRes.Ok)(new _exclusiveExperiment.ExclusiveExperimentCondition(a)):b===_types.TargetingType.TARGET_EXPERIMENT?(0,_tsRes.Ok)(new _targetExperiment.TargetExperimentCondition(a)):b===_types.TargetingType.TARGET_FEATURE_FLAG?(0,_tsRes.Ok)(new _targetFeatureFlag.TargetFeatureFlag(a)):b===_types.TargetingType.TARGET_PERSONALIZATION?(0,_tsRes.Ok)(new _targetPersonalization.TargetPersonalizationCondition(a)):b===_types.TargetingType.DEVICE_TYPE?(0,_tsRes.Ok)(new _device.Device(a)):b===_types.TargetingType.BROWSER?(0,_tsRes.Ok)(new _browser.Browser(a)):b===_types.TargetingType.PAGE_URL?(0,_tsRes.Ok)(new _pageUrl.PageUrl(a)):b===_types.TargetingType.PAGE_TITLE?(0,_tsRes.Ok)(new _pageTitle.PageTitle(a)):b===_types.TargetingType.CONVERSIONS?(0,_tsRes.Ok)(new _conversion.Conversion(a)):b===_types.TargetingType.VISITOR_CODE?(0,_tsRes.Ok)(new _visitorCode.VisitorCode(a)):b===_types.TargetingType.SDK_LANGUAGE?(0,_tsRes.Ok)(new _sdkLanguage.SdkLanguage(a)):b===_types.TargetingType.COOKIE?(0,_tsRes.Ok)(new _cookie.Cookie(a)):b===_types.TargetingType.OPERATING_SYSTEM?(0,_tsRes.Ok)(new _operatingSystem.OperatingSystem(a)):b===_types.TargetingType.GEOLOCATION?(0,_tsRes.Ok)(new _geolocation.GeolocationCondition(a)):b===_types.TargetingType.SEGMENT?(0,_tsRes.Ok)(new _segment.Segment(a)):b===_types.TargetingType.APPLICATION_VERSION?(0,_tsRes.Ok)(new _applicationVersion.ApplicationVersion(a)):b===_types.TargetingType.PREVIOUS_PAGE?(0,_tsRes.Ok)(new _previousPage.PreviousPage(a)):b===_types.TargetingType.PAGE_VIEWS?(0,_tsRes.Ok)(new _visitedPages.VisitedPages(a)):b===_types.TargetingType.LAST_VISIT?(0,_tsRes.Ok)(new _lastVisit.LastVisit(a)):b===_types.TargetingType.FIRST_VISIT?(0,_tsRes.Ok)(new _firstVisit.FirstVisit(a)):b===_types.TargetingType.SAME_DAY_VISITS?(0,_tsRes.Ok)(new _sameDayVisits.SameDayVisits(a)):b===_types.TargetingType.VISITS?(0,_tsRes.Ok)(new _visits.Visits(a)):b===_types.TargetingType.NEW_VISITORS?(0,_tsRes.Ok)(new _newVisitor.NewVisitor(a)):b===_types.TargetingType.HEAT_SLICE?(0,_tsRes.Ok)(new _conversionLikelihood.ConversionLikelihood(a)):(_logging.KameleoonLogger.error`Unsupported targeted condition type found: ${b}`,(0,_tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.TargetingCondition,b)))}}exports.ConditionFactory=ConditionFactory;
|
package/dist/tracking/tracker.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Tracker=void 0;var _kameleoonData=require("../kameleoonData"),_types=require("../types"),_bodyProvider=require("./bodyProvider"),_logging=require("../logging"),_staticData=require("../kameleoonData/staticData");function _defineProperty(a,b,c){return(b=_toPropertyKey(b))in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}function _toPropertyKey(a){var b=_toPrimitive(a,"string");return"symbol"==typeof b?b:b+""}function _toPrimitive(a,b){if("object"!=typeof a||!a)return a;var c=a[Symbol.toPrimitive];if(void 0!==c){var d=c.call(a,b||"default");if("object"!=typeof d)return d;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===b?String:Number)(a)}class Tracker{constructor(a){let{dataManager:b,trackingStorage:c,variationConfiguration:d,trackingInterval:e,requester:f,prng:g}=a;_defineProperty(this,"dataManager",void 0),_defineProperty(this,"variationConfiguration",void 0),_defineProperty(this,"requester",void 0),_defineProperty(this,"bodyProvider",void 0),_defineProperty(this,"intervalId",null),_defineProperty(this,"trackingStorage",void 0),_logging.KameleoonLogger.debug`CALL: new Tracker(dataManager, trackingStorage, variationConfiguration, trackingInterval: ${e}, requester, prng)`,this.dataManager=b,this.trackingStorage=c,this.variationConfiguration=d,this.requester=f,this.bodyProvider=new _bodyProvider.BodyProvider(g);try{this.intervalId=setInterval(()=>{this.sendData()},e)}catch(a){throw this.intervalId&&clearInterval(this.intervalId),a}_logging.KameleoonLogger.debug`RETURN: new Tracker(dataManager, trackingStorage, variationConfiguration, trackingInterval: ${e}, requester, prng)`}scheduleVisitor(a,b){_logging.KameleoonLogger.debug`CALL: Tracker.scheduleVisitor(visitorCode: ${a}, isConsentProvided: ${b})`,this.trackingStorage.read().and(c=>{c.scheduledVisitors[`_${a}`]={isConsentProvided:b},this.trackingStorage.write(c)}),_logging.KameleoonLogger.debug`RETURN: Tracker.scheduleVisitor(visitorCode: ${a}, isConsentProvided: ${b})`}checkIsIdentifier(a){var b,c;const d=this.dataManager.isUniqueIdentifier(a),e=null!==(b=null===(c=this.dataManager.getMappingIdentifier(a))||void 0===c?void 0:c.mappingIdentifier)&&void 0!==b?b:a;let f=!1;if(d){const b=this.dataManager.getLinkedVisitor(a),c=this.dataManager.identifierCustomDataIndex;b||"number"!=typeof c?f=!0:this.dataManager.storeData(a,new _kameleoonData.CustomData(c,a))}return f&&a!=e}getUserAgent(a){const b=this.dataManager.getVisitorData(a);if(b){const a=b[_kameleoonData.KameleoonData.UserAgent];if(a)return a.value}}async sendData(){const a={},b=this.trackingStorage.read();if(!b.ok)return;const{scheduledVisitors:c}=b.data,d=[];let e=!1,f={};for(const[b,{isConsentProvided:g}]of Object.entries(c)){if(e){f[b]={isConsentProvided:g};continue}let c=b.startsWith("_")?b.substring(1):b;const h=this.checkIsIdentifier(c),i=this.getUserAgent(c),j=this.getUnsentVisitorData(c,g),k=this.getUnsentVariationData(c,g),l=this.bodyProvider.addData({visitorCode:c,variationData:k,visitorData:j,userAgent:i,isConsentProvided:g,isMappingIdentifier:h});l.ok?(a[c]={visitorData:j,variationData:k},d.push({visitorCode:c,isConsentProvided:g})):(e=!0,f[b]={isConsentProvided:g},_logging.KameleoonLogger.warning("Visitor data to be tracked exceeded the request size limit. Some visitor data is kept to be sent later. If it is not caused by the peak load, decreasing the tracking interval is recommended."))}const{body:g,hasUserAgent:h}=this.bodyProvider.getTrackingBody();if(
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Tracker=void 0;var _kameleoonData=require("../kameleoonData"),_types=require("../types"),_bodyProvider=require("./bodyProvider"),_logging=require("../logging"),_staticData=require("../kameleoonData/staticData");function _defineProperty(a,b,c){return(b=_toPropertyKey(b))in a?Object.defineProperty(a,b,{value:c,enumerable:!0,configurable:!0,writable:!0}):a[b]=c,a}function _toPropertyKey(a){var b=_toPrimitive(a,"string");return"symbol"==typeof b?b:b+""}function _toPrimitive(a,b){if("object"!=typeof a||!a)return a;var c=a[Symbol.toPrimitive];if(void 0!==c){var d=c.call(a,b||"default");if("object"!=typeof d)return d;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===b?String:Number)(a)}class Tracker{constructor(a){let{dataManager:b,trackingStorage:c,variationConfiguration:d,trackingInterval:e,requester:f,prng:g}=a;_defineProperty(this,"dataManager",void 0),_defineProperty(this,"variationConfiguration",void 0),_defineProperty(this,"requester",void 0),_defineProperty(this,"bodyProvider",void 0),_defineProperty(this,"intervalId",null),_defineProperty(this,"trackingStorage",void 0),_logging.KameleoonLogger.debug`CALL: new Tracker(dataManager, trackingStorage, variationConfiguration, trackingInterval: ${e}, requester, prng)`,this.dataManager=b,this.trackingStorage=c,this.variationConfiguration=d,this.requester=f,this.bodyProvider=new _bodyProvider.BodyProvider(g);try{this.intervalId=setInterval(()=>{this.sendData()},e)}catch(a){throw this.intervalId&&clearInterval(this.intervalId),a}_logging.KameleoonLogger.debug`RETURN: new Tracker(dataManager, trackingStorage, variationConfiguration, trackingInterval: ${e}, requester, prng)`}scheduleVisitor(a,b){_logging.KameleoonLogger.debug`CALL: Tracker.scheduleVisitor(visitorCode: ${a}, isConsentProvided: ${b})`,this.trackingStorage.read().and(c=>{c.scheduledVisitors[`_${a}`]={isConsentProvided:b},this.trackingStorage.write(c)}),_logging.KameleoonLogger.debug`RETURN: Tracker.scheduleVisitor(visitorCode: ${a}, isConsentProvided: ${b})`}checkIsIdentifier(a){var b,c;const d=this.dataManager.isUniqueIdentifier(a),e=null!==(b=null===(c=this.dataManager.getMappingIdentifier(a))||void 0===c?void 0:c.mappingIdentifier)&&void 0!==b?b:a;let f=!1;if(d){const b=this.dataManager.getLinkedVisitor(a),c=this.dataManager.identifierCustomDataIndex;b||"number"!=typeof c?f=!0:this.dataManager.storeData(a,new _kameleoonData.CustomData(c,a))}return f&&a!=e}getUserAgent(a){const b=this.dataManager.getVisitorData(a);if(b){const a=b[_kameleoonData.KameleoonData.UserAgent];if(a)return a.value}}async sendData(){const a={},b=this.trackingStorage.read();if(!b.ok)return;const{scheduledVisitors:c}=b.data,d=[];let e=!1,f={};for(const[b,{isConsentProvided:g}]of Object.entries(c)){if(e){f[b]={isConsentProvided:g};continue}let c=b.startsWith("_")?b.substring(1):b;const h=this.checkIsIdentifier(c),i=this.getUserAgent(c),j=this.getUnsentVisitorData(c,g),k=this.getUnsentVariationData(c,g),l=this.bodyProvider.addData({visitorCode:c,variationData:k,visitorData:j,userAgent:i,isConsentProvided:g,isMappingIdentifier:h});l.ok?(a[c]={visitorData:j,variationData:k},d.push({visitorCode:c,isConsentProvided:g})):(e=!0,f[b]={isConsentProvided:g},_logging.KameleoonLogger.warning("Visitor data to be tracked exceeded the request size limit. Some visitor data is kept to be sent later. If it is not caused by the peak load, decreasing the tracking interval is recommended."))}const{body:g,hasUserAgent:h}=this.bodyProvider.getTrackingBody();if(this.trackingStorage.write({scheduledVisitors:f}),!!g){const b=await this.requester.track(g,h);if(b.ok)_logging.KameleoonLogger.info`Successful request for tracking visitors: ${d}, data: ${a}`,this.updateDataStatus(a,_types.TrackingStatus.Sent);else{_logging.KameleoonLogger.error("Tracking request failed"),_logging.KameleoonLogger.info`Failed request for tracking visitors: ${d}, data: ${a}`,this.updateDataStatus(a,_types.TrackingStatus.Unsent);let b={};for(let{visitorCode:a,isConsentProvided:c}of d)a=`_${a}`,b[a]={isConsentProvided:c};this.addNotTrackedVisitors(b)}}}addNotTrackedVisitors(a){const b=this.trackingStorage.read();if(!b.ok)return;const{scheduledVisitors:c}=b.data;Object.entries(a).forEach(a=>{let[b,{isConsentProvided:d}]=a;c[b]||(c[b]={isConsentProvided:d})}),this.trackingStorage.write({scheduledVisitors:c})}updateDataStatus(a,b){let c={};for(const[d,{visitorData:e,variationData:f}]of Object.entries(a)){const a=e.filter(a=>!(a instanceof _staticData.StaticData)).map(a=>{const c=a;return c.status=b,c});a.length&&(c[d]=a);const g=f.map(a=>a.experimentId+"");this.variationConfiguration.updateDataStatus({visitorCode:d,experimentIdList:g,status:b})}0===Object.keys(c).length||(b===_types.TrackingStatus.Sent?this.dataManager.storeTrackedData(c):this.dataManager.storeData(c))}getUnsentVisitorData(a,b){const c=this.dataManager.getUnsentData(a),d=[];if(!c.length)return[];for(const e of c)e.url&&(b||!(e instanceof _staticData.StaticData)&&e.data.type===_kameleoonData.KameleoonData.Conversion)&&d.push(e);if(d.length){const b=d.filter(a=>!(a instanceof _staticData.StaticData)).map(a=>{const b=a;return b.status=_types.TrackingStatus.Pending,b});this.dataManager.storeTrackedData({[a]:b})}return d}getUnsentVariationData(a,b){const c=this.variationConfiguration.getUnsentData(a),d=new Set;if(!c.length)return[];const e=c.filter(a=>{const c=a.isTargetedRule||b;return c&&d.add(a.experimentId+""),c});return this.variationConfiguration.updateDataStatus({visitorCode:a,experimentIdList:Array.from(d),status:_types.TrackingStatus.Pending}),e}}exports.Tracker=Tracker;
|