-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathBrowserClient.ts
More file actions
367 lines (338 loc) · 14 KB
/
BrowserClient.ts
File metadata and controls
367 lines (338 loc) · 14 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
365
366
367
import {
AutoEnvAttributes,
base64UrlEncode,
BasicLogger,
cancelableTimedPromise,
Configuration,
Encoding,
FlagManager,
Hook,
internal,
LDClientImpl,
LDContext,
LDEmitter,
LDEmitterEventName,
LDFlagValue,
LDHeaders,
LDIdentifyResult,
LDPluginEnvironmentMetadata,
Platform,
} from '@launchdarkly/js-client-sdk-common';
import { getHref } from './BrowserApi';
import BrowserDataManager from './BrowserDataManager';
import { BrowserIdentifyOptions as LDIdentifyOptions } from './BrowserIdentifyOptions';
import { registerStateDetection } from './BrowserStateDetector';
import GoalManager from './goals/GoalManager';
import { Goal, isClick } from './goals/Goals';
import {
LDClient,
LDWaitForInitializationComplete,
LDWaitForInitializationFailed,
LDWaitForInitializationOptions,
LDWaitForInitializationResult,
LDWaitForInitializationTimeout,
} from './LDClient';
import { LDPlugin } from './LDPlugin';
import validateBrowserOptions, { BrowserOptions, filterToBaseOptionsWithDefaults } from './options';
import BrowserPlatform from './platform/BrowserPlatform';
class BrowserClientImpl extends LDClientImpl {
private readonly _goalManager?: GoalManager;
private readonly _plugins?: LDPlugin[];
private _initializedPromise?: Promise<LDWaitForInitializationResult>;
private _initResolve?: (result: LDWaitForInitializationResult) => void;
private _initializeResult?: 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;
super(
clientSideId,
autoEnvAttributes,
platform,
baseOptionsWithDefaults,
(
flagManager: FlagManager,
configuration: Configuration,
baseHeaders: LDHeaders,
emitter: LDEmitter,
diagnosticsManager?: internal.DiagnosticsManager,
) =>
new BrowserDataManager(
platform,
flagManager,
clientSideId,
configuration,
validatedBrowserOptions,
() => ({
pathGet(encoding: Encoding, _plainContextString: string): string {
return `/sdk/evalx/${clientSideId}/contexts/${base64UrlEncode(_plainContextString, encoding)}`;
},
pathReport(_encoding: Encoding, _plainContextString: string): string {
return `/sdk/evalx/${clientSideId}/context`;
},
pathPing(_encoding: Encoding, _plainContextString: string): string {
// Note: if you are seeing this error, it is a coding error. This DataSourcePaths implementation is for polling endpoints. /ping is not currently
// used in a polling situation. It is probably the case that this was called by streaming logic erroneously.
throw new Error('Ping for polling unsupported.');
},
}),
() => ({
pathGet(encoding: Encoding, _plainContextString: string): string {
return `/eval/${clientSideId}/${base64UrlEncode(_plainContextString, encoding)}`;
},
pathReport(_encoding: Encoding, _plainContextString: string): string {
return `/eval/${clientSideId}`;
},
pathPing(_encoding: Encoding, _plainContextString: string): string {
return `/ping/${clientSideId}`;
},
}),
baseHeaders,
emitter,
diagnosticsManager,
),
{
analyticsEventPath: `/events/bulk/${clientSideId}`,
diagnosticEventPath: `/events/diagnostic/${clientSideId}`,
includeAuthorizationHeader: false,
highTimeoutThreshold: 5,
userAgentHeaderName: 'x-launchdarkly-user-agent',
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._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 || [],
);
}
override async identify(context: LDContext, identifyOptions?: LDIdentifyOptions): Promise<void> {
return super.identify(context, identifyOptions);
}
override async identifyResult(
context: LDContext,
identifyOptions?: LDIdentifyOptions,
): Promise<LDIdentifyResult> {
const identifyOptionsWithUpdatedDefaults = {
...identifyOptions,
};
if (identifyOptions?.sheddable === undefined) {
identifyOptionsWithUpdatedDefaults.sheddable = true;
}
const res = await super.identifyResult(context, identifyOptionsWithUpdatedDefaults);
if (res.status === 'completed') {
this._initializeResult = { status: 'complete' };
this._initResolve?.(this._initializeResult);
} else if (res.status === 'error') {
this._initializeResult = { status: 'failed', error: res.error };
this._initResolve?.(this._initializeResult);
}
this._goalManager?.startTracking();
return res;
}
waitForInitialization(
options?: LDWaitForInitializationOptions,
): Promise<LDWaitForInitializationResult> {
const timeout = options?.timeout ?? 5;
// If initialization has already completed (successfully or failed), return the result immediately.
if (this._initializeResult) {
return Promise.resolve(this._initializeResult);
}
// It waitForInitialization was previously called, then return the promise with a timeout.
// This condition should only be triggered if waitForInitialization was called multiple times.
if (this._initializedPromise) {
return this._promiseWithTimeout(this._initializedPromise, timeout);
}
if (!this._initializedPromise) {
this._initializedPromise = new Promise((resolve) => {
this._initResolve = resolve;
});
}
return this._promiseWithTimeout(this._initializedPromise, timeout);
}
/**
* Apply a timeout promise to a base promise. This is for use with waitForInitialization.
*
* @param basePromise The promise to race against a timeout.
* @param timeout The timeout in seconds.
* @param logger A logger to log when the timeout expires.
* @returns
*/
private _promiseWithTimeout(
basePromise: Promise<LDWaitForInitializationResult>,
timeout: number,
): Promise<LDWaitForInitializationResult> {
const cancelableTimeout = cancelableTimedPromise(timeout, 'waitForInitialization');
return Promise.race([
basePromise.then((res: LDWaitForInitializationResult) => {
cancelableTimeout.cancel();
return res;
}),
cancelableTimeout.promise
// If the promise resolves without error, then the initialization completed successfully.
// NOTE: this should never return as the resolution would only be triggered by the basePromise
// being resolved.
.then(() => ({ status: 'complete' }) as LDWaitForInitializationComplete)
.catch(() => ({ status: 'timeout' }) as LDWaitForInitializationTimeout),
]).catch((reason) => {
this.logger?.error(reason.message);
return { status: 'failed', error: reason as Error } as LDWaitForInitializationFailed;
});
}
setStreaming(streaming?: boolean): void {
// With FDv2 we may want to consider if we support connection mode directly.
// Maybe with an extension to connection mode for 'automatic'.
const browserDataManager = this.dataManager as BrowserDataManager;
browserDataManager.setForcedStreaming(streaming);
}
private _updateAutomaticStreamingState() {
const browserDataManager = this.dataManager as BrowserDataManager;
// This will need changed if support for listening to individual flag change
// events it added.
browserDataManager.setAutomaticStreamingState(!!this.emitter.listenerCount('change'));
}
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,
autoEnvAttributes: AutoEnvAttributes,
options: BrowserOptions = {},
overridePlatform?: Platform,
): LDClient {
const impl = new BrowserClientImpl(clientSideId, autoEnvAttributes, options, overridePlatform);
// 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,
};
impl.registerPlugins(client);
return client;
}