@configdirector/client-sdk 1.7.0 → 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.
@@ -88,9 +88,76 @@ type ConfigDirectorMetaContext = {
88
88
  appVersion?: string;
89
89
  appName?: string;
90
90
  };
91
- 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>;
92
101
  //#endregion
93
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
+ };
94
161
  /**
95
162
  * Configuration options for the {@link ConfigDirectorClient}
96
163
  */
@@ -102,39 +169,7 @@ type ConfigDirectorClientOptions = {
102
169
  /**
103
170
  * Connection options
104
171
  */
105
- connection?: {
106
- /**
107
- * The connection mode to be used, one of `streaming` (default) or `polling`.
108
- * If set to `streaming`, the connection will remain open and receive updates whenever
109
- * config state is updated on the ConfigDirector dashboard.
110
- * When set to `polling`, there will be an initial request to retrieve config state during
111
- * initialization, and additional requests on a `pollingInterval`.
112
- *
113
- * Defaults to `streaming`
114
- */
115
- mode?: ConnectionMode;
116
- /**
117
- * The polling interval in _seconds_ when the `mode` is set to `polling`. This option has no
118
- * effect when the `mode` is set to `streaming`.
119
- *
120
- * Defaults to 60 seconds. The minimum is 30 seconds. A value below the minimum is raised to the
121
- * minimum and a warning is logged.
122
- */
123
- pollingInterval?: number;
124
- /**
125
- * The timeout, in _milliseconds_, to be used in initialization and when updating the context.
126
- * If streaming is enabled, the operation (initialization or context update) may still succeed
127
- * after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
128
- * If streaming is disabled, if the operation times out, it will not be retried.
129
- */
130
- timeout?: number;
131
- /**
132
- * The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
133
- * proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
134
- * a proxy for the client SDK.
135
- */
136
- url?: string;
137
- };
172
+ connection?: ConnectionOptions;
138
173
  /**
139
174
  * A logger that implements {@link ConfigDirectorLogger}. It defaults to the ConfigDirector console
140
175
  * logger set to 'warn' level.
@@ -166,6 +201,14 @@ type ConfigDirectorClientOptions = {
166
201
  */
167
202
  hooks?: ClientHooks;
168
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
+ };
169
212
  type ClientHooks = {
170
213
  clientReady?: HookHandler<"clientReady"> | HookHandler<"clientReady">[];
171
214
  configsUpdated?: HookHandler<"configsUpdated"> | HookHandler<"configsUpdated">[];
@@ -323,6 +366,10 @@ declare class ConfigDirectorValidationError extends Error {
323
366
  readonly name: string;
324
367
  constructor(message: string);
325
368
  }
369
+ declare class ConfigDirectorInitializationError extends Error {
370
+ readonly name: string;
371
+ constructor(message: string);
372
+ }
326
373
  //#endregion
327
- 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 };
328
- //# sourceMappingURL=errors-T_hDavJF.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":";KAAK,SAAA;AAAA,KACA,YAAA,GAAe,MAAA,CAAO,SAAA;AAAA,KAEtB,OAAA,uBAA8B,YAAA,qBAAiC,aAAA,KAClE,OAAA,EAAS,aAAA,CAAc,IAAA;AAAA,UAGR,aAAA,uBAAoC,YAAA;EACnD,EAAA,qBAAuB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,EAAS,OAAA,CAAQ,aAAA,EAAe,KAAA;EACnF,GAAA,qBAAwB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,GAAU,OAAA,CAAQ,aAAA,EAAe,KAAA;EACrF,KAAA;AAAA;;;KCEU,kBAAA;EAAA,CAAwB,GAAA;AAAA;AAAA,KAExB,eAAA,wCAAuD,kBAAA;AAAA,KAevD,0BAAA;AAAA,UAEK,oBAAA;EACf,KAAA,CAAM,OAAA,aAAoB,IAAA;EAE1B,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,KAAA,CAAM,OAAA,aAAoB,IAAA;AAAA;AAAA,UAGX,iCAAA;EACf,eAAA,CAAgB,OAAA;AAAA;AAAA,KAGN,gBAAA;AAAA,KAUA,gBAAA;EACV,GAAA;EACA,KAAA,EAAO,eAAA;EACP,OAAA;EACA,cAAA;EACA,MAAA,EAAQ,gBAAA;EACR,OAAA,GAAU,qBAAA;AAAA;;;;;;KAOA,qBAAA;ED3DoD;;;;;;;;ECoE9D,EAAA;EDrEsC;;;;;;;;;;;ECkFtC,IAAA;EDjFq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A,SACxB,IAAA;cAEb,OAAA;AAAA;AAAA,cAOD,iCAAA,SAA0C,KAAA;EAAA,SAC5B,IAAA;cAEb,OAAA;AAAA"}
@@ -88,9 +88,76 @@ type ConfigDirectorMetaContext = {
88
88
  appVersion?: string;
89
89
  appName?: string;
90
90
  };
91
- 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>;
92
101
  //#endregion
93
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
+ };
94
161
  /**
95
162
  * Configuration options for the {@link ConfigDirectorClient}
96
163
  */
@@ -102,39 +169,7 @@ type ConfigDirectorClientOptions = {
102
169
  /**
103
170
  * Connection options
104
171
  */
105
- connection?: {
106
- /**
107
- * The connection mode to be used, one of `streaming` (default) or `polling`.
108
- * If set to `streaming`, the connection will remain open and receive updates whenever
109
- * config state is updated on the ConfigDirector dashboard.
110
- * When set to `polling`, there will be an initial request to retrieve config state during
111
- * initialization, and additional requests on a `pollingInterval`.
112
- *
113
- * Defaults to `streaming`
114
- */
115
- mode?: ConnectionMode;
116
- /**
117
- * The polling interval in _seconds_ when the `mode` is set to `polling`. This option has no
118
- * effect when the `mode` is set to `streaming`.
119
- *
120
- * Defaults to 60 seconds. The minimum is 30 seconds. A value below the minimum is raised to the
121
- * minimum and a warning is logged.
122
- */
123
- pollingInterval?: number;
124
- /**
125
- * The timeout, in _milliseconds_, to be used in initialization and when updating the context.
126
- * If streaming is enabled, the operation (initialization or context update) may still succeed
127
- * after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
128
- * If streaming is disabled, if the operation times out, it will not be retried.
129
- */
130
- timeout?: number;
131
- /**
132
- * The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
133
- * proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
134
- * a proxy for the client SDK.
135
- */
136
- url?: string;
137
- };
172
+ connection?: ConnectionOptions;
138
173
  /**
139
174
  * A logger that implements {@link ConfigDirectorLogger}. It defaults to the ConfigDirector console
140
175
  * logger set to 'warn' level.
@@ -166,6 +201,14 @@ type ConfigDirectorClientOptions = {
166
201
  */
167
202
  hooks?: ClientHooks;
168
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
+ };
169
212
  type ClientHooks = {
170
213
  clientReady?: HookHandler<"clientReady"> | HookHandler<"clientReady">[];
171
214
  configsUpdated?: HookHandler<"configsUpdated"> | HookHandler<"configsUpdated">[];
@@ -323,6 +366,10 @@ declare class ConfigDirectorValidationError extends Error {
323
366
  readonly name: string;
324
367
  constructor(message: string);
325
368
  }
369
+ declare class ConfigDirectorInitializationError extends Error {
370
+ readonly name: string;
371
+ constructor(message: string);
372
+ }
326
373
  //#endregion
327
- 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 };
328
- //# sourceMappingURL=errors-DTlTJsJh.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":";KAAK,SAAA;AAAA,KACA,YAAA,GAAe,MAAA,CAAO,SAAA;AAAA,KAEtB,OAAA,uBAA8B,YAAA,qBAAiC,aAAA,KAClE,OAAA,EAAS,aAAA,CAAc,IAAA;AAAA,UAGR,aAAA,uBAAoC,YAAA;EACnD,EAAA,qBAAuB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,EAAS,OAAA,CAAQ,aAAA,EAAe,KAAA;EACnF,GAAA,qBAAwB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,GAAU,OAAA,CAAQ,aAAA,EAAe,KAAA;EACrF,KAAA;AAAA;;;KCEU,kBAAA;EAAA,CAAwB,GAAA;AAAA;AAAA,KAExB,eAAA,wCAAuD,kBAAA;AAAA,KAevD,0BAAA;AAAA,UAEK,oBAAA;EACf,KAAA,CAAM,OAAA,aAAoB,IAAA;EAE1B,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,KAAA,CAAM,OAAA,aAAoB,IAAA;AAAA;AAAA,UAGX,iCAAA;EACf,eAAA,CAAgB,OAAA;AAAA;AAAA,KAGN,gBAAA;AAAA,KAUA,gBAAA;EACV,GAAA;EACA,KAAA,EAAO,eAAA;EACP,OAAA;EACA,cAAA;EACA,MAAA,EAAQ,gBAAA;EACR,OAAA,GAAU,qBAAA;AAAA;;;;;;KAOA,qBAAA;ED3DoD;;;;;;;;ECoE9D,EAAA;EDrEsC;;;;;;;;;;;ECkFtC,IAAA;EDjFqF;;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ACxB,IAAA;cAEb,OAAA;AAAA;AAAA,cAOD,iCAAA,SAA0C,KAAA;EAAA,SAC5B,IAAA;cAEb,OAAA;AAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@configdirector/client-sdk",
3
- "version": "1.7.0",
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,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.connectionGeneration=0,this.options=t,this.logger=t.logger,this.url=t.resolveUrl(`client/sse/v1`,t.baseUrl)}async connect(e,t){var n=this;let r=++n.connectionGeneration,i=await n.options.clientSession;if(r!==n.connectionGeneration)return n;n.eventSource&&n.close();let a=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:i.instanceId,ephemeral:i.ephemeral}),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([a,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;this.connectionGeneration++,(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=1e3,V=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,H=(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},U=(e,t)=>{let n=`configdirector.instanceId.v1|${e}|${t}`,r=H(n,2166136261);return H(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},W=()=>{try{var e;return(e=globalThis.localStorage)==null?void 0:e}catch(e){return}},G=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||!V.test(n)?!1:i===U(n,r)},K=async(e,t)=>{let n;try{n=await e.getItem(z)}catch(e){return t.debug(`[ConfigDirectorClient] Could not read the stored instance id, using an ephemeral one`,e),{outcome:`failed`}}if(typeof n!=`string`||n===``)return{outcome:`nothing usable`};let r;try{r=JSON.parse(n)}catch(e){return t.debug(`[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one`),{outcome:`nothing usable`}}if(!G(r))return t.debug(`[ConfigDirectorClient] The stored instance id failed validation, generating a new one`),{outcome:`nothing usable`};let i=Date.now()-r.createdAt;return i<0||i>=216e5?(t.debug(`[ConfigDirectorClient] The stored instance id has expired, generating a new one`),{outcome:`nothing usable`}):{outcome:`stored`,instanceId:r.id}},q=async(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:U(t,r)};try{return await e.setItem(z,JSON.stringify(i)),!0}catch(e){return n.debug(`[ConfigDirectorClient] Could not persist the instance id, using it as an ephemeral one`,e),!1}},J=async(e,t,n,r)=>{let i=await K(e,r);switch(i.outcome){case`stored`:return{instanceId:i.instanceId};case`failed`:return{instanceId:t,ephemeral:!0};case`nothing usable`:break}return n.passed?{instanceId:t,ephemeral:!0}:await q(e,t,r)?{instanceId:t}:{instanceId:t,ephemeral:!0}},Y=(e,t=W())=>{let n=R();if(!t)return e.debug(`[ConfigDirectorClient] No instance id storage is available, using an ephemeral instance id`),Promise.resolve({instanceId:n,ephemeral:!0});let r={passed:!1},i,a=new Promise(t=>{i=setTimeout(()=>{r.passed=!0,e.warn(`[ConfigDirectorClient] The instance id storage did not respond within ${B}ms, using an ephemeral instance id`),t({instanceId:n,ephemeral:!0})},B)});return Promise.race([J(t,n,r,e),a]).finally(()=>clearTimeout(i))};var X=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 Z=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 Q=class extends X{constructor(t){var n;super(),this.options=t,this.eventEmitter=new e,this.connectionGeneration=0,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;let r=++n.connectionGeneration;n.clearPollingInterval();let i=await n.options.clientSession;if(r!==n.connectionGeneration)return n;try{await n.fetchConfigs(e,t,i)}finally{n.fatalError||n.schedulePollingInterval(()=>{n.fetchConfigs(e,t,i).catch(e=>{n.logger.error(`[PollingTransport] Error during polling:`,e)})})}return n}close(){this.connectionGeneration++,super.close()}async fetchConfigs(e,t,n){var r=this;if(r.fatalError){r.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let i=await Z(t,r.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:r.options.metaContext,clientSdkKey:r.options.clientSdkKey,instanceId:n.instanceId,ephemeral:n.ephemeral,lastUpdateTimestamp:r.lastUpdateTimestamp})},r.logger);if(await r.handleNonOkResponse(i),i.status==200){let e=JSON.parse(await i.text());r.lastUpdateTimestamp=e.timestamp,r.eventEmitter.emit(`configSetReceived`,e)}}catch(e){try{r.handleFetchError(e)}catch(e){throw r.fatalError&&r.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 $=e=>{try{return e(globalThis)}catch(e){return}},ee=()=>$(e=>{var t;return(t=e.navigator)==null?void 0:t.userAgent}),te=()=>$(e=>{var t;return(t=e.location)==null?void 0:t.host}),ne=e=>e>=`a`&&e<=`z`||e>=`0`&&e<=`9`||e===`-`||e===`_`,re=e=>{if(e.length<1||e.length>64)return!1;for(let t of e)if(!ne(t))return!1;return!0},ie=e=>e==null||typeof e==`string`&&re(e),ae=e=>{if(typeof e==`string`)return e;try{return String(e)}catch(t){return Object.prototype.toString.call(e)}},oe=(e,t)=>{let n=``,r=0;for(let i of e){if(r===t)break;n+=i,r+=1}return n},se=e=>{let t=e==null?void 0:e.kind;return ie(t)?{outcome:`admitted`,context:e}:{outcome:`ignored`,kindSample:oe(ae(t),128)}};var ce=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.clientSession=Y(this.logger,a==null?void 0:a.instanceIdStorage),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))({clientSession:this.clientSession,clientSdkKey:e,baseUrl:n,resolveUrl:r,metaContext:f(f({},i==null?void 0:i.metadata),{},{sdkName:t.sdkName,sdkVersion:t.sdkVersion,userAgent:ee(),host:te()}),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 Q;default:return _}}async initialize(e){var t=this;t.hasReceivedConfigSet||(t.initializing=!0),await t.submitContext(e,`initialization`)}async updateContext(e){await this.submitContext(e,`context update`)}async submitContext(e,t){var n=this;await n.connectToTransport(n.contextToConnectWith(e,t),t)}contextToConnectWith(e,t){let n=se(e);switch(n.outcome){case`admitted`:return n.context;case`ignored`:this.logger.error(`[ConfigDirectorClient] Ignored the context supplied for ${t} because its kind '${n.kindSample}' is invalid; connecting as if no context was supplied. A context kind has 1 to 64 characters, using only lowercase letters, digits, '-' and '_'.`),this.telemetryClient.recordInvalidContext(n.kindSample);return}}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,ce as t};
6
- //# sourceMappingURL=DefaultConfigDirectorClient-DWgN1o7o.mjs.map