@configdirector/client-sdk 1.6.1 → 1.8.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.
@@ -33,27 +33,40 @@ type ConfigEvaluation = {
33
33
  context?: ConfigDirectorContext;
34
34
  };
35
35
  /**
36
- * The user's context to be sent to ConfigDirector. This context will be used for targeting
37
- * rules evaluation.
36
+ * The context to be sent to ConfigDirector: the user or other entity, such as a device or an
37
+ * organization, that configs are evaluated for. This context will be used for targeting rules
38
+ * evaluation.
38
39
  */
39
40
  type ConfigDirectorContext = {
40
41
  /**
41
- * The user's identifier. This should be a value that uniquely identifies an application
42
- * user.
42
+ * The context's identifier. This should be a value that uniquely identifies the user or other
43
+ * entity among contexts of the same {@link kind}.
43
44
  * In the case of anonymous users, you could generate a UUID or alternatively not provide
44
45
  * 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.
46
+ * value is used for segmenting contexts in percentage rollouts, and changes to the {@link id}
47
+ * could result in the context being assigned to a different percentile.
47
48
  */
48
49
  id?: string;
49
50
  /**
50
- * The user's display name. This will be shown in the ConfigDirector dashboard and may be
51
+ * The kind of entity this context represents, such as `user`, `device`, `organization`,
52
+ * `tenant` or `listing`. You can use any other kind that fits your application. A kind has 1
53
+ * to 64 characters, using only lowercase letters (`a`-`z`), digits, `-` and `_`. It is used
54
+ * exactly as given, without trimming or changing its case.
55
+ *
56
+ * A context with an invalid kind is ignored as a whole: the SDK logs an error and evaluates
57
+ * as if no context had been provided.
58
+ *
59
+ * @default "user"
60
+ */
61
+ kind?: string;
62
+ /**
63
+ * The context's display name. This will be shown in the ConfigDirector dashboard and may be
51
64
  * used for targeting rules.
52
65
  */
53
66
  name?: string;
54
67
  /**
55
- * Any arbitrary traits for the current user. They will be shown in the ConfigDirector
56
- * dashboard and may be used for targeting rules.
68
+ * Any arbitrary traits for the context. They will be shown in the ConfigDirector dashboard
69
+ * and may be used for targeting rules.
57
70
  */
58
71
  traits?: {
59
72
  [key: string]: unknown;
@@ -75,9 +88,76 @@ type ConfigDirectorMetaContext = {
75
88
  appVersion?: string;
76
89
  appName?: string;
77
90
  };
78
- type ConnectionMode = "streaming" | "polling";
91
+ type ConnectionMode = "streaming" | "polling" | "offline";
92
+ //#endregion
93
+ //#region ../shared/src/native-values.d.ts
94
+ type NativeJsonValue = boolean | number | string | null | NativeJsonValue[] | {
95
+ [key: string]: NativeJsonValue;
96
+ };
97
+ type NativeValue = boolean | number | string | NativeJsonValue[] | {
98
+ [key: string]: NativeJsonValue;
99
+ };
100
+ type NativeValues = Record<string, NativeValue>;
79
101
  //#endregion
80
102
  //#region ../js-client-core/src/types.d.ts
103
+ /**
104
+ * One value an offline client serves for a config key. The config type follows from the value: a
105
+ * boolean, an integral number (`integer`), any other number (`float`), a string, or a plain object
106
+ * or array (`json`).
107
+ */
108
+ type OfflineValue = NativeValue;
109
+ /**
110
+ * The values an offline client serves, keyed by config key. See {@link OfflineValue} for how each
111
+ * value's config type is decided. Every context receives the same value.
112
+ */
113
+ type OfflineValues = NativeValues;
114
+ /**
115
+ * Connection options of the {@link ConfigDirectorClient}
116
+ */
117
+ type ConnectionOptions = {
118
+ /**
119
+ * The connection mode to be used, one of `streaming` (default), `polling` or `offline`.
120
+ * If set to `streaming`, the connection will remain open and receive updates whenever
121
+ * config state is updated on the ConfigDirector dashboard.
122
+ * When set to `polling`, there will be an initial request to retrieve config state during
123
+ * initialization, and additional requests on a `pollingInterval`.
124
+ * When set to `offline`, the client never connects to ConfigDirector and sends nothing: it serves
125
+ * the values given in {@link values} to every context, or the in-code default values when none
126
+ * are given. No SDK key is needed.
127
+ *
128
+ * Defaults to `streaming`
129
+ */
130
+ mode?: ConnectionMode;
131
+ /**
132
+ * The values to serve in `offline` mode, keyed by config key. A value such as `null` makes
133
+ * `initialize` reject with a `ConfigDirectorInitializationError`.
134
+ *
135
+ * Can be given only in `offline` mode; otherwise `initialize` rejects.
136
+ */
137
+ values?: OfflineValues;
138
+ /**
139
+ * The polling interval in _seconds_ when the `mode` is set to `polling`. This option has no
140
+ * effect in the other modes.
141
+ *
142
+ * Defaults to 60 seconds. The minimum is 30 seconds. A value below the minimum is raised to the
143
+ * minimum and a warning is logged.
144
+ */
145
+ pollingInterval?: number;
146
+ /**
147
+ * The timeout, in _milliseconds_, to be used in initialization and when updating the context.
148
+ * If streaming is enabled, the operation (initialization or context update) may still succeed
149
+ * after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
150
+ * If streaming is disabled, if the operation times out, it will not be retried. This option has
151
+ * no effect in `offline` mode.
152
+ */
153
+ timeout?: number;
154
+ /**
155
+ * The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
156
+ * proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
157
+ * a proxy for the client SDK. This option has no effect in `offline` mode.
158
+ */
159
+ url?: string;
160
+ };
81
161
  /**
82
162
  * Configuration options for the {@link ConfigDirectorClient}
83
163
  */
@@ -89,39 +169,7 @@ type ConfigDirectorClientOptions = {
89
169
  /**
90
170
  * Connection options
91
171
  */
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 60 seconds. The minimum is 30 seconds. A value below the minimum is raised to the
108
- * minimum and a warning is logged.
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
- };
172
+ connection?: ConnectionOptions;
125
173
  /**
126
174
  * A logger that implements {@link ConfigDirectorLogger}. It defaults to the ConfigDirector console
127
175
  * logger set to 'warn' level.
@@ -153,6 +201,14 @@ type ConfigDirectorClientOptions = {
153
201
  */
154
202
  hooks?: ClientHooks;
155
203
  };
204
+ /**
205
+ * The options of a client created without a client SDK key: the connection mode is `offline`.
206
+ */
207
+ type OfflineClientOptions = ConfigDirectorClientOptions & {
208
+ connection: ConnectionOptions & {
209
+ mode: "offline";
210
+ };
211
+ };
156
212
  type ClientHooks = {
157
213
  clientReady?: HookHandler<"clientReady"> | HookHandler<"clientReady">[];
158
214
  configsUpdated?: HookHandler<"configsUpdated"> | HookHandler<"configsUpdated">[];
@@ -202,17 +258,25 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
202
258
  * not attempt to re-connect and an error will be logged to the console or the provided
203
259
  * logger.
204
260
  *
205
- * @param context The current user's context to be used for evaluating targeting rules (optional).
261
+ * A context whose {@link ConfigDirectorContext.kind} is invalid is ignored as a whole: an error is
262
+ * logged, and the client connects as if no context had been provided.
263
+ *
264
+ * @param context The current context to be used for evaluating targeting rules (optional).
206
265
  */
207
266
  initialize(context?: ConfigDirectorContext): Promise<void>;
208
267
  /**
209
- * Updates the user's context and re-evaluates all config and flag values based on the new context.
268
+ * Updates the context and re-evaluates all config and flag values based on the new context.
210
269
  *
211
- * @param context The current user's context to be used for evaluating targeting rules (required).
270
+ * A context whose {@link ConfigDirectorContext.kind} is invalid is ignored as a whole: an error is
271
+ * logged, the previous context is no longer used, and the client connects as if no context had been
272
+ * provided.
273
+ *
274
+ * @param context The current context to be used for evaluating targeting rules (required).
212
275
  */
213
276
  updateContext(context: ConfigDirectorContext): Promise<void>;
214
277
  /**
215
- * Returns the current context the client is configured with, or undefined if there is no context.
278
+ * Returns the current context the client is configured with, or undefined if there is no context,
279
+ * including after a context with an invalid kind was ignored.
216
280
  *
217
281
  * Note that the value returned does not updated immediately after calling {@link updateContext}. Only
218
282
  * once the underlying connection was successful or timed out, the current context is updated. This is
@@ -302,6 +366,10 @@ declare class ConfigDirectorValidationError extends Error {
302
366
  readonly name: string;
303
367
  constructor(message: string);
304
368
  }
369
+ declare class ConfigDirectorInitializationError extends Error {
370
+ readonly name: string;
371
+ constructor(message: string);
372
+ }
305
373
  //#endregion
306
- export { ConfigDirectorContext as a, ConfigDirectorLoggingLevel as c, ConfigDirectorClientOptions as i, ConfigValueType as l, ConfigDirectorValidationError as n, ConfigDirectorLogMessageDecorator as o, ConfigDirectorClient as r, ConfigDirectorLogger as s, ConfigDirectorConnectionError as t };
307
- //# sourceMappingURL=errors-zagImFi0.d.mts.map
374
+ export { ConfigDirectorClientOptions as a, OfflineValues as c, NativeValues as d, ConfigDirectorContext as f, ConfigValueType as g, ConfigDirectorLoggingLevel as h, ConfigDirectorClient as i, NativeJsonValue as l, ConfigDirectorLogger as m, ConfigDirectorInitializationError as n, OfflineClientOptions as o, ConfigDirectorLogMessageDecorator as p, ConfigDirectorValidationError as r, OfflineValue as s, ConfigDirectorConnectionError as t, NativeValue as u };
375
+ //# sourceMappingURL=errors-CyYEwUC9.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-CyYEwUC9.d.cts","names":[],"sources":["../../js-client-core/src/Emitter.ts","../../shared/src/types.ts","../../shared/src/native-values.ts","../../js-client-core/src/types.ts","../../shared/src/errors.ts"],"mappings":"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"}
@@ -33,27 +33,40 @@ type ConfigEvaluation = {
33
33
  context?: ConfigDirectorContext;
34
34
  };
35
35
  /**
36
- * The user's context to be sent to ConfigDirector. This context will be used for targeting
37
- * rules evaluation.
36
+ * The context to be sent to ConfigDirector: the user or other entity, such as a device or an
37
+ * organization, that configs are evaluated for. This context will be used for targeting rules
38
+ * evaluation.
38
39
  */
39
40
  type ConfigDirectorContext = {
40
41
  /**
41
- * The user's identifier. This should be a value that uniquely identifies an application
42
- * user.
42
+ * The context's identifier. This should be a value that uniquely identifies the user or other
43
+ * entity among contexts of the same {@link kind}.
43
44
  * In the case of anonymous users, you could generate a UUID or alternatively not provide
44
45
  * 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.
46
+ * value is used for segmenting contexts in percentage rollouts, and changes to the {@link id}
47
+ * could result in the context being assigned to a different percentile.
47
48
  */
48
49
  id?: string;
49
50
  /**
50
- * The user's display name. This will be shown in the ConfigDirector dashboard and may be
51
+ * The kind of entity this context represents, such as `user`, `device`, `organization`,
52
+ * `tenant` or `listing`. You can use any other kind that fits your application. A kind has 1
53
+ * to 64 characters, using only lowercase letters (`a`-`z`), digits, `-` and `_`. It is used
54
+ * exactly as given, without trimming or changing its case.
55
+ *
56
+ * A context with an invalid kind is ignored as a whole: the SDK logs an error and evaluates
57
+ * as if no context had been provided.
58
+ *
59
+ * @default "user"
60
+ */
61
+ kind?: string;
62
+ /**
63
+ * The context's display name. This will be shown in the ConfigDirector dashboard and may be
51
64
  * used for targeting rules.
52
65
  */
53
66
  name?: string;
54
67
  /**
55
- * Any arbitrary traits for the current user. They will be shown in the ConfigDirector
56
- * dashboard and may be used for targeting rules.
68
+ * Any arbitrary traits for the context. They will be shown in the ConfigDirector dashboard
69
+ * and may be used for targeting rules.
57
70
  */
58
71
  traits?: {
59
72
  [key: string]: unknown;
@@ -75,9 +88,76 @@ type ConfigDirectorMetaContext = {
75
88
  appVersion?: string;
76
89
  appName?: string;
77
90
  };
78
- type ConnectionMode = "streaming" | "polling";
91
+ type ConnectionMode = "streaming" | "polling" | "offline";
92
+ //#endregion
93
+ //#region ../shared/src/native-values.d.ts
94
+ type NativeJsonValue = boolean | number | string | null | NativeJsonValue[] | {
95
+ [key: string]: NativeJsonValue;
96
+ };
97
+ type NativeValue = boolean | number | string | NativeJsonValue[] | {
98
+ [key: string]: NativeJsonValue;
99
+ };
100
+ type NativeValues = Record<string, NativeValue>;
79
101
  //#endregion
80
102
  //#region ../js-client-core/src/types.d.ts
103
+ /**
104
+ * One value an offline client serves for a config key. The config type follows from the value: a
105
+ * boolean, an integral number (`integer`), any other number (`float`), a string, or a plain object
106
+ * or array (`json`).
107
+ */
108
+ type OfflineValue = NativeValue;
109
+ /**
110
+ * The values an offline client serves, keyed by config key. See {@link OfflineValue} for how each
111
+ * value's config type is decided. Every context receives the same value.
112
+ */
113
+ type OfflineValues = NativeValues;
114
+ /**
115
+ * Connection options of the {@link ConfigDirectorClient}
116
+ */
117
+ type ConnectionOptions = {
118
+ /**
119
+ * The connection mode to be used, one of `streaming` (default), `polling` or `offline`.
120
+ * If set to `streaming`, the connection will remain open and receive updates whenever
121
+ * config state is updated on the ConfigDirector dashboard.
122
+ * When set to `polling`, there will be an initial request to retrieve config state during
123
+ * initialization, and additional requests on a `pollingInterval`.
124
+ * When set to `offline`, the client never connects to ConfigDirector and sends nothing: it serves
125
+ * the values given in {@link values} to every context, or the in-code default values when none
126
+ * are given. No SDK key is needed.
127
+ *
128
+ * Defaults to `streaming`
129
+ */
130
+ mode?: ConnectionMode;
131
+ /**
132
+ * The values to serve in `offline` mode, keyed by config key. A value such as `null` makes
133
+ * `initialize` reject with a `ConfigDirectorInitializationError`.
134
+ *
135
+ * Can be given only in `offline` mode; otherwise `initialize` rejects.
136
+ */
137
+ values?: OfflineValues;
138
+ /**
139
+ * The polling interval in _seconds_ when the `mode` is set to `polling`. This option has no
140
+ * effect in the other modes.
141
+ *
142
+ * Defaults to 60 seconds. The minimum is 30 seconds. A value below the minimum is raised to the
143
+ * minimum and a warning is logged.
144
+ */
145
+ pollingInterval?: number;
146
+ /**
147
+ * The timeout, in _milliseconds_, to be used in initialization and when updating the context.
148
+ * If streaming is enabled, the operation (initialization or context update) may still succeed
149
+ * after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
150
+ * If streaming is disabled, if the operation times out, it will not be retried. This option has
151
+ * no effect in `offline` mode.
152
+ */
153
+ timeout?: number;
154
+ /**
155
+ * The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
156
+ * proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
157
+ * a proxy for the client SDK. This option has no effect in `offline` mode.
158
+ */
159
+ url?: string;
160
+ };
81
161
  /**
82
162
  * Configuration options for the {@link ConfigDirectorClient}
83
163
  */
@@ -89,39 +169,7 @@ type ConfigDirectorClientOptions = {
89
169
  /**
90
170
  * Connection options
91
171
  */
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 60 seconds. The minimum is 30 seconds. A value below the minimum is raised to the
108
- * minimum and a warning is logged.
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
- };
172
+ connection?: ConnectionOptions;
125
173
  /**
126
174
  * A logger that implements {@link ConfigDirectorLogger}. It defaults to the ConfigDirector console
127
175
  * logger set to 'warn' level.
@@ -153,6 +201,14 @@ type ConfigDirectorClientOptions = {
153
201
  */
154
202
  hooks?: ClientHooks;
155
203
  };
204
+ /**
205
+ * The options of a client created without a client SDK key: the connection mode is `offline`.
206
+ */
207
+ type OfflineClientOptions = ConfigDirectorClientOptions & {
208
+ connection: ConnectionOptions & {
209
+ mode: "offline";
210
+ };
211
+ };
156
212
  type ClientHooks = {
157
213
  clientReady?: HookHandler<"clientReady"> | HookHandler<"clientReady">[];
158
214
  configsUpdated?: HookHandler<"configsUpdated"> | HookHandler<"configsUpdated">[];
@@ -202,17 +258,25 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
202
258
  * not attempt to re-connect and an error will be logged to the console or the provided
203
259
  * logger.
204
260
  *
205
- * @param context The current user's context to be used for evaluating targeting rules (optional).
261
+ * A context whose {@link ConfigDirectorContext.kind} is invalid is ignored as a whole: an error is
262
+ * logged, and the client connects as if no context had been provided.
263
+ *
264
+ * @param context The current context to be used for evaluating targeting rules (optional).
206
265
  */
207
266
  initialize(context?: ConfigDirectorContext): Promise<void>;
208
267
  /**
209
- * Updates the user's context and re-evaluates all config and flag values based on the new context.
268
+ * Updates the context and re-evaluates all config and flag values based on the new context.
210
269
  *
211
- * @param context The current user's context to be used for evaluating targeting rules (required).
270
+ * A context whose {@link ConfigDirectorContext.kind} is invalid is ignored as a whole: an error is
271
+ * logged, the previous context is no longer used, and the client connects as if no context had been
272
+ * provided.
273
+ *
274
+ * @param context The current context to be used for evaluating targeting rules (required).
212
275
  */
213
276
  updateContext(context: ConfigDirectorContext): Promise<void>;
214
277
  /**
215
- * Returns the current context the client is configured with, or undefined if there is no context.
278
+ * Returns the current context the client is configured with, or undefined if there is no context,
279
+ * including after a context with an invalid kind was ignored.
216
280
  *
217
281
  * Note that the value returned does not updated immediately after calling {@link updateContext}. Only
218
282
  * once the underlying connection was successful or timed out, the current context is updated. This is
@@ -302,6 +366,10 @@ declare class ConfigDirectorValidationError extends Error {
302
366
  readonly name: string;
303
367
  constructor(message: string);
304
368
  }
369
+ declare class ConfigDirectorInitializationError extends Error {
370
+ readonly name: string;
371
+ constructor(message: string);
372
+ }
305
373
  //#endregion
306
- export { ConfigDirectorContext as a, ConfigDirectorLoggingLevel as c, ConfigDirectorClientOptions as i, ConfigValueType as l, ConfigDirectorValidationError as n, ConfigDirectorLogMessageDecorator as o, ConfigDirectorClient as r, ConfigDirectorLogger as s, ConfigDirectorConnectionError as t };
307
- //# sourceMappingURL=errors-BOgYEeJ6.d.cts.map
374
+ export { ConfigDirectorClientOptions as a, OfflineValues as c, NativeValues as d, ConfigDirectorContext as f, ConfigValueType as g, ConfigDirectorLoggingLevel as h, ConfigDirectorClient as i, NativeJsonValue as l, ConfigDirectorLogger as m, ConfigDirectorInitializationError as n, OfflineClientOptions as o, ConfigDirectorLogMessageDecorator as p, ConfigDirectorValidationError as r, OfflineValue as s, ConfigDirectorConnectionError as t, NativeValue as u };
375
+ //# sourceMappingURL=errors-M2Tlq4Yu.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-M2Tlq4Yu.d.mts","names":[],"sources":["../../js-client-core/src/Emitter.ts","../../shared/src/types.ts","../../shared/src/native-values.ts","../../js-client-core/src/types.ts","../../shared/src/errors.ts"],"mappings":"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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@configdirector/client-sdk",
3
- "version": "1.6.1",
3
+ "version": "1.8.0",
4
4
  "description": "Javascript client SDK for ConfigDirector. ConfigDirector is a remote configuration and feature flag service.",
5
5
  "license": "MIT",
6
6
  "author": "ConfigDirector",
@@ -1,5 +0,0 @@
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)}},s=class{constructor(e){this.isFirstChunk=!0,this.bufferedInput=``,this.currentEvent={data:``},this.currentEvent={data:``},this.onEvent=e.onEvent??(()=>{}),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(`:`)){this.onComment?.(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({...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`:/^\d+$/.test(e.value)&&this.onRetry?.(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 c=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var l=class{constructor(e){this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=c.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers={Accept:`text/event-stream`,...e.headers};let t=e.body;this.body=typeof t==`function`?t:()=>t,this.requestOptions={method:e.method??`GET`,mode:e.mode,credentials:e.credentials,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy},this._fetch=e.fetch??((e,t)=>fetch(e,t)),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===c.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=c.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=c.CONNECTING,this._fetch(this.url,{...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){let{body:t,status:n}=e;if(n===204){this.disconnected();return}if(n>=400){this.scheduleReconnect({status:n});return}if(!t)throw new i(`The server response did not have a body`);this._readyState=c.OPEN,this._onConnect(),this.reconnectAttempt=0;let a=new s({onEvent:e=>{typeof e.id==`string`&&(this.lastEventId=e.id),this._onMessage(e)},onComment:e=>this._onComment(e),onRetry:e=>this.serverReconnectionTime=e});await this.readResponseStream(t,a),this.scheduleReconnect({status:n,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=c.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return{...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=c.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 u=e=>new l(e);var d=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){this.eventSource&&this.close();let n=new Promise((t,n)=>{this.eventSource=u({url:this.url,method:`POST`,headers:{"Content-Type":`application/json`},fetch:this.options.fetch,body:JSON.stringify({givenContext:e,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey,instanceId:this.options.instanceId}),onMessage:({data:e})=>{this.dispatchMessage(e)},onConnect:()=>{this.logger.debug(`[StreamingTransport] Connected`),t(this)},shouldReconnect:e=>{let t=!this.isStatusFatal(e.status);if(!t){let t=this.prepareFatalError(e.status,e.error);this.eventEmitter.emit(`connectionError`,t),n(t)}return t},calculateReconnectDelay:e=>{let t=this.options.connectionRetryDelay(e.attempt),n=`[StreamingTransport] Scheduling reconnect attempt #${e.attempt} in ${t}ms.`;return e.attempt<=5?this.logger.info(n):this.logger.warn(n),t},onError:e=>{this.logger.debug(`[StreamingTransport] Error: `,e)},onDisconnect:()=>{this.logger.debug(`[StreamingTransport] Disconnected`)}}),this.eventSource.connect()});return clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,Promise.race([n,new Promise(e=>{this.timeoutTimer=setTimeout(()=>e(this),t)})]).finally(()=>clearTimeout(this.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??0;return new t(`${`Connection failed with status: ${e??`unknown`}.`}${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(){this.eventSource?.close(),clearTimeout(this.timeoutTimer)}dispose(){this.close(),this.clear()}};const f=e=>{let t=typeof e;if(t===`object`)try{return e.constructor?.name??t}catch{return t}else if(t===`function`)try{let n=e.name;return n?`function: ${n}`:t}catch{return t}return t},p=e=>e===`number`||e===`bigint`,m=new Set([`boolean`,`integer`,`float`]),h=(e,t)=>{let n=e.value,r=f(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return x(n,t,r,e.valueId);if(typeof t==`string`)return m.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=g(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(p(typeof t)&&e.type===`integer`){let i=_(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(p(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=v(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`}},g=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},_=e=>{let t=y(e);return t==null?void 0:Math.trunc(t)},v=e=>y(e),y=e=>{if(!e||!b(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},b=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},x=(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 S(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{return{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`invalid-json`}}},S=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},C={off:-1,error:0,warn:1,info:2,debug:3},w=()=>{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,{...e,fractionalSecondDigits:3})}catch{return new Intl.DateTimeFormat(void 0,e)}};var T=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=w()}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){C[this.level]>=C[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},E=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const D=(e,t)=>new T(e??`warn`,t??new E),O=(e,t)=>new URL(e,t?.toString()),k=e=>{if(e)try{return new URL(e)}catch(t){throw new n(`Invalid URL '${e}'. Parsing failed: ${t}`)}},A=(e,t)=>e===void 0?{seconds:t.defaultSeconds,warning:void 0}:e>=t.minimumSeconds?{seconds:e,warning:void 0}:{seconds:t.minimumSeconds,warning:`pollingInterval of ${e} seconds is below the minimum of ${t.minimumSeconds} seconds. Using ${t.minimumSeconds} seconds.`},j=()=>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)}),M=`configdirector-sdk:instance-id`,N=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,P=(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},F=(e,t)=>{let n=`configdirector.instanceId.v1|${e}|${t}`,r=P(n,2166136261);return P(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},I=()=>{try{return globalThis.localStorage??void 0}catch{return}},L=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||!N.test(n)?!1:i===F(n,r)},R=(e,t)=>{let n;try{n=e.getItem(M)}catch(e){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{t?.debug(`[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one`);return}if(!L(r)){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?.debug(`[ConfigDirectorClient] The stored instance id has expired, generating a new one`);return}return r.id},z=(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:F(t,r)};try{e.setItem(M,JSON.stringify(i))}catch(e){n?.debug(`[ConfigDirectorClient] Could not persist the instance id`,e)}},B=e=>{let t=I();if(!t)return j();let n=R(t,e);if(n)return n;let r=j();return z(t,r,e),r};var V=class{constructor(){this.fatalError=!1}clearPollingInterval(){clearInterval(this.pollingInterval)}schedulePollingInterval(e){clearInterval(this.pollingInterval),!(this.pollingIntervalSeconds<=0)&&(this.pollingInterval=setInterval(e,this.pollingIntervalSeconds*1e3))}async handleNonOkResponse(e){if(!e.ok)throw this.isStatusFatal(e.status)?(this.fatalError=!0,this.close(),this.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){let r=e??0;return new t(`${`Connection failed with status: ${e??`unknown`}`}${(n?.trim()?.length??0)>0?` (${n})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,r)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}isFetchErrorFatal(e){return e?.name===`NotAllowedError`}get isConnected(){return this.pollingInterval!==void 0}close(){clearInterval(this.pollingInterval),this.pollingInterval=void 0}dispose(){this.close(),this.clear()}};const H=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}};var U=class extends V{constructor(t){super(),this.options=t,this.eventEmitter=new e,this.options=t,this.logger=t.logger,this.url=t.resolveUrl(`client/polling/v1`,t.baseUrl),this.pollingIntervalSeconds=t.pollingInterval??60}async connect(e,t){this.clearPollingInterval();try{await this.fetchConfigs(e,t)}finally{this.fatalError||this.schedulePollingInterval(()=>{this.fetchConfigs(e,t).catch(e=>{this.logger.error(`[PollingTransport] Error during polling:`,e)})})}return this}async fetchConfigs(e,t){if(this.fatalError){this.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let n=await H(t,this.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey,instanceId:this.options.instanceId,lastUpdateTimestamp:this.lastUpdateTimestamp})},this.logger);if(await this.handleNonOkResponse(n),n.status==200){let e=JSON.parse(await n.text());this.lastUpdateTimestamp=e.timestamp,this.eventEmitter.emit(`configSetReceived`,e)}}catch(e){try{this.handleFetchError(e)}catch(e){throw this.fatalError&&this.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 W=e=>{try{return e(globalThis)}catch{return}},G=()=>W(e=>e.navigator?.userAgent),K=()=>W(e=>e.location?.host);var q=class{constructor(t,n,r,i,a){this.handlersMap=new Map,this.eventEmitter=new e,this.ready=!1,this.initializing=!1,this.hasReceivedConfigSet=!1,this.logger=i?.logger??D(),this.instanceId=B(this.logger),this.timeout=i?.connection?.timeout??3e3,this.validateSdkKeyPresence(n);let o=a?.urlFactory??O,s=this.parseUrl(i?.connection?.url,o)??`https://client-sdk-api.configdirector.com`;this.connectionMode=i?.connection?.mode??`streaming`,this.telemetryClient=t,this.transport=a?.transport??this.buildTransport(n,r,s,o,i,a),this.transport.on(`configSetReceived`,e=>{this.hasReceivedConfigSet=!0,this.readyResolve?.();let t=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:this.configSet.configs={...this.configSet.configs,...e.configs};let n=Object.keys(e.configs);this.emit(`configsUpdated`,{keys:n,removedKeys:t}),this.updateWatchers([...n,...t]),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server:`,{keys:n,removedKeys:t})}),this.transport.on(`connectionError`,e=>{this.initializing=!1,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?.hooks?.clientReady),this.registerHandler(`configEvaluated`,i?.hooks?.configEvaluated),this.registerHandler(`configsUpdated`,i?.hooks?.configsUpdated),this.registerHandler(`contextUpdated`,i?.hooks?.contextUpdated),this.registerHandler(`connectionError`,i?.hooks?.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)}resolvePollingIntervalForMode(e){if(this.connectionMode!==`polling`)return;let t=A(e,{defaultSeconds:60,minimumSeconds:30});return t.warning&&this.logger.warn(`[ConfigDirectorClient] ${t.warning}`),t.seconds}buildTransport(e,t,n,r,i,a){return new(this.getTransportConstructor(this.connectionMode))({instanceId:this.instanceId,clientSdkKey:e,baseUrl:n,resolveUrl:r,metaContext:{...i?.metadata,sdkName:t.sdkName,sdkVersion:t.sdkVersion,userAgent:G(),host:K()},logger:this.logger,fetch:a?.fetch,connectionRetryDelay:a?.connectionRetryDelay??(e=>2**Math.min(e,9)*1e3),pollingInterval:this.resolvePollingIntervalForMode(i?.connection?.pollingInterval)})}getTransportConstructor(e){switch(e){case`polling`:return U;default:return d}}async initialize(e){this.hasReceivedConfigSet||(this.initializing=!0),await this.connectToTransport(e,`initialization`)}async updateContext(e){await this.connectToTransport(e,`context update`)}get context(){return this.currentContext}async connectToTransport(e,t){try{this.ready=!1,this.readyPromise=new Promise(e=>{this.readyResolve=e}).then(e=>{e||(this.ready=!0,this.initializing=!1,this.emit(`clientReady`,{action:t}),this.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))});let n=new Date().getTime();await this.transport.connect(e??{},this.timeout,t),this.currentContext=e,this.telemetryClient.updateContext(e).catch(e=>this.logger.warn(`[ConfigDirectorClient] Telemetry could not update the context: `,e)),this.emit(`contextUpdated`,{context:e});let r=new Date().getTime()-n,i=this.timeout-r;clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,i>0&&await Promise.race([this.readyPromise,new Promise(e=>{this.timeoutTimer=setTimeout(()=>e(),i)})]).finally(()=>clearTimeout(this.timeoutTimer)),this.ready||this.logger.warn(`[ConfigDirectorClient] Timed out waiting for ${t} after ${this.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){this.logger.error(`[ConfigDirectorClient] An error occurred during ${t}: `,e)}}findKeysRemovedBy(e){return!this.configSet||e.kind!=`full`?[]:Object.keys(this.configSet.configs).filter(t=>!Object.prototype.hasOwnProperty.call(e.configs,t))}updateWatchers(e){e.forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){let t=this.configSet?.configs[e];this.handlersMap.get(e)?.forEach(n=>{let r=this.getValueFromConfigState(e,t,n.defaultValue);n.handler(r)})}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?.splice(e,1)}else n.splice(0)}getValue(e,t){this.validateDefaultValue(t);let n=this.configSet?.configs[e];return this.getValueFromConfigState(e,n,t)}getValueFromConfigState(e,t,n){if(!t){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:this.currentContext?.id,key:e,defaultValue:n,requestedType:f(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:this.context}),n}let r=h(t,n);return this.telemetryClient.evaluatedConfig({contextId:this.currentContext?.id,type:t.type,key:e,defaultValue:n,requestedType:r.requestedType,evaluatedValue:r.parsedValue,evaluatedValueId:r.parsedValueId,usedDefault:r.usedDefault,evaluationReason:r.reason}),this.dispatchEvaluationEvent({key:e,value:r.parsedValue,valueId:r.parsedValueId??void 0,isDefaultValue:r.usedDefault,reason:r.reason,context:this.context}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${r.parsedValue}'`),r.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(){await this.connectToTransport(this.currentContext,`network resume`)}async close(){this.logger.debug(`[ConfigDirectorClient] close() has been called, closing connection to server`),clearTimeout(this.timeoutTimer),this.readyResolve?.(!0),this.telemetryClient.close().catch(e=>this.logger.warn(`[ConfigDirectorClient] Telemetry could not close: `,e)),this.transport.close(),this.ready=!1,this.initializing=!1}dispose(){this.clear(),this.close()}};Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return`https://client-sdk-api.configdirector.com`}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return q}});
@@ -1,6 +0,0 @@
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||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return D(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||!E(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},E=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},D=(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 O(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`}}},O=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},k={off:-1,error:0,warn:1,info:2,debug:3},A=()=>{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 j=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=A()}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(k[this.level]>=k[t]){var i;e(`[${this.dateFormatter.format(new Date)}] ${(i=this.decorator)==null?void 0:i.decorateMessage(n)}`,...r)}}},M=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const N=(e,t)=>new j(e==null?`warn`:e,t==null?new M:t),P=(e,t)=>new URL(e,t==null?void 0:t.toString()),F=e=>{if(e)try{return new URL(e)}catch(t){throw new n(`Invalid URL '${e}'. Parsing failed: ${t}`)}},I=`https://client-sdk-api.configdirector.com`,L=(e,t)=>e===void 0?{seconds:t.defaultSeconds,warning:void 0}:e>=t.minimumSeconds?{seconds:e,warning:void 0}:{seconds:t.minimumSeconds,warning:`pollingInterval of ${e} seconds is below the minimum of ${t.minimumSeconds} seconds. Using ${t.minimumSeconds} seconds.`},R=()=>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)}),z=`configdirector-sdk:instance-id`,B=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,V=(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},H=(e,t)=>{let n=`configdirector.instanceId.v1|${e}|${t}`,r=V(n,2166136261);return V(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},U=()=>{try{var e;return(e=globalThis.localStorage)==null?void 0:e}catch(e){return}},W=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||!B.test(n)?!1:i===H(n,r)},G=(e,t)=>{let n;try{n=e.getItem(z)}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(!W(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},K=(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:H(t,r)};try{e.setItem(z,JSON.stringify(i))}catch(e){n==null||n.debug(`[ConfigDirectorClient] Could not persist the instance id`,e)}},q=e=>{let t=U();if(!t)return R();let n=G(t,e);if(n)return n;let r=R();return K(t,r,e),r};var J=class{constructor(){this.fatalError=!1}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 Y=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 X=class extends J{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),this.pollingIntervalSeconds=(n=t.pollingInterval)==null?60:n}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 Y(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 Z=e=>{try{return e(globalThis)}catch(e){return}},Q=()=>Z(e=>{var t;return(t=e.navigator)==null?void 0:t.userAgent}),$=()=>Z(e=>{var t;return(t=e.location)==null?void 0:t.host});var ee=class{constructor(t,n,r,i,a){var o,s,c,l,u,d,p,m,h,g,_,v,y,b;this.handlersMap=new Map,this.eventEmitter=new e,this.ready=!1,this.initializing=!1,this.hasReceivedConfigSet=!1,this.logger=(o=i==null?void 0:i.logger)==null?N():o,this.instanceId=q(this.logger),this.timeout=(s=i==null||(c=i.connection)==null?void 0:c.timeout)==null?3e3:s,this.validateSdkKeyPresence(n);let x=(l=a==null?void 0:a.urlFactory)==null?P:l,S=(u=this.parseUrl(i==null||(d=i.connection)==null?void 0:d.url,x))==null?I:u;this.connectionMode=(p=i==null||(m=i.connection)==null?void 0:m.mode)==null?`streaming`:p,this.telemetryClient=t,this.transport=(h=a==null?void 0:a.transport)==null?this.buildTransport(n,r,S,x,i,a):h,this.transport.on(`configSetReceived`,e=>{var t;this.hasReceivedConfigSet=!0,(t=this.readyResolve)==null||t.call(this);let n=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:this.configSet.configs=f(f({},this.configSet.configs),e.configs);let r=Object.keys(e.configs);this.emit(`configsUpdated`,{keys:r,removedKeys:n}),this.updateWatchers([...r,...n]),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server:`,{keys:r,removedKeys:n})}),this.transport.on(`connectionError`,e=>{this.initializing=!1,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||(g=i.hooks)==null?void 0:g.clientReady),this.registerHandler(`configEvaluated`,i==null||(_=i.hooks)==null?void 0:_.configEvaluated),this.registerHandler(`configsUpdated`,i==null||(v=i.hooks)==null?void 0:v.configsUpdated),this.registerHandler(`contextUpdated`,i==null||(y=i.hooks)==null?void 0:y.contextUpdated),this.registerHandler(`connectionError`,i==null||(b=i.hooks)==null?void 0:b.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)}resolvePollingIntervalForMode(e){if(this.connectionMode!==`polling`)return;let t=L(e,{defaultSeconds:60,minimumSeconds:30});return t.warning&&this.logger.warn(`[ConfigDirectorClient] ${t.warning}`),t.seconds}buildTransport(e,t,n,r,i,a){var o,s;return new(this.getTransportConstructor(this.connectionMode))({instanceId:this.instanceId,clientSdkKey:e,baseUrl:n,resolveUrl:r,metaContext:f(f({},i==null?void 0:i.metadata),{},{sdkName:t.sdkName,sdkVersion:t.sdkVersion,userAgent:Q(),host:$()}),logger:this.logger,fetch:a==null?void 0:a.fetch,connectionRetryDelay:(o=a==null?void 0:a.connectionRetryDelay)==null?(e=>2**Math.min(e,9)*1e3):o,pollingInterval:this.resolvePollingIntervalForMode(i==null||(s=i.connection)==null?void 0:s.pollingInterval)})}getTransportConstructor(e){switch(e){case`polling`:return X;default:return _}}async initialize(e){var t=this;t.hasReceivedConfigSet||(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,t),n.currentContext=e,n.telemetryClient.updateContext(e).catch(e=>n.logger.warn(`[ConfigDirectorClient] Telemetry could not update the context: `,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)}}findKeysRemovedBy(e){return!this.configSet||e.kind!=`full`?[]:Object.keys(this.configSet.configs).filter(t=>!Object.prototype.hasOwnProperty.call(e.configs,t))}updateWatchers(e){e.forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){var t,n;let r=(t=this.configSet)==null?void 0:t.configs[e];(n=this.handlersMap.get(e))==null||n.forEach(t=>{let n=this.getValueFromConfigState(e,r,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().catch(t=>e.logger.warn(`[ConfigDirectorClient] Telemetry could not close: `,t)),e.transport.close(),e.ready=!1,e.initializing=!1}dispose(){this.clear(),this.close()}};export{N as a,n as c,F as i,e as l,I as n,f as o,P as r,t as s,ee as t};
6
- //# sourceMappingURL=DefaultConfigDirectorClient-D-prfiJx.mjs.map