-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcallbackManager.ts
82 lines (74 loc) · 2.69 KB
/
callbackManager.ts
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
import { SdkBase } from './sdkBase';
import { Identity } from './Identity';
import { Logger } from './sdk/logger';
export enum EventType {
InitCompleted = 'InitCompleted',
IdentityUpdated = 'IdentityUpdated',
SdkLoaded = 'SdkLoaded',
OptoutReceived = 'OptoutReceived',
NoIdentityAvailable = 'NoIdentityAvailable',
}
export type CallbackPayload = SdkLoadedPayload | PayloadWithIdentity;
export type CallbackHandler = (event: EventType, payload: CallbackPayload) => void;
export type SdkLoadedPayload = Record<string, never>;
export type PayloadWithIdentity = {
identity: Identity | null;
};
export class CallbackManager {
private _getIdentity: () => Identity | null | undefined;
private _logger: Logger;
private _sdk: SdkBase;
private _productName: string;
constructor(
sdk: SdkBase,
productName: string,
getIdentity: () => Identity | null | undefined,
logger: Logger
) {
this._productName = productName;
this._logger = logger;
this._getIdentity = getIdentity;
this._sdk = sdk;
this._sdk.callbacks.push = this.callbackPushInterceptor.bind(this);
}
private static _sentSdkLoaded: Record<string, boolean> = {};
private _sentInit = false;
private callbackPushInterceptor(...args: CallbackHandler[]) {
for (const c of args) {
if (CallbackManager._sentSdkLoaded[this._productName])
this.safeRunCallback(c, EventType.SdkLoaded, {});
if (this._sentInit)
this.safeRunCallback(c, EventType.InitCompleted, {
identity: this._getIdentity() ?? null,
});
}
return Array.prototype.push.apply(this._sdk.callbacks, args);
}
public runCallbacks(event: EventType, payload: CallbackPayload) {
if (event === EventType.InitCompleted) this._sentInit = true;
if (event === EventType.SdkLoaded) CallbackManager._sentSdkLoaded[this._productName] = true;
// if SDK has not been loaded yet, callbacks should not run
if (!CallbackManager._sentSdkLoaded[this._productName]) return;
const enrichedPayload = {
...payload,
identity: this._getIdentity() ?? null,
};
if (event === EventType.NoIdentityAvailable && enrichedPayload.identity) {
enrichedPayload.identity = null;
}
for (const callback of this._sdk.callbacks) {
this.safeRunCallback(callback, event, enrichedPayload);
}
}
private safeRunCallback(callback: CallbackHandler, event: EventType, payload: CallbackPayload) {
if (typeof callback === 'function') {
try {
callback(event, payload);
} catch (exception) {
this._logger.warn('SDK callback threw an exception', exception);
}
} else {
this._logger.warn("An SDK callback was supplied which isn't a function.");
}
}
}