@configdirector/react-native-sdk 1.5.1 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1341 @@
1
+ //#region \0@oxc-project+runtime@0.122.0/helpers/typeof.js
2
+ function _typeof(o) {
3
+ "@babel/helpers - typeof";
4
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
5
+ return typeof o;
6
+ } : function(o) {
7
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
8
+ }, _typeof(o);
9
+ }
10
+ //#endregion
11
+ //#region \0@oxc-project+runtime@0.122.0/helpers/toPrimitive.js
12
+ function toPrimitive(t, r) {
13
+ if ("object" != _typeof(t) || !t) return t;
14
+ var e = t[Symbol.toPrimitive];
15
+ if (void 0 !== e) {
16
+ var i = e.call(t, r || "default");
17
+ if ("object" != _typeof(i)) return i;
18
+ throw new TypeError("@@toPrimitive must return a primitive value.");
19
+ }
20
+ return ("string" === r ? String : Number)(t);
21
+ }
22
+ //#endregion
23
+ //#region \0@oxc-project+runtime@0.122.0/helpers/toPropertyKey.js
24
+ function toPropertyKey(t) {
25
+ var i = toPrimitive(t, "string");
26
+ return "symbol" == _typeof(i) ? i : i + "";
27
+ }
28
+ //#endregion
29
+ //#region \0@oxc-project+runtime@0.122.0/helpers/defineProperty.js
30
+ function _defineProperty(e, r, t) {
31
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
32
+ value: t,
33
+ enumerable: !0,
34
+ configurable: !0,
35
+ writable: !0
36
+ }) : e[r] = t, e;
37
+ }
38
+ //#endregion
39
+ //#region ../js-client-core/src/Emitter.ts
40
+ var Emitter = class {
41
+ constructor() {
42
+ _defineProperty(this, "handlerMap", /* @__PURE__ */ new Map());
43
+ }
44
+ on(name, handler) {
45
+ const handlers = this.handlerMap.get(name);
46
+ if (handlers) handlers.push(handler);
47
+ else this.handlerMap.set(name, [handler]);
48
+ }
49
+ once(name, handler) {
50
+ const self = this;
51
+ function onceHandler(payload) {
52
+ self.off(name, onceHandler);
53
+ handler.apply(self, payload);
54
+ }
55
+ this.on(name, onceHandler);
56
+ }
57
+ off(name, handler) {
58
+ const handlers = this.handlerMap.get(name);
59
+ if (!handlers) return;
60
+ if (handler) {
61
+ const listenerIndex = handlers.indexOf(handler);
62
+ if (listenerIndex >= 0) handlers.splice(listenerIndex, 1);
63
+ } else this.handlerMap.set(name, []);
64
+ }
65
+ clear() {
66
+ this.handlerMap.clear();
67
+ }
68
+ emit(name, payload) {
69
+ const handlers = this.handlerMap.get(name);
70
+ if (!handlers) return;
71
+ handlers.slice().map((h) => h(payload));
72
+ }
73
+ };
74
+ //#endregion
75
+ //#region ../shared/src/errors.ts
76
+ var ConfigDirectorConnectionError = class ConfigDirectorConnectionError extends Error {
77
+ constructor(message, status) {
78
+ super(message);
79
+ _defineProperty(this, "name", "ConfigDirectorConnectionError");
80
+ _defineProperty(this, "status", void 0);
81
+ this.status = status;
82
+ Object.setPrototypeOf(this, ConfigDirectorConnectionError.prototype);
83
+ }
84
+ };
85
+ var ConfigDirectorValidationError = class ConfigDirectorValidationError extends Error {
86
+ constructor(message) {
87
+ super(message);
88
+ _defineProperty(this, "name", "ConfigDirectorValidationError");
89
+ Object.setPrototypeOf(this, ConfigDirectorValidationError.prototype);
90
+ }
91
+ };
92
+ //#endregion
93
+ //#region ../js-client-core/src/errors.ts
94
+ const isFetchErrorFatal = (fetchError) => {
95
+ if ((fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) === "NotAllowedError") return true;
96
+ else if (fetchError instanceof TypeError) return true;
97
+ return false;
98
+ };
99
+ //#endregion
100
+ //#region ../eventsource/src/errors.ts
101
+ var StreamClosedError = class StreamClosedError extends Error {
102
+ constructor(message) {
103
+ super(message);
104
+ _defineProperty(this, "name", "StreamClosedError");
105
+ Object.setPrototypeOf(this, StreamClosedError.prototype);
106
+ }
107
+ };
108
+ var MissingResponseBodyError = class MissingResponseBodyError extends Error {
109
+ constructor(message) {
110
+ super(message);
111
+ _defineProperty(this, "name", "MissingResponseBodyError");
112
+ Object.setPrototypeOf(this, MissingResponseBodyError.prototype);
113
+ }
114
+ };
115
+ var InvalidOptionError = class InvalidOptionError extends Error {
116
+ constructor(message) {
117
+ super(message);
118
+ _defineProperty(this, "name", "InvalidOptionError");
119
+ Object.setPrototypeOf(this, InvalidOptionError.prototype);
120
+ }
121
+ };
122
+ var ValueOutOfRangeError = class ValueOutOfRangeError extends Error {
123
+ constructor(message) {
124
+ super(message);
125
+ _defineProperty(this, "name", "ValueOutOfRangeError");
126
+ Object.setPrototypeOf(this, ValueOutOfRangeError.prototype);
127
+ }
128
+ };
129
+ //#endregion
130
+ //#region ../eventsource/src/types.ts
131
+ let ReadyState = /* @__PURE__ */ function(ReadyState) {
132
+ ReadyState["OPEN"] = "open";
133
+ ReadyState["CLOSED"] = "closed";
134
+ ReadyState["CONNECTING"] = "connecting";
135
+ return ReadyState;
136
+ }({});
137
+ //#endregion
138
+ //#region ../eventsource/src/EventSourceParser.ts
139
+ var EventSourceParser = class {
140
+ constructor(options) {
141
+ var _options$onEvent;
142
+ _defineProperty(this, "isFirstChunk", true);
143
+ _defineProperty(this, "bufferedInput", "");
144
+ _defineProperty(this, "currentEvent", { data: "" });
145
+ _defineProperty(this, "lastEventId", void 0);
146
+ _defineProperty(this, "onEvent", void 0);
147
+ _defineProperty(this, "onRetry", void 0);
148
+ _defineProperty(this, "onComment", void 0);
149
+ this.currentEvent = { data: "" };
150
+ this.onEvent = (_options$onEvent = options.onEvent) !== null && _options$onEvent !== void 0 ? _options$onEvent : (() => {});
151
+ this.onRetry = options.onRetry;
152
+ this.onComment = options.onComment;
153
+ }
154
+ parse(chunk) {
155
+ let input = chunk;
156
+ if (this.isFirstChunk) {
157
+ this.isFirstChunk = false;
158
+ if (input.startsWith("")) input = input.slice(1);
159
+ else if (input.startsWith("")) input = input.slice(3);
160
+ }
161
+ const lines = this.scanLines(this.bufferedInput + input);
162
+ for (const line of lines) this.dispatchLine(line);
163
+ }
164
+ finish() {
165
+ this.bufferedInput = "";
166
+ }
167
+ /**
168
+ * Scans `text` character by character to extract complete lines, recognizing
169
+ * CR, LF, and CRLF as line terminators per the SSE spec. Any unterminated
170
+ * trailing text is buffered and prepended to the next chunk.
171
+ */
172
+ scanLines(text) {
173
+ const lines = [];
174
+ let lineStart = 0;
175
+ let i = 0;
176
+ while (i < text.length) {
177
+ const ch = text[i];
178
+ if (ch === "\r" || ch === "\n") {
179
+ lines.push(text.slice(lineStart, i));
180
+ if (ch === "\r" && text[i + 1] === "\n") i++;
181
+ i++;
182
+ lineStart = i;
183
+ } else i++;
184
+ }
185
+ this.bufferedInput = text.slice(lineStart);
186
+ return lines;
187
+ }
188
+ dispatchLine(line) {
189
+ if (line.startsWith(":")) {
190
+ var _this$onComment;
191
+ (_this$onComment = this.onComment) === null || _this$onComment === void 0 || _this$onComment.call(this, this.extractValue(line, 1));
192
+ return;
193
+ }
194
+ if (line === "") {
195
+ this.emitEvent();
196
+ return;
197
+ }
198
+ this.applyField(this.parseField(line));
199
+ }
200
+ emitEvent() {
201
+ const data = this.currentEvent.data.endsWith("\n") ? this.currentEvent.data.slice(0, -1) : this.currentEvent.data;
202
+ if (data !== "") this.onEvent({
203
+ ...this.currentEvent,
204
+ id: this.lastEventId,
205
+ data
206
+ });
207
+ this.currentEvent = { data: "" };
208
+ }
209
+ applyField(parsed) {
210
+ switch (parsed.field) {
211
+ case "event":
212
+ this.currentEvent.type = parsed.value;
213
+ break;
214
+ case "data":
215
+ this.currentEvent.data += parsed.value + "\n";
216
+ break;
217
+ case "id":
218
+ if (!parsed.value.includes("\0")) this.lastEventId = parsed.value;
219
+ break;
220
+ case "retry":
221
+ if (/^\d+$/.test(parsed.value)) {
222
+ var _this$onRetry;
223
+ (_this$onRetry = this.onRetry) === null || _this$onRetry === void 0 || _this$onRetry.call(this, Number.parseInt(parsed.value, 10));
224
+ }
225
+ break;
226
+ default: break;
227
+ }
228
+ }
229
+ parseField(line) {
230
+ const colon = line.indexOf(":");
231
+ if (colon === -1) return {
232
+ field: line,
233
+ value: ""
234
+ };
235
+ return {
236
+ field: line.slice(0, colon),
237
+ value: this.extractValue(line, colon + 1)
238
+ };
239
+ }
240
+ /** Returns the value portion of a line, stripping a single leading space per spec. */
241
+ extractValue(line, from) {
242
+ return line[from] === " " ? line.slice(from + 1) : line.slice(from);
243
+ }
244
+ };
245
+ //#endregion
246
+ //#region ../eventsource/src/EventSourceClient.ts
247
+ var EventSourceClient = class {
248
+ constructor(options) {
249
+ var _options$method, _options$fetch;
250
+ _defineProperty(this, "DEFAULT_SHOULD_RECONNECT", () => true);
251
+ _defineProperty(this, "DEFAULT_CALCULATE_RECONNECT_DELAY", () => this.serverReconnectionTime);
252
+ _defineProperty(this, "url", void 0);
253
+ _defineProperty(this, "headers", void 0);
254
+ _defineProperty(this, "body", void 0);
255
+ _defineProperty(this, "requestOptions", void 0);
256
+ _defineProperty(this, "lastEventId", void 0);
257
+ _defineProperty(this, "reconnectAttempt", 0);
258
+ _defineProperty(this, "abortController", new AbortController());
259
+ _defineProperty(this, "reconnectTimeout", void 0);
260
+ _defineProperty(this, "_readyState", ReadyState.CLOSED);
261
+ _defineProperty(this, "serverReconnectionTime", 2e3);
262
+ _defineProperty(this, "_fetch", void 0);
263
+ _defineProperty(this, "_onError", void 0);
264
+ _defineProperty(this, "_onMessage", void 0);
265
+ _defineProperty(this, "_onComment", void 0);
266
+ _defineProperty(this, "_onConnect", void 0);
267
+ _defineProperty(this, "_onDisconnect", void 0);
268
+ _defineProperty(this, "_shouldReconnect", void 0);
269
+ _defineProperty(this, "_calculateReconnectDelay", void 0);
270
+ this.url = options.url.toString();
271
+ this.lastEventId = options.lastEventId;
272
+ this.headers = {
273
+ Accept: "text/event-stream",
274
+ ...options.headers
275
+ };
276
+ const body = options.body;
277
+ this.body = typeof body === "function" ? body : () => body;
278
+ this.requestOptions = {
279
+ method: (_options$method = options.method) !== null && _options$method !== void 0 ? _options$method : "GET",
280
+ mode: options.mode,
281
+ credentials: options.credentials,
282
+ redirect: options.redirect,
283
+ referrer: options.referrer,
284
+ referrerPolicy: options.referrerPolicy
285
+ };
286
+ this._fetch = (_options$fetch = options.fetch) !== null && _options$fetch !== void 0 ? _options$fetch : ((url, init) => fetch(url, init));
287
+ this._onError = this.resolveCallback(options.onError, () => {}, "onError");
288
+ this._onConnect = this.resolveCallback(options.onConnect, () => {}, "onConnect");
289
+ this._onDisconnect = this.resolveCallback(options.onDisconnect, () => {}, "onDisconnect");
290
+ this._onMessage = this.resolveCallback(options.onMessage, () => {}, "onMessage");
291
+ this._onComment = this.resolveCallback(options.onComment, () => {}, "onComment");
292
+ this._shouldReconnect = this.resolveCallback(options.shouldReconnect, this.DEFAULT_SHOULD_RECONNECT, "shouldReconnect");
293
+ this._calculateReconnectDelay = this.resolveCallback(options.calculateReconnectDelay, this.DEFAULT_CALCULATE_RECONNECT_DELAY, "calculateReconnectDelay");
294
+ }
295
+ set onError(value) {
296
+ this._onError = this.resolveCallback(value, () => {}, "onError");
297
+ }
298
+ set onMessage(value) {
299
+ this._onMessage = this.resolveCallback(value, () => {}, "onMessage");
300
+ }
301
+ set onComment(value) {
302
+ this._onComment = this.resolveCallback(value, () => {}, "onComment");
303
+ }
304
+ set onConnect(value) {
305
+ this._onConnect = this.resolveCallback(value, () => {}, "onConnect");
306
+ }
307
+ set onDisconnect(value) {
308
+ this._onDisconnect = this.resolveCallback(value, () => {}, "onDisconnect");
309
+ }
310
+ set shouldReconnect(value) {
311
+ this._shouldReconnect = this.resolveCallback(value, this.DEFAULT_SHOULD_RECONNECT, "shouldReconnect");
312
+ }
313
+ set calculateReconnectDelay(value) {
314
+ this._calculateReconnectDelay = this.resolveCallback(value, this.DEFAULT_CALCULATE_RECONNECT_DELAY, "shouldReconnect");
315
+ }
316
+ get readyState() {
317
+ return this._readyState;
318
+ }
319
+ connect() {
320
+ if (this._readyState !== ReadyState.CLOSED) return;
321
+ this.reconnectAttempt = 0;
322
+ this.initiateConnection();
323
+ }
324
+ close() {
325
+ clearTimeout(this.reconnectTimeout);
326
+ this._readyState = ReadyState.CLOSED;
327
+ this.abortController.abort();
328
+ }
329
+ initiateConnection() {
330
+ this.abortController = new AbortController();
331
+ this._readyState = ReadyState.CONNECTING;
332
+ this._fetch(this.url, {
333
+ ...this.requestOptions,
334
+ body: this.body(),
335
+ headers: this.buildRequestHeaders(),
336
+ signal: this.abortController.signal,
337
+ cache: "no-store"
338
+ }).then((response) => this.handleFetchResponse(response)).catch((error) => {
339
+ if (error.name === "AbortError" || this.abortController.signal.aborted) {
340
+ this.close();
341
+ return;
342
+ }
343
+ this._onError(error);
344
+ this.scheduleReconnect({ error });
345
+ });
346
+ }
347
+ async handleFetchResponse(response) {
348
+ const { body, status } = response;
349
+ if (status === 204) {
350
+ this.disconnected();
351
+ return;
352
+ }
353
+ if (status >= 400) {
354
+ this.scheduleReconnect({ status });
355
+ return;
356
+ }
357
+ if (!body) throw new MissingResponseBodyError("The server response did not have a body");
358
+ this._readyState = ReadyState.OPEN;
359
+ this._onConnect();
360
+ this.reconnectAttempt = 0;
361
+ const parser = new EventSourceParser({
362
+ onEvent: (event) => {
363
+ if (typeof event.id === "string") this.lastEventId = event.id;
364
+ this._onMessage(event);
365
+ },
366
+ onComment: (comment) => this._onComment(comment),
367
+ onRetry: (retryDelay) => this.serverReconnectionTime = retryDelay
368
+ });
369
+ await this.readResponseStream(body, parser);
370
+ this.scheduleReconnect({
371
+ status,
372
+ error: new StreamClosedError("The server response stream was closed")
373
+ });
374
+ }
375
+ async readResponseStream(body, parser) {
376
+ const reader = body.getReader();
377
+ const decoder = new TextDecoder();
378
+ let done = false;
379
+ while (!done) {
380
+ const result = await reader.read();
381
+ if (result.value) parser.parse(decoder.decode(result.value, { stream: true }));
382
+ done = result.done;
383
+ }
384
+ parser.finish();
385
+ }
386
+ disconnected() {
387
+ clearTimeout(this.reconnectTimeout);
388
+ this._readyState = ReadyState.CLOSED;
389
+ this._onDisconnect();
390
+ }
391
+ buildRequestHeaders() {
392
+ const lastEventIdHeader = this.lastEventId ? { "Last-Event-ID": this.lastEventId } : void 0;
393
+ return {
394
+ ...this.headers,
395
+ ...lastEventIdHeader
396
+ };
397
+ }
398
+ scheduleReconnect(state) {
399
+ if (this.abortController.signal.aborted) return;
400
+ clearTimeout(this.reconnectTimeout);
401
+ this.reconnectAttempt += 1;
402
+ const reconnectionState = {
403
+ attempt: this.reconnectAttempt,
404
+ status: state.status,
405
+ error: state.error,
406
+ serverReconnectionTime: this.serverReconnectionTime
407
+ };
408
+ if (!this._shouldReconnect(reconnectionState)) {
409
+ this.disconnected();
410
+ return;
411
+ }
412
+ this._readyState = ReadyState.CONNECTING;
413
+ let delay = this._calculateReconnectDelay(reconnectionState);
414
+ if (!Number.isFinite(delay) || delay < 1 || delay > 1e3 * 60 * 60) {
415
+ this._onError(new ValueOutOfRangeError(`The calculated reconnect delay is out of range: ${delay}. Defaulting to ${this.serverReconnectionTime}`));
416
+ delay = this.serverReconnectionTime;
417
+ }
418
+ this.reconnectTimeout = setTimeout(() => this.initiateConnection(), delay);
419
+ }
420
+ resolveCallback(provided, fallback, optionName) {
421
+ if (provided == null) return fallback;
422
+ if (typeof provided !== "function") throw new InvalidOptionError(`${optionName} must be a function`);
423
+ return provided;
424
+ }
425
+ };
426
+ //#endregion
427
+ //#region ../eventsource/src/index.ts
428
+ const createEventSourceClient = (options) => {
429
+ return new EventSourceClient(options);
430
+ };
431
+ //#endregion
432
+ //#region ../js-client-core/src/StreamingTransport.ts
433
+ var StreamingTransport = class {
434
+ constructor(options) {
435
+ this.options = options;
436
+ _defineProperty(this, "logger", void 0);
437
+ _defineProperty(this, "eventSource", void 0);
438
+ _defineProperty(this, "eventEmitter", new Emitter());
439
+ _defineProperty(this, "url", void 0);
440
+ _defineProperty(this, "timeoutTimer", void 0);
441
+ this.options = options;
442
+ this.logger = options.logger;
443
+ this.url = options.resolveUrl("client/sse/v1", options.baseUrl);
444
+ }
445
+ async connect(context, timeout) {
446
+ if (this.eventSource) this.close();
447
+ const eventSourcePromise = new Promise((resolve, reject) => {
448
+ this.eventSource = createEventSourceClient({
449
+ url: this.url,
450
+ method: "POST",
451
+ headers: { "Content-Type": "application/json" },
452
+ fetch: this.options.fetch,
453
+ body: JSON.stringify({
454
+ givenContext: context,
455
+ metaContext: this.options.metaContext,
456
+ clientSdkKey: this.options.clientSdkKey,
457
+ instanceId: this.options.instanceId
458
+ }),
459
+ onMessage: ({ data }) => {
460
+ this.dispatchMessage(data);
461
+ },
462
+ onConnect: () => {
463
+ this.logger.debug("[StreamingTransport] Connected");
464
+ resolve(this);
465
+ },
466
+ shouldReconnect: (state) => {
467
+ const reconnect = !this.isStatusFatal(state.status);
468
+ if (!reconnect) {
469
+ const error = this.prepareFatalError(state.status, state.error);
470
+ this.eventEmitter.emit("connectionError", error);
471
+ reject(error);
472
+ }
473
+ return reconnect;
474
+ },
475
+ calculateReconnectDelay: (state) => {
476
+ const delay = this.options.connectionRetryDelay(state.attempt);
477
+ const logMessage = `[StreamingTransport] Scheduling reconnect attempt #${state.attempt} in ${delay}ms.`;
478
+ if (state.attempt <= 5) this.logger.info(logMessage);
479
+ else this.logger.warn(logMessage);
480
+ return delay;
481
+ },
482
+ onError: (error) => {
483
+ this.logger.debug("[StreamingTransport] Error: ", error);
484
+ },
485
+ onDisconnect: () => {
486
+ this.logger.debug("[StreamingTransport] Disconnected");
487
+ }
488
+ });
489
+ this.eventSource.connect();
490
+ });
491
+ clearTimeout(this.timeoutTimer);
492
+ this.timeoutTimer = void 0;
493
+ return Promise.race([eventSourcePromise, new Promise((resolve) => {
494
+ this.timeoutTimer = setTimeout(() => resolve(this), timeout);
495
+ })]).finally(() => clearTimeout(this.timeoutTimer));
496
+ }
497
+ dispatchMessage(data) {
498
+ try {
499
+ const json = JSON.parse(data);
500
+ this.eventEmitter.emit("configSetReceived", json);
501
+ } catch (error) {
502
+ this.logger.error("[StreamingTransport] Error parsing and dispatching config data update: ", error);
503
+ }
504
+ }
505
+ prepareFatalError(responseStatus, error) {
506
+ const status = responseStatus !== null && responseStatus !== void 0 ? responseStatus : 0;
507
+ return new ConfigDirectorConnectionError(`${`Connection failed with status: ${responseStatus !== null && responseStatus !== void 0 ? responseStatus : "unknown"}.`}${error ? ` Error: ${error}` : ""}. This is an unrecoverable error, will not attempt to reconnect.`, status);
508
+ }
509
+ isStatusFatal(status) {
510
+ return !!status && status >= 400 && status < 500 && status != 429;
511
+ }
512
+ on(name, handler) {
513
+ this.eventEmitter.on(name, handler);
514
+ }
515
+ off(name, handler) {
516
+ this.eventEmitter.off(name, handler);
517
+ }
518
+ clear() {
519
+ this.eventEmitter.clear();
520
+ }
521
+ close() {
522
+ var _this$eventSource;
523
+ (_this$eventSource = this.eventSource) === null || _this$eventSource === void 0 || _this$eventSource.close();
524
+ clearTimeout(this.timeoutTimer);
525
+ }
526
+ dispose() {
527
+ this.close();
528
+ this.clear();
529
+ }
530
+ };
531
+ //#endregion
532
+ //#region ../shared/src/value-parser.ts
533
+ const getRequestedType = (defaultValue) => {
534
+ const baseType = typeof defaultValue;
535
+ if (baseType === "object") try {
536
+ var _constructor$name, _constructor;
537
+ return (_constructor$name = (_constructor = defaultValue.constructor) === null || _constructor === void 0 ? void 0 : _constructor.name) !== null && _constructor$name !== void 0 ? _constructor$name : baseType;
538
+ } catch {
539
+ return baseType;
540
+ }
541
+ else if (baseType === "function") try {
542
+ const functionName = defaultValue.name;
543
+ return functionName ? `function: ${functionName}` : baseType;
544
+ } catch {
545
+ return baseType;
546
+ }
547
+ return baseType;
548
+ };
549
+ const isNumericNativeType = (requestedType) => {
550
+ return requestedType === "number" || requestedType === "bigint";
551
+ };
552
+ const configTypesNotReadableAsString = new Set([
553
+ "boolean",
554
+ "integer",
555
+ "float"
556
+ ]);
557
+ const parseConfigValue = (configState, defaultValue) => {
558
+ const value = configState.value;
559
+ const requestedType = getRequestedType(defaultValue);
560
+ if (value == null || value === "") return {
561
+ parsedValue: defaultValue,
562
+ parsedValueId: void 0,
563
+ requestedType,
564
+ usedDefault: true,
565
+ reason: "value-missing"
566
+ };
567
+ if (configState.type === "json") return parseJson(value, defaultValue, requestedType, configState.valueId);
568
+ if (typeof defaultValue === "string") {
569
+ if (configTypesNotReadableAsString.has(configState.type)) return {
570
+ parsedValue: defaultValue,
571
+ parsedValueId: void 0,
572
+ requestedType,
573
+ usedDefault: true,
574
+ reason: "type-mismatch"
575
+ };
576
+ return {
577
+ parsedValue: value,
578
+ parsedValueId: configState.valueId,
579
+ requestedType,
580
+ usedDefault: false,
581
+ reason: "found-match"
582
+ };
583
+ }
584
+ if (typeof defaultValue === "boolean" && (configState.type === "boolean" || configState.type === "string" || configState.type === "enum")) {
585
+ const boolValue = parseConfigBoolean(value);
586
+ const hasBoolean = typeof boolValue === "boolean";
587
+ return {
588
+ parsedValue: hasBoolean ? boolValue : defaultValue,
589
+ parsedValueId: hasBoolean ? configState.valueId : void 0,
590
+ requestedType,
591
+ usedDefault: !hasBoolean,
592
+ reason: hasBoolean ? "found-match" : "invalid-boolean"
593
+ };
594
+ }
595
+ if (isNumericNativeType(typeof defaultValue) && configState.type === "integer") {
596
+ const numValue = parseConfigInteger(value);
597
+ const hasNumber = typeof numValue === "number";
598
+ return {
599
+ parsedValue: hasNumber ? numValue : defaultValue,
600
+ parsedValueId: hasNumber ? configState.valueId : void 0,
601
+ requestedType,
602
+ usedDefault: !hasNumber,
603
+ reason: hasNumber ? "found-match" : "invalid-number"
604
+ };
605
+ }
606
+ if (isNumericNativeType(typeof defaultValue) && (configState.type === "float" || configState.type === "enum" || configState.type === "string")) {
607
+ const numValue = parseConfigFloat(value);
608
+ const hasNumber = typeof numValue === "number";
609
+ return {
610
+ parsedValue: hasNumber ? numValue : defaultValue,
611
+ parsedValueId: hasNumber ? configState.valueId : void 0,
612
+ requestedType,
613
+ usedDefault: !hasNumber,
614
+ reason: hasNumber ? "found-match" : "invalid-number"
615
+ };
616
+ }
617
+ return {
618
+ parsedValue: defaultValue,
619
+ parsedValueId: void 0,
620
+ requestedType,
621
+ usedDefault: true,
622
+ reason: "type-mismatch"
623
+ };
624
+ };
625
+ const parseConfigBoolean = (value) => {
626
+ if (!value) return;
627
+ const lowerValue = value.toLowerCase();
628
+ if (lowerValue != "true" && lowerValue != "false") return;
629
+ return lowerValue === "true";
630
+ };
631
+ const parseConfigInteger = (value) => {
632
+ const num = parseStrictNumber(value);
633
+ return num == null ? void 0 : Math.trunc(num);
634
+ };
635
+ const parseConfigFloat = (value) => {
636
+ return parseStrictNumber(value);
637
+ };
638
+ const parseStrictNumber = (value) => {
639
+ if (!value || !isDecimalCharacters(value)) return;
640
+ const num = Number(value);
641
+ if (isNaN(num) || !isFinite(num)) return;
642
+ return num;
643
+ };
644
+ const isDecimalCharacters = (value) => {
645
+ for (const character of value) if (!(character >= "0" && character <= "9") && !"+-.eE".includes(character)) return false;
646
+ return true;
647
+ };
648
+ const parseJson = (jsonString, defaultValue, requestedType, valueId) => {
649
+ if (typeof defaultValue === "string") return {
650
+ parsedValue: jsonString,
651
+ parsedValueId: valueId,
652
+ requestedType,
653
+ usedDefault: false,
654
+ reason: "found-match"
655
+ };
656
+ try {
657
+ const parsed = JSON.parse(jsonString);
658
+ if (!isJsonTypeCompatible(parsed, defaultValue)) return {
659
+ parsedValue: defaultValue,
660
+ parsedValueId: void 0,
661
+ requestedType,
662
+ usedDefault: true,
663
+ reason: "type-mismatch"
664
+ };
665
+ return {
666
+ parsedValue: parsed,
667
+ parsedValueId: valueId,
668
+ requestedType,
669
+ usedDefault: false,
670
+ reason: "found-match"
671
+ };
672
+ } catch {
673
+ return {
674
+ parsedValue: defaultValue,
675
+ parsedValueId: void 0,
676
+ requestedType,
677
+ usedDefault: true,
678
+ reason: "invalid-json"
679
+ };
680
+ }
681
+ };
682
+ const isJsonTypeCompatible = (parsed, defaultValue) => {
683
+ if (parsed === null) return false;
684
+ const defaultType = typeof defaultValue;
685
+ if (defaultType === "bigint") return typeof parsed === "number";
686
+ return typeof parsed === defaultType;
687
+ };
688
+ //#endregion
689
+ //#region ../shared/src/logger.ts
690
+ const LEVELS = {
691
+ off: -1,
692
+ error: 0,
693
+ warn: 1,
694
+ info: 2,
695
+ debug: 3
696
+ };
697
+ const buildDateFormatter = () => {
698
+ const baseOptions = {
699
+ year: "numeric",
700
+ month: "2-digit",
701
+ day: "2-digit",
702
+ hour: "2-digit",
703
+ minute: "2-digit",
704
+ second: "2-digit",
705
+ timeZoneName: "short"
706
+ };
707
+ try {
708
+ return new Intl.DateTimeFormat(void 0, {
709
+ ...baseOptions,
710
+ fractionalSecondDigits: 3
711
+ });
712
+ } catch {
713
+ return new Intl.DateTimeFormat(void 0, baseOptions);
714
+ }
715
+ };
716
+ var DefaultConsoleLogger = class {
717
+ constructor(level, decorator) {
718
+ this.level = level;
719
+ this.decorator = decorator;
720
+ _defineProperty(this, "dateFormatter", void 0);
721
+ this.level = level;
722
+ this.decorator = decorator;
723
+ this.dateFormatter = buildDateFormatter();
724
+ }
725
+ debug(message, ...args) {
726
+ this.log(console.debug, "debug", message, ...args);
727
+ }
728
+ info(message, ...args) {
729
+ this.log(console.info, "info", message, ...args);
730
+ }
731
+ warn(message, ...args) {
732
+ this.log(console.warn, "warn", message, ...args);
733
+ }
734
+ error(message, ...args) {
735
+ this.log(console.error, "error", message, ...args);
736
+ }
737
+ log(loggerFunction, level, message, ...args) {
738
+ if (LEVELS[this.level] >= LEVELS[level]) {
739
+ var _this$decorator;
740
+ loggerFunction(`[${this.dateFormatter.format(/* @__PURE__ */ new Date())}] ${(_this$decorator = this.decorator) === null || _this$decorator === void 0 ? void 0 : _this$decorator.decorateMessage(message)}`, ...args);
741
+ }
742
+ }
743
+ };
744
+ //#endregion
745
+ //#region ../js-client-core/src/logger.ts
746
+ var LogMessageDecorator = class {
747
+ decorateMessage(message) {
748
+ return `[ConfigDirector:js-client-sdk] ${message}`;
749
+ }
750
+ };
751
+ const createDefaultLogger = (level, messageDecorator) => {
752
+ return new DefaultConsoleLogger(level !== null && level !== void 0 ? level : "warn", messageDecorator !== null && messageDecorator !== void 0 ? messageDecorator : new LogMessageDecorator());
753
+ };
754
+ //#endregion
755
+ //#region ../shared/src/url.ts
756
+ const defaultUrlFactory = (input, base) => new URL(input, base === null || base === void 0 ? void 0 : base.toString());
757
+ //#endregion
758
+ //#region ../shared/src/constants.ts
759
+ const CLIENT_BASE_URL = "https://client-sdk-api.configdirector.com";
760
+ //#endregion
761
+ //#region ../shared/src/transport/pollingInterval.ts
762
+ const resolvePollingInterval = (configuredSeconds, defaults) => {
763
+ if (configuredSeconds === void 0) return {
764
+ seconds: defaults.defaultSeconds,
765
+ warning: void 0
766
+ };
767
+ if (configuredSeconds >= defaults.minimumSeconds) return {
768
+ seconds: configuredSeconds,
769
+ warning: void 0
770
+ };
771
+ return {
772
+ seconds: defaults.minimumSeconds,
773
+ warning: `pollingInterval of ${configuredSeconds} seconds is below the minimum of ${defaults.minimumSeconds} seconds. Using ${defaults.minimumSeconds} seconds.`
774
+ };
775
+ };
776
+ //#endregion
777
+ //#region ../shared/src/instance-id.ts
778
+ const generateInstanceId = () => {
779
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return crypto.randomUUID();
780
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (placeholder) => {
781
+ const random = Math.random() * 16 | 0;
782
+ return (placeholder === "x" ? random : random & 3 | 8).toString(16);
783
+ });
784
+ };
785
+ //#endregion
786
+ //#region ../js-client-core/src/instance-id.ts
787
+ const STORAGE_KEY = "configdirector-sdk:instance-id";
788
+ const RECORD_VERSION = 1;
789
+ const MAX_AGE_MS = 360 * 60 * 1e3;
790
+ const CHECKSUM_SALT = "configdirector.instanceId.v1";
791
+ const UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
792
+ const fnv1a = (input, offsetBasis) => {
793
+ let hash = offsetBasis;
794
+ for (let i = 0; i < input.length; i++) {
795
+ hash ^= input.charCodeAt(i);
796
+ hash = Math.imul(hash, 16777619);
797
+ }
798
+ return hash >>> 0;
799
+ };
800
+ const checksumFor = (id, createdAt) => {
801
+ const payload = `${CHECKSUM_SALT}|${id}|${createdAt}`;
802
+ const low = fnv1a(payload, 2166136261);
803
+ return fnv1a(`${low}|${payload}`, 16777619).toString(16).padStart(8, "0") + low.toString(16).padStart(8, "0");
804
+ };
805
+ const getLocalStorage = () => {
806
+ try {
807
+ var _localStorage;
808
+ return (_localStorage = globalThis.localStorage) !== null && _localStorage !== void 0 ? _localStorage : void 0;
809
+ } catch {
810
+ return;
811
+ }
812
+ };
813
+ const isUsableRecord = (record) => {
814
+ if (!record || typeof record !== "object") return false;
815
+ const { v, id, createdAt, checksum } = record;
816
+ if (v !== RECORD_VERSION || typeof id !== "string" || typeof checksum !== "string") return false;
817
+ if (typeof createdAt !== "number" || !Number.isInteger(createdAt) || createdAt <= 0) return false;
818
+ if (!UUID_V4_PATTERN.test(id)) return false;
819
+ return checksum === checksumFor(id, createdAt);
820
+ };
821
+ const readStoredInstanceId = (storage, logger) => {
822
+ let raw;
823
+ try {
824
+ raw = storage.getItem(STORAGE_KEY);
825
+ } catch (error) {
826
+ logger === null || logger === void 0 || logger.debug("[ConfigDirectorClient] Could not read the stored instance id, generating a new one", error);
827
+ return;
828
+ }
829
+ if (!raw) return;
830
+ let record;
831
+ try {
832
+ record = JSON.parse(raw);
833
+ } catch {
834
+ logger === null || logger === void 0 || logger.debug("[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one");
835
+ return;
836
+ }
837
+ if (!isUsableRecord(record)) {
838
+ logger === null || logger === void 0 || logger.debug("[ConfigDirectorClient] The stored instance id failed validation, generating a new one");
839
+ return;
840
+ }
841
+ const age = Date.now() - record.createdAt;
842
+ if (age < 0 || age >= MAX_AGE_MS) {
843
+ logger === null || logger === void 0 || logger.debug("[ConfigDirectorClient] The stored instance id has expired, generating a new one");
844
+ return;
845
+ }
846
+ return record.id;
847
+ };
848
+ const storeInstanceId = (storage, id, logger) => {
849
+ const createdAt = Date.now();
850
+ const record = {
851
+ v: RECORD_VERSION,
852
+ id,
853
+ createdAt,
854
+ checksum: checksumFor(id, createdAt)
855
+ };
856
+ try {
857
+ storage.setItem(STORAGE_KEY, JSON.stringify(record));
858
+ } catch (error) {
859
+ logger === null || logger === void 0 || logger.debug("[ConfigDirectorClient] Could not persist the instance id", error);
860
+ }
861
+ };
862
+ const resolveInstanceId = (logger) => {
863
+ const storage = getLocalStorage();
864
+ if (!storage) return generateInstanceId();
865
+ const storedInstanceId = readStoredInstanceId(storage, logger);
866
+ if (storedInstanceId) return storedInstanceId;
867
+ const instanceId = generateInstanceId();
868
+ storeInstanceId(storage, instanceId, logger);
869
+ return instanceId;
870
+ };
871
+ //#endregion
872
+ //#region ../shared/src/transport/AbstractPollingTransport.ts
873
+ var AbstractPollingTransport = class {
874
+ constructor() {
875
+ _defineProperty(this, "fatalError", false);
876
+ _defineProperty(this, "pollingInterval", void 0);
877
+ }
878
+ clearPollingInterval() {
879
+ clearInterval(this.pollingInterval);
880
+ }
881
+ schedulePollingInterval(callback) {
882
+ clearInterval(this.pollingInterval);
883
+ if (this.pollingIntervalSeconds <= 0) return;
884
+ this.pollingInterval = setInterval(callback, this.pollingIntervalSeconds * 1e3);
885
+ }
886
+ async handleNonOkResponse(response) {
887
+ if (!response.ok) if (this.isStatusFatal(response.status)) {
888
+ this.fatalError = true;
889
+ this.close();
890
+ throw this.prepareFatalResponseStatusError(response.status, await response.text());
891
+ } else throw new ConfigDirectorConnectionError(`Connection failed with status: ${response.status}`, response.status);
892
+ }
893
+ handleFetchError(fetchError) {
894
+ if (this.isFetchErrorFatal(fetchError)) {
895
+ this.fatalError = true;
896
+ this.close();
897
+ throw new ConfigDirectorConnectionError(`Connection failed with fatal error: ${fetchError}. This is an unrecoverable error, retry attempts will be ignored.`);
898
+ } else if (fetchError instanceof SyntaxError) throw new ConfigDirectorConnectionError(`Failed to parse the response from the server: ${fetchError}`);
899
+ else throw new ConfigDirectorConnectionError(`Connection failed with error: ${fetchError}.`);
900
+ }
901
+ prepareFatalResponseStatusError(responseStatus, errorBody) {
902
+ var _errorBody$trim$lengt, _errorBody$trim;
903
+ const status = responseStatus !== null && responseStatus !== void 0 ? responseStatus : 0;
904
+ return new ConfigDirectorConnectionError(`${`Connection failed with status: ${responseStatus !== null && responseStatus !== void 0 ? responseStatus : "unknown"}`}${((_errorBody$trim$lengt = errorBody === null || errorBody === void 0 || (_errorBody$trim = errorBody.trim()) === null || _errorBody$trim === void 0 ? void 0 : _errorBody$trim.length) !== null && _errorBody$trim$lengt !== void 0 ? _errorBody$trim$lengt : 0) > 0 ? ` (${errorBody})` : ""}. This is an unrecoverable error, retry attempts will be ignored.`, status);
905
+ }
906
+ isStatusFatal(status) {
907
+ return !!status && status >= 400 && status < 500 && status != 429;
908
+ }
909
+ isFetchErrorFatal(fetchError) {
910
+ return (fetchError === null || fetchError === void 0 ? void 0 : fetchError.name) === "NotAllowedError";
911
+ }
912
+ get isConnected() {
913
+ return this.pollingInterval !== void 0;
914
+ }
915
+ close() {
916
+ clearInterval(this.pollingInterval);
917
+ this.pollingInterval = void 0;
918
+ }
919
+ dispose() {
920
+ this.close();
921
+ this.clear();
922
+ }
923
+ };
924
+ //#endregion
925
+ //#region ../shared/src/fetchWithTimeout.ts
926
+ const fetchWithTimeout = async (timeout, resource, options, logger) => {
927
+ const abortController = new AbortController();
928
+ const abortTimeoutId = setTimeout(() => {
929
+ logger.debug("[fetchWithTimeout] Reached timeout, aborting request");
930
+ abortController.abort();
931
+ }, timeout);
932
+ try {
933
+ const response = await fetch(typeof resource === "string" || resource instanceof Request ? resource : resource.toString(), {
934
+ ...options,
935
+ signal: abortController.signal
936
+ });
937
+ clearTimeout(abortTimeoutId);
938
+ return response;
939
+ } catch (error) {
940
+ logger.warn("[fetchWithTimeout] Fetch error: ", error);
941
+ clearTimeout(abortTimeoutId);
942
+ throw error;
943
+ }
944
+ };
945
+ //#endregion
946
+ //#region ../js-client-core/src/PollingTransport.ts
947
+ var PollingTransport = class extends AbstractPollingTransport {
948
+ constructor(options) {
949
+ var _options$pollingInter;
950
+ super();
951
+ this.options = options;
952
+ _defineProperty(this, "pollingIntervalSeconds", void 0);
953
+ _defineProperty(this, "logger", void 0);
954
+ _defineProperty(this, "eventEmitter", new Emitter());
955
+ _defineProperty(this, "url", void 0);
956
+ _defineProperty(this, "lastUpdateTimestamp", void 0);
957
+ this.options = options;
958
+ this.logger = options.logger;
959
+ this.url = options.resolveUrl("client/polling/v1", options.baseUrl);
960
+ this.pollingIntervalSeconds = (_options$pollingInter = options.pollingInterval) !== null && _options$pollingInter !== void 0 ? _options$pollingInter : 60;
961
+ }
962
+ async connect(context, timeout) {
963
+ this.clearPollingInterval();
964
+ try {
965
+ await this.fetchConfigs(context, timeout);
966
+ } finally {
967
+ if (!this.fatalError) this.schedulePollingInterval(() => {
968
+ this.fetchConfigs(context, timeout).catch((error) => {
969
+ this.logger.error("[PollingTransport] Error during polling:", error);
970
+ });
971
+ });
972
+ }
973
+ return this;
974
+ }
975
+ async fetchConfigs(context, timeout) {
976
+ if (this.fatalError) {
977
+ this.logger.warn("[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.");
978
+ return;
979
+ }
980
+ try {
981
+ const response = await fetchWithTimeout(timeout, this.url, {
982
+ method: "POST",
983
+ headers: { "Content-Type": "application/json" },
984
+ body: JSON.stringify({
985
+ givenContext: context,
986
+ metaContext: this.options.metaContext,
987
+ clientSdkKey: this.options.clientSdkKey,
988
+ instanceId: this.options.instanceId,
989
+ lastUpdateTimestamp: this.lastUpdateTimestamp
990
+ })
991
+ }, this.logger);
992
+ await this.handleNonOkResponse(response);
993
+ if (response.status == 200) {
994
+ const json = JSON.parse(await response.text());
995
+ this.lastUpdateTimestamp = json.timestamp;
996
+ this.eventEmitter.emit("configSetReceived", json);
997
+ }
998
+ } catch (fetchError) {
999
+ try {
1000
+ this.handleFetchError(fetchError);
1001
+ } catch (handledError) {
1002
+ if (this.fatalError) this.eventEmitter.emit("connectionError", handledError);
1003
+ throw handledError;
1004
+ }
1005
+ }
1006
+ }
1007
+ on(name, handler) {
1008
+ this.eventEmitter.on(name, handler);
1009
+ }
1010
+ off(name, handler) {
1011
+ this.eventEmitter.off(name, handler);
1012
+ }
1013
+ clear() {
1014
+ this.eventEmitter.clear();
1015
+ }
1016
+ };
1017
+ //#endregion
1018
+ //#region ../js-client-core/src/browser-globals.ts
1019
+ const read = (readValue) => {
1020
+ try {
1021
+ return readValue(globalThis);
1022
+ } catch {
1023
+ return;
1024
+ }
1025
+ };
1026
+ const readUserAgent = () => read((globals) => {
1027
+ var _globals$navigator;
1028
+ return (_globals$navigator = globals.navigator) === null || _globals$navigator === void 0 ? void 0 : _globals$navigator.userAgent;
1029
+ });
1030
+ const readHost = () => read((globals) => {
1031
+ var _globals$location;
1032
+ return (_globals$location = globals.location) === null || _globals$location === void 0 ? void 0 : _globals$location.host;
1033
+ });
1034
+ //#endregion
1035
+ //#region ../js-client-core/src/DefaultConfigDirectorClient.ts
1036
+ const MAX_EXPONENTIAL_DELAY = 9;
1037
+ var DefaultConfigDirectorClient = class {
1038
+ constructor(telemetryClient, clientSdkKey, sdkOptions, clientOptions, internalClientOptions) {
1039
+ var _clientOptions$logger, _clientOptions$connec, _clientOptions$connec2, _internalClientOption, _this$parseUrl, _clientOptions$connec3, _clientOptions$connec4, _clientOptions$connec5, _internalClientOption2, _clientOptions$hooks, _clientOptions$hooks2, _clientOptions$hooks3, _clientOptions$hooks4, _clientOptions$hooks5;
1040
+ _defineProperty(this, "logger", void 0);
1041
+ _defineProperty(this, "telemetryClient", void 0);
1042
+ _defineProperty(this, "configSet", void 0);
1043
+ _defineProperty(this, "handlersMap", /* @__PURE__ */ new Map());
1044
+ _defineProperty(this, "transport", void 0);
1045
+ _defineProperty(this, "eventEmitter", new Emitter());
1046
+ _defineProperty(this, "timeout", void 0);
1047
+ _defineProperty(this, "timeoutTimer", void 0);
1048
+ _defineProperty(this, "ready", false);
1049
+ _defineProperty(this, "initializing", false);
1050
+ _defineProperty(this, "hasReceivedConfigSet", false);
1051
+ _defineProperty(this, "readyPromise", void 0);
1052
+ _defineProperty(this, "readyResolve", void 0);
1053
+ _defineProperty(this, "currentContext", void 0);
1054
+ _defineProperty(this, "connectionMode", void 0);
1055
+ _defineProperty(this, "instanceId", void 0);
1056
+ this.logger = (_clientOptions$logger = clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.logger) !== null && _clientOptions$logger !== void 0 ? _clientOptions$logger : createDefaultLogger();
1057
+ this.instanceId = resolveInstanceId(this.logger);
1058
+ this.timeout = (_clientOptions$connec = clientOptions === null || clientOptions === void 0 || (_clientOptions$connec2 = clientOptions.connection) === null || _clientOptions$connec2 === void 0 ? void 0 : _clientOptions$connec2.timeout) !== null && _clientOptions$connec !== void 0 ? _clientOptions$connec : 3e3;
1059
+ this.validateSdkKeyPresence(clientSdkKey);
1060
+ const urlFactory = (_internalClientOption = internalClientOptions === null || internalClientOptions === void 0 ? void 0 : internalClientOptions.urlFactory) !== null && _internalClientOption !== void 0 ? _internalClientOption : defaultUrlFactory;
1061
+ const baseUrl = (_this$parseUrl = this.parseUrl(clientOptions === null || clientOptions === void 0 || (_clientOptions$connec3 = clientOptions.connection) === null || _clientOptions$connec3 === void 0 ? void 0 : _clientOptions$connec3.url, urlFactory)) !== null && _this$parseUrl !== void 0 ? _this$parseUrl : CLIENT_BASE_URL;
1062
+ this.connectionMode = (_clientOptions$connec4 = clientOptions === null || clientOptions === void 0 || (_clientOptions$connec5 = clientOptions.connection) === null || _clientOptions$connec5 === void 0 ? void 0 : _clientOptions$connec5.mode) !== null && _clientOptions$connec4 !== void 0 ? _clientOptions$connec4 : "streaming";
1063
+ this.telemetryClient = telemetryClient;
1064
+ this.transport = (_internalClientOption2 = internalClientOptions === null || internalClientOptions === void 0 ? void 0 : internalClientOptions.transport) !== null && _internalClientOption2 !== void 0 ? _internalClientOption2 : this.buildTransport(clientSdkKey, sdkOptions, baseUrl, urlFactory, clientOptions, internalClientOptions);
1065
+ this.transport.on("configSetReceived", (configSet) => {
1066
+ var _this$readyResolve;
1067
+ this.hasReceivedConfigSet = true;
1068
+ (_this$readyResolve = this.readyResolve) === null || _this$readyResolve === void 0 || _this$readyResolve.call(this);
1069
+ const removedKeys = this.findKeysRemovedBy(configSet);
1070
+ if (!this.configSet || configSet.kind == "full") this.configSet = configSet;
1071
+ else this.configSet.configs = {
1072
+ ...this.configSet.configs,
1073
+ ...configSet.configs
1074
+ };
1075
+ const keys = Object.keys(configSet.configs);
1076
+ this.emit("configsUpdated", {
1077
+ keys,
1078
+ removedKeys
1079
+ });
1080
+ this.updateWatchers([...keys, ...removedKeys]);
1081
+ this.logger.debug("[ConfigDirectorClient] ConfigSet updated from server:", {
1082
+ keys,
1083
+ removedKeys
1084
+ });
1085
+ });
1086
+ this.transport.on("connectionError", (error) => {
1087
+ this.initializing = false;
1088
+ this.logger.error("[ConfigDirectorClient] The connection encountered an unrecoverable error and will not be retried. Configs will no longer receive updates.", error);
1089
+ this.emit("connectionError", { error });
1090
+ });
1091
+ this.registerHandler("clientReady", clientOptions === null || clientOptions === void 0 || (_clientOptions$hooks = clientOptions.hooks) === null || _clientOptions$hooks === void 0 ? void 0 : _clientOptions$hooks.clientReady);
1092
+ this.registerHandler("configEvaluated", clientOptions === null || clientOptions === void 0 || (_clientOptions$hooks2 = clientOptions.hooks) === null || _clientOptions$hooks2 === void 0 ? void 0 : _clientOptions$hooks2.configEvaluated);
1093
+ this.registerHandler("configsUpdated", clientOptions === null || clientOptions === void 0 || (_clientOptions$hooks3 = clientOptions.hooks) === null || _clientOptions$hooks3 === void 0 ? void 0 : _clientOptions$hooks3.configsUpdated);
1094
+ this.registerHandler("contextUpdated", clientOptions === null || clientOptions === void 0 || (_clientOptions$hooks4 = clientOptions.hooks) === null || _clientOptions$hooks4 === void 0 ? void 0 : _clientOptions$hooks4.contextUpdated);
1095
+ this.registerHandler("connectionError", clientOptions === null || clientOptions === void 0 || (_clientOptions$hooks5 = clientOptions.hooks) === null || _clientOptions$hooks5 === void 0 ? void 0 : _clientOptions$hooks5.connectionError);
1096
+ }
1097
+ registerHandler(event, handler) {
1098
+ if (!handler) return;
1099
+ const handlers = Array.isArray(handler) ? handler : [handler];
1100
+ for (const h of handlers) if (typeof h === "function") this.on(event, h);
1101
+ }
1102
+ resolvePollingIntervalForMode(configuredSeconds) {
1103
+ if (this.connectionMode !== "polling") return;
1104
+ const resolved = resolvePollingInterval(configuredSeconds, {
1105
+ defaultSeconds: 60,
1106
+ minimumSeconds: 30
1107
+ });
1108
+ if (resolved.warning) this.logger.warn(`[ConfigDirectorClient] ${resolved.warning}`);
1109
+ return resolved.seconds;
1110
+ }
1111
+ buildTransport(clientSdkKey, sdkOptions, baseUrl, urlFactory, clientOptions, internalClientOptions) {
1112
+ var _internalClientOption3, _clientOptions$connec6;
1113
+ return new (this.getTransportConstructor(this.connectionMode))({
1114
+ instanceId: this.instanceId,
1115
+ clientSdkKey,
1116
+ baseUrl,
1117
+ resolveUrl: urlFactory,
1118
+ metaContext: {
1119
+ ...clientOptions === null || clientOptions === void 0 ? void 0 : clientOptions.metadata,
1120
+ sdkName: sdkOptions.sdkName,
1121
+ sdkVersion: sdkOptions.sdkVersion,
1122
+ userAgent: readUserAgent(),
1123
+ host: readHost()
1124
+ },
1125
+ logger: this.logger,
1126
+ fetch: internalClientOptions === null || internalClientOptions === void 0 ? void 0 : internalClientOptions.fetch,
1127
+ connectionRetryDelay: (_internalClientOption3 = internalClientOptions === null || internalClientOptions === void 0 ? void 0 : internalClientOptions.connectionRetryDelay) !== null && _internalClientOption3 !== void 0 ? _internalClientOption3 : ((attempt) => {
1128
+ return Math.pow(2, Math.min(attempt, MAX_EXPONENTIAL_DELAY)) * 1e3;
1129
+ }),
1130
+ pollingInterval: this.resolvePollingIntervalForMode(clientOptions === null || clientOptions === void 0 || (_clientOptions$connec6 = clientOptions.connection) === null || _clientOptions$connec6 === void 0 ? void 0 : _clientOptions$connec6.pollingInterval)
1131
+ });
1132
+ }
1133
+ getTransportConstructor(connectionMode) {
1134
+ switch (connectionMode) {
1135
+ case "polling": return PollingTransport;
1136
+ default: return StreamingTransport;
1137
+ }
1138
+ }
1139
+ async initialize(context) {
1140
+ if (!this.hasReceivedConfigSet) this.initializing = true;
1141
+ await this.connectToTransport(context, "initialization");
1142
+ }
1143
+ async updateContext(context) {
1144
+ await this.connectToTransport(context, "context update");
1145
+ }
1146
+ get context() {
1147
+ return this.currentContext;
1148
+ }
1149
+ async connectToTransport(context, caller) {
1150
+ try {
1151
+ this.ready = false;
1152
+ this.readyPromise = new Promise((resolve) => {
1153
+ this.readyResolve = resolve;
1154
+ }).then((cancelled) => {
1155
+ if (cancelled) return;
1156
+ this.ready = true;
1157
+ this.initializing = false;
1158
+ this.emit("clientReady", { action: caller });
1159
+ this.logger.debug("[ConfigDirectorClient] Received initial payload from the server, client is ready");
1160
+ });
1161
+ const startTime = (/* @__PURE__ */ new Date()).getTime();
1162
+ await this.transport.connect(context !== null && context !== void 0 ? context : {}, this.timeout, caller);
1163
+ this.currentContext = context;
1164
+ this.telemetryClient.updateContext(context);
1165
+ this.emit("contextUpdated", { context });
1166
+ const elapsedTime = (/* @__PURE__ */ new Date()).getTime() - startTime;
1167
+ const remainingTimeout = this.timeout - elapsedTime;
1168
+ clearTimeout(this.timeoutTimer);
1169
+ this.timeoutTimer = void 0;
1170
+ if (remainingTimeout > 0) await Promise.race([this.readyPromise, new Promise((resolve) => {
1171
+ this.timeoutTimer = setTimeout(() => resolve(), remainingTimeout);
1172
+ })]).finally(() => clearTimeout(this.timeoutTimer));
1173
+ if (!this.ready) this.logger.warn(`[ConfigDirectorClient] Timed out waiting for ${caller} 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.`);
1174
+ } catch (error) {
1175
+ this.logger.error(`[ConfigDirectorClient] An error occurred during ${caller}: `, error);
1176
+ }
1177
+ }
1178
+ findKeysRemovedBy(configSet) {
1179
+ if (!this.configSet || configSet.kind != "full") return [];
1180
+ return Object.keys(this.configSet.configs).filter((key) => !Object.prototype.hasOwnProperty.call(configSet.configs, key));
1181
+ }
1182
+ updateWatchers(configKeys) {
1183
+ configKeys.forEach((configKey) => this.updateWatchersForConfig(configKey));
1184
+ }
1185
+ updateWatchersForConfig(configKey) {
1186
+ var _this$configSet, _this$handlersMap$get;
1187
+ const configState = (_this$configSet = this.configSet) === null || _this$configSet === void 0 ? void 0 : _this$configSet.configs[configKey];
1188
+ (_this$handlersMap$get = this.handlersMap.get(configKey)) === null || _this$handlersMap$get === void 0 || _this$handlersMap$get.forEach((h) => {
1189
+ const value = this.getValueFromConfigState(configKey, configState, h.defaultValue);
1190
+ h.handler(value);
1191
+ });
1192
+ }
1193
+ watch(configKey, defaultValue, callback) {
1194
+ this.validateDefaultValue(defaultValue);
1195
+ const handlers = this.handlersMap.get(configKey);
1196
+ const handlerWithOptions = {
1197
+ handler: callback,
1198
+ defaultValue,
1199
+ requestedType: typeof defaultValue
1200
+ };
1201
+ if (handlers) handlers.push(handlerWithOptions);
1202
+ else this.handlersMap.set(configKey, [handlerWithOptions]);
1203
+ return () => this.unwatch(configKey, callback);
1204
+ }
1205
+ unwatch(configKey, callback) {
1206
+ const handlers = this.handlersMap.get(configKey);
1207
+ if (!handlers) return;
1208
+ if (callback) {
1209
+ const index = handlers.findIndex((h) => h.handler == callback);
1210
+ if (index >= 0) handlers === null || handlers === void 0 || handlers.splice(index, 1);
1211
+ } else handlers.splice(0);
1212
+ }
1213
+ getValue(configKey, defaultValue) {
1214
+ var _this$configSet2;
1215
+ this.validateDefaultValue(defaultValue);
1216
+ const configState = (_this$configSet2 = this.configSet) === null || _this$configSet2 === void 0 ? void 0 : _this$configSet2.configs[configKey];
1217
+ return this.getValueFromConfigState(configKey, configState, defaultValue);
1218
+ }
1219
+ getValueFromConfigState(configKey, configState, defaultValue) {
1220
+ var _this$currentContext2, _parseResult$parsedVa;
1221
+ if (!configState) {
1222
+ var _this$currentContext;
1223
+ this.logger.debug(`[ConfigDirectorClient] No config state found for '${configKey}', returning default value '${defaultValue}'`);
1224
+ const reason = this.isReady ? "config-state-missing" : "client-not-ready";
1225
+ this.telemetryClient.evaluatedConfig({
1226
+ contextId: (_this$currentContext = this.currentContext) === null || _this$currentContext === void 0 ? void 0 : _this$currentContext.id,
1227
+ key: configKey,
1228
+ defaultValue,
1229
+ requestedType: getRequestedType(defaultValue),
1230
+ evaluatedValue: defaultValue,
1231
+ usedDefault: true,
1232
+ evaluationReason: reason
1233
+ });
1234
+ this.dispatchEvaluationEvent({
1235
+ key: configKey,
1236
+ value: defaultValue,
1237
+ isDefaultValue: true,
1238
+ reason,
1239
+ context: this.context
1240
+ });
1241
+ return defaultValue;
1242
+ }
1243
+ const parseResult = parseConfigValue(configState, defaultValue);
1244
+ this.telemetryClient.evaluatedConfig({
1245
+ contextId: (_this$currentContext2 = this.currentContext) === null || _this$currentContext2 === void 0 ? void 0 : _this$currentContext2.id,
1246
+ type: configState.type,
1247
+ key: configKey,
1248
+ defaultValue,
1249
+ requestedType: parseResult.requestedType,
1250
+ evaluatedValue: parseResult.parsedValue,
1251
+ evaluatedValueId: parseResult.parsedValueId,
1252
+ usedDefault: parseResult.usedDefault,
1253
+ evaluationReason: parseResult.reason
1254
+ });
1255
+ this.dispatchEvaluationEvent({
1256
+ key: configKey,
1257
+ value: parseResult.parsedValue,
1258
+ valueId: (_parseResult$parsedVa = parseResult.parsedValueId) !== null && _parseResult$parsedVa !== void 0 ? _parseResult$parsedVa : void 0,
1259
+ isDefaultValue: parseResult.usedDefault,
1260
+ reason: parseResult.reason,
1261
+ context: this.context
1262
+ });
1263
+ this.logger.debug(`[ConfigDirectorClient] Evaluated '${configKey}' to '${parseResult.parsedValue}'`);
1264
+ return parseResult.parsedValue;
1265
+ }
1266
+ dispatchEvaluationEvent(event) {
1267
+ setTimeout(() => this.emit("configEvaluated", { evaluation: event }), 0);
1268
+ }
1269
+ emit(name, payload) {
1270
+ try {
1271
+ this.eventEmitter.emit(name, payload);
1272
+ } catch (error) {
1273
+ this.logger.error(`[ConfigDirectorClient] Error executing event handlers for '${name}'`, error);
1274
+ }
1275
+ }
1276
+ parseUrl(url, urlFactory) {
1277
+ if (!url) return;
1278
+ try {
1279
+ return urlFactory(url);
1280
+ } catch (error) {
1281
+ throw new ConfigDirectorValidationError(`Invalid base URL '${url}'. Parsing failed: ${error}`);
1282
+ }
1283
+ }
1284
+ validateSdkKeyPresence(sdkKey) {
1285
+ if (!sdkKey || sdkKey.trim().length == 0) throw new ConfigDirectorValidationError("No client SDK key was provided, the client cannot be instantiated without a valid client SDK key");
1286
+ }
1287
+ validateDefaultValue(defaultValue) {
1288
+ if (defaultValue === void 0 || defaultValue === null) throw new ConfigDirectorValidationError("Invalid default value. The default value for a config must be defined and non-null.");
1289
+ if (typeof defaultValue === "function") throw new ConfigDirectorValidationError("Invalid default value. The default value for a config cannot be a function.");
1290
+ }
1291
+ get isReady() {
1292
+ return this.ready;
1293
+ }
1294
+ get isInitializing() {
1295
+ return this.initializing;
1296
+ }
1297
+ on(eventName, handler) {
1298
+ this.eventEmitter.on(eventName, handler);
1299
+ }
1300
+ off(eventName, handler) {
1301
+ this.eventEmitter.off(eventName, handler);
1302
+ }
1303
+ clear() {
1304
+ this.logger.debug("[ConfigDirectorClient] clear() has been called, removing all observers");
1305
+ this.eventEmitter.clear();
1306
+ this.handlersMap.clear();
1307
+ }
1308
+ unwatchAll() {
1309
+ this.handlersMap.clear();
1310
+ }
1311
+ pauseNetwork() {
1312
+ this.logger.debug("[ConfigDirectorClient] pauseNetwork() called, pausing transport connection");
1313
+ clearTimeout(this.timeoutTimer);
1314
+ this.timeoutTimer = void 0;
1315
+ this.transport.close();
1316
+ this.ready = false;
1317
+ }
1318
+ async resumeNetwork() {
1319
+ await this.connectToTransport(this.currentContext, "network resume");
1320
+ }
1321
+ async close() {
1322
+ var _this$readyResolve2;
1323
+ this.logger.debug("[ConfigDirectorClient] close() has been called, closing connection to server");
1324
+ clearTimeout(this.timeoutTimer);
1325
+ (_this$readyResolve2 = this.readyResolve) === null || _this$readyResolve2 === void 0 || _this$readyResolve2.call(this, true);
1326
+ this.telemetryClient.close();
1327
+ this.transport.close();
1328
+ this.ready = false;
1329
+ this.initializing = false;
1330
+ }
1331
+ dispose() {
1332
+ this.clear();
1333
+ this.close();
1334
+ }
1335
+ };
1336
+ //#endregion
1337
+ //#region ../js-client-core/src/installedTestClient.ts
1338
+ const INSTALLED_TEST_CLIENT_SLOT = Symbol.for("@configdirector/installed-test-client");
1339
+ const readInstalledTestClient = () => globalThis[INSTALLED_TEST_CLIENT_SLOT];
1340
+ //#endregion
1341
+ export { CLIENT_BASE_URL as a, ConfigDirectorConnectionError as c, _defineProperty as d, fetchWithTimeout as i, ConfigDirectorValidationError as l, readInstalledTestClient as n, createDefaultLogger as o, DefaultConfigDirectorClient as r, isFetchErrorFatal as s, INSTALLED_TEST_CLIENT_SLOT as t, Emitter as u };