@dotcms/experiments 0.0.1-alpha

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/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@dotcms/experiments",
3
+ "version": "0.0.1-alpha",
4
+ "description": "Official JavaScript library to use Experiments with DotCMS.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/dotCMS/core.git#master"
8
+ },
9
+ "keywords": [
10
+ "dotCMS",
11
+ "CMS",
12
+ "Content Management",
13
+ "A/B testing",
14
+ "Experiments"
15
+ ],
16
+ "author": "dotcms <dev@dotcms.com>",
17
+ "license": "MIT",
18
+ "bugs": {
19
+ "url": "https://github.com/dotCMS/core/issues"
20
+ },
21
+ "homepage": "https://github.com/dotCMS/core/tree/master/core-web/libs/sdk/experiments/README.md",
22
+ "dependencies": {
23
+ "@jitsu/sdk-js": "^3.1.5"
24
+ },
25
+ "peerDependencies": {
26
+ "react": ">=18",
27
+ "react-dom": ">=18",
28
+ "@dotcms/client": "0.0.1-alpha.12"
29
+ },
30
+ "module": "./index.esm.js",
31
+ "type": "module",
32
+ "main": "./index.esm.js"
33
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './lib/hooks/useExperiments';
2
+ export * from './lib/components/DotExperimentsProvider';
3
+ export * from './lib/contexts/DotExperimentsContext';
@@ -0,0 +1,47 @@
1
+ import { ReactElement, ReactNode } from 'react';
2
+ import { DotExperimentConfig } from '../shared/models';
3
+ interface DotExperimentsProviderProps {
4
+ children?: ReactNode;
5
+ config: DotExperimentConfig;
6
+ }
7
+ /**
8
+ * `DotExperimentsProvider` is a component that uses React's Context API to provide
9
+ * an instance of `DotExperiments` to all of its descendants.
10
+ *
11
+ *
12
+ * @component
13
+ * @example
14
+ * ```jsx
15
+ *
16
+ * // Your application component
17
+ * function App() {
18
+ *
19
+ * // Configuration options could be taken from environment variables or can send you own.
20
+ * const experimentConfig = {
21
+ * apiKey: process.env.NEXT_PUBLIC_EXPERIMENTS_API_KEY ,
22
+ * server: process.env.NEXT_PUBLIC_DOTCMS_HOST ,
23
+ * debug: process.env.NEXT_PUBLIC_EXPERIMENTS_DEBUG,
24
+ * redirectFn: YourRedirectFunction
25
+ * };
26
+ *
27
+ * return (
28
+ * <DotExperimentsProvider config={experimentConfig}>
29
+ * <Header>
30
+ * <Navigation items={nav} />
31
+ * </Header>
32
+ * <DotcmsLayout entity={{...}} config={{...}} />
33
+ * </DotExperimentsProvider>
34
+ * );
35
+ * }
36
+ * ```
37
+ *
38
+ * @param {object} props - The properties that define the `DotExperimentsProvider`.
39
+ * @param {ReactNode} props.children - The descendants of this provider, which will
40
+ * have access to the provided `DotExperiments` instance.
41
+ * @param {DotExperimentConfig} props.config - The configuration object for `DotExperiments`.
42
+ *
43
+ * @returns {ReactElement} The provider component, which should wrap the components
44
+ * that need access to the `DotExperiments` instance.
45
+ */
46
+ export declare const DotExperimentsProvider: ({ children, config }: DotExperimentsProviderProps) => ReactElement;
47
+ export {};
@@ -0,0 +1,12 @@
1
+ import { DotExperiments } from '../dot-experiments';
2
+ /**
3
+ * `DotExperimentsContext` is a React context that is designed to provide an instance of
4
+ * `DotExperiments` to all of the components within its tree that are Consumers of this context.
5
+ *
6
+ * The context is created with a default value of `null`. It is meant to be provided a real value
7
+ * using the `DotExperimentsProvider` component.
8
+ *
9
+ * @see {@link https://reactjs.org/docs/context.html|React Context}
10
+ */
11
+ declare const DotExperimentsContext: import("react").Context<DotExperiments | null>;
12
+ export default DotExperimentsContext;
@@ -0,0 +1,289 @@
1
+ import { DotExperimentConfig, Experiment, Variant } from './shared/models';
2
+ /**
3
+ * `DotExperiments` is a Typescript class to handles all operations related to fetching, storing, parsing, and navigating
4
+ * data for Experiments (A/B Testing).
5
+ *
6
+ * It requires a configuration object for instantiation, please instance it using the method `getInstance` sending
7
+ * an object with `api-key`, `server` and `debug`.
8
+ *
9
+ * Here's an example of how you can instantiate DotExperiments class:
10
+ * @example
11
+ * ```typescript
12
+ * const instance = DotExperiments.getInstance({
13
+ * server: "yourServerUrl",
14
+ * "api-key": "yourApiKey"
15
+ * });
16
+ * ```
17
+ *
18
+ * @export
19
+ * @class DotExperiments
20
+ *
21
+ */
22
+ export declare class DotExperiments {
23
+ private readonly config;
24
+ /**
25
+ * The instance of the DotExperiments class.
26
+ * @private
27
+ */
28
+ private static instance;
29
+ /**
30
+ * Represents the default configuration for the DotExperiment library.
31
+ * @property {boolean} trackPageView - Specifies whether to track page view or not. Default value is true.
32
+ */
33
+ private static readonly defaultConfig;
34
+ /**
35
+ * Represents the promise for the initialization process.
36
+ * @private
37
+ */
38
+ private initializationPromise;
39
+ /**
40
+ * Represents the analytics client for Analytics.
41
+ * @private
42
+ */
43
+ private analytics;
44
+ /**
45
+ * Class representing a database handler for IndexDB.
46
+ * @class
47
+ */
48
+ private persistenceHandler;
49
+ /**
50
+ * Represents the stored data in the IndexedDB.
51
+ * @private
52
+ */
53
+ private experimentsAssigned;
54
+ /**
55
+ * A logger utility for logging messages.
56
+ *
57
+ * @class
58
+ */
59
+ private logger;
60
+ /**
61
+ * Represents the current location.
62
+ * @private
63
+ */
64
+ private currentLocation;
65
+ /**
66
+ * Represents the previous location.
67
+ *
68
+ * @type {string}
69
+ */
70
+ private prevLocation;
71
+ private constructor();
72
+ /**
73
+ * Retrieves the array of experiments assigned to an instance of the class.
74
+ *
75
+ * @return {Experiment[]} An array containing the experiments assigned to the instance.
76
+ */
77
+ get experiments(): Experiment[];
78
+ /**
79
+ * Returns a custom redirect function. If a custom redirect function is not configured,
80
+ * the default redirect function will be used.
81
+ *
82
+ * @return {function} A function that accepts a URL string parameter and performs a redirect.
83
+ * If no parameter is provided, the function will not perform any action.
84
+ */
85
+ get customRedirectFn(): (url: string) => void;
86
+ /**
87
+ * Retrieves the current location.
88
+ *
89
+ * @returns {Location} The current location.
90
+ */
91
+ get location(): Location;
92
+ /**
93
+ * Retrieves instance of DotExperiments class if it doesn't exist create a new one.
94
+ * If the instance does not exist, it creates a new instance with the provided configuration and calls the `getExperimentData` method.
95
+ *
96
+ * @param {DotExperimentConfig} config - The configuration object for initializing the DotExperiments instance.
97
+ * @return {DotExperiments} - The instance of the DotExperiments class.
98
+ */
99
+ static getInstance(config?: DotExperimentConfig): DotExperiments;
100
+ /**
101
+ * Waits for the initialization process to be completed.
102
+ *
103
+ * @return {Promise<void>} A Promise that resolves when the initialization is ready.
104
+ */
105
+ ready(): Promise<void>;
106
+ /**
107
+ * This method appends variant parameters to navigation links based on the provided navClass.
108
+ *
109
+ * Note: In order for this method's functionality to apply, you need to define a class for the navigation elements (anchors)
110
+ * to which you would like this functionality applied and pass it as an argument when calling this method.
111
+ *
112
+ * @param {string} navClass - The class of the navigation elements to which variant parameters should be appended. Such elements should be anchors (`<a>`).
113
+ *
114
+ * @example
115
+ * <ul class="navbar-nav me-auto mb-2 mb-md-0">
116
+ * <li class="nav-item">
117
+ * <a class="nav-link " aria-current="page" href="/">Home</a>
118
+ * </li>
119
+ * <li class="nav-item ">
120
+ * <a class="nav-link active" href="/blog">Travel Blog</a>
121
+ * </li>
122
+ * <li class="nav-item">
123
+ * <a class="nav-link" href="/destinations">Destinations</a>
124
+ * </li>
125
+ * </ul>
126
+ *
127
+ * dotExperiment.ready().then(() => {
128
+ * dotExperiment.appendVariantParams('.navbar-nav .nav-link');
129
+ * });
130
+ * appendVariantParams('nav-item-class');
131
+ *
132
+ * @returns {void}
133
+ */
134
+ appendVariantParams(navClass: string): void;
135
+ /**
136
+ * Retrieves the current debug status.
137
+ *
138
+ * @private
139
+ * @returns {boolean} - The debug status.
140
+ */
141
+ getIsDebugActive(): boolean;
142
+ /**
143
+ * Updates the current location and checks if a variant should be applied.
144
+ * Redirects to the variant URL if necessary.
145
+ *
146
+ * @param {Location} location - The new location.
147
+ * @param redirectFunction
148
+ */
149
+ locationChanged(location: Location, redirectFunction?: (url: string) => void): Promise<void>;
150
+ /**
151
+ * Tracks a page view event in the analytics system.
152
+ *
153
+ * @return {void}
154
+ */
155
+ trackPageView(): void;
156
+ /**
157
+ * This method is used to retrieve the variant associated with a given URL.
158
+ *
159
+ * It checks if the URL is part of an experiment by verifying it against an experiment's regex. If the URL matches the regex of an experiment,
160
+ * it returns the variant attached to that experiment; otherwise, it returns null.
161
+ *
162
+ * @param {string | null} path - The URL to check for a variant. This should be the path of the URL.
163
+ *
164
+ * @returns {Variant | null} The variant associated with the URL if it exists, null otherwise.
165
+ */
166
+ getVariantFromHref(path: string | null): Variant | null;
167
+ /**
168
+ * Returns the experiment variant name as a URL search parameter.
169
+ *
170
+ * @param {string|null} path - The path to the current page.
171
+ * @returns {URLSearchParams} - The URL search parameters containing the experiment variant name.
172
+ */
173
+ getVariantAsQueryParam(path: string | null): URLSearchParams;
174
+ /**
175
+ * Determines whether a page view should be tracked.
176
+ *
177
+ * @private
178
+ * @returns {boolean} True if a page view should be tracked, otherwise false.
179
+ */
180
+ private shouldTrackPageView;
181
+ /**
182
+ * Tracks an event using the analytics service.
183
+ *
184
+ * @param {string} typeName - The type of event to track.
185
+ * @param {EventPayload} [payload] - Optional payload associated with the event.
186
+ * @return {void}
187
+ */
188
+ private track;
189
+ /**
190
+ * Initializes the application using lazy initialization. This method performs
191
+ * necessary setup steps and should be invoked to ensure proper execution of the application.
192
+ *
193
+ * Note: This method uses lazy initialization. Make sure to call this method to ensure
194
+ * the application works correctly.
195
+ *
196
+ * @return {Promise<void>} A promise that resolves when the initialization is complete.
197
+ */
198
+ private initialize;
199
+ /**
200
+ * Fetches experiments from the server.
201
+ *
202
+ * @private
203
+ * @returns {Promise<AssignedExperiments>} - The entity object returned from the server.
204
+ * @throws {Error} - If an HTTP error occurs or an error occurs during the fetch request.
205
+ */
206
+ private getExperimentsFromServer;
207
+ /**
208
+ * This method is responsible for retrieving and persisting experiment data from the server to the local indexDB database.
209
+ *
210
+ * - Checks whether making a request to the server to fetch experiment data is required.
211
+ * - Sends the request to the server for data if required.
212
+ * - Parses the fetched data to the form required for storage in the database.
213
+ * - Persists the data in the indexDB database.
214
+ *
215
+ * @private
216
+ * @method verifyExperimentData
217
+ * @async
218
+ * @throws {Error} Throws an error with details if there is any failure in loading the experiments or during their persistence in indexDB.
219
+ *
220
+ * @returns {Promise<void>} An empty promise that fulfills once the experiment data has been successfully loaded and persisted.
221
+ */
222
+ private verifyExperimentData;
223
+ /**
224
+ * Persists the parsed experiment data into the indexDB database.
225
+ *
226
+ * The method does the following:
227
+ * - Receives the parsed data.
228
+ * - Updates the creation date.
229
+ * - Clears existing data from the indexDB database.
230
+ * - Stores the new data in the indexDB database.
231
+ *
232
+ * If there are no experiments in the received data, the method will not attempt to clear or persist anything and will return immediately.
233
+ *.
234
+ *
235
+ * @note This method utilizes Promises for the asynchronous handling of data persistence. Errors during data persistence are caught and logged, but not re-thrown.
236
+ *
237
+ * @private
238
+ * @method persistExperiments
239
+ * @throws Nothing – Errors are caught and logged, but not re-thrown.
240
+ *
241
+ * @param experiments
242
+ */
243
+ private persistExperiments;
244
+ /**
245
+ * Initializes the database handler.
246
+ *
247
+ * This private method instantiates the class handling the IndexDB database
248
+ * and assigns this instance to 'persistenceHandler'.
249
+ *
250
+ * @private
251
+ */
252
+ private initializeDatabaseHandler;
253
+ /**
254
+ * Initializes the Jitsu analytics client.
255
+ *
256
+ * This private method sets up the Jitsu client responsible for sending events
257
+ * to the server with the provided configuration. It also uses the parsed data
258
+ * and registers it as global within Jitsu.
259
+ *
260
+ * @private
261
+ */
262
+ private initAnalyticsClient;
263
+ /**
264
+ * Updates the analytics client's data using the experiments data
265
+ * currently available in the IndexDB database, based on the current location.
266
+ *
267
+ * Retrieves and processes the experiments information according to the
268
+ * current location into a suitable format for `analytics.set()`.
269
+ *
270
+ * @private
271
+ * @method refreshAnalyticsForCurrentLocation
272
+ * @returns {void}
273
+ */
274
+ private refreshAnalyticsForCurrentLocation;
275
+ /**
276
+ * Determines whether analytics should be checked.
277
+ *
278
+ * @private
279
+ * @returns {Promise<boolean>} A boolean value indicating whether analytics should be checked.
280
+ */
281
+ private shouldFetchNewData;
282
+ /**
283
+ * Retrieves persisted data from the database.
284
+ *
285
+ * @private
286
+ * @returns {Promise<void>} A promise that resolves with no value.
287
+ */
288
+ private getPersistedData;
289
+ }
@@ -0,0 +1,14 @@
1
+ import { DotExperiments } from '../dot-experiments';
2
+ /**
3
+ * Custom hook `useExperiments`.
4
+ *
5
+ * This hook is designed to handle changes in the location of the current DotExperiments
6
+ * instance and set a global click handler that redirects the application when an element with an
7
+ * assigned variant is clicked.
8
+ *
9
+ * It also manages adding or removing the experimentation query parameter from the URL as
10
+ * appropriate when a click occurs.
11
+ *
12
+ * @returns {void}
13
+ */
14
+ export declare const useExperiments: (instance: DotExperiments | null) => void;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * The key for identifying the Window key for SdkExperiment.
3
+ *
4
+ * @constant {string}
5
+ */
6
+ export declare const EXPERIMENT_WINDOWS_KEY = "dotExperiment";
7
+ /**
8
+ * The default variant name for an experiment.
9
+ *
10
+ * @type {string}
11
+ * @constant
12
+ */
13
+ export declare const EXPERIMENT_DEFAULT_VARIANT_NAME = "DEFAULT";
14
+ /**
15
+ * The key used to store or retrieve the information in the SessionStore
16
+ *
17
+ * @constant {string}
18
+ */
19
+ export declare const EXPERIMENT_QUERY_PARAM_KEY = "variantName";
20
+ /**
21
+ * The key used to store or retrieve the information in the SessionStore
22
+ * indicating whether an experiment has already been checked.
23
+ *
24
+ * @constant {string}
25
+ */
26
+ export declare const EXPERIMENT_ALREADY_CHECKED_KEY = "experimentAlreadyCheck";
27
+ /**
28
+ * EXPERIMENT_FETCH_EXPIRE_TIME is a constant that represents the name of the variable used to store
29
+ * the expire time for experiment fetching. It is a string value 'experimentFetchExpireTime'.
30
+ *
31
+ * @constant {string}
32
+ */
33
+ export declare const EXPERIMENT_FETCH_EXPIRE_TIME_KEY = "experimentFetchExpireTime";
34
+ /**
35
+ * The duration in milliseconds for which data should be stored in the local storage.
36
+ *
37
+ * @type {number}
38
+ * @constant
39
+ * @default 86400000 (A day)
40
+ *
41
+ */
42
+ export declare const LOCAL_STORAGE_TIME_DURATION_MILLISECONDS: number;
43
+ /**
44
+ * The name of the experiment script file.
45
+ *
46
+ * @constant {string}
47
+ */
48
+ export declare const EXPERIMENT_SCRIPT_FILE_NAME = "dot-experiments.min.iife.js";
49
+ /**
50
+ * The prefix used for the experiment script data attributes.
51
+ *
52
+ * @constant {string}
53
+ */
54
+ export declare const EXPERIMENT_SCRIPT_DATA_PREFIX = "data-experiment-";
55
+ /**
56
+ * Array containing the allowed data attributes for an experiment.
57
+ *
58
+ * @type {Array.<string>}
59
+ * @constant
60
+ */
61
+ export declare const EXPERIMENT_ALLOWED_DATA_ATTRIBUTES: string[];
62
+ /**
63
+ * API_EXPERIMENTS_URL
64
+ *
65
+ * The URL of the endpoint to check if a user is included in experiments.
66
+ *
67
+ * @type {string}
68
+ * @constant
69
+ */
70
+ export declare const API_EXPERIMENTS_URL = "api/v1/experiments/isUserIncluded";
71
+ /**
72
+ * The name of the experiment database store in indexDB.
73
+ *
74
+ * @type {string}
75
+ * @constant
76
+ */
77
+ export declare const EXPERIMENT_DB_STORE_NAME = "dotExperimentStore";
78
+ /**
79
+ * The path to the key in the database IndexDB representing the running experiment data.
80
+ * @type {string}
81
+ */
82
+ export declare const EXPERIMENT_DB_KEY_PATH = "running_experiment";
83
+ /**
84
+ * Enumeration of debug levels.
85
+ *
86
+ * @enum {string}
87
+ * @readonly
88
+ */
89
+ export declare enum DEBUG_LEVELS {
90
+ NONE = "NONE",
91
+ DEBUG = "DEBUG",
92
+ WARN = "WARN",
93
+ ERROR = "ERROR"
94
+ }
95
+ export declare const PAGE_VIEW_EVENT_NAME = "pageview";
@@ -0,0 +1,41 @@
1
+ import { Experiment, ExperimentEvent, IsUserIncludedApiResponse } from '../models';
2
+ /**
3
+ * Represents the response object for the IsUserIncluded API.
4
+ * @typedef {Object} IsUserIncludedResponse
5
+ * @property {IsUserIncludedApiResponse} entity - The response entity.
6
+ * @property {string[]} errors - Array of error messages, if any.
7
+ * @property {Object} i18nMessagesMap - Map of internationalization messages.
8
+ * @property {string[]} messages - Array of additional messages, if any.
9
+ */
10
+ export declare const IsUserIncludedResponse: IsUserIncludedApiResponse;
11
+ export declare const NewIsUserIncludedResponse: IsUserIncludedApiResponse;
12
+ export declare const MOCK_CURRENT_TIMESTAMP = 1704096000000;
13
+ export declare const TIME_15_DAYS_MILLISECONDS: number;
14
+ export declare const TIME_5_DAYS_MILLISECONDS: number;
15
+ export declare const MockDataStoredIndexDB: Experiment[];
16
+ export declare const MockDataStoredIndexDBNew: Experiment[];
17
+ export declare const MockDataStoredIndexDBWithNew: Experiment[];
18
+ export declare const MockDataStoredIndexDBWithNew15DaysLater: Experiment[];
19
+ /**
20
+ * Represents an event that indicates the expected experiments parsed from a response to send to Analytics.
21
+ *
22
+ * @typedef {Object} ExpectedExperimentsParsedEvent
23
+ * @property {ExperimentEvent[]} experiments - An array of experiment events.
24
+ */
25
+ export declare const ExpectedExperimentsParsedEvent: ExperimentEvent[];
26
+ /**
27
+ * Represents a mock location object.
28
+ *
29
+ * @typedef {Object} LocationMock
30
+ * @property {string} href - The complete URL.
31
+ *
32
+ */
33
+ export declare const LocationMock: Location;
34
+ export declare const sessionStorageMock: {
35
+ getItem: (key: string) => string | null;
36
+ setItem: (key: string, value: string) => void;
37
+ removeItem: (key: string) => void;
38
+ clear: () => void;
39
+ key: (index: number) => string | null;
40
+ readonly length: number;
41
+ };