-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathBrowserClient.ts
More file actions
364 lines (325 loc) · 13.1 KB
/
BrowserClient.ts
File metadata and controls
364 lines (325 loc) · 13.1 KB
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
import {
AutoEnvAttributes,
BasicLogger,
BROWSER_DATA_SYSTEM_DEFAULTS,
browserFdv1Endpoints,
Configuration,
FlagManager,
Hook,
internal,
LDClientImpl,
LDContext,
LDEmitter,
LDEmitterEventName,
LDFlagValue,
LDHeaders,
LDIdentifyResult,
LDPluginEnvironmentMetadata,
LDWaitForInitializationOptions,
LDWaitForInitializationResult,
Platform,
readFlagsFromBootstrap,
safeRegisterDebugOverridePlugins,
} from '@launchdarkly/js-client-sdk-common';
import { getHref } from './BrowserApi';
import BrowserDataManager from './BrowserDataManager';
import BrowserFDv2DataManager from './BrowserFDv2DataManager';
import { BrowserIdentifyOptions as LDIdentifyOptions } from './BrowserIdentifyOptions';
import { registerStateDetection } from './BrowserStateDetector';
import GoalManager from './goals/GoalManager';
import { Goal, isClick } from './goals/Goals';
import { LDClient, LDStartOptions } from './LDClient';
import { LDPlugin } from './LDPlugin';
import validateBrowserOptions, { BrowserOptions, filterToBaseOptionsWithDefaults } from './options';
import BrowserPlatform from './platform/BrowserPlatform';
import { getAllStorageKeys } from './platform/LocalStorage';
class BrowserClientImpl extends LDClientImpl {
private readonly _goalManager?: GoalManager;
private readonly _plugins?: LDPlugin[];
private _initialContext?: LDContext;
// NOTE: This also keeps track of when we tried to initialize the client.
private _startPromise?: Promise<LDWaitForInitializationResult>;
constructor(
clientSideId: string,
autoEnvAttributes: AutoEnvAttributes,
options: BrowserOptions = {},
overridePlatform?: Platform,
) {
const { logger: customLogger, debug } = options;
// Overrides the default logger from the common implementation.
const logger =
customLogger ??
new BasicLogger({
destination: {
// eslint-disable-next-line no-console
debug: console.debug,
// eslint-disable-next-line no-console
info: console.info,
// eslint-disable-next-line no-console
warn: console.warn,
// eslint-disable-next-line no-console
error: console.error,
},
level: debug ? 'debug' : 'info',
});
// TODO: Use the already-configured baseUri from the SDK config. SDK-560
const baseUrl = options.baseUri ?? 'https://clientsdk.launchdarkly.com';
const platform = overridePlatform ?? new BrowserPlatform(logger, options);
// Only the browser-specific options are in validatedBrowserOptions.
const validatedBrowserOptions = validateBrowserOptions(options, logger);
// The base options are in baseOptionsWithDefaults.
const baseOptionsWithDefaults = filterToBaseOptionsWithDefaults({ ...options, logger });
const { eventUrlTransformer } = validatedBrowserOptions;
const endpoints = browserFdv1Endpoints(clientSideId);
const dataManagerFactory = (
flagManager: FlagManager,
configuration: Configuration,
baseHeaders: LDHeaders,
emitter: LDEmitter,
diagnosticsManager?: internal.DiagnosticsManager,
) =>
configuration.dataSystem
? new BrowserFDv2DataManager(
platform,
flagManager,
clientSideId,
configuration,
baseHeaders,
emitter,
)
: new BrowserDataManager(
platform,
flagManager,
clientSideId,
configuration,
validatedBrowserOptions,
endpoints.polling,
endpoints.streaming,
baseHeaders,
emitter,
diagnosticsManager,
);
super(clientSideId, autoEnvAttributes, platform, baseOptionsWithDefaults, dataManagerFactory, {
// This logic is derived from https://github.com/launchdarkly/js-sdk-common/blob/main/src/PersistentFlagStore.js
getLegacyStorageKeys: () =>
getAllStorageKeys().filter((key) => key.startsWith(`ld:${clientSideId}:`)),
analyticsEventPath: `/events/bulk/${clientSideId}`,
diagnosticEventPath: `/events/diagnostic/${clientSideId}`,
includeAuthorizationHeader: false,
highTimeoutThreshold: 5,
userAgentHeaderName: 'x-launchdarkly-user-agent',
dataSystemDefaults: BROWSER_DATA_SYSTEM_DEFAULTS,
trackEventModifier: (event: internal.InputCustomEvent) =>
new internal.InputCustomEvent(
event.context,
event.key,
event.data,
event.metricValue,
event.samplingRatio,
eventUrlTransformer(getHref()),
),
getImplementationHooks: (environmentMetadata: LDPluginEnvironmentMetadata) =>
internal.safeGetHooks(logger, environmentMetadata, validatedBrowserOptions.plugins),
credentialType: 'clientSideId',
});
this.setEventSendingEnabled(true, false);
this.dataManager.setFlushCallback?.(() => this.flush());
this._plugins = validatedBrowserOptions.plugins;
if (validatedBrowserOptions.fetchGoals) {
this._goalManager = new GoalManager(
clientSideId,
platform.requests,
baseUrl,
(err) => {
// TODO: May need to emit. SDK-561
logger.error(err.message);
},
(url: string, goal: Goal) => {
const context = this.getInternalContext();
if (!context) {
return;
}
const transformedUrl = eventUrlTransformer(url);
if (isClick(goal)) {
this.sendEvent({
kind: 'click',
url: transformedUrl,
samplingRatio: 1,
key: goal.key,
creationDate: Date.now(),
context,
selector: goal.selector,
});
} else {
this.sendEvent({
kind: 'pageview',
url: transformedUrl,
samplingRatio: 1,
key: goal.key,
creationDate: Date.now(),
context,
});
}
},
);
// This is intentionally not awaited. If we want to add a "goalsready" event, or
// "waitForGoalsReady", then we would make an async immediately invoked function expression
// which emits the event, and assign its promise to a member. The "waitForGoalsReady" function
// would return that promise.
this._goalManager.initialize();
if (validatedBrowserOptions.automaticBackgroundHandling) {
registerStateDetection(() => this.flush());
}
}
}
registerPlugins(client: LDClient): void {
internal.safeRegisterPlugins(
this.logger,
this.environmentMetadata,
client,
this._plugins || [],
);
const override = this.getDebugOverrides();
if (override) {
safeRegisterDebugOverridePlugins(this.logger, override, this._plugins || []);
}
}
setInitialContext(context: LDContext): void {
this._initialContext = context;
}
override async identify(context: LDContext, identifyOptions?: LDIdentifyOptions): Promise<void> {
return super.identify(context, identifyOptions);
}
override async identifyResult(
context: LDContext,
identifyOptions?: LDIdentifyOptions,
): Promise<LDIdentifyResult> {
if (!this._startPromise) {
this.logger.error(
'Client must be started before it can identify a context, did you forget to call start()?',
);
return { status: 'error', error: new Error('Identify called before start') };
}
const identifyOptionsWithUpdatedDefaults = {
...identifyOptions,
};
if (identifyOptions?.sheddable === undefined) {
identifyOptionsWithUpdatedDefaults.sheddable = true;
}
const res = await super.identifyResult(context, identifyOptionsWithUpdatedDefaults);
this._goalManager?.startTracking();
return res;
}
start(options?: LDStartOptions): Promise<LDWaitForInitializationResult> {
if (this.initializeResult) {
return Promise.resolve(this.initializeResult);
}
if (this._startPromise) {
return this._startPromise;
}
if (!this._initialContext) {
this.logger.error('Initial context not set');
return Promise.resolve({ status: 'failed', error: new Error('Initial context not set') });
}
// When we get to this point, we assume this is the first time that start is being
// attempted. This line should only be called once during the lifetime of the client.
const identifyOptions = {
...(options?.identifyOptions ?? {}),
// Initial identify operations are not sheddable.
sheddable: false,
};
// If the bootstrap data is provided in the start options, and the identify options do not have bootstrap data,
// then use the bootstrap data from the start options.
if (options?.bootstrap && !identifyOptions.bootstrap) {
identifyOptions.bootstrap = options.bootstrap;
}
if (identifyOptions?.bootstrap) {
try {
if (!identifyOptions.bootstrapParsed) {
identifyOptions.bootstrapParsed = readFlagsFromBootstrap(
this.logger,
identifyOptions.bootstrap,
);
}
this.presetFlags(identifyOptions.bootstrapParsed!);
} catch (error) {
this.logger.error('Failed to bootstrap data', error);
}
}
if (!this.initializedPromise) {
this.initializedPromise = new Promise((resolve) => {
this.initResolve = resolve;
});
}
this._startPromise = this.promiseWithTimeout(this.initializedPromise!, options?.timeout ?? 5);
this.identifyResult(this._initialContext!, identifyOptions);
return this._startPromise;
}
setStreaming(streaming?: boolean): void {
this.dataManager.setForcedStreaming?.(streaming);
}
private _updateAutomaticStreamingState() {
const hasListeners = this.emitter
.eventNames()
.some((name) => name.startsWith('change:') || name === 'change');
this.dataManager.setAutomaticStreamingState?.(hasListeners);
}
override on(eventName: LDEmitterEventName, listener: Function): void {
super.on(eventName, listener);
this._updateAutomaticStreamingState();
}
override off(eventName: LDEmitterEventName, listener: Function): void {
super.off(eventName, listener);
this._updateAutomaticStreamingState();
}
}
export function makeClient(
clientSideId: string,
initialContext: LDContext,
autoEnvAttributes: AutoEnvAttributes,
options: BrowserOptions = {},
overridePlatform?: Platform,
): LDClient {
const impl = new BrowserClientImpl(clientSideId, autoEnvAttributes, options, overridePlatform);
impl.setInitialContext(initialContext);
// Return a PIMPL style implementation. This decouples the interface from the interface of the implementation.
// In the future we should consider updating the common SDK code to not use inheritance and instead compose
// the leaf-implementation.
// The purpose for this in the short-term is to have a signature for identify that is different than the class implementation.
// Using an object with PIMPL here also allows us to completely hide the underlying implementation, where with a class
// it is trivial to access what should be protected (or even private) fields.
const client: LDClient = {
variation: (key: string, defaultValue?: LDFlagValue) => impl.variation(key, defaultValue),
variationDetail: (key: string, defaultValue?: LDFlagValue) =>
impl.variationDetail(key, defaultValue),
boolVariation: (key: string, defaultValue: boolean) => impl.boolVariation(key, defaultValue),
boolVariationDetail: (key: string, defaultValue: boolean) =>
impl.boolVariationDetail(key, defaultValue),
numberVariation: (key: string, defaultValue: number) => impl.numberVariation(key, defaultValue),
numberVariationDetail: (key: string, defaultValue: number) =>
impl.numberVariationDetail(key, defaultValue),
stringVariation: (key: string, defaultValue: string) => impl.stringVariation(key, defaultValue),
stringVariationDetail: (key: string, defaultValue: string) =>
impl.stringVariationDetail(key, defaultValue),
jsonVariation: (key: string, defaultValue: unknown) => impl.jsonVariation(key, defaultValue),
jsonVariationDetail: (key: string, defaultValue: unknown) =>
impl.jsonVariationDetail(key, defaultValue),
track: (key: string, data?: any, metricValue?: number) => impl.track(key, data, metricValue),
on: (key: LDEmitterEventName, callback: (...args: any[]) => void) => impl.on(key, callback),
off: (key: LDEmitterEventName, callback: (...args: any[]) => void) => impl.off(key, callback),
flush: () => impl.flush(),
setStreaming: (streaming?: boolean) => impl.setStreaming(streaming),
identify: (pristineContext: LDContext, identifyOptions?: LDIdentifyOptions) =>
impl.identifyResult(pristineContext, identifyOptions),
getContext: () => impl.getContext(),
close: () => impl.close(),
allFlags: () => impl.allFlags(),
addHook: (hook: Hook) => impl.addHook(hook),
waitForInitialization: (waitOptions?: LDWaitForInitializationOptions) =>
impl.waitForInitialization(waitOptions),
logger: impl.logger,
start: (startOptions?: LDStartOptions) => impl.start(startOptions),
};
impl.registerPlugins(client);
return client;
}