Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@kameleoon/javascript-sdk-core

Package Overview
Dependencies
Maintainers
3
Versions
68
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@kameleoon/javascript-sdk-core - npm Package Compare versions

Comparing version 2.3.0 to 2.4.0

4

dist/campaignConfiguration/campaignConfiguration.d.ts

@@ -8,3 +8,3 @@ import { Result } from 'ts-res';

interface ICampaignConfiguration {
initialize: (eventSource: IExternalEventSourceConstructor) => Promise<Result<void, KameleoonError>>;
initialize: (eventSource: IExternalEventSourceConstructor, useCache?: boolean) => Promise<Result<void, KameleoonError>>;
addTargetingData: (visitorCode: string, ...data: KameleoonDataType[]) => Result<void, KameleoonError>;

@@ -33,3 +33,3 @@ getUnsentData: (visitorCode: string) => KameleoonDataType[];

constructor({ settings, storage, requester, externalClientConfiguration, targetingCleanupInterval, }: CampaignConfigurationParametersType);
initialize(externalEventSource: IExternalEventSourceConstructor): Promise<Result<void, KameleoonError>>;
initialize(externalEventSource: IExternalEventSourceConstructor, useCache?: boolean): Promise<Result<void, KameleoonError>>;
addTargetingData(visitorCode: string, ...data: KameleoonDataType[]): Result<void, KameleoonError>;

@@ -36,0 +36,0 @@ getUnsentData(visitorCode: string): KameleoonDataType[];

@@ -58,3 +58,3 @@ "use strict";

}
async initialize(externalEventSource) {
async initialize(externalEventSource, useCache) {
const shouldUpdate = this.checkShouldUpdate();

@@ -64,3 +64,5 @@

if (shouldUpdate) {
const updateResult = await this.updateClientConfiguration();
const updateResult = await this.updateClientConfiguration({
useCache
});
if (!updateResult.ok) {

@@ -80,3 +82,5 @@ return updateResult;

const updateEventCallback = _timeStamp => {
this.updateClientConfiguration();
this.updateClientConfiguration({
useCache
});
if (this.configurationUpdateCallback) {

@@ -102,3 +106,5 @@ this.configurationUpdateCallback();

try {
this.updateConfigurationIntervalId = setInterval(this.updateClientConfiguration.bind(this), this.settings.updateInterval);
this.updateConfigurationIntervalId = setInterval(() => this.updateClientConfiguration.bind(this)({
useCache
}), this.settings.updateInterval);
} catch (err) {

@@ -215,3 +221,6 @@ if (this.updateConfigurationIntervalId) {

}
async updateClientConfiguration(timeStamp) {
async updateClientConfiguration({
useCache = false,
timeStamp
} = {}) {
// --- Note ---

@@ -236,2 +245,9 @@ // if `externalClientConfiguration` is passed, fetching is disabled and passed config is used instead

if (!clientConfigurationResult.ok) {
const {
featureFlags,
experiments
} = this.configurationData;
if (useCache && featureFlags.length && experiments.length) {
return (0, _tsRes.Ok)(true);
}
return clientConfigurationResult;

@@ -238,0 +254,0 @@ }

@@ -7,2 +7,6 @@ import { ClientSettingsType } from '../clientSettings';

import { VariableType } from '../types';
export type UpdateClientConfigurationParameters = {
timeStamp?: number;
useCache?: boolean;
};
export type ScheduleType = {

@@ -9,0 +13,0 @@ dateStart: string;

@@ -13,3 +13,3 @@ "use strict";

constructor(siteCode, configuration) {
_defineProperty(this, "updateInterval", 30 * _types.Milliseconds.Minute);
_defineProperty(this, "updateInterval", 60 * _types.Milliseconds.Minute);
_defineProperty(this, "environment", void 0);

@@ -16,0 +16,0 @@ _defineProperty(this, "siteCode", void 0);

@@ -17,3 +17,3 @@ "use strict";

_defineProperty(this, "siteCode", void 0);
const url = _requester.URL.EVENTS + _constants.UrlQuery.Sse + siteCode;
const url = _requester.URL.SERVER_SENT_EVENTS + _constants.UrlQuery.Sse + siteCode;
const eventSource = externalEventSource.initialize(url);

@@ -20,0 +20,0 @@ this.eventSource = eventSource;

@@ -10,2 +10,3 @@ import { JSONType } from './campaignConfiguration';

* @method initialize - an asynchronous method for KameleoonClient initialization by fetching Kameleoon SDK related data from server or by retrieving data from local source if data is up-to-date or update interval has not been reached
* @param {boolean | undefined} useCache - optional parameter for activating SDK offline mode, if `true` is passed failed polls will not return error and will use cached data if such data is available, default value is `false`. Note: if offline mode is on, SDK will still try to retrieve the latest data.
* @returns {Promise<boolean>} Promise resolved into boolean field indicating success or fail

@@ -18,3 +19,4 @@ * @throws `KameleoonError` with one of the following `type` s:

*/
initialize: () => Promise<boolean>;
initialize(useCache?: boolean): Promise<boolean>;
initialize(): Promise<boolean>;
/**

@@ -33,2 +35,12 @@ * @method addData - method for adding targeting data to the storage so that other methods could decide whether the current visitor is targeted or not. Note: userAgent data will not be stored in storage like other data, and it will be sent with every tracking request for bot filtration.

/**
* @method getRemoteVisitorData - an asynchronous method for retrieving custom data for the latest visit of `visitorCode` from Kameleoon Data API and optionally adding it to the storage so that other methods could decide whether the current visitor is targeted or not.
* @param {string} visitorCode - unique visitor identification string, can't exceed 255 characters length
* @param {boolean | undefined} shouldAddData - optional parameter for adding retrieved data to the storage like `addData` method does, default value is `true`
* @returns {KameleoonDataType[]} promise resolved to an array of `KameleoonData` instances, only includes custom data
* @throws `KameleoonError` with one of the following `type` s:
*
* - `KameleoonException.RemoteData` - Couldn't retrieve data from Kameleoon server
*/
getRemoteVisitorData: (visitorCode: string, shouldAddData?: boolean) => Promise<KameleoonDataType[]>;
/**
* @method triggerExperiment - triggers experiment by assigning the variation to the user with `visitorCode`, if the variation is already assigned just returns it's id. Note: returned id `0` indicates default variation. At the same time executes `flushData` without sending extra request.

@@ -188,8 +200,8 @@ * @param {string} visitorCode - unique visitor identification string, can't exceed 255 characters length

export declare class KameleoonClient implements IKameleoonClient {
private internalConfiguration;
private variationConfiguration?;
private campaignConfiguration?;
private settings;
private campaignConfiguration;
private variationDataStorage;
private trackingCache;
private requester;
private externalEventSource;
/**

@@ -199,4 +211,5 @@ * @param {SDKCoreParameters} sdkCoreParameters - parameters for initializing sdk core

constructor({ siteCode, configuration, internalConfiguration, }: SDKCoreParameters);
initialize(): Promise<boolean>;
initialize(useCache?: boolean): Promise<boolean>;
addData(visitorCode: string, ...data: KameleoonDataType[]): void;
getRemoteVisitorData(visitorCode: string, shouldAddData?: boolean): Promise<KameleoonDataType[]>;
triggerExperiment(visitorCode: string, experimentId: number): number;

@@ -203,0 +216,0 @@ trackConversion({ visitorCode, goalId, revenue, }: TrackConversionParamsType): void;

@@ -38,8 +38,8 @@ "use strict";

}) {
_defineProperty(this, "internalConfiguration", void 0);
_defineProperty(this, "variationConfiguration", void 0);
_defineProperty(this, "campaignConfiguration", void 0);
_defineProperty(this, "settings", void 0);
_defineProperty(this, "variationDataStorage", void 0);
_defineProperty(this, "trackingCache", void 0);
_defineProperty(this, "requester", void 0);
_defineProperty(this, "externalEventSource", void 0);
const {

@@ -49,4 +49,8 @@ settings: clientSettings

const {
externalStorage,
externalEventSource,
externalPackageInfo,
externalRequestDispatcher
externalRequestDispatcher,
externalClientConfiguration,
targetingDataCleanupInterval
} = internalConfiguration;

@@ -60,28 +64,22 @@ const requester = new _requester.Requester({

const trackingCache = new _cacheManager.CacheManager(_constants.CACHE_CLEANUP_TIMEOUT);
this.requester = requester;
this.settings = clientSettings;
this.trackingCache = trackingCache;
this.internalConfiguration = internalConfiguration;
}
async initialize() {
const {
externalStorage,
externalEventSource,
externalClientConfiguration,
targetingDataCleanupInterval
} = this.internalConfiguration;
const clientDataStorage = new _externalStorage.ExternalStorage(externalStorage.initialize(_storage.KameleoonStorageKey.ClientData));
const variationDataStorage = new _externalStorage.ExternalStorage(externalStorage.initialize(_storage.KameleoonStorageKey.VariationData));
const campaignConfiguration = new _campaignConfiguration.CampaignConfiguration({
settings: this.settings,
settings: clientSettings,
storage: clientDataStorage,
requester: this.requester,
requester,
externalClientConfiguration,
targetingCleanupInterval: targetingDataCleanupInterval
});
const result = await campaignConfiguration.initialize(externalEventSource);
this.requester = requester;
this.trackingCache = trackingCache;
this.campaignConfiguration = campaignConfiguration;
this.variationDataStorage = variationDataStorage;
this.externalEventSource = externalEventSource;
}
async initialize(useCache) {
const result = await this.campaignConfiguration.initialize(this.externalEventSource, useCache);
result.throw();
const variationConfiguration = new _variationConfiguration.VariationConfiguration(campaignConfiguration.experiments, variationDataStorage);
const variationConfiguration = new _variationConfiguration.VariationConfiguration(this.campaignConfiguration.experiments, this.variationDataStorage);
this.variationConfiguration = variationConfiguration;
this.campaignConfiguration = campaignConfiguration;
return result.ok;

@@ -96,2 +94,13 @@ }

}
async getRemoteVisitorData(visitorCode, shouldAddData = true) {
const result = await this.requester.getVisitorData(visitorCode);
const data = result.throw();
const visitorData = _utilities.Utilities.parseVisitorData(data);
if (shouldAddData) {
for (const item of visitorData) {
this.addData(visitorCode, item);
}
}
return visitorData;
}
triggerExperiment(visitorCode, experimentId) {

@@ -98,0 +107,0 @@ _utilities.Utilities.validateVisitorCode(visitorCode).throw();

@@ -10,6 +10,7 @@ import { EventType, ParameterType, QueryType, StrictEventTypeRecord, StrictParameterRecord, StrictQueryRecord, StrictTrackingRecord, TrackingType } from './types';

export declare const URL: {
EVENTS: string;
TRACKING: string;
DATA: string;
SERVER_SENT_EVENTS: string;
CLIENT_CONFIGURATION: string;
VISIT_EVENT: string;
VISIT_DATA: string;
DATA_MAP: string;
};

@@ -10,5 +10,7 @@ "use strict";

return Header;
}({});
}({}); // TODO:
// IMPORTANT! Change the top level domain to 'net' for test environment when test server is fixed
// Temporary workaround for an urgent release
exports.Header = Header;
const topLevelDomain = undefined === 'test' ? 'net' : 'com';
const topLevelDomain = undefined === 'test' ? 'com' : 'com';
const dataTopLevelDomain = undefined === 'test' ? 'net' : 'io';

@@ -45,3 +47,6 @@ const UrlEventType = {

Nonce: '&nonce=',
Id: '&id='
Id: '&id=',
CustomData: '&customData=',
CurrentVisit: '&currentVisit=',
MaxNumberPreviousVisits: '&maxNumberPreviousVisits='
};

@@ -53,3 +58,4 @@ exports.UrlParameter = UrlParameter;

Map: 'map?siteCode=',
Events: 'events?siteCode='
Events: 'events?siteCode=',
Visitor: 'visitor?siteCode='
};

@@ -62,9 +68,11 @@ exports.UrlQuery = UrlQuery;

exports.UrlTracking = UrlTracking;
const URL_DATA_API = `https://data.kameleoon.${dataTopLevelDomain}`;
const URL = {
EVENTS: `https://events.kameleoon.${topLevelDomain}:8110/`,
TRACKING: `https://data.kameleoon.${dataTopLevelDomain}/${UrlTracking.Visit + UrlQuery.Events}`,
DATA: `https://data.kameleoon.${dataTopLevelDomain}/${UrlTracking.Map + UrlQuery.Map}`,
CLIENT_CONFIGURATION: `https://client-config.kameleoon.${topLevelDomain}/`
SERVER_SENT_EVENTS: `https://events.kameleoon.${topLevelDomain}:8110/`,
CLIENT_CONFIGURATION: `https://client-config.kameleoon.${topLevelDomain}/`,
VISIT_EVENT: `${URL_DATA_API}/${UrlTracking.Visit + UrlQuery.Events}`,
VISIT_DATA: `${URL_DATA_API}/${UrlTracking.Visit + UrlQuery.Visitor}`,
DATA_MAP: `${URL_DATA_API}/${UrlTracking.Map + UrlQuery.Map}`
};
exports.URL = URL;
//# sourceMappingURL=constants.js.map
export { Requester } from './requester';
export { URL, UrlEventType, UrlParameter, Header, } from './constants';
export { HttpMethod, TrackParametersType, TrackExperimentParamsType, IExternalRequestDispatcher, GetClientConfigurationResultType, } from './types';
export { URL, UrlEventType, UrlParameter, Header } from './constants';
export { HttpMethod, VisitType, TrackParametersType, TrackExperimentParamsType, IExternalRequestDispatcher, GetVisitorDataResultType, GetClientConfigurationResultType, } from './types';

@@ -12,2 +12,8 @@ "use strict";

});
Object.defineProperty(exports, "GetVisitorDataResultType", {
enumerable: true,
get: function () {
return _types.GetVisitorDataResultType;
}
});
Object.defineProperty(exports, "Header", {

@@ -67,2 +73,8 @@ enumerable: true,

});
Object.defineProperty(exports, "VisitType", {
enumerable: true,
get: function () {
return _types.VisitType;
}
});
var _requester = require("./requester");

@@ -69,0 +81,0 @@ var _constants = require("./constants");

import { Result } from 'ts-res';
import { KameleoonError } from '../kameleoonError';
import { GetClientConfigurationResultType, RequesterParamsType, TrackDataParamsType, TrackExperimentParamsType } from './types';
import { GetClientConfigurationResultType, RequesterParamsType, TrackDataParamsType, TrackExperimentParamsType, GetVisitorDataResultType } from './types';
import { JSONType } from '../campaignConfiguration';

@@ -20,2 +20,3 @@ import { Nonce } from '../kameleoonData/nonce';

getRemoteData(key: string): Promise<Result<JSONType, KameleoonError>>;
getVisitorData(visitorCode: string): Promise<Result<GetVisitorDataResultType, KameleoonError>>;
trackExperiment({ variationId, visitorCode, experimentId, isUnallocated, body, userAgent, callback, }: TrackExperimentParamsType): Promise<void>;

@@ -22,0 +23,0 @@ trackData({ visitorCode, body, userAgent, }: TrackDataParamsType): Promise<void>;

@@ -43,3 +43,3 @@ "use strict";

async getRemoteData(key) {
const requestUrl = _constants.URL.DATA + this.siteCode + _constants.UrlParameter.Key + encodeURI(key);
const requestUrl = _constants.URL.DATA_MAP + this.siteCode + _constants.UrlParameter.Key + encodeURI(key);
const response = await this.requestDispatcher.getRemoteData(requestUrl);

@@ -51,2 +51,10 @@ if (!response) {

}
async getVisitorData(visitorCode) {
const requestUrl = _constants.URL.VISIT_DATA + this.siteCode + _constants.UrlParameter.VisitorCode + visitorCode + _constants.UrlParameter.MaxNumberPreviousVisits + 1 + _constants.UrlParameter.CustomData + true + _constants.UrlParameter.CurrentVisit + true;
const response = await this.requestDispatcher.getRemoteData(requestUrl);
if (!response) {
return (0, _tsRes.Err)(new _kameleoonError.KameleoonError(_kameleoonError.KameleoonException.RemoteData));
}
return (0, _tsRes.Ok)(response);
}
async trackExperiment({

@@ -97,3 +105,3 @@ variationId,

} = this.packageInfo;
return _constants.URL.TRACKING + this.siteCode + _constants.UrlParameter.VisitorCode + encodeURIComponent(visitorCode) + _constants.UrlParameter.SdkName + type + _constants.UrlParameter.SdkVersion + version;
return _constants.URL.VISIT_EVENT + this.siteCode + _constants.UrlParameter.VisitorCode + encodeURIComponent(visitorCode) + _constants.UrlParameter.SdkName + type + _constants.UrlParameter.SdkVersion + version;
}

@@ -100,0 +108,0 @@ }

@@ -24,2 +24,27 @@ import { JSONType, FeatureFlagType, ConfigurationDataType } from '../campaignConfiguration';

};
type CustomDataEventType = {
sdk: {
name: string;
version: string;
};
itp: boolean;
time: number;
data: {
index: number;
valuesCountMap: {
[value: string]: number;
};
overwrite: boolean;
mappingIdentifier: boolean;
};
};
export type VisitType = {
siteCode: string;
visitorCode: string;
customDataEvents: CustomDataEventType[];
};
export type GetVisitorDataResultType = {
previousVisits?: VisitType;
currentVisits?: VisitType;
};
export type GetClientConfigurationResultType = Omit<ConfigurationDataType, 'featureFlags'> & {

@@ -33,5 +58,5 @@ featureFlagConfigurations: FeatureFlagType[];

declare const EVENT_TYPE_KEYS: readonly ["customData", "staticData", "page", "conversion", "activity", "experiment"];
declare const PARAMETER_KEYS: readonly ["valuesCountMap", "id", "nonce", "sdkName", "sdkVersion", "browserIndex", "siteCode", "environment", "visitorCode", "negative", "revenue", "title", "referrersIndices", "overwrite", "index", "href", "variationId", "deviceType", "goalId", "ts", "key"];
declare const PARAMETER_KEYS: readonly ["valuesCountMap", "id", "nonce", "sdkName", "sdkVersion", "browserIndex", "siteCode", "environment", "visitorCode", "currentVisit", "maxNumberPreviousVisits", "customData", "negative", "revenue", "title", "referrersIndices", "overwrite", "index", "href", "variationId", "deviceType", "goalId", "ts", "key"];
declare const TRACKING_KEYS: readonly ["visit", "map"];
declare const QUERY_KEYS: readonly ["sse", "mobile", "map", "events"];
declare const QUERY_KEYS: readonly ["sse", "visitor", "mobile", "map", "events"];
export type TrackingType = Record<Capitalize<(typeof TRACKING_KEYS)[number]>, string>;

@@ -38,0 +63,0 @@ export type QueryType = Record<Capitalize<(typeof QUERY_KEYS)[number]>, string>;

@@ -14,5 +14,5 @@ "use strict";

const EVENT_TYPE_KEYS = ['customData', 'staticData', 'page', 'conversion', 'activity', 'experiment'];
const PARAMETER_KEYS = ['valuesCountMap', 'id', 'nonce', 'sdkName', 'sdkVersion', 'browserIndex', 'siteCode', 'environment', 'visitorCode', 'negative', 'revenue', 'title', 'referrersIndices', 'overwrite', 'index', 'href', 'variationId', 'deviceType', 'goalId', 'ts', 'key'];
const PARAMETER_KEYS = ['valuesCountMap', 'id', 'nonce', 'sdkName', 'sdkVersion', 'browserIndex', 'siteCode', 'environment', 'visitorCode', 'currentVisit', 'maxNumberPreviousVisits', 'customData', 'negative', 'revenue', 'title', 'referrersIndices', 'overwrite', 'index', 'href', 'variationId', 'deviceType', 'goalId', 'ts', 'key'];
const TRACKING_KEYS = ['visit', 'map'];
const QUERY_KEYS = ['sse', 'mobile', 'map', 'events'];
const QUERY_KEYS = ['sse', 'visitor', 'mobile', 'map', 'events'];
//# sourceMappingURL=types.js.map

@@ -6,3 +6,5 @@ import { Result } from 'ts-res';

import { CampaignConfiguration, FeatureVariableType } from '../campaignConfiguration';
import { KameleoonDataType } from '../kameleoonData';
import { CacheManager } from '../cacheManager';
import { GetVisitorDataResultType } from '../requester';
export declare class Utilities {

@@ -14,2 +16,3 @@ static checkTargeting({ segment, visitorCode, targetingData, experimentId, variationConfiguration, }: CheckTargetingParamsType): Result<boolean, KameleoonError>;

static parseFeatureVariable(variable: FeatureVariableType): Result<FeatureVariableResultType, KameleoonError>;
static parseVisitorData(data: GetVisitorDataResultType): KameleoonDataType[];
static getUserAgent(visitorCode: string, campaignConfiguration: CampaignConfiguration): string | undefined;

@@ -16,0 +19,0 @@ static updateCache({ cacheManager, visitorCode, experimentId, variationId, }: ManageCacheParametersType): void;

@@ -123,2 +123,30 @@ "use strict";

}
static parseVisitorData(data) {
const {
currentVisits,
previousVisits
} = data;
let visits;
if (currentVisits) {
visits = currentVisits;
} else if (previousVisits) {
visits = previousVisits;
}
if (!visits) {
return [];
}
const indexMap = new Map();
const resultData = [];
const customDataEvents = [...visits.customDataEvents];
customDataEvents.sort((a, b) => b.time - a.time);
for (const customDataEvent of customDataEvents) {
const customDataIndex = customDataEvent.data.index;
if (!indexMap.has(customDataIndex)) {
indexMap.set(customDataIndex, true);
const values = Object.keys(customDataEvent.data.valuesCountMap);
resultData.push(new _kameleoonData.CustomData(customDataIndex, ...values));
}
}
return resultData;
}
static getUserAgent(visitorCode, campaignConfiguration) {

@@ -125,0 +153,0 @@ const isUserAgent = data => data.type === _kameleoonData.KameleoonData.UserAgent;

{
"name": "@kameleoon/javascript-sdk-core",
"version": "2.3.0",
"version": "2.4.0",
"description": "Kameleoon JS SDK Core",

@@ -5,0 +5,0 @@ "main": "dist/index.js",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc