forked from rudderlabs/rudder-sdk-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanalytics.js
576 lines (525 loc) · 15.7 KB
/
analytics.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
import {
getJSONTrimmed,
generateUUID,
handleError,
getDefaultPageProperties
} from "./utils/utils";
import {
CONFIG_URL,
ECommerceEvents,
MAX_WAIT_FOR_INTEGRATION_LOAD,
INTEGRATION_LOAD_CHECK_INTERVAL
} from "./utils/constants";
import { integrations } from "./integrations";
import RudderElementBuilder from "./utils/RudderElementBuilder";
import Storage from "./utils/storage";
import { EventRepository } from "./utils/EventRepository";
import logger from "./utils/logUtil";
//https://unpkg.com/[email protected]/dist/browser.js
/**
* Add the rudderelement object to flush queue
*
* @param {RudderElement} rudderElement
*/
function enqueue(rudderElement, type) {
if (!this.eventRepository) {
this.eventRepository = EventRepository;
}
this.eventRepository.enqueue(rudderElement, type);
}
/**
* class responsible for handling core
* event tracking functionalities
*/
class Analytics {
/**
* Creates an instance of Analytics.
* @memberof Analytics
*/
constructor() {
this.initialized = false;
this.ready = false;
this.eventsBuffer = [];
this.clientIntegrations = [];
this.configArray = [];
this.clientIntegrationObjects = undefined;
this.successfullyLoadedIntegration = [];
this.failedToBeLoadedIntegration = [];
this.toBeProcessedArray = [];
this.toBeProcessedByIntegrationArray = [];
this.storage = new Storage();
this.userId =
this.storage.getUserId() != undefined ? this.storage.getUserId() : "";
this.userTraits =
this.storage.getUserTraits() != undefined
? this.storage.getUserTraits()
: {};
this.anonymousId = this.storage.getAnonymousId()
? this.storage.getAnonymousId()
: generateUUID();
this.storage.setUserId(this.userId);
this.storage.setAnonymousId(this.anonymousId);
this.eventRepository = EventRepository;
}
/**
* Process the response from control plane and
* call initialize for integrations
*
* @param {*} status
* @param {*} response
* @memberof Analytics
*/
processResponse(status, response) {
logger.debug("===in process response=== " + status);
response = JSON.parse(response);
response.source.destinations.forEach(function(destination, index) {
logger.debug(
"Destination " +
index +
" Enabled? " +
destination.enabled +
" Type: " +
destination.destinationDefinition.name +
" Use Native SDK? " +
destination.config.useNativeSDK
);
if (destination.enabled) {
this.clientIntegrations.push(destination.destinationDefinition.name);
this.configArray.push(destination.config);
}
}, this);
this.init(this.clientIntegrations, this.configArray);
}
/**
* Initialize integrations by addinfg respective scripts
* keep the instances reference in core
*
* @param {*} intgArray
* @param {*} configArray
* @returns
* @memberof Analytics
*/
init(intgArray, configArray) {
logger.debug("supported intgs ", integrations);
this.clientIntegrationObjects = [];
if (!intgArray || intgArray.length == 0) {
this.toBeProcessedByIntegrationArray = [];
return;
}
intgArray.forEach((intg, index) => {
let intgClass = integrations[intg];
let destConfig = configArray[index];
let intgInstance = new intgClass(destConfig);
intgInstance.init();
logger.debug("initializing destination: ", intg);
this.isInitialized(intgInstance).then(this.replayEvents);
});
}
replayEvents(object) {
if (
object.successfullyLoadedIntegration.length +
object.failedToBeLoadedIntegration.length ==
object.clientIntegrations.length
) {
object.clientIntegrationObjects = object.successfullyLoadedIntegration;
//send the queued events to the fetched integration
object.toBeProcessedByIntegrationArray.forEach(event => {
let methodName = event[0];
event.shift();
let integrationOptions = event[0].message.integrations;
for (let i = 0; i < object.clientIntegrationObjects.length; i++) {
if (
integrationOptions[object.clientIntegrationObjects[i].name] ||
(integrationOptions[object.clientIntegrationObjects[i].name] ==
undefined &&
integrationOptions["All"])
) {
try {
object.clientIntegrationObjects[i][methodName](...event);
} catch (error) {
handleError(error);
}
}
}
});
object.toBeProcessedByIntegrationArray = [];
}
}
pause(time) {
return new Promise(resolve => {
setTimeout(resolve, time);
});
}
isInitialized(instance, time = 0) {
return new Promise(resolve => {
if (instance.isLoaded()) {
this.successfullyLoadedIntegration.push(instance);
return resolve(this);
}
if (time >= MAX_WAIT_FOR_INTEGRATION_LOAD) {
logger.debug("====max wait over====");
this.failedToBeLoadedIntegration.push(instance);
return resolve(this);
}
this.pause(INTEGRATION_LOAD_CHECK_INTERVAL).then(() => {
return this.isInitialized(
instance,
time + INTEGRATION_LOAD_CHECK_INTERVAL
).then(resolve);
});
});
}
/**
* Process page params and forward to page call
*
* @param {*} category
* @param {*} name
* @param {*} properties
* @param {*} options
* @param {*} callback
* @memberof Analytics
*/
page(category, name, properties, options, callback) {
if (typeof options == "function") (callback = options), (options = null);
if (typeof properties == "function")
(callback = properties), (options = properties = null);
if (typeof name == "function")
(callback = name), (options = properties = name = null);
if (typeof category === "object")
(options = name), (properties = category), (name = category = null);
if (typeof name === "object")
(options = properties), (properties = name), (name = null);
if (typeof category === "string" && typeof name !== "string")
(name = category), (category = null);
this.processPage(category, name, properties, options, callback);
}
/**
* Process track params and forward to track call
*
* @param {*} event
* @param {*} properties
* @param {*} options
* @param {*} callback
* @memberof Analytics
*/
track(event, properties, options, callback) {
if (typeof options == "function") (callback = options), (options = null);
if (typeof properties == "function")
(callback = properties), (options = null), (properties = null);
this.processTrack(event, properties, options, callback);
}
/**
* Process identify params and forward to indentify call
*
* @param {*} userId
* @param {*} traits
* @param {*} options
* @param {*} callback
* @memberof Analytics
*/
identify(userId, traits, options, callback) {
if (typeof options == "function") (callback = options), (options = null);
if (typeof traits == "function")
(callback = traits), (options = null), (traits = null);
if (typeof userId == "object")
(options = traits), (traits = userId), (userId = this.userId);
this.processIdentify(userId, traits, options, callback);
}
/**
* Send page call to Rudder BE and to initialized integrations
*
* @param {*} category
* @param {*} name
* @param {*} properties
* @param {*} options
* @param {*} callback
* @memberof Analytics
*/
processPage(category, name, properties, options, callback) {
let rudderElement = new RudderElementBuilder().setType("page").build();
if (name) {
rudderElement["message"]["name"] = name;
}
if (!properties) {
properties = {};
}
if (category) {
properties["category"] = category;
}
if (properties) {
rudderElement["message"]["properties"] = this.getPageProperties(
properties
); //properties;
}
this.trackPage(rudderElement, options, callback);
}
/**
* Send track call to Rudder BE and to initialized integrations
*
* @param {*} event
* @param {*} properties
* @param {*} options
* @param {*} callback
* @memberof Analytics
*/
processTrack(event, properties, options, callback) {
let rudderElement = new RudderElementBuilder().setType("track").build();
if (event) {
rudderElement.setEventName(event);
}
if (properties) {
rudderElement.setProperty(properties);
} else {
rudderElement.setProperty({});
}
this.trackEvent(rudderElement, options, callback);
}
/**
* Send identify call to Rudder BE and to initialized integrations
*
* @param {*} userId
* @param {*} traits
* @param {*} options
* @param {*} callback
* @memberof Analytics
*/
processIdentify(userId, traits, options, callback) {
if (userId && this.userId && userId !== this.userId) {
this.reset();
}
this.userId = userId;
this.storage.setUserId(this.userId);
let rudderElement = new RudderElementBuilder().setType("identify").build();
if (traits) {
for (let key in traits) {
this.userTraits[key] = traits[key];
}
this.storage.setUserTraits(this.userTraits);
}
this.identifyUser(rudderElement, options, callback);
}
/**
* Identify call supporting rudderelement from builder
*
* @param {*} rudderElement
* @param {*} callback
* @memberof Analytics
*/
identifyUser(rudderElement, options, callback) {
if (rudderElement["message"]["userId"]) {
this.userId = rudderElement["message"]["userId"];
this.storage.setUserId(this.userId);
}
if (
rudderElement &&
rudderElement["message"] &&
rudderElement["message"]["context"] &&
rudderElement["message"]["context"]["traits"]
) {
this.userTraits = Object.assign(
{},
rudderElement["message"]["context"]["traits"]
);
this.storage.setUserTraits(this.userTraits);
}
this.processAndSendDataToDestinations(
"identify",
rudderElement,
options,
callback
);
}
/**
* Page call supporting rudderelement from builder
*
* @param {*} rudderElement
* @param {*} callback
* @memberof Analytics
*/
trackPage(rudderElement, options, callback) {
this.processAndSendDataToDestinations(
"page",
rudderElement,
options,
callback
);
}
/**
* Track call supporting rudderelement from builder
*
* @param {*} rudderElement
* @param {*} callback
* @memberof Analytics
*/
trackEvent(rudderElement, options, callback) {
this.processAndSendDataToDestinations(
"track",
rudderElement,
options,
callback
);
}
/**
* Process and send data to destinations along with rudder BE
*
* @param {*} type
* @param {*} rudderElement
* @param {*} callback
* @memberof Analytics
*/
processAndSendDataToDestinations(type, rudderElement, options, callback) {
try {
if (!this.anonymousId) {
this.anonymousId = generateUUID();
this.storage.setAnonymousId(this.anonymousId);
}
rudderElement["message"]["context"]["traits"] = Object.assign(
{},
this.userTraits
);
console.log("anonymousId: ", this.anonymousId);
rudderElement["message"]["anonymousId"] = this.anonymousId;
rudderElement["message"]["userId"] = this.userId;
if (options) {
this.processOptionsParam(rudderElement, options);
}
logger.debug(JSON.stringify(rudderElement));
var integrations = rudderElement.message.integrations;
//try to first send to all integrations, if list populated from BE
if (this.clientIntegrationObjects) {
this.clientIntegrationObjects.forEach(obj => {
logger.debug("called in normal flow");
if (
integrations[obj.name] ||
(integrations[obj.name] == undefined && integrations["All"])
) {
obj[type](rudderElement);
}
});
}
if (!this.clientIntegrationObjects) {
logger.debug("pushing in replay queue");
//new event processing after analytics initialized but integrations not fetched from BE
this.toBeProcessedByIntegrationArray.push([type, rudderElement]);
}
// self analytics process
enqueue.call(this, rudderElement, type);
logger.debug(type + " is called ");
if (callback) {
callback();
}
} catch (error) {
handleError(error);
}
}
/**
* process options parameter
*
* @param {*} rudderElement
* @param {*} options
* @memberof Analytics
*/
processOptionsParam(rudderElement, options) {
var toplevelElements = ["integrations", "anonymousId", "originalTimestamp"];
for (let key in options) {
if (toplevelElements.includes(key)) {
rudderElement.message[key] = options[key];
//special handle for ananymousId as transformation expects anonymousId in traits.
/* if (key === "anonymousId") {
rudderElement.message.context.traits["anonymousId"] = options[key];
} */
} else {
if (key !== "context")
rudderElement.message.context[key] = options[key];
else {
for (let k in options[key]) {
rudderElement.message.context[k] = options[key][k];
}
}
}
}
}
getPageProperties(properties) {
let defaultPageProperties = getDefaultPageProperties();
for (let key in defaultPageProperties) {
if (properties[key] === undefined) {
properties[key] = defaultPageProperties[key];
}
}
return properties;
}
/**
* Clear user information
*
* @memberof Analytics
*/
reset() {
this.userId = "";
this.userTraits = {};
this.anonymousId = "";
this.storage.clear();
}
/**
* Call control pane to get client configs
*
* @param {*} writeKey
* @memberof Analytics
*/
load(writeKey, serverUrl, options) {
if (!writeKey || !serverUrl || serverUrl.length == 0) {
handleError({
message: "Unable to load due to wrong writeKey or serverUrl"
});
throw Error("failed to initialize");
}
if (options && options.logLevel) {
logger.setLogLevel(options.logLevel);
}
logger.debug("inside load ");
this.eventRepository.writeKey = writeKey;
if (serverUrl) {
this.eventRepository.url = serverUrl;
}
getJSONTrimmed(this, CONFIG_URL, writeKey, this.processResponse);
}
}
if (process.browser) {
window.addEventListener(
"error",
function(e) {
handleError(e);
},
true
);
}
let instance = new Analytics();
if (process.browser) {
let eventsPushedAlready =
!!window.rudderanalytics &&
window.rudderanalytics.push == Array.prototype.push;
let methodArg = window.rudderanalytics ? window.rudderanalytics[0] : [];
if (methodArg.length > 0 && methodArg[0] == "load") {
let method = methodArg[0];
methodArg.shift();
instance[method](...methodArg);
}
if (eventsPushedAlready) {
for (let i = 1; i < window.rudderanalytics.length; i++) {
instance.toBeProcessedArray.push(window.rudderanalytics[i]);
}
for (let i = 0; i < instance.toBeProcessedArray.length; i++) {
let event = [...instance.toBeProcessedArray[i]];
let method = event[0];
event.shift();
instance[method](...event);
}
instance.toBeProcessedArray = [];
}
}
let identify = instance.identify.bind(instance);
let page = instance.page.bind(instance);
let track = instance.track.bind(instance);
let reset = instance.reset.bind(instance);
let load = instance.load.bind(instance);
let initialized = (instance.initialized = true);
export { initialized, page, track, load, identify, reset };