@configdirector/client-sdk 1.5.1 → 1.6.0
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/README.md +28 -0
- package/dist/DefaultConfigDirectorClient-D-Dl3XYG.cjs +5 -0
- package/dist/DefaultConfigDirectorClient-a018lfK_.mjs +6 -0
- package/dist/DefaultConfigDirectorClient-a018lfK_.mjs.map +1 -0
- package/dist/configdirector-client-testing.cjs +1 -0
- package/dist/configdirector-client-testing.d.cts +119 -0
- package/dist/configdirector-client-testing.d.cts.map +1 -0
- package/dist/configdirector-client-testing.d.mts +119 -0
- package/dist/configdirector-client-testing.d.mts.map +1 -0
- package/dist/configdirector-client-testing.mjs +2 -0
- package/dist/configdirector-client-testing.mjs.map +1 -0
- package/dist/configdirector-client.cjs +1 -5
- package/dist/configdirector-client.d.cts +2 -301
- package/dist/configdirector-client.d.cts.map +1 -1
- package/dist/configdirector-client.d.mts +2 -301
- package/dist/configdirector-client.d.mts.map +1 -1
- package/dist/configdirector-client.mjs +1 -5
- package/dist/configdirector-client.mjs.map +1 -1
- package/dist/errors-BOgYEeJ6.d.cts +307 -0
- package/dist/errors-BOgYEeJ6.d.cts.map +1 -0
- package/dist/errors-zagImFi0.d.mts +307 -0
- package/dist/errors-zagImFi0.d.mts.map +1 -0
- package/package.json +19 -2
|
@@ -1,293 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
type EventsRecord = Record<EventType, any>;
|
|
4
|
-
type Handler<TEventsRecord extends EventsRecord, TKey extends keyof TEventsRecord> = (payload: TEventsRecord[TKey]) => void;
|
|
5
|
-
interface EventProvider<TEventsRecord extends EventsRecord> {
|
|
6
|
-
on<TName extends keyof TEventsRecord>(name: TName, handler: Handler<TEventsRecord, TName>): void;
|
|
7
|
-
off<TName extends keyof TEventsRecord>(name: TName, handler?: Handler<TEventsRecord, TName>): void;
|
|
8
|
-
clear(): void;
|
|
9
|
-
}
|
|
10
|
-
//#endregion
|
|
11
|
-
//#region ../shared/src/types.d.ts
|
|
12
|
-
type ConfigEnumLikeType = {
|
|
13
|
-
[key: string]: string | number;
|
|
14
|
-
};
|
|
15
|
-
type ConfigValueType = string | number | boolean | object | ConfigEnumLikeType;
|
|
16
|
-
type ConfigDirectorLoggingLevel = "debug" | "info" | "warn" | "error" | "off";
|
|
17
|
-
interface ConfigDirectorLogger {
|
|
18
|
-
debug(message: string, ...args: any): void;
|
|
19
|
-
info(message: string, ...args: any): void;
|
|
20
|
-
warn(message: string, ...args: any): void;
|
|
21
|
-
error(message: string, ...args: any): void;
|
|
22
|
-
}
|
|
23
|
-
interface ConfigDirectorLogMessageDecorator {
|
|
24
|
-
decorateMessage(message: string): string;
|
|
25
|
-
}
|
|
26
|
-
type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean";
|
|
27
|
-
type ConfigEvaluation = {
|
|
28
|
-
key: string;
|
|
29
|
-
value: ConfigValueType;
|
|
30
|
-
valueId?: string;
|
|
31
|
-
isDefaultValue: boolean;
|
|
32
|
-
reason: EvaluationReason;
|
|
33
|
-
context?: ConfigDirectorContext;
|
|
34
|
-
};
|
|
35
|
-
/**
|
|
36
|
-
* The user's context to be sent to ConfigDirector. This context will be used for targeting
|
|
37
|
-
* rules evaluation.
|
|
38
|
-
*/
|
|
39
|
-
type ConfigDirectorContext = {
|
|
40
|
-
/**
|
|
41
|
-
* The user's identifier. This should be a value that uniquely identifies an application
|
|
42
|
-
* user.
|
|
43
|
-
* In the case of anonymous users, you could generate a UUID or alternatively not provide
|
|
44
|
-
* the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
|
|
45
|
-
* value is used for segmenting users in percentage rollouts, and changes to the {@link id}
|
|
46
|
-
* could result in the user being assigned to a different percentile.
|
|
47
|
-
*/
|
|
48
|
-
id?: string;
|
|
49
|
-
/**
|
|
50
|
-
* The user's display name. This will be shown in the ConfigDirector dashboard and may be
|
|
51
|
-
* used for targeting rules.
|
|
52
|
-
*/
|
|
53
|
-
name?: string;
|
|
54
|
-
/**
|
|
55
|
-
* Any arbitrary traits for the current user. They will be shown in the ConfigDirector
|
|
56
|
-
* dashboard and may be used for targeting rules.
|
|
57
|
-
*/
|
|
58
|
-
traits?: {
|
|
59
|
-
[key: string]: unknown;
|
|
60
|
-
};
|
|
61
|
-
/**
|
|
62
|
-
* Whether or not to treat the context as anonymous during evaluation. When `true`, the
|
|
63
|
-
* context values will be used for targeting rules evaluation but the context will not be
|
|
64
|
-
* persisted and will not appear in the dashboard.
|
|
65
|
-
*
|
|
66
|
-
* @default false
|
|
67
|
-
*/
|
|
68
|
-
anonymous?: boolean;
|
|
69
|
-
};
|
|
70
|
-
/**
|
|
71
|
-
* Metadata about your application. It is recommended you include these values when configuring
|
|
72
|
-
* a ConfigDirector client so that you can use them in targeting rules.
|
|
73
|
-
*/
|
|
74
|
-
type ConfigDirectorMetaContext = {
|
|
75
|
-
appVersion?: string;
|
|
76
|
-
appName?: string;
|
|
77
|
-
};
|
|
78
|
-
type ConnectionMode = "streaming" | "polling";
|
|
79
|
-
//#endregion
|
|
80
|
-
//#region ../js-client-core/src/types.d.ts
|
|
81
|
-
/**
|
|
82
|
-
* Configuration options for the {@link ConfigDirectorClient}
|
|
83
|
-
*/
|
|
84
|
-
type ConfigDirectorClientOptions = {
|
|
85
|
-
/**
|
|
86
|
-
* Application metadata that remains constant through the lifetime of the connection
|
|
87
|
-
*/
|
|
88
|
-
metadata?: ConfigDirectorMetaContext;
|
|
89
|
-
/**
|
|
90
|
-
* Connection options
|
|
91
|
-
*/
|
|
92
|
-
connection?: {
|
|
93
|
-
/**
|
|
94
|
-
* The connection mode to be used, one of `streaming` (default) or `polling`.
|
|
95
|
-
* If set to `streaming`, the connection will remain open and receive updates whenever
|
|
96
|
-
* config state is updated on the ConfigDirector dashboard.
|
|
97
|
-
* When set to `polling`, there will be an initial request to retrieve config state during
|
|
98
|
-
* initialization, and additional requests on a `pollingInterval`.
|
|
99
|
-
*
|
|
100
|
-
* Defaults to `streaming`
|
|
101
|
-
*/
|
|
102
|
-
mode?: ConnectionMode;
|
|
103
|
-
/**
|
|
104
|
-
* The polling interval in _seconds_ when the `mode` is set to `polling`. This option has no
|
|
105
|
-
* effect when the `mode` is set to `streaming`.
|
|
106
|
-
*
|
|
107
|
-
* Defaults to 300 seconds (5 minutes). Values below the minimum of 60 seconds are raised
|
|
108
|
-
* to 60 seconds.
|
|
109
|
-
*/
|
|
110
|
-
pollingInterval?: number;
|
|
111
|
-
/**
|
|
112
|
-
* The timeout, in _milliseconds_, to be used in initialization and when updating the context.
|
|
113
|
-
* If streaming is enabled, the operation (initialization or context update) may still succeed
|
|
114
|
-
* after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
|
|
115
|
-
* If streaming is disabled, if the operation times out, it will not be retried.
|
|
116
|
-
*/
|
|
117
|
-
timeout?: number;
|
|
118
|
-
/**
|
|
119
|
-
* The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
|
|
120
|
-
* proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
|
|
121
|
-
* a proxy for the client SDK.
|
|
122
|
-
*/
|
|
123
|
-
url?: string;
|
|
124
|
-
};
|
|
125
|
-
/**
|
|
126
|
-
* A logger that implements {@link ConfigDirectorLogger}. It defaults to the ConfigDirector console
|
|
127
|
-
* logger set to 'warn' level.
|
|
128
|
-
*
|
|
129
|
-
* The log level of the default logger can be adjusted by creating a default logger with the desired
|
|
130
|
-
* level and providing it in this property:
|
|
131
|
-
* @example
|
|
132
|
-
* import { createClient, createConsoleLogger } from "@configdirector/client-sdk";
|
|
133
|
-
* const client = createClient(
|
|
134
|
-
* "YOUR-SDK-KEY",
|
|
135
|
-
* { logger: createConsoleLogger("debug") },
|
|
136
|
-
* );
|
|
137
|
-
*/
|
|
138
|
-
logger?: ConfigDirectorLogger;
|
|
139
|
-
/**
|
|
140
|
-
* Handlers for hooks/events emitted by the client. Each hook accepts either a single event handler or
|
|
141
|
-
* an array of event handlers.
|
|
142
|
-
*
|
|
143
|
-
* @example
|
|
144
|
-
* import { createClient, createConsoleLogger } from "@configdirector/client-sdk";
|
|
145
|
-
* const client = createClient(
|
|
146
|
-
* "YOUR-SDK-KEY",
|
|
147
|
-
* {
|
|
148
|
-
* hooks: {
|
|
149
|
-
* configEvaluated: (event) => { console.log(event.evaluation); }
|
|
150
|
-
* },
|
|
151
|
-
* },
|
|
152
|
-
* );
|
|
153
|
-
*/
|
|
154
|
-
hooks?: ClientHooks;
|
|
155
|
-
};
|
|
156
|
-
type ClientHooks = {
|
|
157
|
-
clientReady?: HookHandler<"clientReady"> | HookHandler<"clientReady">[];
|
|
158
|
-
configsUpdated?: HookHandler<"configsUpdated"> | HookHandler<"configsUpdated">[];
|
|
159
|
-
contextUpdated?: HookHandler<"contextUpdated"> | HookHandler<"contextUpdated">[];
|
|
160
|
-
configEvaluated?: HookHandler<"configEvaluated"> | HookHandler<"configEvaluated">[];
|
|
161
|
-
connectionError?: HookHandler<"connectionError"> | HookHandler<"connectionError">[];
|
|
162
|
-
};
|
|
163
|
-
type ClientConnectAction = "initialization" | "context update" | "network resume";
|
|
164
|
-
type HookHandler<TEvent extends keyof ClientEvents> = (payload: ClientEvents[TEvent]) => void;
|
|
165
|
-
type ClientEvents = {
|
|
166
|
-
configsUpdated: {
|
|
167
|
-
keys: string[];
|
|
168
|
-
};
|
|
169
|
-
clientReady: {
|
|
170
|
-
action: ClientConnectAction;
|
|
171
|
-
};
|
|
172
|
-
contextUpdated: {
|
|
173
|
-
context: ConfigDirectorContext | undefined;
|
|
174
|
-
};
|
|
175
|
-
configEvaluated: {
|
|
176
|
-
evaluation: ConfigEvaluation;
|
|
177
|
-
};
|
|
178
|
-
connectionError: {
|
|
179
|
-
error: Error;
|
|
180
|
-
};
|
|
181
|
-
};
|
|
182
|
-
type WatchHandler<T extends ConfigValueType> = (message: T) => void;
|
|
183
|
-
/**
|
|
184
|
-
* The ConfigDirector SDK client object.
|
|
185
|
-
*
|
|
186
|
-
* Applications should create a single instance of `ConfigDirectorClient`, and call
|
|
187
|
-
* {@link initialize} during application initialization.
|
|
188
|
-
*
|
|
189
|
-
* After initialization, to update the user's context, so that targeting rules are evaluated
|
|
190
|
-
* with the updated context, call {@link updateContext}.
|
|
191
|
-
*/
|
|
192
|
-
interface ConfigDirectorClient extends EventProvider<ClientEvents> {
|
|
193
|
-
/**
|
|
194
|
-
* Initializes the connection to ConfigDirector to retrieve config evaluations. Until
|
|
195
|
-
* initialization is successful, all flags will return their default value provided to
|
|
196
|
-
* {@link watch} or {@link getValue}.
|
|
197
|
-
*
|
|
198
|
-
* If the connection fails or is interrupted with a transient error (network error,
|
|
199
|
-
* internal server error, etc) the client will continue to attempt to connect. However,
|
|
200
|
-
* if the connection fails with a persistent error, like an invalid SDK key, the client will
|
|
201
|
-
* not attempt to re-connect and an error will be logged to the console or the provided
|
|
202
|
-
* logger.
|
|
203
|
-
*
|
|
204
|
-
* @param context The current user's context to be used for evaluating targeting rules (optional).
|
|
205
|
-
*/
|
|
206
|
-
initialize(context?: ConfigDirectorContext): Promise<void>;
|
|
207
|
-
/**
|
|
208
|
-
* Updates the user's context and re-evaluates all config and flag values based on the new context.
|
|
209
|
-
*
|
|
210
|
-
* @param context The current user's context to be used for evaluating targeting rules (required).
|
|
211
|
-
*/
|
|
212
|
-
updateContext(context: ConfigDirectorContext): Promise<void>;
|
|
213
|
-
/**
|
|
214
|
-
* Returns the current context the client is configured with, or undefined if there is no context.
|
|
215
|
-
*
|
|
216
|
-
* Note that the value returned does not updated immediately after calling {@link updateContext}. Only
|
|
217
|
-
* once the underlying connection was successful or timed out, the current context is updated. This is
|
|
218
|
-
* because while the context update is in progress, configs are still evaluated on the previous context.
|
|
219
|
-
*
|
|
220
|
-
*/
|
|
221
|
-
get context(): ConfigDirectorContext | undefined;
|
|
222
|
-
/**
|
|
223
|
-
* Returns whether or not the client is ready after calling {@link initialize} or {@link updateContext}
|
|
224
|
-
*
|
|
225
|
-
* The definition of ready is that the connection to the server was successful, and config state
|
|
226
|
-
* was received.
|
|
227
|
-
*/
|
|
228
|
-
get isReady(): boolean;
|
|
229
|
-
/**
|
|
230
|
-
* Returns whether or not the client is currently initializing. Upon client creation, it is `false`.
|
|
231
|
-
* It is `true` after calling `initialize` and becomes `false` again once initialization is completed.
|
|
232
|
-
*/
|
|
233
|
-
get isInitializing(): boolean;
|
|
234
|
-
/**
|
|
235
|
-
* Evaluates a config and returns its value based on the current context and targeting rules
|
|
236
|
-
*
|
|
237
|
-
* @returns The evaluated config value, or the `defaultValue` if the config state was unavailable
|
|
238
|
-
* @param configKey The config key to evaluate
|
|
239
|
-
* @param defaultValue The default value to be returned if the config state is unavailable. For
|
|
240
|
-
* example, if the client cannot connect to the server due to network conditions, or if getValue
|
|
241
|
-
* is called before initialization is done.
|
|
242
|
-
*/
|
|
243
|
-
getValue<T extends ConfigValueType>(configKey: string, defaultValue: T): T;
|
|
244
|
-
/**
|
|
245
|
-
* Watches for changes to a a config evaluation value. Whenever the config value changes, the
|
|
246
|
-
* provided callback function will be called with the new value. Changes can happen due to updates
|
|
247
|
-
* to the config in the ConfigDirector dashboard, or if the context is updated via {@link updateContext}.
|
|
248
|
-
*
|
|
249
|
-
* @returns An 'unwatch' function that can be called to remove the subscriber
|
|
250
|
-
*
|
|
251
|
-
* @param configKey The config key to watch
|
|
252
|
-
* @param defaultValue The default value to be referenced if the config state is unavailable
|
|
253
|
-
* @param callback The callback function to be called whenever the config value is updated
|
|
254
|
-
*/
|
|
255
|
-
watch<T extends ConfigValueType>(configKey: string, defaultValue: T, callback: WatchHandler<T>): () => void;
|
|
256
|
-
/**
|
|
257
|
-
* Removes a particular subscriber to the given `configKey`, or all subscribers if no callback
|
|
258
|
-
* is provided.
|
|
259
|
-
*
|
|
260
|
-
* @param configKey The config key to remove subscribers from
|
|
261
|
-
* @param callback The subscriber to be removed. If not provided, all subscribers are removed for
|
|
262
|
-
* the given `configKey`.
|
|
263
|
-
*/
|
|
264
|
-
unwatch<T extends ConfigValueType>(configKey: string, callback?: WatchHandler<T>): void;
|
|
265
|
-
/**
|
|
266
|
-
* Removes all subscribers from all config keys
|
|
267
|
-
*/
|
|
268
|
-
unwatchAll(): void;
|
|
269
|
-
/**
|
|
270
|
-
* Pauses the network connection without clearing event handlers, watch handlers, or config
|
|
271
|
-
* state. Intended for mobile environments where the OS may kill background connections (e.g.
|
|
272
|
-
* when the app is backgrounded on iOS/Android).
|
|
273
|
-
*
|
|
274
|
-
* Call {@link resumeNetwork} to re-establish the connection.
|
|
275
|
-
*/
|
|
276
|
-
pauseNetwork(): void;
|
|
277
|
-
/**
|
|
278
|
-
* Resumes a connection that was paused via {@link pauseNetwork}, using the last context that
|
|
279
|
-
* was provided to {@link initialize} or {@link updateContext}.
|
|
280
|
-
*/
|
|
281
|
-
resumeNetwork(): Promise<void>;
|
|
282
|
-
/**
|
|
283
|
-
* Disposes of the client. All connections are closed, and all event and config key subscribers
|
|
284
|
-
* are removed.
|
|
285
|
-
*
|
|
286
|
-
* Intended to be called when your application shuts down
|
|
287
|
-
*/
|
|
288
|
-
dispose(): void;
|
|
289
|
-
}
|
|
290
|
-
//#endregion
|
|
1
|
+
import { a as ConfigDirectorContext, c as ConfigDirectorLoggingLevel, i as ConfigDirectorClientOptions, l as ConfigValueType, n as ConfigDirectorValidationError, o as ConfigDirectorLogMessageDecorator, r as ConfigDirectorClient, s as ConfigDirectorLogger, t as ConfigDirectorConnectionError } from "./errors-zagImFi0.mjs";
|
|
2
|
+
|
|
291
3
|
//#region ../shared/src/logger.d.ts
|
|
292
4
|
declare class DefaultConsoleLogger implements ConfigDirectorLogger {
|
|
293
5
|
private readonly level;
|
|
@@ -301,17 +13,6 @@ declare class DefaultConsoleLogger implements ConfigDirectorLogger {
|
|
|
301
13
|
protected log(loggerFunction: (...args: any) => void, level: ConfigDirectorLoggingLevel, message: string, ...args: any): void;
|
|
302
14
|
}
|
|
303
15
|
//#endregion
|
|
304
|
-
//#region ../shared/src/errors.d.ts
|
|
305
|
-
declare class ConfigDirectorConnectionError extends Error {
|
|
306
|
-
readonly name: string;
|
|
307
|
-
readonly status?: number;
|
|
308
|
-
constructor(message: string, status?: number);
|
|
309
|
-
}
|
|
310
|
-
declare class ConfigDirectorValidationError extends Error {
|
|
311
|
-
readonly name: string;
|
|
312
|
-
constructor(message: string);
|
|
313
|
-
}
|
|
314
|
-
//#endregion
|
|
315
16
|
//#region src/api.d.ts
|
|
316
17
|
/**
|
|
317
18
|
* Creates a `ConfigDirectorClient` object with the given `clientSdkKey` and optional
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"configdirector-client.d.mts","names":[],"sources":["../../
|
|
1
|
+
{"version":3,"file":"configdirector-client.d.mts","names":[],"sources":["../../shared/src/logger.ts","../src/api.ts"],"mappings":";;;cA+Ba,oBAAA,YAAgC,oBAAA;EAAA,iBAGd,KAAA;EAAA,iBAAoD,SAAA;EAAA,iBAFhE,aAAA;cAEY,KAAA,EAAO,0BAAA,EAA6C,SAAA,EAAW,iCAAA;EAM5F,KAAA,CAAM,OAAA,aAAoB,IAAA;EAI1B,IAAA,CAAK,OAAA,aAAoB,IAAA;EAIzB,IAAA,CAAK,OAAA,aAAoB,IAAA;EAIzB,KAAA,CAAM,OAAA,aAAoB,IAAA;EAAA,UAIhB,GAAA,CAAI,cAAA,MAAoB,IAAA,gBAAoB,KAAA,EAAO,0BAAA,EAA4B,OAAA,aAAoB,IAAA;AAAA;;;;;AAzB/G;;;;;;;;;;;;cCVa,YAAA,GACX,YAAA,UACA,aAAA,GAAgB,2BAAA,KACf,oBAAA;AAAA,cAQU,mBAAA,GACX,KAAA,EAAO,0BAAA,EACP,gBAAA,GAAmB,iCAAA,KAAiC,oBAAA"}
|
|
@@ -1,6 +1,2 @@
|
|
|
1
|
-
var e=class{constructor(){this.handlerMap=new Map}on(e,t){let n=this.handlerMap.get(e);n?n.push(t):this.handlerMap.set(e,[t])}once(e,t){let n=this;function r(i){n.off(e,r),t.apply(n,i)}this.on(e,r)}off(e,t){let n=this.handlerMap.get(e);if(n)if(t){let e=n.indexOf(t);e>=0&&n.splice(e,1)}else this.handlerMap.set(e,[])}clear(){this.handlerMap.clear()}emit(e,t){let n=this.handlerMap.get(e);n&&n.slice().map(e=>e(t))}},t=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},n=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}},r=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},i=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},a=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},o=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}};function s(e){"@babel/helpers - typeof";return s=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},s(e)}function c(e,t){if(s(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(s(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function l(e){var t=c(e,`string`);return s(t)==`symbol`?t:t+``}function u(e,t,n){return(t=l(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function d(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function f(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?d(Object(n),!0).forEach(function(t){u(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):d(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var p=class{constructor(e){var t;this.isFirstChunk=!0,this.bufferedInput=``,this.currentEvent={data:``},this.currentEvent={data:``},this.onEvent=(t=e.onEvent)==null?(()=>{}):t,this.onRetry=e.onRetry,this.onComment=e.onComment}parse(e){let t=e;this.isFirstChunk&&(this.isFirstChunk=!1,t.startsWith(``)?t=t.slice(1):t.startsWith(``)&&(t=t.slice(3)));let n=this.scanLines(this.bufferedInput+t);for(let e of n)this.dispatchLine(e)}finish(){this.bufferedInput=``}scanLines(e){let t=[],n=0,r=0;for(;r<e.length;){let i=e[r];i===`\r`||i===`
|
|
2
|
-
`?(t.push(e.slice(n,r)),i===`\r`&&e[r+1]===`
|
|
3
|
-
`&&r++,r++,n=r):r++}return this.bufferedInput=e.slice(n),t}dispatchLine(e){if(e.startsWith(`:`)){var t;(t=this.onComment)==null||t.call(this,this.extractValue(e,1));return}if(e===``){this.emitEvent();return}this.applyField(this.parseField(e))}emitEvent(){let e=this.currentEvent.data.endsWith(`
|
|
4
|
-
`)?this.currentEvent.data.slice(0,-1):this.currentEvent.data;e!==``&&this.onEvent(f(f({},this.currentEvent),{},{id:this.lastEventId,data:e})),this.currentEvent={data:``}}applyField(e){switch(e.field){case`event`:this.currentEvent.type=e.value;break;case`data`:this.currentEvent.data+=e.value+`
|
|
5
|
-
`;break;case`id`:e.value.includes(`\0`)||(this.lastEventId=e.value);break;case`retry`:if(/^\d+$/.test(e.value)){var t;(t=this.onRetry)==null||t.call(this,Number.parseInt(e.value,10))}break;default:break}}parseField(e){let t=e.indexOf(`:`);return t===-1?{field:e,value:``}:{field:e.slice(0,t),value:this.extractValue(e,t+1)}}extractValue(e,t){return e[t]===` `?e.slice(t+1):e.slice(t)}};let m=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var h=class{constructor(e){var t,n;this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=m.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers=f({Accept:`text/event-stream`},e.headers);let r=e.body;this.body=typeof r==`function`?r:()=>r,this.requestOptions={method:(t=e.method)==null?`GET`:t,mode:e.mode,credentials:e.credentials,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy},this._fetch=(n=e.fetch)==null?((e,t)=>fetch(e,t)):n,this._onError=this.resolveCallback(e.onError,()=>{},`onError`),this._onConnect=this.resolveCallback(e.onConnect,()=>{},`onConnect`),this._onDisconnect=this.resolveCallback(e.onDisconnect,()=>{},`onDisconnect`),this._onMessage=this.resolveCallback(e.onMessage,()=>{},`onMessage`),this._onComment=this.resolveCallback(e.onComment,()=>{},`onComment`),this._shouldReconnect=this.resolveCallback(e.shouldReconnect,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`),this._calculateReconnectDelay=this.resolveCallback(e.calculateReconnectDelay,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`calculateReconnectDelay`)}set onError(e){this._onError=this.resolveCallback(e,()=>{},`onError`)}set onMessage(e){this._onMessage=this.resolveCallback(e,()=>{},`onMessage`)}set onComment(e){this._onComment=this.resolveCallback(e,()=>{},`onComment`)}set onConnect(e){this._onConnect=this.resolveCallback(e,()=>{},`onConnect`)}set onDisconnect(e){this._onDisconnect=this.resolveCallback(e,()=>{},`onDisconnect`)}set shouldReconnect(e){this._shouldReconnect=this.resolveCallback(e,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`)}set calculateReconnectDelay(e){this._calculateReconnectDelay=this.resolveCallback(e,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`shouldReconnect`)}get readyState(){return this._readyState}connect(){this._readyState===m.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=m.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=m.CONNECTING,this._fetch(this.url,f(f({},this.requestOptions),{},{body:this.body(),headers:this.buildRequestHeaders(),signal:this.abortController.signal,cache:`no-store`})).then(e=>this.handleFetchResponse(e)).catch(e=>{if(e.name===`AbortError`||this.abortController.signal.aborted){this.close();return}this._onError(e),this.scheduleReconnect({error:e})})}async handleFetchResponse(e){var t=this;let{body:n,status:a}=e;if(a===204){t.disconnected();return}if(a>=400){t.scheduleReconnect({status:a});return}if(!n)throw new i(`The server response did not have a body`);t._readyState=m.OPEN,t._onConnect(),t.reconnectAttempt=0;let o=new p({onEvent:e=>{typeof e.id==`string`&&(t.lastEventId=e.id),t._onMessage(e)},onComment:e=>t._onComment(e),onRetry:e=>t.serverReconnectionTime=e});await t.readResponseStream(n,o),t.scheduleReconnect({status:a,error:new r(`The server response stream was closed`)})}async readResponseStream(e,t){let n=e.getReader(),r=new TextDecoder,i=!1;for(;!i;){let e=await n.read();e.value&&t.parse(r.decode(e.value,{stream:!0})),i=e.done}t.finish()}disconnected(){clearTimeout(this.reconnectTimeout),this._readyState=m.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return f(f({},this.headers),e)}scheduleReconnect(e){if(this.abortController.signal.aborted)return;clearTimeout(this.reconnectTimeout),this.reconnectAttempt+=1;let t={attempt:this.reconnectAttempt,status:e.status,error:e.error,serverReconnectionTime:this.serverReconnectionTime};if(!this._shouldReconnect(t)){this.disconnected();return}this._readyState=m.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new o(`The calculated reconnect delay is out of range: ${n}. Defaulting to ${this.serverReconnectionTime}`)),n=this.serverReconnectionTime),this.reconnectTimeout=setTimeout(()=>this.initiateConnection(),n)}resolveCallback(e,t,n){if(e==null)return t;if(typeof e!=`function`)throw new a(`${n} must be a function`);return e}};const g=e=>new h(e);var _=class{constructor(t){this.options=t,this.eventEmitter=new e,this.options=t,this.logger=t.logger,this.url=t.resolveUrl(`client/sse/v1`,t.baseUrl)}async connect(e,t){var n=this;n.eventSource&&n.close();let r=new Promise((t,r)=>{n.eventSource=g({url:n.url,method:`POST`,headers:{"Content-Type":`application/json`},fetch:n.options.fetch,body:JSON.stringify({givenContext:e,metaContext:n.options.metaContext,clientSdkKey:n.options.clientSdkKey,instanceId:n.options.instanceId}),onMessage:({data:e})=>{n.dispatchMessage(e)},onConnect:()=>{n.logger.debug(`[StreamingTransport] Connected`),t(n)},shouldReconnect:e=>{let t=!n.isStatusFatal(e.status);if(!t){let t=n.prepareFatalError(e.status,e.error);n.eventEmitter.emit(`connectionError`,t),r(t)}return t},calculateReconnectDelay:e=>{let t=n.options.connectionRetryDelay(e.attempt),r=`[StreamingTransport] Scheduling reconnect attempt #${e.attempt} in ${t}ms.`;return e.attempt<=5?n.logger.info(r):n.logger.warn(r),t},onError:e=>{n.logger.debug(`[StreamingTransport] Error: `,e)},onDisconnect:()=>{n.logger.debug(`[StreamingTransport] Disconnected`)}}),n.eventSource.connect()});return clearTimeout(n.timeoutTimer),n.timeoutTimer=void 0,Promise.race([r,new Promise(e=>{n.timeoutTimer=setTimeout(()=>e(n),t)})]).finally(()=>clearTimeout(n.timeoutTimer))}dispatchMessage(e){try{let t=JSON.parse(e);this.eventEmitter.emit(`configSetReceived`,t)}catch(e){this.logger.error(`[StreamingTransport] Error parsing and dispatching config data update: `,e)}}prepareFatalError(e,n){let r=e==null?0:e;return new t(`${`Connection failed with status: ${e==null?`unknown`:e}.`}${n?` Error: ${n}`:``}. This is an unrecoverable error, will not attempt to reconnect.`,r)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}close(){var e;(e=this.eventSource)==null||e.close(),clearTimeout(this.timeoutTimer)}dispose(){this.close(),this.clear()}};const v=e=>{let t=typeof e;if(t===`object`)try{var n,r;return(n=(r=e.constructor)==null?void 0:r.name)==null?t:n}catch(e){return t}else if(t===`function`)try{let n=e.name;return n?`function: ${n}`:t}catch(e){return t}return t},y=e=>e===`number`||e===`bigint`,b=new Set([`boolean`,`integer`,`float`]),x=(e,t)=>{let n=e.value,r=v(t);if(n==null)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return E(n,t,r,e.valueId);if(typeof t==`string`)return b.has(e.type)?{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`type-mismatch`}:{parsedValue:n,parsedValueId:e.valueId,requestedType:r,usedDefault:!1,reason:`found-match`};if(typeof t==`boolean`&&(e.type===`boolean`||e.type===`string`||e.type===`enum`)){let i=S(n),a=typeof i==`boolean`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-boolean`}}if(y(typeof t)&&e.type===`integer`){let i=C(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}if(y(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=w(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`type-mismatch`}},S=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},C=e=>{let t=T(e);return t==null?void 0:Math.trunc(t)},w=e=>T(e),T=e=>{if(!e||!ee(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},ee=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},E=(e,t,n,r)=>{if(typeof t==`string`)return{parsedValue:e,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`};try{let i=JSON.parse(e);return D(i,t)?{parsedValue:i,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`}:{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`type-mismatch`}}catch(e){return{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`invalid-json`}}},D=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},O={off:-1,error:0,warn:1,info:2,debug:3},k=()=>{let e={year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,timeZoneName:`short`};try{return new Intl.DateTimeFormat(void 0,f(f({},e),{},{fractionalSecondDigits:3}))}catch(t){return new Intl.DateTimeFormat(void 0,e)}};var A=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=k()}debug(e,...t){this.log(console.debug,`debug`,e,...t)}info(e,...t){this.log(console.info,`info`,e,...t)}warn(e,...t){this.log(console.warn,`warn`,e,...t)}error(e,...t){this.log(console.error,`error`,e,...t)}log(e,t,n,...r){if(O[this.level]>=O[t]){var i;e(`[${this.dateFormatter.format(new Date)}] ${(i=this.decorator)==null?void 0:i.decorateMessage(n)}`,...r)}}},j=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const M=(e,t)=>new A(e==null?`warn`:e,t==null?new j:t),N=(e,t)=>new URL(e,t==null?void 0:t.toString()),P=e=>{if(e)try{return new URL(e)}catch(t){throw new n(`Invalid URL '${e}'. Parsing failed: ${t}`)}},F=`https://client-sdk-api.configdirector.com`,I=()=>typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)}),L=`configdirector-sdk:instance-id`,R=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,z=(e,t)=>{let n=t;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return n>>>0},B=(e,t)=>{let n=`configdirector.instanceId.v1|${e}|${t}`,r=z(n,2166136261);return z(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},V=()=>{try{var e;return(e=globalThis.localStorage)==null?void 0:e}catch(e){return}},H=e=>{if(!e||typeof e!=`object`)return!1;let{v:t,id:n,createdAt:r,checksum:i}=e;return t!==1||typeof n!=`string`||typeof i!=`string`||typeof r!=`number`||!Number.isInteger(r)||r<=0||!R.test(n)?!1:i===B(n,r)},U=(e,t)=>{let n;try{n=e.getItem(L)}catch(e){t==null||t.debug(`[ConfigDirectorClient] Could not read the stored instance id, generating a new one`,e);return}if(!n)return;let r;try{r=JSON.parse(n)}catch(e){t==null||t.debug(`[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one`);return}if(!H(r)){t==null||t.debug(`[ConfigDirectorClient] The stored instance id failed validation, generating a new one`);return}let i=Date.now()-r.createdAt;if(i<0||i>=216e5){t==null||t.debug(`[ConfigDirectorClient] The stored instance id has expired, generating a new one`);return}return r.id},W=(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:B(t,r)};try{e.setItem(L,JSON.stringify(i))}catch(e){n==null||n.debug(`[ConfigDirectorClient] Could not persist the instance id`,e)}},G=e=>{let t=V();if(!t)return I();let n=U(t,e);if(n)return n;let r=I();return W(t,r,e),r};var K=class{constructor(){this.fatalError=!1,this.pollingIntervalSeconds=60}clearPollingInterval(){clearInterval(this.pollingInterval)}schedulePollingInterval(e){clearInterval(this.pollingInterval),!(this.pollingIntervalSeconds<=0)&&(this.pollingInterval=setInterval(e,this.pollingIntervalSeconds*1e3))}async handleNonOkResponse(e){var n=this;if(!e.ok)throw n.isStatusFatal(e.status)?(n.fatalError=!0,n.close(),n.prepareFatalResponseStatusError(e.status,await e.text())):new t(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new t(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new t(`Failed to parse the response from the server: ${e}`):new t(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,n){var r,i;let a=e==null?0:e;return new t(`${`Connection failed with status: ${e==null?`unknown`:e}`}${((r=n==null||(i=n.trim())==null?void 0:i.length)==null?0:r)>0?` (${n})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,a)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}isFetchErrorFatal(e){return(e==null?void 0:e.name)===`NotAllowedError`}get isConnected(){return this.pollingInterval!==void 0}close(){clearInterval(this.pollingInterval),this.pollingInterval=void 0}dispose(){this.close(),this.clear()}};const q=async(e,t,n,r)=>{let i=new AbortController,a=setTimeout(()=>{r.debug(`[fetchWithTimeout] Reached timeout, aborting request`),i.abort()},e);try{let e=await fetch(typeof t==`string`||t instanceof Request?t:t.toString(),f(f({},n),{},{signal:i.signal}));return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}};var J=class extends K{constructor(t){var n;super(),this.options=t,this.eventEmitter=new e,this.options=t,this.logger=t.logger,this.url=t.resolveUrl(`client/polling/v1`,t.baseUrl);let r=(n=t.pollingInterval)==null?300:n;r<60&&this.logger.warn(`[PollingTransport] pollingInterval of ${r} seconds is below the minimum of 60 seconds. Using 60 seconds.`),this.pollingIntervalSeconds=Math.max(r,60)}async connect(e,t){var n=this;n.clearPollingInterval();try{await n.fetchConfigs(e,t)}finally{n.fatalError||n.schedulePollingInterval(()=>{n.fetchConfigs(e,t).catch(e=>{n.logger.error(`[PollingTransport] Error during polling:`,e)})})}return n}async fetchConfigs(e,t){var n=this;if(n.fatalError){n.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let r=await q(t,n.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:n.options.metaContext,clientSdkKey:n.options.clientSdkKey,instanceId:n.options.instanceId,lastUpdateTimestamp:n.lastUpdateTimestamp})},n.logger);if(await n.handleNonOkResponse(r),r.status==200){let e=JSON.parse(await r.text());n.lastUpdateTimestamp=e.timestamp,n.eventEmitter.emit(`configSetReceived`,e)}}catch(e){try{n.handleFetchError(e)}catch(e){throw n.fatalError&&n.eventEmitter.emit(`connectionError`,e),e}}}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}};const Y=e=>{try{return e(globalThis)}catch(e){return}},X=()=>Y(e=>{var t;return(t=e.navigator)==null?void 0:t.userAgent}),Z=()=>Y(e=>{var t;return(t=e.location)==null?void 0:t.host});var Q=class{constructor(t,n,r,i,a){var o,s,c,l,u,d,p,m,h,g,_,v,y,b,x;this.handlersMap=new Map,this.eventEmitter=new e,this.ready=!1,this.initializing=!1,this.logger=(o=i==null?void 0:i.logger)==null?M():o,this.instanceId=G(this.logger),this.timeout=(s=i==null||(c=i.connection)==null?void 0:c.timeout)==null?3e3:s,this.validateSdkKeyPresence(n);let S=(l=a==null?void 0:a.urlFactory)==null?N:l,C=(u=this.parseUrl(i==null||(d=i.connection)==null?void 0:d.url,S))==null?F:u;this.connectionMode=(p=i==null||(m=i.connection)==null?void 0:m.mode)==null?`streaming`:p;let w=this.getTransportConstructor(this.connectionMode);this.telemetryClient=t,this.transport=new w({instanceId:this.instanceId,clientSdkKey:n,baseUrl:C,resolveUrl:S,metaContext:f(f({},i==null?void 0:i.metadata),{},{sdkName:r.sdkName,sdkVersion:r.sdkVersion,userAgent:X(),host:Z()}),logger:this.logger,fetch:a==null?void 0:a.fetch,connectionRetryDelay:(h=a==null?void 0:a.connectionRetryDelay)==null?(e=>2**Math.min(e,9)*1e3):h,pollingInterval:i==null||(g=i.connection)==null?void 0:g.pollingInterval}),this.transport.on(`configSetReceived`,e=>{var t;(t=this.readyResolve)==null||t.call(this);let n=Object.keys(e.configs);!this.configSet||e.kind==`full`?(this.configSet=e,this.emit(`configsUpdated`,{keys:n}),this.updateWatchers(e.configs)):(this.configSet.configs=f(f({},this.configSet.configs),e.configs),this.emit(`configsUpdated`,{keys:n}),this.updateWatchers(e.configs)),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server:`,{keys:n})}),this.transport.on(`connectionError`,e=>{this.logger.error(`[ConfigDirectorClient] The connection encountered an unrecoverable error and will not be retried. Configs will no longer receive updates.`,e),this.emit(`connectionError`,{error:e})}),this.registerHandler(`clientReady`,i==null||(_=i.hooks)==null?void 0:_.clientReady),this.registerHandler(`configEvaluated`,i==null||(v=i.hooks)==null?void 0:v.configEvaluated),this.registerHandler(`configsUpdated`,i==null||(y=i.hooks)==null?void 0:y.configsUpdated),this.registerHandler(`contextUpdated`,i==null||(b=i.hooks)==null?void 0:b.contextUpdated),this.registerHandler(`connectionError`,i==null||(x=i.hooks)==null?void 0:x.connectionError)}registerHandler(e,t){if(!t)return;let n=Array.isArray(t)?t:[t];for(let t of n)typeof t==`function`&&this.on(e,t)}getTransportConstructor(e){switch(e){case`polling`:return J;default:return _}}async initialize(e){var t=this;t.initializing=!0,await t.connectToTransport(e,`initialization`)}async updateContext(e){await this.connectToTransport(e,`context update`)}get context(){return this.currentContext}async connectToTransport(e,t){var n=this;try{n.ready=!1,n.readyPromise=new Promise(e=>{n.readyResolve=e}).then(e=>{e||(n.ready=!0,n.initializing=!1,n.emit(`clientReady`,{action:t}),n.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))});let r=new Date().getTime();await n.transport.connect(e==null?{}:e,n.timeout),n.currentContext=e,n.telemetryClient.updateContext(e),n.emit(`contextUpdated`,{context:e});let i=new Date().getTime()-r,a=n.timeout-i;clearTimeout(n.timeoutTimer),n.timeoutTimer=void 0,a>0&&await Promise.race([n.readyPromise,new Promise(e=>{n.timeoutTimer=setTimeout(()=>e(),a)})]).finally(()=>clearTimeout(n.timeoutTimer)),n.ready||n.logger.warn(`[ConfigDirectorClient] Timed out waiting for ${t} after ${n.timeout}ms. The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`)}catch(e){n.logger.error(`[ConfigDirectorClient] An error occurred during ${t}: `,e)}}updateWatchers(e){Object.values(e).forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){var t;(t=this.handlersMap.get(e.key))==null||t.forEach(t=>{let n=this.getValueFromConfigState(e.key,e,t.defaultValue);t.handler(n)})}watch(e,t,n){this.validateDefaultValue(t);let r=this.handlersMap.get(e),i={handler:n,defaultValue:t,requestedType:typeof t};return r?r.push(i):this.handlersMap.set(e,[i]),()=>this.unwatch(e,n)}unwatch(e,t){let n=this.handlersMap.get(e);if(n)if(t){let e=n.findIndex(e=>e.handler==t);e>=0&&(n==null||n.splice(e,1))}else n.splice(0)}getValue(e,t){var n;this.validateDefaultValue(t);let r=(n=this.configSet)==null?void 0:n.configs[e];return this.getValueFromConfigState(e,r,t)}getValueFromConfigState(e,t,n){var r,i;if(!t){var a;this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`);let t=this.isReady?`config-state-missing`:`client-not-ready`;return this.telemetryClient.evaluatedConfig({contextId:(a=this.currentContext)==null?void 0:a.id,key:e,defaultValue:n,requestedType:v(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:this.context}),n}let o=x(t,n);return this.telemetryClient.evaluatedConfig({contextId:(r=this.currentContext)==null?void 0:r.id,type:t.type,key:e,defaultValue:n,requestedType:o.requestedType,evaluatedValue:o.parsedValue,evaluatedValueId:o.parsedValueId,usedDefault:o.usedDefault,evaluationReason:o.reason}),this.dispatchEvaluationEvent({key:e,value:o.parsedValue,valueId:(i=o.parsedValueId)==null?void 0:i,isDefaultValue:o.usedDefault,reason:o.reason,context:this.context}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${o.parsedValue}'`),o.parsedValue}dispatchEvaluationEvent(e){setTimeout(()=>this.emit(`configEvaluated`,{evaluation:e}),0)}emit(e,t){try{this.eventEmitter.emit(e,t)}catch(t){this.logger.error(`[ConfigDirectorClient] Error executing event handlers for '${e}'`,t)}}parseUrl(e,t){if(e)try{return t(e)}catch(t){throw new n(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateSdkKeyPresence(e){if(!e||e.trim().length==0)throw new n(`No client SDK key was provided, the client cannot be instantiated without a valid client SDK key`)}validateDefaultValue(e){if(e==null)throw new n(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new n(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}get isInitializing(){return this.initializing}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.logger.debug(`[ConfigDirectorClient] clear() has been called, removing all observers`),this.eventEmitter.clear(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}pauseNetwork(){this.logger.debug(`[ConfigDirectorClient] pauseNetwork() called, pausing transport connection`),clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,this.transport.close(),this.ready=!1}async resumeNetwork(){var e=this;await e.connectToTransport(e.currentContext,`network resume`)}async close(){var e=this,t;e.logger.debug(`[ConfigDirectorClient] close() has been called, closing connection to server`),clearTimeout(e.timeoutTimer),(t=e.readyResolve)==null||t.call(e,!0),e.telemetryClient.close(),e.transport.close(),e.ready=!1,e.initializing=!1}dispose(){this.clear(),this.close()}};const $=e=>{var t;if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch(t){return{value:e.value.toString(),type:`json`}}}let n=(t=e.value)==null?void 0:t.toString();return n&&n.length<=500?{value:n}:e.valueId?{valueId:e.valueId}:{value:n}};var te=class{constructor(e){var t,n,r,i;this.logger=e.logger,this.workerCloseTimeout=(t=e.workerCloseTimeout)==null?6e3:t;let a={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:(n=e.evaluationQueueLimit)==null?1e3:n,initialFlushIntervalDelay:(r=e.initialFlushIntervalDelay)==null?5e3:r,flushIntervalDelay:(i=e.flushIntervalDelay)==null?3e4:i}};this.worker=new Worker(URL.createObjectURL(new Blob(["(function(){let e=async(e,t)=>e.valueId?{valueId:e.valueId}:e.value?e.value.length<=500&&e.type!=`json`?{value:e.value}:{valueId:await t(e.value)}:e,t=e=>{let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]?.length??0)>0)return!1;return!0},n=e=>{if(!e)return!0;let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]??0)>0)return!1;return!0},r=async(e,t,n,r)=>{let i=new AbortController,a=setTimeout(()=>{r.debug(`[fetchWithTimeout] Reached timeout, aborting request`),i.abort()},e);try{let e=await fetch(typeof t==`string`||t instanceof Request?t:t.toString(),{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}},i=e=>e?.name===`NotAllowedError`?!0:e instanceof TypeError;var a=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.sdkIdentity=e.sdkIdentity,this.metaContext=e.metaContext,this.url=e.urlFactory(`client/telemetry/v1`,e.baseUrl)}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let i={clientSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(i))return{success:!0,fatalError:!1};let a=await this.sendReport(i);return a.fatalError&&(this.executeRequests=!1),a}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=await r(5e3,this.url,{method:`POST`,body:JSON.stringify(e),keepalive:!0},this.logger),n=this.isStatusFatal(t.status);return n&&this.logger.warn(`[EventReporter] Received a fatal status response (${t.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{success:t.ok,fatalError:n}}catch(e){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},o=class{aggregate(e){if(e.events.length==0)return[];let t=new Map;for(let n of e.events){let e=JSON.stringify(n),r=t.get(e)?.count||0;t.set(e,{event:n,count:r+1})}return Array.from(t).map(([,t])=>({startTime:e.startTime,endTime:e.endTime,count:t.count,event:t.event}))}},s=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||=new Date;let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}},c=class{constructor(e){this.aggregator=new o,this.collectEvents=!0,this.logger=e.logger,this.evaluationEventQueue=new s(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4;let t=e.initialFlushIntervalDelay??5e3;this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),t)}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},l=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},u=class extends c{constructor(e){super(e),this.reporter=new a(e),this.evaluationEventSnapshotPreprocessor=new l(e.valueIdGenerator)}async updateContext(e){this.cancelScheduledFlush(),await this.flush(),this._context=e,await this.flushAndScheduleNext()}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(e)}async forceFlush(){this.cancelScheduledFlush(),await this.flushAndScheduleNext()}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot());return await this.reporter?.report({context:this._context,discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount}})}};let d=(e,t)=>new URL(e,t?.toString()),f=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},p=Math.ceil(128/Math.log2(62)),m=new TextEncoder,h=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,m.encode(e?.toString()??``));return f(new Uint8Array(t,0,16),p)},g,_=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),v=e=>{try{self.postMessage(e)}catch{self.postMessage(_(e.payload.level,e.payload.message))}},y={debug:function(e,...t){v(_(`debug`,e,t))},info:function(e,...t){v(_(`info`,e,t))},warn:function(e,...t){v(_(`warn`,e,t))},error:function(e,...t){v(_(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!g){y.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(y.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(g){y.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}g=new u({...t.payload,baseUrl:d(t.payload.baseUrl),urlFactory:d,valueIdGenerator:h,logger:y});break;case`EvaluatedConfigEvent`:g?.evaluatedConfig(t.payload);break;case`UpdateContext`:g?.updateContext(t.payload.context);break;case`Flush`:g?.forceFlush();break;case`Close`:(g?.close()??Promise.resolve()).then(()=>{self.postMessage({type:`Closed`}),self.close()});break}})})();"],{type:`application/javascript`}))),this.worker.onmessage=e=>{this.handleWorkerEvent(e.data)},this.worker.postMessage(a),this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()};try{document.addEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}}async updateContext(e){var t=this;let n={type:`UpdateContext`,payload:{context:e}};t.worker.postMessage(n)}evaluatedConfig(e){let t={type:`EvaluatedConfigEvent`,payload:this.sanitizeEvaluatedConfigEvent(e)};this.worker.postMessage(t)}sanitizeEvaluatedConfigEvent(e){return f(f({},e),{},{defaultValue:$({value:e.defaultValue,type:e.type}),evaluatedValue:$({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})})}handleWorkerEvent(e){var t,n;if(e.type===`Closed`){this.finishClose();return}if(!((t=e.payload)!=null&&t.level)||!((n=e.payload)!=null&&n.message))return;let{level:r,message:i,args:a}=e.payload;switch(r){case`debug`:this.logger.debug(i,...a);break;case`info`:this.logger.info(i,...a);break;case`warn`:this.logger.warn(i,...a);break;case`error`:this.logger.error(i,...a);break}}flush(){this.worker.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(e=>{this.closeResolve=e,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),this.worker.postMessage({type:`Close`})}),this.closePromise}finishClose(){var e;clearTimeout(this.closeTimer),this.closeTimer=void 0,this.worker.terminate(),(e=this.closeResolve)==null||e.call(this)}};const ne=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},re=Math.ceil(128/Math.log2(62)),ie=new TextEncoder,ae=async e=>{var t;if(typeof crypto>`u`||crypto.subtle==null)return;let n=await crypto.subtle.digest(`SHA-256`,ie.encode((t=e==null?void 0:e.toString())==null?``:t));return ne(new Uint8Array(n,0,16),re)},oe=(e,t,n)=>{var r,i,a,o,s;let c=(r=n==null?void 0:n.logger)==null?M():r,l=(i=P(n==null||(a=n.connection)==null?void 0:a.url))==null?F:i;return new Q(new te({sdkKey:e,sdkIdentity:{sdkName:t.sdkName,sdkVersion:t.sdkVersion},metaContext:{appName:n==null||(o=n.metadata)==null?void 0:o.appName,appVersion:n==null||(s=n.metadata)==null?void 0:s.appVersion},logger:c,baseUrl:l,urlFactory:N,valueIdGenerator:ae}),e,t,f(f({},n),{},{logger:c}))},se=(e,t)=>oe(e,{sdkName:`js-client-sdk`,sdkVersion:`1.5.1`},t),ce=(e,t)=>M(e,t);export{se as createClient,ce as createConsoleLogger};
|
|
1
|
+
import{a as e,i as t,n,o as r,r as i,t as a}from"./DefaultConfigDirectorClient-a018lfK_.mjs";const o=e=>{var t;if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch(t){return{value:e.value.toString(),type:`json`}}}let n=(t=e.value)==null?void 0:t.toString();return n&&n.length<=500?{value:n}:e.valueId?{valueId:e.valueId}:{value:n}};var s=class{constructor(e){var t,n,r,i;this.pendingEvaluations=[],this.logger=e.logger,this.workerCloseTimeout=(t=e.workerCloseTimeout)==null?6e3:t,this.pendingEvaluationLimit=(n=e.evaluationQueueLimit)==null?1e3:n,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:(r=e.initialFlushIntervalDelay)==null?5e3:r,flushIntervalDelay:(i=e.flushIntervalDelay)==null?3e4:i}},this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()}}startWorker(){if(this.worker)return this.worker;let e=new Worker(URL.createObjectURL(new Blob(["(function(){let e=async(e,t)=>e.valueId?{valueId:e.valueId}:e.value?e.value.length<=500&&e.type!=`json`?{value:e.value}:{valueId:await t(e.value)}:e,t=e=>{let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]?.length??0)>0)return!1;return!0},n=e=>{if(!e)return!0;let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]??0)>0)return!1;return!0},r=async(e,t,n,r)=>{let i=new AbortController,a=setTimeout(()=>{r.debug(`[fetchWithTimeout] Reached timeout, aborting request`),i.abort()},e);try{let e=await fetch(typeof t==`string`||t instanceof Request?t:t.toString(),{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}},i=e=>e?.name===`NotAllowedError`?!0:e instanceof TypeError;var a=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.sdkIdentity=e.sdkIdentity,this.metaContext=e.metaContext,this.url=e.urlFactory(`client/telemetry/v1`,e.baseUrl)}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let i={clientSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(i))return{success:!0,fatalError:!1};let a=await this.sendReport(i);return a.fatalError&&(this.executeRequests=!1),a}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=await r(5e3,this.url,{method:`POST`,body:JSON.stringify(e),keepalive:!0},this.logger),n=this.isStatusFatal(t.status);return n&&this.logger.warn(`[EventReporter] Received a fatal status response (${t.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{success:t.ok,fatalError:n}}catch(e){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},o=class{aggregate(e){if(e.events.length==0)return[];let t=new Map;for(let n of e.events){let e=JSON.stringify(n),r=t.get(e)?.count||0;t.set(e,{event:n,count:r+1})}return Array.from(t).map(([,t])=>({startTime:e.startTime,endTime:e.endTime,count:t.count,event:t.event}))}},s=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||=new Date;let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}},c=class{constructor(e){this.aggregator=new o,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new s(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4,this.initialFlushIntervalDelay=e.initialFlushIntervalDelay??5e3}start(){this.started||!this.collectEvents||(this.started=!0,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.initialFlushIntervalDelay))}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},l=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},u=class extends c{constructor(e){super(e),this.reporter=new a(e),this.evaluationEventSnapshotPreprocessor=new l(e.valueIdGenerator)}async updateContext(e){this.cancelScheduledFlush(),await this.flush(),this._context=e,await this.flushAndScheduleNext()}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(e)}async forceFlush(){this.cancelScheduledFlush(),await this.flushAndScheduleNext()}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot());return await this.reporter?.report({context:this._context,discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount}})}};let d=(e,t)=>new URL(e,t?.toString()),f=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},p=Math.ceil(128/Math.log2(62)),m=new TextEncoder,h=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,m.encode(e?.toString()??``));return f(new Uint8Array(t,0,16),p)},g,_=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),v=e=>{try{self.postMessage(e)}catch{self.postMessage(_(e.payload.level,e.payload.message))}},y={debug:function(e,...t){v(_(`debug`,e,t))},info:function(e,...t){v(_(`info`,e,t))},warn:function(e,...t){v(_(`warn`,e,t))},error:function(e,...t){v(_(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!g){y.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(y.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(g){y.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}g=new u({...t.payload,baseUrl:d(t.payload.baseUrl),urlFactory:d,valueIdGenerator:h,logger:y}),g.start();break;case`EvaluatedConfigEvent`:g?.evaluatedConfig(t.payload);break;case`UpdateContext`:g?.updateContext(t.payload.context);break;case`Flush`:g?.forceFlush();break;case`Close`:(g?.close()??Promise.resolve()).then(()=>{self.postMessage({type:`Closed`}),self.close()});break}})})();"],{type:`application/javascript`})));e.onmessage=e=>{this.handleWorkerEvent(e.data)},e.postMessage(this.initializeMessage),this.worker=e;try{document.addEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}for(let t of this.pendingEvaluations)e.postMessage(t);return this.pendingEvaluations.length=0,e}async updateContext(e){var t=this;if(t.closePromise)return;let n={type:`UpdateContext`,payload:{context:e}};t.startWorker().postMessage(n)}evaluatedConfig(e){let t={type:`EvaluatedConfigEvent`,payload:this.sanitizeEvaluatedConfigEvent(e)};if(this.worker){this.worker.postMessage(t);return}this.pendingEvaluations.length>=this.pendingEvaluationLimit&&this.pendingEvaluations.shift(),this.pendingEvaluations.push(t)}sanitizeEvaluatedConfigEvent(e){return r(r({},e),{},{defaultValue:o({value:e.defaultValue,type:e.type}),evaluatedValue:o({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})})}handleWorkerEvent(e){var t,n;if(e.type===`Closed`){this.finishClose();return}if(!((t=e.payload)!=null&&t.level)||!((n=e.payload)!=null&&n.message))return;let{level:r,message:i,args:a}=e.payload;switch(r){case`debug`:this.logger.debug(i,...a);break;case`info`:this.logger.info(i,...a);break;case`warn`:this.logger.warn(i,...a);break;case`error`:this.logger.error(i,...a);break}}flush(){var e;(e=this.worker)==null||e.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){let e=this.worker;if(!e)return this.pendingEvaluations.length=0,this.closePromise=Promise.resolve(),this.closePromise;try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(t=>{this.closeResolve=t,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),e.postMessage({type:`Close`})}),this.closePromise}finishClose(){var e,t;clearTimeout(this.closeTimer),this.closeTimer=void 0,(e=this.worker)==null||e.terminate(),(t=this.closeResolve)==null||t.call(this)}};const c=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},l=Math.ceil(128/Math.log2(62)),u=new TextEncoder,d=async e=>{var t;if(typeof crypto>`u`||crypto.subtle==null)return;let n=await crypto.subtle.digest(`SHA-256`,u.encode((t=e==null?void 0:e.toString())==null?``:t));return c(new Uint8Array(n,0,16),l)},f=(o,c,l)=>{var u,f,p,m,h;let g=(u=l==null?void 0:l.logger)==null?e():u,_=(f=t(l==null||(p=l.connection)==null?void 0:p.url))==null?n:f;return new a(new s({sdkKey:o,sdkIdentity:{sdkName:c.sdkName,sdkVersion:c.sdkVersion},metaContext:{appName:l==null||(m=l.metadata)==null?void 0:m.appName,appVersion:l==null||(h=l.metadata)==null?void 0:h.appVersion},logger:g,baseUrl:_,urlFactory:i,valueIdGenerator:d}),o,c,r(r({},l),{},{logger:g}))},p=(e,t)=>f(e,{sdkName:`js-client-sdk`,sdkVersion:`1.6.0`},t),m=(t,n)=>e(t,n);export{p as createClient,m as createConsoleLogger};
|
|
6
2
|
//# sourceMappingURL=configdirector-client.mjs.map
|