@launchdarkly/js-client-sdk-common 1.21.0 → 1.23.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.
Files changed (116) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/dist/cjs/DataManager.d.ts +24 -0
  3. package/dist/cjs/DataManager.d.ts.map +1 -1
  4. package/dist/cjs/LDClientImpl.d.ts.map +1 -1
  5. package/dist/cjs/api/LDOptions.d.ts +8 -0
  6. package/dist/cjs/api/LDOptions.d.ts.map +1 -1
  7. package/dist/cjs/api/datasource/DataSourceEntry.d.ts +11 -0
  8. package/dist/cjs/api/datasource/DataSourceEntry.d.ts.map +1 -1
  9. package/dist/cjs/api/datasource/LDClientDataSystemOptions.d.ts +22 -0
  10. package/dist/cjs/api/datasource/LDClientDataSystemOptions.d.ts.map +1 -1
  11. package/dist/cjs/api/datasource/ModeDefinition.d.ts +3 -3
  12. package/dist/cjs/api/datasource/ModeDefinition.d.ts.map +1 -1
  13. package/dist/cjs/api/datasource/ModeResolution.d.ts +75 -0
  14. package/dist/cjs/api/datasource/ModeResolution.d.ts.map +1 -0
  15. package/dist/cjs/api/datasource/index.d.ts +2 -1
  16. package/dist/cjs/api/datasource/index.d.ts.map +1 -1
  17. package/dist/cjs/configuration/Configuration.d.ts +6 -0
  18. package/dist/cjs/configuration/Configuration.d.ts.map +1 -1
  19. package/dist/cjs/configuration/validateOptions.d.ts +1 -1
  20. package/dist/cjs/configuration/validateOptions.d.ts.map +1 -1
  21. package/dist/cjs/configuration/validators.d.ts +5 -2
  22. package/dist/cjs/configuration/validators.d.ts.map +1 -1
  23. package/dist/cjs/datasource/ConnectionModeConfig.d.ts.map +1 -1
  24. package/dist/cjs/datasource/LDClientDataSystemOptions.d.ts +1 -0
  25. package/dist/cjs/datasource/LDClientDataSystemOptions.d.ts.map +1 -1
  26. package/dist/cjs/datasource/ModeResolver.d.ts +30 -0
  27. package/dist/cjs/datasource/ModeResolver.d.ts.map +1 -0
  28. package/dist/cjs/datasource/SourceFactoryProvider.d.ts +77 -0
  29. package/dist/cjs/datasource/SourceFactoryProvider.d.ts.map +1 -0
  30. package/dist/cjs/datasource/fdv2/CacheInitializer.d.ts +17 -0
  31. package/dist/cjs/datasource/fdv2/CacheInitializer.d.ts.map +1 -0
  32. package/dist/cjs/datasource/fdv2/FDv1PollingSynchronizer.d.ts +2 -0
  33. package/dist/cjs/datasource/fdv2/FDv1PollingSynchronizer.d.ts.map +1 -0
  34. package/dist/cjs/datasource/fdv2/FDv2DataSource.d.ts.map +1 -1
  35. package/dist/cjs/datasource/fdv2/FDv2SourceResult.d.ts +3 -1
  36. package/dist/cjs/datasource/fdv2/FDv2SourceResult.d.ts.map +1 -1
  37. package/dist/cjs/datasource/fdv2/calculatePollDelay.d.ts +2 -0
  38. package/dist/cjs/datasource/fdv2/calculatePollDelay.d.ts.map +1 -0
  39. package/dist/cjs/datasource/fdv2/index.d.ts +4 -0
  40. package/dist/cjs/datasource/fdv2/index.d.ts.map +1 -1
  41. package/dist/cjs/datasource/flagEvalMapper.d.ts +3 -3
  42. package/dist/cjs/flag-manager/FlagManager.d.ts +18 -2
  43. package/dist/cjs/flag-manager/FlagManager.d.ts.map +1 -1
  44. package/dist/cjs/flag-manager/FlagPersistence.d.ts +21 -2
  45. package/dist/cjs/flag-manager/FlagPersistence.d.ts.map +1 -1
  46. package/dist/cjs/flag-manager/FlagStore.d.ts +10 -0
  47. package/dist/cjs/flag-manager/FlagStore.d.ts.map +1 -1
  48. package/dist/cjs/flag-manager/FlagUpdater.d.ts +13 -1
  49. package/dist/cjs/flag-manager/FlagUpdater.d.ts.map +1 -1
  50. package/dist/cjs/index.cjs +1463 -60
  51. package/dist/cjs/index.cjs.map +1 -1
  52. package/dist/cjs/index.d.ts +8 -1
  53. package/dist/cjs/index.d.ts.map +1 -1
  54. package/dist/cjs/storage/freshness.d.ts +27 -0
  55. package/dist/cjs/storage/freshness.d.ts.map +1 -0
  56. package/dist/cjs/storage/loadCachedFlags.d.ts +25 -0
  57. package/dist/cjs/storage/loadCachedFlags.d.ts.map +1 -0
  58. package/dist/cjs/types/index.d.ts +2 -2
  59. package/dist/esm/DataManager.d.ts +24 -0
  60. package/dist/esm/DataManager.d.ts.map +1 -1
  61. package/dist/esm/LDClientImpl.d.ts.map +1 -1
  62. package/dist/esm/api/LDOptions.d.ts +8 -0
  63. package/dist/esm/api/LDOptions.d.ts.map +1 -1
  64. package/dist/esm/api/datasource/DataSourceEntry.d.ts +11 -0
  65. package/dist/esm/api/datasource/DataSourceEntry.d.ts.map +1 -1
  66. package/dist/esm/api/datasource/LDClientDataSystemOptions.d.ts +22 -0
  67. package/dist/esm/api/datasource/LDClientDataSystemOptions.d.ts.map +1 -1
  68. package/dist/esm/api/datasource/ModeDefinition.d.ts +3 -3
  69. package/dist/esm/api/datasource/ModeDefinition.d.ts.map +1 -1
  70. package/dist/esm/api/datasource/ModeResolution.d.ts +75 -0
  71. package/dist/esm/api/datasource/ModeResolution.d.ts.map +1 -0
  72. package/dist/esm/api/datasource/index.d.ts +2 -1
  73. package/dist/esm/api/datasource/index.d.ts.map +1 -1
  74. package/dist/esm/configuration/Configuration.d.ts +6 -0
  75. package/dist/esm/configuration/Configuration.d.ts.map +1 -1
  76. package/dist/esm/configuration/validateOptions.d.ts +1 -1
  77. package/dist/esm/configuration/validateOptions.d.ts.map +1 -1
  78. package/dist/esm/configuration/validators.d.ts +5 -2
  79. package/dist/esm/configuration/validators.d.ts.map +1 -1
  80. package/dist/esm/datasource/ConnectionModeConfig.d.ts.map +1 -1
  81. package/dist/esm/datasource/LDClientDataSystemOptions.d.ts +1 -0
  82. package/dist/esm/datasource/LDClientDataSystemOptions.d.ts.map +1 -1
  83. package/dist/esm/datasource/ModeResolver.d.ts +30 -0
  84. package/dist/esm/datasource/ModeResolver.d.ts.map +1 -0
  85. package/dist/esm/datasource/SourceFactoryProvider.d.ts +77 -0
  86. package/dist/esm/datasource/SourceFactoryProvider.d.ts.map +1 -0
  87. package/dist/esm/datasource/fdv2/CacheInitializer.d.ts +17 -0
  88. package/dist/esm/datasource/fdv2/CacheInitializer.d.ts.map +1 -0
  89. package/dist/esm/datasource/fdv2/FDv1PollingSynchronizer.d.ts +2 -0
  90. package/dist/esm/datasource/fdv2/FDv1PollingSynchronizer.d.ts.map +1 -0
  91. package/dist/esm/datasource/fdv2/FDv2DataSource.d.ts.map +1 -1
  92. package/dist/esm/datasource/fdv2/FDv2SourceResult.d.ts +3 -1
  93. package/dist/esm/datasource/fdv2/FDv2SourceResult.d.ts.map +1 -1
  94. package/dist/esm/datasource/fdv2/calculatePollDelay.d.ts +2 -0
  95. package/dist/esm/datasource/fdv2/calculatePollDelay.d.ts.map +1 -0
  96. package/dist/esm/datasource/fdv2/index.d.ts +4 -0
  97. package/dist/esm/datasource/fdv2/index.d.ts.map +1 -1
  98. package/dist/esm/datasource/flagEvalMapper.d.ts +3 -3
  99. package/dist/esm/flag-manager/FlagManager.d.ts +18 -2
  100. package/dist/esm/flag-manager/FlagManager.d.ts.map +1 -1
  101. package/dist/esm/flag-manager/FlagPersistence.d.ts +21 -2
  102. package/dist/esm/flag-manager/FlagPersistence.d.ts.map +1 -1
  103. package/dist/esm/flag-manager/FlagStore.d.ts +10 -0
  104. package/dist/esm/flag-manager/FlagStore.d.ts.map +1 -1
  105. package/dist/esm/flag-manager/FlagUpdater.d.ts +13 -1
  106. package/dist/esm/flag-manager/FlagUpdater.d.ts.map +1 -1
  107. package/dist/esm/index.d.ts +8 -1
  108. package/dist/esm/index.d.ts.map +1 -1
  109. package/dist/esm/index.mjs +1453 -61
  110. package/dist/esm/index.mjs.map +1 -1
  111. package/dist/esm/storage/freshness.d.ts +27 -0
  112. package/dist/esm/storage/freshness.d.ts.map +1 -0
  113. package/dist/esm/storage/loadCachedFlags.d.ts +25 -0
  114. package/dist/esm/storage/loadCachedFlags.d.ts.map +1 -0
  115. package/dist/esm/types/index.d.ts +2 -2
  116. package/package.json +2 -2
@@ -271,35 +271,290 @@ function validateOptions(input, validatorMap, defaults, logger, prefix) {
271
271
  });
272
272
  return result;
273
273
  }
274
+ /**
275
+ * Creates a validator for nested objects. When used in a validator map,
276
+ * `validateOptions` will recursively validate the nested object's properties.
277
+ * Defaults for nested fields are passed through from the parent.
278
+ */
279
+ function validatorOf(validators, builtInDefaults) {
280
+ return {
281
+ is: (u) => TypeValidators.Object.is(u),
282
+ getType: () => 'object',
283
+ validate(value, name, logger, defaults) {
284
+ if (!TypeValidators.Object.is(value)) {
285
+ logger?.warn(OptionMessages.wrongOptionType(name, 'object', typeof value));
286
+ return undefined;
287
+ }
288
+ const nestedDefaults = builtInDefaults ??
289
+ (TypeValidators.Object.is(defaults) ? defaults : {});
290
+ const nested = validateOptions(value, validators, nestedDefaults, logger, name);
291
+ return Object.keys(nested).length > 0 ? { value: nested } : undefined;
292
+ },
293
+ };
294
+ }
295
+ /**
296
+ * Creates a validator for arrays of discriminated objects. Each item in the
297
+ * array must be an object containing a `discriminant` field whose value
298
+ * selects which validator map to apply. The valid discriminant values are
299
+ * the keys of `validatorsByType`. Items that are not objects, or whose
300
+ * discriminant value is missing or unrecognized, are filtered out with a
301
+ * warning.
302
+ *
303
+ * @param discriminant - The field name used to determine each item's type.
304
+ * @param validatorsByType - A mapping from discriminant values to the
305
+ * validator maps used to validate items of that type. Each validator map
306
+ * should include a validator for the discriminant field itself.
307
+ *
308
+ * @example
309
+ * ```ts
310
+ * // Validates an array like:
311
+ * // [{ type: 'polling', pollInterval: 60 }, { type: 'cache' }]
312
+ *
313
+ * const validator = arrayOf('type', {
314
+ * cache: { type: TypeValidators.String },
315
+ * polling: { type: TypeValidators.String, pollInterval: TypeValidators.numberWithMin(30) },
316
+ * streaming: { type: TypeValidators.String, initialReconnectDelay: TypeValidators.numberWithMin(1) },
317
+ * });
318
+ * ```
319
+ */
320
+ function arrayOf(discriminant, validatorsByType) {
321
+ return {
322
+ is: (u) => Array.isArray(u),
323
+ getType: () => 'array',
324
+ validate(value, name, logger) {
325
+ if (!Array.isArray(value)) {
326
+ logger?.warn(OptionMessages.wrongOptionType(name, 'array', typeof value));
327
+ return undefined;
328
+ }
329
+ const results = [];
330
+ value.forEach((item, i) => {
331
+ const itemPath = `${name}[${i}]`;
332
+ if (isNullish(item) || !TypeValidators.Object.is(item)) {
333
+ logger?.warn(OptionMessages.wrongOptionType(itemPath, 'object', typeof item));
334
+ return;
335
+ }
336
+ const obj = item;
337
+ const typeValue = obj[discriminant];
338
+ const validators = typeof typeValue === 'string' ? validatorsByType[typeValue] : undefined;
339
+ if (!validators) {
340
+ const expected = Object.keys(validatorsByType).join(' | ');
341
+ const received = typeof typeValue === 'string' ? typeValue : typeof typeValue;
342
+ logger?.warn(OptionMessages.wrongOptionType(`${itemPath}.${discriminant}`, expected, received));
343
+ return;
344
+ }
345
+ results.push(validateOptions(obj, validators, {}, logger, itemPath));
346
+ });
347
+ return { value: results };
348
+ },
349
+ };
350
+ }
351
+ /**
352
+ * Creates a validator that tries each provided validator in order and uses the
353
+ * first one whose `is()` check passes. For compound validators the value is
354
+ * processed through `validate()`; for simple validators the value is accepted
355
+ * as-is. If no validator matches, a warning is logged and the default is
356
+ * preserved.
357
+ *
358
+ * @example
359
+ * ```ts
360
+ * // Accepts either a boolean or a nested object with specific fields:
361
+ * anyOf(TypeValidators.Boolean, validatorOf({ lifecycle: TypeValidators.Boolean }))
362
+ * ```
363
+ */
364
+ function anyOf(...validators) {
365
+ return {
366
+ is: (u) => validators.some((v) => v.is(u)),
367
+ getType: () => validators.map((v) => v.getType()).join(' | '),
368
+ validate(value, name, logger, defaults) {
369
+ const match = validators.find((v) => v.is(value));
370
+ if (match) {
371
+ return isCompoundValidator(match)
372
+ ? match.validate(value, name, logger, defaults)
373
+ : { value };
374
+ }
375
+ logger?.warn(OptionMessages.wrongOptionType(name, this.getType(), typeof value));
376
+ return undefined;
377
+ },
378
+ };
379
+ }
380
+ /**
381
+ * Creates a validator for objects with dynamic keys. Each key in the input
382
+ * object is checked against `keyValidator`; unrecognized keys produce a
383
+ * warning. Each value is validated by `valueValidator`. Defaults for
384
+ * individual entries are passed through from the parent so partial overrides
385
+ * preserve non-overridden entries.
386
+ *
387
+ * @param keyValidator - Validates that each key is an allowed value.
388
+ * @param valueValidator - Validates each value in the record.
389
+ *
390
+ * @example
391
+ * ```ts
392
+ * // Validates a record like { streaming: { ... }, polling: { ... } }
393
+ * // where keys must be valid connection modes:
394
+ * recordOf(
395
+ * TypeValidators.oneOf('streaming', 'polling', 'offline'),
396
+ * validatorOf({ initializers: arrayValidator, synchronizers: arrayValidator }),
397
+ * )
398
+ * ```
399
+ */
400
+ function recordOf(keyValidator, valueValidator) {
401
+ return {
402
+ is: (u) => TypeValidators.Object.is(u),
403
+ getType: () => 'object',
404
+ validate(value, name, logger, defaults) {
405
+ if (isNullish(value)) {
406
+ return undefined;
407
+ }
408
+ if (!TypeValidators.Object.is(value)) {
409
+ logger?.warn(OptionMessages.wrongOptionType(name, 'object', typeof value));
410
+ return undefined;
411
+ }
412
+ // Filter invalid keys, then delegate to validateOptions.
413
+ const obj = value;
414
+ const filtered = {};
415
+ const validatorMap = {};
416
+ Object.keys(obj).forEach((key) => {
417
+ if (keyValidator.is(key)) {
418
+ filtered[key] = obj[key];
419
+ validatorMap[key] = valueValidator;
420
+ }
421
+ else {
422
+ logger?.warn(OptionMessages.wrongOptionType(name, keyValidator.getType(), key));
423
+ }
424
+ });
425
+ const recordDefaults = TypeValidators.Object.is(defaults)
426
+ ? defaults
427
+ : {};
428
+ return { value: validateOptions(filtered, validatorMap, recordDefaults, logger, name) };
429
+ },
430
+ };
431
+ }
274
432
 
275
- // eslint-disable-next-line max-classes-per-file
276
- const validators = {
277
- logger: TypeValidators.Object,
278
- maxCachedContexts: TypeValidators.numberWithMin(0),
279
- baseUri: TypeValidators.String,
280
- streamUri: TypeValidators.String,
281
- eventsUri: TypeValidators.String,
282
- capacity: TypeValidators.numberWithMin(1),
283
- diagnosticRecordingInterval: TypeValidators.numberWithMin(2),
284
- flushInterval: TypeValidators.numberWithMin(2),
285
- streamInitialReconnectDelay: TypeValidators.numberWithMin(0),
286
- allAttributesPrivate: TypeValidators.Boolean,
287
- debug: TypeValidators.Boolean,
288
- diagnosticOptOut: TypeValidators.Boolean,
289
- withReasons: TypeValidators.Boolean,
290
- sendEvents: TypeValidators.Boolean,
433
+ const BACKGROUND_POLL_INTERVAL_SECONDS = 3600;
434
+ const dataSourceTypeValidator = TypeValidators.oneOf('cache', 'polling', 'streaming');
435
+ const connectionModeValidator = TypeValidators.oneOf('streaming', 'polling', 'offline', 'one-shot', 'background');
436
+ const endpointValidators = {
437
+ pollingBaseUri: TypeValidators.String,
438
+ streamingBaseUri: TypeValidators.String,
439
+ };
440
+ const cacheEntryValidators = {
441
+ type: dataSourceTypeValidator,
442
+ };
443
+ const pollingEntryValidators = {
444
+ type: dataSourceTypeValidator,
291
445
  pollInterval: TypeValidators.numberWithMin(30),
292
- useReport: TypeValidators.Boolean,
293
- privateAttributes: TypeValidators.StringArray,
294
- applicationInfo: TypeValidators.Object,
295
- wrapperName: TypeValidators.String,
296
- wrapperVersion: TypeValidators.String,
297
- payloadFilterKey: TypeValidators.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),
298
- hooks: TypeValidators.createTypeArray('Hook[]', {}),
299
- inspectors: TypeValidators.createTypeArray('LDInspection', {}),
300
- cleanOldPersistentData: TypeValidators.Boolean,
446
+ endpoints: validatorOf(endpointValidators),
447
+ };
448
+ const streamingEntryValidators = {
449
+ type: dataSourceTypeValidator,
450
+ initialReconnectDelay: TypeValidators.numberWithMin(1),
451
+ endpoints: validatorOf(endpointValidators),
452
+ };
453
+ const initializerEntryArrayValidator = arrayOf('type', {
454
+ cache: cacheEntryValidators,
455
+ polling: pollingEntryValidators,
456
+ streaming: streamingEntryValidators,
457
+ });
458
+ const synchronizerEntryArrayValidator = arrayOf('type', {
459
+ polling: pollingEntryValidators,
460
+ streaming: streamingEntryValidators,
461
+ });
462
+ const modeDefinitionValidators = {
463
+ initializers: initializerEntryArrayValidator,
464
+ synchronizers: synchronizerEntryArrayValidator,
465
+ };
466
+ const connectionModesValidator = recordOf(connectionModeValidator, validatorOf(modeDefinitionValidators));
467
+ const MODE_TABLE = {
468
+ streaming: {
469
+ initializers: [{ type: 'cache' }, { type: 'polling' }],
470
+ synchronizers: [{ type: 'streaming' }, { type: 'polling' }],
471
+ },
472
+ polling: {
473
+ initializers: [{ type: 'cache' }],
474
+ synchronizers: [{ type: 'polling' }],
475
+ },
476
+ offline: {
477
+ initializers: [{ type: 'cache' }],
478
+ synchronizers: [],
479
+ },
480
+ 'one-shot': {
481
+ initializers: [{ type: 'cache' }, { type: 'polling' }, { type: 'streaming' }],
482
+ synchronizers: [],
483
+ },
484
+ background: {
485
+ initializers: [{ type: 'cache' }],
486
+ synchronizers: [{ type: 'polling', pollInterval: BACKGROUND_POLL_INTERVAL_SECONDS }],
487
+ },
301
488
  };
302
489
 
490
+ const modeSwitchingValidators = {
491
+ lifecycle: TypeValidators.Boolean,
492
+ network: TypeValidators.Boolean,
493
+ };
494
+ const dataSystemValidators = {
495
+ initialConnectionMode: connectionModeValidator,
496
+ backgroundConnectionMode: connectionModeValidator,
497
+ automaticModeSwitching: anyOf(TypeValidators.Boolean, validatorOf(modeSwitchingValidators)),
498
+ connectionModes: connectionModesValidator,
499
+ };
500
+ /**
501
+ * Default FDv2 data system configuration for browser SDKs.
502
+ */
503
+ const BROWSER_DATA_SYSTEM_DEFAULTS = {
504
+ initialConnectionMode: 'one-shot',
505
+ backgroundConnectionMode: undefined,
506
+ automaticModeSwitching: false,
507
+ };
508
+ /**
509
+ * Default FDv2 data system configuration for mobile (React Native) SDKs.
510
+ */
511
+ const MOBILE_DATA_SYSTEM_DEFAULTS = {
512
+ initialConnectionMode: 'streaming',
513
+ backgroundConnectionMode: 'background',
514
+ automaticModeSwitching: true,
515
+ };
516
+ /**
517
+ * Default FDv2 data system configuration for desktop SDKs (Electron, etc.).
518
+ */
519
+ const DESKTOP_DATA_SYSTEM_DEFAULTS = {
520
+ initialConnectionMode: 'streaming',
521
+ backgroundConnectionMode: undefined,
522
+ automaticModeSwitching: false,
523
+ };
524
+
525
+ function createValidators(options) {
526
+ return {
527
+ logger: TypeValidators.Object,
528
+ maxCachedContexts: TypeValidators.numberWithMin(0),
529
+ baseUri: TypeValidators.String,
530
+ streamUri: TypeValidators.String,
531
+ eventsUri: TypeValidators.String,
532
+ capacity: TypeValidators.numberWithMin(1),
533
+ diagnosticRecordingInterval: TypeValidators.numberWithMin(2),
534
+ flushInterval: TypeValidators.numberWithMin(2),
535
+ streamInitialReconnectDelay: TypeValidators.numberWithMin(0),
536
+ allAttributesPrivate: TypeValidators.Boolean,
537
+ debug: TypeValidators.Boolean,
538
+ diagnosticOptOut: TypeValidators.Boolean,
539
+ withReasons: TypeValidators.Boolean,
540
+ sendEvents: TypeValidators.Boolean,
541
+ pollInterval: TypeValidators.numberWithMin(30),
542
+ useReport: TypeValidators.Boolean,
543
+ privateAttributes: TypeValidators.StringArray,
544
+ disableCache: TypeValidators.Boolean,
545
+ applicationInfo: TypeValidators.Object,
546
+ wrapperName: TypeValidators.String,
547
+ wrapperVersion: TypeValidators.String,
548
+ payloadFilterKey: TypeValidators.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),
549
+ hooks: TypeValidators.createTypeArray('Hook[]', {}),
550
+ inspectors: TypeValidators.createTypeArray('LDInspection', {}),
551
+ cleanOldPersistentData: TypeValidators.Boolean,
552
+ dataSystem: options?.dataSystemDefaults
553
+ ? validatorOf(dataSystemValidators, options.dataSystemDefaults)
554
+ : TypeValidators.Object,
555
+ };
556
+ }
557
+
303
558
  const DEFAULT_POLLING_INTERVAL = 60 * 5;
304
559
  const DEFAULT_POLLING = 'https://clientsdk.launchdarkly.com';
305
560
  const DEFAULT_STREAM = 'https://clientstream.launchdarkly.com';
@@ -325,6 +580,7 @@ class ConfigurationImpl {
325
580
  // eslint-disable-next-line @typescript-eslint/naming-convention
326
581
  this.streamUri = DEFAULT_STREAM;
327
582
  this.maxCachedContexts = 5;
583
+ this.disableCache = false;
328
584
  this.capacity = 100;
329
585
  this.diagnosticRecordingInterval = 900;
330
586
  this.flushInterval = 30;
@@ -341,6 +597,9 @@ class ConfigurationImpl {
341
597
  this.hooks = [];
342
598
  this.inspectors = [];
343
599
  this.logger = ensureSafeLogger(pristineOptions.logger);
600
+ const validators = createValidators({
601
+ dataSystemDefaults: internalOptions.dataSystemDefaults,
602
+ });
344
603
  const validated = validateOptions(pristineOptions, validators, {}, this.logger);
345
604
  Object.entries(validated).forEach(([k, v]) => {
346
605
  if (k !== 'logger') {
@@ -693,6 +952,98 @@ class EventFactory extends internal.EventFactoryBase {
693
952
  }
694
953
  }
695
954
 
955
+ /**
956
+ * Suffix appended to context storage keys to form the freshness storage key.
957
+ */
958
+ const FRESHNESS_SUFFIX = '_freshness';
959
+ /**
960
+ * Computes a SHA-256 hash of the context's full canonical JSON.
961
+ * Returns `undefined` if the context cannot be serialized.
962
+ */
963
+ async function hashContext(crypto, context) {
964
+ const json = context.canonicalUnfilteredJson();
965
+ if (!json) {
966
+ return undefined;
967
+ }
968
+ return digest(crypto.createHash('sha256').update(json), 'base64');
969
+ }
970
+ /**
971
+ * Reads the freshness timestamp from storage for the given context.
972
+ *
973
+ * Returns `undefined` if no freshness record exists, the data is corrupt,
974
+ * or the context attributes have changed since the freshness was recorded.
975
+ */
976
+ async function readFreshness(storage, crypto, environmentNamespace, context, logger) {
977
+ const contextStorageKey = await namespaceForContextData(crypto, environmentNamespace, context);
978
+ const json = await storage.get(`${contextStorageKey}${FRESHNESS_SUFFIX}`);
979
+ if (json === null || json === undefined) {
980
+ return undefined;
981
+ }
982
+ try {
983
+ const record = JSON.parse(json);
984
+ const currentHash = await hashContext(crypto, context);
985
+ if (currentHash === undefined || record.contextHash !== currentHash) {
986
+ return undefined;
987
+ }
988
+ return typeof record.timestamp === 'number' && !Number.isNaN(record.timestamp)
989
+ ? record.timestamp
990
+ : undefined;
991
+ }
992
+ catch (e) {
993
+ logger?.warn(`Could not read freshness data from persistent storage: ${e.message}`);
994
+ return undefined;
995
+ }
996
+ }
997
+
998
+ function isValidFlag(value) {
999
+ return value !== null && typeof value === 'object' && typeof value.version === 'number';
1000
+ }
1001
+ /**
1002
+ * Loads cached flag data from storage for the given context.
1003
+ *
1004
+ * Checks the current storage key first, then falls back to the legacy
1005
+ * canonical key location (pre-10.3.1). Does NOT perform migration — the
1006
+ * caller is responsible for migrating data if {@link CachedFlagData.fromLegacyKey}
1007
+ * is true.
1008
+ *
1009
+ * @returns The cached flag data, or `undefined` on cache miss or parse error.
1010
+ */
1011
+ async function loadCachedFlags(storage, crypto, environmentNamespace, context, logger) {
1012
+ const storageKey = await namespaceForContextData(crypto, environmentNamespace, context);
1013
+ let flagsJson = await storage.get(storageKey);
1014
+ let fromLegacyKey = false;
1015
+ if (flagsJson === null || flagsJson === undefined) {
1016
+ // Fallback: in version <10.3.1 flag data was stored under the canonical key.
1017
+ flagsJson = await storage.get(context.canonicalKey);
1018
+ if (flagsJson === null || flagsJson === undefined) {
1019
+ return undefined;
1020
+ }
1021
+ fromLegacyKey = true;
1022
+ }
1023
+ try {
1024
+ const parsed = JSON.parse(flagsJson);
1025
+ if (parsed === null || typeof parsed !== 'object') {
1026
+ logger?.warn('Cached flag data is not a valid object');
1027
+ return undefined;
1028
+ }
1029
+ const entries = Object.entries(parsed);
1030
+ const invalidKey = entries.find(([, value]) => !isValidFlag(value));
1031
+ if (invalidKey) {
1032
+ logger?.warn(`Discarding cached flags due to invalid entry: ${invalidKey[0]}`);
1033
+ return undefined;
1034
+ }
1035
+ const flags = entries.reduce((acc, [key, value]) => {
1036
+ acc[key] = value;
1037
+ return acc;
1038
+ }, {});
1039
+ return { flags, storageKey, fromLegacyKey };
1040
+ }
1041
+ catch (e) {
1042
+ logger?.warn(`Could not parse cached flag evaluations from persistent storage: ${e.message}`);
1043
+ return undefined;
1044
+ }
1045
+ }
1046
+
696
1047
  /**
697
1048
  * An index for tracking the most recently used contexts by timestamp with the ability to
698
1049
  * update entry timestamps and prune out least used contexts above a max capacity provided.
@@ -758,12 +1109,18 @@ class ContextIndex {
758
1109
  * This class handles persisting and loading flag values from a persistent
759
1110
  * store. It intercepts updates and forwards them to the flag updater and
760
1111
  * then persists changes after the updater has completed.
1112
+ *
1113
+ * Freshness metadata (timestamp + context attribute hash) is stored in a
1114
+ * separate storage key (`{contextKey}_freshness`) alongside the flag data.
1115
+ * Both keys are managed together — when a context is evicted, both the flag
1116
+ * data and freshness record are cleared.
761
1117
  */
762
1118
  class FlagPersistence {
763
- constructor(_platform, _environmentNamespace, _maxCachedContexts, _flagStore, _flagUpdater, _logger, _timeStamper = () => Date.now()) {
1119
+ constructor(_platform, _environmentNamespace, _maxCachedContexts, _disableCache, _flagStore, _flagUpdater, _logger, _timeStamper = () => Date.now()) {
764
1120
  this._platform = _platform;
765
1121
  this._environmentNamespace = _environmentNamespace;
766
1122
  this._maxCachedContexts = _maxCachedContexts;
1123
+ this._disableCache = _disableCache;
767
1124
  this._flagStore = _flagStore;
768
1125
  this._flagUpdater = _flagUpdater;
769
1126
  this._logger = _logger;
@@ -790,40 +1147,56 @@ class FlagPersistence {
790
1147
  }
791
1148
  return false;
792
1149
  }
1150
+ /**
1151
+ * Applies a changeset to the flag store.
1152
+ * - `'full'`: replaces all flags via {@link FlagUpdater.init}.
1153
+ * - `'partial'`: upserts individual flags via {@link FlagUpdater.upsert}.
1154
+ * - `'none'`: no flag changes, only persists cache to update freshness.
1155
+ *
1156
+ * Always persists to cache afterwards, which updates the freshness timestamp
1157
+ * even when no flags change (e.g., transfer-none).
1158
+ */
1159
+ async applyChanges(context, updates, type) {
1160
+ this._flagUpdater.applyChanges(context, updates, type);
1161
+ await this._storeCache(context);
1162
+ }
793
1163
  /**
794
1164
  * Loads the flags from persistence for the provided context and gives those to the
795
1165
  * {@link FlagUpdater} this {@link FlagPersistence} was constructed with.
796
1166
  */
797
1167
  async loadCached(context) {
798
- const storageKey = await namespaceForContextData(this._platform.crypto, this._environmentNamespace, context);
799
- let flagsJson = await this._platform.storage?.get(storageKey);
800
- if (flagsJson === null || flagsJson === undefined) {
801
- // Fallback: in version <10.3.1 flag data was stored under the canonical key, check
802
- // to see if data is present and migrate the data if present.
803
- flagsJson = await this._platform.storage?.get(context.canonicalKey);
804
- if (flagsJson === null || flagsJson === undefined) {
805
- // return false indicating cache did not load if flag json is still absent
806
- return false;
807
- }
808
- // migrate data from version <10.3.1 and cleanup data that was under canonical key
809
- await this._platform.storage?.set(storageKey, flagsJson);
810
- await this._platform.storage?.clear(context.canonicalKey);
1168
+ if (this._disableCache || this._maxCachedContexts <= 0) {
1169
+ return false;
811
1170
  }
812
- try {
813
- const flags = JSON.parse(flagsJson);
814
- // mapping flags to item descriptors
815
- const descriptors = Object.entries(flags).reduce((acc, [key, flag]) => {
816
- acc[key] = { version: flag.version, flag };
817
- return acc;
818
- }, {});
819
- this._flagUpdater.initCached(context, descriptors);
820
- this._logger.debug('Loaded cached flag evaluations from persistent storage');
821
- return true;
1171
+ if (!this._platform.storage) {
1172
+ return false;
822
1173
  }
823
- catch (e) {
824
- this._logger.warn(`Could not load cached flag evaluations from persistent storage: ${e.message}`);
1174
+ const cached = await loadCachedFlags(this._platform.storage, this._platform.crypto, this._environmentNamespace, context, this._logger);
1175
+ if (!cached) {
825
1176
  return false;
826
1177
  }
1178
+ // Migrate data from version <10.3.1 stored under the canonical key
1179
+ if (cached.fromLegacyKey) {
1180
+ await this._platform.storage.set(cached.storageKey, JSON.stringify(cached.flags));
1181
+ await this._platform.storage.clear(context.canonicalKey);
1182
+ }
1183
+ // mapping flags to item descriptors
1184
+ const descriptors = Object.entries(cached.flags).reduce((acc, [key, flag]) => {
1185
+ acc[key] = { version: flag.version, flag };
1186
+ return acc;
1187
+ }, {});
1188
+ this._flagUpdater.initCached(context, descriptors);
1189
+ this._logger.debug('Loaded cached flag evaluations from persistent storage');
1190
+ return true;
1191
+ }
1192
+ async _storeFreshness(contextStorageKey, context, timestamp) {
1193
+ const contextHash = await hashContext(this._platform.crypto, context);
1194
+ if (contextHash === undefined) {
1195
+ this._logger.error('Could not serialize context for freshness tracking');
1196
+ return;
1197
+ }
1198
+ const record = { timestamp, contextHash };
1199
+ await this._platform.storage?.set(`${contextStorageKey}${FRESHNESS_SUFFIX}`, JSON.stringify(record));
827
1200
  }
828
1201
  async _loadIndex() {
829
1202
  if (this._contextIndex !== undefined) {
@@ -845,13 +1218,26 @@ class FlagPersistence {
845
1218
  return this._contextIndex;
846
1219
  }
847
1220
  async _storeCache(context) {
1221
+ if (this._disableCache) {
1222
+ return;
1223
+ }
1224
+ const now = this._timeStamper();
848
1225
  const index = await this._loadIndex();
849
1226
  const storageKey = await namespaceForContextData(this._platform.crypto, this._environmentNamespace, context);
850
- index.notice(storageKey, this._timeStamper());
1227
+ if (this._maxCachedContexts > 0) {
1228
+ index.notice(storageKey, now);
1229
+ }
851
1230
  const pruned = index.prune(this._maxCachedContexts);
852
- await Promise.all(pruned.map(async (it) => this._platform.storage?.clear(it.id)));
853
- // store index
1231
+ // If maxCachedContexts <= 0, current context was never added, so always skip flag write
1232
+ const currentContextWasPruned = this._maxCachedContexts <= 0 || pruned.some((it) => it.id === storageKey);
1233
+ await Promise.all(pruned.flatMap((it) => [
1234
+ this._platform.storage?.clear(it.id),
1235
+ this._platform.storage?.clear(`${it.id}${FRESHNESS_SUFFIX}`),
1236
+ ]));
854
1237
  await this._platform.storage?.set(await this._indexKeyPromise, index.toJson());
1238
+ if (currentContextWasPruned) {
1239
+ return;
1240
+ }
855
1241
  const allFlags = this._flagStore.getAll();
856
1242
  // mapping item descriptors to flags
857
1243
  const flags = Object.entries(allFlags).reduce((acc, [key, descriptor]) => {
@@ -861,8 +1247,15 @@ class FlagPersistence {
861
1247
  return acc;
862
1248
  }, {});
863
1249
  const jsonAll = JSON.stringify(flags);
864
- // store flag data
1250
+ // store flag data first, so freshness is never newer than the flags it describes
865
1251
  await this._platform.storage?.set(storageKey, jsonAll);
1252
+ // store freshness — best-effort, must not block flag persistence
1253
+ try {
1254
+ await this._storeFreshness(storageKey, context, now);
1255
+ }
1256
+ catch (e) {
1257
+ this._logger.warn(`Failed to store freshness data: ${e.message}`);
1258
+ }
866
1259
  }
867
1260
  }
868
1261
 
@@ -890,6 +1283,16 @@ function createDefaultFlagStore() {
890
1283
  getAll() {
891
1284
  return flags;
892
1285
  },
1286
+ applyChanges(updates, type) {
1287
+ if (type === 'full') {
1288
+ this.init(updates);
1289
+ }
1290
+ else if (type === 'partial') {
1291
+ Object.entries(updates).forEach(([key, descriptor]) => {
1292
+ flags[key] = descriptor;
1293
+ });
1294
+ }
1295
+ },
893
1296
  };
894
1297
  }
895
1298
 
@@ -947,6 +1350,24 @@ function createFlagUpdater(_flagStore, _logger) {
947
1350
  }
948
1351
  this.init(context, newFlags);
949
1352
  },
1353
+ applyChanges(context, updates, type) {
1354
+ activeContext = context;
1355
+ const oldFlags = flagStore.getAll();
1356
+ flagStore.applyChanges(updates, type);
1357
+ if (type === 'full') {
1358
+ const changed = calculateChangedKeys(oldFlags, updates);
1359
+ if (changed.length > 0) {
1360
+ this.handleFlagChanges(changed, 'init');
1361
+ }
1362
+ }
1363
+ else if (type === 'partial') {
1364
+ const keys = Object.keys(updates);
1365
+ if (keys.length > 0) {
1366
+ this.handleFlagChanges(keys, 'patch');
1367
+ }
1368
+ }
1369
+ // 'none' — no flag changes, caller handles freshness.
1370
+ },
950
1371
  upsert(context, key, item) {
951
1372
  if (activeContext?.canonicalKey !== context.canonicalKey) {
952
1373
  logger.warn('Received an update for an inactive context.');
@@ -978,17 +1399,18 @@ class DefaultFlagManager {
978
1399
  * @param platform implementation of various platform provided functionality
979
1400
  * @param sdkKey that will be used to distinguish different environments
980
1401
  * @param maxCachedContexts that specifies the max number of contexts that will be cached in persistence
1402
+ * @param disableCache set to true to completely disable the persistent flag cache
981
1403
  * @param logger used for logging various messages
982
1404
  * @param timeStamper exists for testing purposes
983
1405
  */
984
- constructor(platform, sdkKey, maxCachedContexts, logger, timeStamper = () => Date.now()) {
1406
+ constructor(platform, sdkKey, maxCachedContexts, disableCache, logger, timeStamper = () => Date.now()) {
985
1407
  this._flagStore = createDefaultFlagStore();
986
1408
  this._flagUpdater = createFlagUpdater(this._flagStore, logger);
987
- this._flagPersistencePromise = this._initPersistence(platform, sdkKey, maxCachedContexts, logger, timeStamper);
1409
+ this._flagPersistencePromise = this._initPersistence(platform, sdkKey, maxCachedContexts, disableCache, logger, timeStamper);
988
1410
  }
989
- async _initPersistence(platform, sdkKey, maxCachedContexts, logger, timeStamper = () => Date.now()) {
1411
+ async _initPersistence(platform, sdkKey, maxCachedContexts, disableCache, logger, timeStamper = () => Date.now()) {
990
1412
  const environmentNamespace = await namespaceForEnvironment(platform.crypto, sdkKey);
991
- return new FlagPersistence(platform, environmentNamespace, maxCachedContexts, this._flagStore, this._flagUpdater, logger, timeStamper);
1413
+ return new FlagPersistence(platform, environmentNamespace, maxCachedContexts, disableCache, this._flagStore, this._flagUpdater, logger, timeStamper);
992
1414
  }
993
1415
  get(key) {
994
1416
  if (this._overrides && Object.prototype.hasOwnProperty.call(this._overrides, key)) {
@@ -1025,6 +1447,9 @@ class DefaultFlagManager {
1025
1447
  async loadCached(context) {
1026
1448
  return (await this._flagPersistencePromise).loadCached(context);
1027
1449
  }
1450
+ async applyChanges(context, updates, type) {
1451
+ return (await this._flagPersistencePromise).applyChanges(context, updates, type);
1452
+ }
1028
1453
  on(callback) {
1029
1454
  this._flagUpdater.on(callback);
1030
1455
  }
@@ -1464,7 +1889,7 @@ class LDClientImpl {
1464
1889
  this._config = new ConfigurationImpl(options, internalOptions);
1465
1890
  this.logger = this._config.logger;
1466
1891
  this._baseHeaders = defaultHeaders(this.sdkKey, this.platform.info, this._config.tags, this._config.serviceEndpoints.includeAuthorizationHeader, this._config.userAgentHeaderName);
1467
- this._flagManager = new DefaultFlagManager(this.platform, sdkKey, this._config.maxCachedContexts, this._config.logger);
1892
+ this._flagManager = new DefaultFlagManager(this.platform, sdkKey, this._config.maxCachedContexts, this._config.disableCache ?? false, this._config.logger);
1468
1893
  this._diagnosticsManager = createDiagnosticsManager(sdkKey, this._config, platform);
1469
1894
  this._eventProcessor = createEventProcessor(sdkKey, this._config, platform, this._baseHeaders, this._diagnosticsManager);
1470
1895
  this.emitter = new LDEmitter();
@@ -2558,5 +2983,972 @@ class BaseDataManager {
2558
2983
  }
2559
2984
  }
2560
2985
 
2561
- export { BaseDataManager, DataSourceState, LDClientImpl, browserFdv1Endpoints, fdv2Endpoints, makeRequestor, mobileFdv1Endpoints, readFlagsFromBootstrap, safeRegisterDebugOverridePlugins, validateOptions };
2986
+ function allConditionsMatch(conditions, input) {
2987
+ return Object.entries(conditions).every(([key, value]) => value === undefined || input[key] === value);
2988
+ }
2989
+ /**
2990
+ * Given a mode resolution table and the current input state, returns the
2991
+ * resolved FDv2 connection mode.
2992
+ *
2993
+ * Iterates entries in order. The first entry whose conditions all match the
2994
+ * input wins. If no entry matches (should not happen when the table ends with
2995
+ * a catch-all), falls back to `input.foregroundMode`.
2996
+ */
2997
+ const CONFIGURED_MODE_MAP = {
2998
+ foreground: 'foregroundMode',
2999
+ background: 'backgroundMode',
3000
+ };
3001
+ function resolveConnectionMode(table, input) {
3002
+ const match = table.find((entry) => allConditionsMatch(entry.conditions, input));
3003
+ if (match) {
3004
+ const { mode } = match;
3005
+ if (typeof mode === 'object') {
3006
+ return input[CONFIGURED_MODE_MAP[mode.configured]];
3007
+ }
3008
+ return mode;
3009
+ }
3010
+ return input.foregroundMode;
3011
+ }
3012
+ /**
3013
+ * Mode resolution table for mobile platforms (React Native, etc.).
3014
+ *
3015
+ * - No network → offline.
3016
+ * - Background → configured background mode.
3017
+ * - Foreground → configured foreground mode.
3018
+ */
3019
+ const MOBILE_TRANSITION_TABLE = [
3020
+ { conditions: { networkAvailable: false }, mode: 'offline' },
3021
+ { conditions: { lifecycle: 'background' }, mode: { configured: 'background' } },
3022
+ { conditions: { lifecycle: 'foreground' }, mode: { configured: 'foreground' } },
3023
+ ];
3024
+ /**
3025
+ * Mode resolution table for browser platforms.
3026
+ *
3027
+ * - No network → offline.
3028
+ * - Otherwise → configured foreground mode.
3029
+ *
3030
+ * Browser listener-driven streaming (auto-promotion to streaming when change
3031
+ * listeners are registered) is handled externally by the caller modifying
3032
+ * `foregroundMode` before consulting this table.
3033
+ */
3034
+ const BROWSER_TRANSITION_TABLE = [
3035
+ { conditions: { networkAvailable: false }, mode: 'offline' },
3036
+ { conditions: {}, mode: { configured: 'foreground' } },
3037
+ ];
3038
+ /**
3039
+ * Mode resolution table for desktop platforms (Electron, etc.).
3040
+ *
3041
+ * - No network → offline.
3042
+ * - Otherwise → configured foreground mode.
3043
+ */
3044
+ const DESKTOP_TRANSITION_TABLE = [
3045
+ { conditions: { networkAvailable: false }, mode: 'offline' },
3046
+ { conditions: {}, mode: { configured: 'foreground' } },
3047
+ ];
3048
+
3049
+ /**
3050
+ * Creates a change set result containing processed flag data.
3051
+ */
3052
+ function changeSet(payload, fdv1Fallback, environmentId, freshness) {
3053
+ return { type: 'changeSet', payload, fdv1Fallback, environmentId, freshness };
3054
+ }
3055
+ /**
3056
+ * Creates an interrupted status result. Indicates a transient error; the
3057
+ * synchronizer will attempt to recover automatically.
3058
+ *
3059
+ * When used with an initializer, this is still a terminal state.
3060
+ */
3061
+ function interrupted(errorInfo, fdv1Fallback) {
3062
+ return { type: 'status', state: 'interrupted', errorInfo, fdv1Fallback };
3063
+ }
3064
+ /**
3065
+ * Creates a shutdown status result. Indicates the data source was closed
3066
+ * gracefully and will not produce any further results.
3067
+ */
3068
+ function shutdown() {
3069
+ return { type: 'status', state: 'shutdown', fdv1Fallback: false };
3070
+ }
3071
+ /**
3072
+ * Creates a terminal error status result. Indicates an unrecoverable error;
3073
+ * the data source will not produce any further results.
3074
+ */
3075
+ function terminalError(errorInfo, fdv1Fallback) {
3076
+ return { type: 'status', state: 'terminal_error', errorInfo, fdv1Fallback };
3077
+ }
3078
+ /**
3079
+ * Creates a goodbye status result. Indicates the server has instructed the
3080
+ * client to disconnect.
3081
+ */
3082
+ function goodbye(reason, fdv1Fallback) {
3083
+ return { type: 'status', state: 'goodbye', reason, fdv1Fallback };
3084
+ }
3085
+ /**
3086
+ * Helper to create a {@link DataSourceStatusErrorInfo} from an HTTP status code.
3087
+ */
3088
+ function errorInfoFromHttpError(statusCode) {
3089
+ return {
3090
+ kind: DataSourceErrorKind.ErrorResponse,
3091
+ message: `Unexpected status code: ${statusCode}`,
3092
+ statusCode,
3093
+ time: Date.now(),
3094
+ };
3095
+ }
3096
+ /**
3097
+ * Helper to create a {@link DataSourceStatusErrorInfo} from a network error.
3098
+ */
3099
+ function errorInfoFromNetworkError(message) {
3100
+ return {
3101
+ kind: DataSourceErrorKind.NetworkError,
3102
+ message,
3103
+ time: Date.now(),
3104
+ };
3105
+ }
3106
+ /**
3107
+ * Helper to create a {@link DataSourceStatusErrorInfo} from invalid data.
3108
+ */
3109
+ function errorInfoFromInvalidData(message) {
3110
+ return {
3111
+ kind: DataSourceErrorKind.InvalidData,
3112
+ message,
3113
+ time: Date.now(),
3114
+ };
3115
+ }
3116
+ /**
3117
+ * Helper to create a {@link DataSourceStatusErrorInfo} for unknown errors.
3118
+ */
3119
+ function errorInfoFromUnknown(message) {
3120
+ return {
3121
+ kind: DataSourceErrorKind.Unknown,
3122
+ message,
3123
+ time: Date.now(),
3124
+ };
3125
+ }
3126
+
3127
+ /**
3128
+ * Strips the `version` field from a stored {@link Flag} to produce the
3129
+ * `FlagEvaluationResult` shape expected in an FDv2 `Update.object`.
3130
+ *
3131
+ * The version is carried on the `Update` envelope, not on the object itself.
3132
+ */
3133
+ function flagToEvaluationResult(flag) {
3134
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
3135
+ const { version, ...evalResult } = flag;
3136
+ return evalResult;
3137
+ }
3138
+ /**
3139
+ * Reads cached flag data and freshness from platform storage and returns
3140
+ * them as an {@link FDv2SourceResult}.
3141
+ */
3142
+ async function loadFromCache(config) {
3143
+ const { storage, crypto, environmentNamespace, context, logger } = config;
3144
+ if (!storage) {
3145
+ logger?.debug('No storage available for cache initializer');
3146
+ return interrupted(errorInfoFromUnknown('No storage available'), false);
3147
+ }
3148
+ const cached = await loadCachedFlags(storage, crypto, environmentNamespace, context, logger);
3149
+ if (!cached) {
3150
+ logger?.debug('Cache miss for context');
3151
+ return interrupted(errorInfoFromUnknown('Cache miss'), false);
3152
+ }
3153
+ const updates = Object.entries(cached.flags).map(([key, flag]) => ({
3154
+ kind: 'flag-eval',
3155
+ key,
3156
+ version: flag.version,
3157
+ object: flagToEvaluationResult(flag),
3158
+ }));
3159
+ const payload = {
3160
+ id: 'cache',
3161
+ version: 0,
3162
+ // No `state` field. The orchestrator sees a changeSet without a selector,
3163
+ // records dataReceived=true, and continues to the next initializer.
3164
+ type: 'full',
3165
+ updates,
3166
+ };
3167
+ const freshness = await readFreshness(storage, crypto, environmentNamespace, context, logger);
3168
+ logger?.debug('Loaded cached flag evaluations via cache initializer');
3169
+ return changeSet(payload, false, undefined, freshness);
3170
+ }
3171
+ /**
3172
+ * Creates an {@link InitializerFactory} that produces cache initializers.
3173
+ *
3174
+ * The cache initializer reads flag data and freshness from persistent storage
3175
+ * for the given context and returns them as a changeSet without a selector.
3176
+ * This allows the orchestrator to provide cached data immediately while
3177
+ * continuing to the next initializer for network-verified data.
3178
+ *
3179
+ * Per spec Requirement 4.1.2, the payload has `persist=false` semantics
3180
+ * (no selector) so the consuming layer should not re-persist it.
3181
+ *
3182
+ * @internal
3183
+ */
3184
+ function createCacheInitializerFactory(config) {
3185
+ // The selectorGetter is ignored — cache data has no selector.
3186
+ return (_selectorGetter) => {
3187
+ let shutdownResolve;
3188
+ const shutdownPromise = new Promise((resolve) => {
3189
+ shutdownResolve = resolve;
3190
+ });
3191
+ return {
3192
+ async run() {
3193
+ return Promise.race([shutdownPromise, loadFromCache(config)]);
3194
+ },
3195
+ close() {
3196
+ shutdownResolve?.(shutdown());
3197
+ shutdownResolve = undefined;
3198
+ },
3199
+ };
3200
+ };
3201
+ }
3202
+
3203
+ /**
3204
+ * Creates an {@link FDv2Requestor} for client-side FDv2 polling.
3205
+ *
3206
+ * @param plainContextString The JSON-serialized evaluation context.
3207
+ * @param serviceEndpoints Service endpoint configuration.
3208
+ * @param paths FDv2 polling endpoint paths.
3209
+ * @param requests Platform HTTP abstraction.
3210
+ * @param encoding Platform encoding abstraction.
3211
+ * @param baseHeaders Default HTTP headers (e.g. authorization).
3212
+ * @param baseQueryParams Additional query parameters to include on every request.
3213
+ * @param usePost If true, use POST with context in body instead of GET with
3214
+ * context in URL path.
3215
+ */
3216
+ function makeFDv2Requestor(plainContextString, serviceEndpoints, paths, requests, encoding, baseHeaders, baseQueryParams, usePost) {
3217
+ const headers = { ...baseHeaders };
3218
+ let body;
3219
+ let method = 'GET';
3220
+ let path;
3221
+ if (usePost) {
3222
+ method = 'POST';
3223
+ headers['content-type'] = 'application/json';
3224
+ body = plainContextString;
3225
+ path = paths.pathPost(encoding, plainContextString);
3226
+ }
3227
+ else {
3228
+ path = paths.pathGet(encoding, plainContextString);
3229
+ }
3230
+ return {
3231
+ async poll(basis) {
3232
+ const parameters = [...(baseQueryParams ?? [])];
3233
+ // Intentionally falsy check: an empty string basis must not be sent as
3234
+ // a query parameter, since it does not represent a valid selector.
3235
+ if (basis) {
3236
+ parameters.push({ key: 'basis', value: basis });
3237
+ }
3238
+ const uri = getPollingUri(serviceEndpoints, path, parameters);
3239
+ const res = await requests.fetch(uri, {
3240
+ method,
3241
+ headers,
3242
+ body,
3243
+ });
3244
+ const responseBody = res.status === 304 ? null : await res.text();
3245
+ return {
3246
+ status: res.status,
3247
+ headers: res.headers,
3248
+ body: responseBody,
3249
+ };
3250
+ },
3251
+ };
3252
+ }
3253
+
3254
+ /**
3255
+ * ObjProcessor for the `flag-eval` object kind. Used by the protocol handler to
3256
+ * process objects received in `put-object` events.
3257
+ *
3258
+ * Client-side evaluation results are already in their final form (pre-evaluated
3259
+ * by the server), so no transformation is needed — this is a passthrough.
3260
+ */
3261
+ function processFlagEval(object) {
3262
+ return object;
3263
+ }
3264
+
3265
+ function getFallback(headers) {
3266
+ const value = headers.get('x-ld-fd-fallback');
3267
+ return value !== null && value.toLowerCase() === 'true';
3268
+ }
3269
+ function getEnvironmentId(headers) {
3270
+ return headers.get('x-ld-envid') ?? undefined;
3271
+ }
3272
+ /**
3273
+ * Process FDv2 events using the protocol handler directly.
3274
+ *
3275
+ * We use `createProtocolHandler` rather than `PayloadProcessor` because
3276
+ * the PayloadProcessor does not surface goodbye/serverError actions —
3277
+ * it only forwards payloads and actionable errors. For polling results,
3278
+ * we need full control over all protocol action types.
3279
+ */
3280
+ function processEvents(events, oneShot, fdv1Fallback, environmentId, logger) {
3281
+ const handler = internal.createProtocolHandler({
3282
+ 'flag-eval': processFlagEval,
3283
+ }, logger);
3284
+ let earlyResult;
3285
+ events.forEach((event) => {
3286
+ if (earlyResult) {
3287
+ return;
3288
+ }
3289
+ const action = handler.processEvent(event);
3290
+ switch (action.type) {
3291
+ case 'payload':
3292
+ earlyResult = changeSet(action.payload, fdv1Fallback, environmentId);
3293
+ break;
3294
+ case 'goodbye':
3295
+ earlyResult = goodbye(action.reason, fdv1Fallback);
3296
+ break;
3297
+ case 'serverError': {
3298
+ const errorInfo = errorInfoFromUnknown(action.reason);
3299
+ logger?.error(`Server error during polling: ${action.reason}`);
3300
+ earlyResult = oneShot
3301
+ ? terminalError(errorInfo, fdv1Fallback)
3302
+ : interrupted(errorInfo, fdv1Fallback);
3303
+ break;
3304
+ }
3305
+ case 'error': {
3306
+ // Actionable protocol errors (MISSING_PAYLOAD, PROTOCOL_ERROR)
3307
+ if (action.kind === 'MISSING_PAYLOAD' || action.kind === 'PROTOCOL_ERROR') {
3308
+ const errorInfo = errorInfoFromInvalidData(action.message);
3309
+ logger?.warn(`Protocol error during polling: ${action.message}`);
3310
+ earlyResult = oneShot
3311
+ ? terminalError(errorInfo, fdv1Fallback)
3312
+ : interrupted(errorInfo, fdv1Fallback);
3313
+ }
3314
+ else {
3315
+ // Non-actionable errors (UNKNOWN_EVENT) are logged but don't stop processing
3316
+ logger?.warn(action.message);
3317
+ }
3318
+ break;
3319
+ }
3320
+ }
3321
+ });
3322
+ if (earlyResult) {
3323
+ return earlyResult;
3324
+ }
3325
+ // Events didn't produce a result
3326
+ const errorInfo = errorInfoFromUnknown('Unexpected end of polling response');
3327
+ logger?.error('Unexpected end of polling response');
3328
+ return oneShot ? terminalError(errorInfo, fdv1Fallback) : interrupted(errorInfo, fdv1Fallback);
3329
+ }
3330
+ /**
3331
+ * Performs a single FDv2 poll request, processes the protocol response, and
3332
+ * returns an {@link FDv2SourceResult}.
3333
+ *
3334
+ * The `oneShot` parameter controls error handling: when true (initializer),
3335
+ * all errors are terminal; when false (synchronizer), recoverable errors
3336
+ * produce interrupted results.
3337
+ *
3338
+ * @internal
3339
+ */
3340
+ async function poll(requestor, basis, oneShot, logger) {
3341
+ let fdv1Fallback = false;
3342
+ let environmentId;
3343
+ try {
3344
+ const response = await requestor.poll(basis);
3345
+ fdv1Fallback = getFallback(response.headers);
3346
+ environmentId = getEnvironmentId(response.headers);
3347
+ // 304 Not Modified: treat as server-intent with intentCode 'none'
3348
+ // (Spec Requirement 10.1.2)
3349
+ if (response.status === 304) {
3350
+ const nonePayload = {
3351
+ id: '',
3352
+ version: 0,
3353
+ type: 'none',
3354
+ updates: [],
3355
+ };
3356
+ return changeSet(nonePayload, fdv1Fallback, environmentId);
3357
+ }
3358
+ // Non-success HTTP status
3359
+ if (response.status < 200 || response.status >= 300) {
3360
+ const errorInfo = errorInfoFromHttpError(response.status);
3361
+ logger?.error(`Polling request failed with HTTP error: ${response.status}`);
3362
+ if (oneShot) {
3363
+ return terminalError(errorInfo, fdv1Fallback);
3364
+ }
3365
+ const recoverable = response.status <= 0 || isHttpRecoverable(response.status);
3366
+ return recoverable
3367
+ ? interrupted(errorInfo, fdv1Fallback)
3368
+ : terminalError(errorInfo, fdv1Fallback);
3369
+ }
3370
+ // Successful response — process FDv2 events
3371
+ if (!response.body) {
3372
+ const errorInfo = errorInfoFromInvalidData('Empty response body');
3373
+ logger?.error('Polling request received empty response body');
3374
+ return oneShot
3375
+ ? terminalError(errorInfo, fdv1Fallback)
3376
+ : interrupted(errorInfo, fdv1Fallback);
3377
+ }
3378
+ let parsed;
3379
+ try {
3380
+ parsed = JSON.parse(response.body);
3381
+ }
3382
+ catch {
3383
+ const errorInfo = errorInfoFromInvalidData('Malformed JSON data in polling response');
3384
+ logger?.error('Polling request received malformed data');
3385
+ return oneShot
3386
+ ? terminalError(errorInfo, fdv1Fallback)
3387
+ : interrupted(errorInfo, fdv1Fallback);
3388
+ }
3389
+ if (!Array.isArray(parsed.events)) {
3390
+ const errorInfo = errorInfoFromInvalidData('Invalid polling response: missing or invalid events array');
3391
+ logger?.error('Polling response does not contain a valid events array');
3392
+ return oneShot
3393
+ ? terminalError(errorInfo, fdv1Fallback)
3394
+ : interrupted(errorInfo, fdv1Fallback);
3395
+ }
3396
+ return processEvents(parsed.events, oneShot, fdv1Fallback, environmentId, logger);
3397
+ }
3398
+ catch (err) {
3399
+ // Network or other I/O error from the fetch itself
3400
+ const message = err?.message ?? String(err);
3401
+ logger?.error(`Polling request failed with network error: ${message}`);
3402
+ const errorInfo = errorInfoFromNetworkError(message);
3403
+ return oneShot ? terminalError(errorInfo, fdv1Fallback) : interrupted(errorInfo, fdv1Fallback);
3404
+ }
3405
+ }
3406
+
3407
+ /**
3408
+ * Creates a one-shot polling initializer that performs a single FDv2 poll
3409
+ * request and returns the result.
3410
+ *
3411
+ * All errors are treated as terminal (oneShot=true). If `close()` is called
3412
+ * before the poll completes, the result will be a shutdown status.
3413
+ *
3414
+ * @internal
3415
+ */
3416
+ function createPollingInitializer(requestor, logger, selectorGetter) {
3417
+ let shutdownResolve;
3418
+ const shutdownPromise = new Promise((resolve) => {
3419
+ shutdownResolve = resolve;
3420
+ });
3421
+ return {
3422
+ async run() {
3423
+ const pollResult = poll(requestor, selectorGetter(), true, logger);
3424
+ // Race the poll against the shutdown signal
3425
+ return Promise.race([shutdownPromise, pollResult]);
3426
+ },
3427
+ close() {
3428
+ shutdownResolve?.(shutdown());
3429
+ shutdownResolve = undefined;
3430
+ },
3431
+ };
3432
+ }
3433
+
3434
+ /**
3435
+ * Creates a new {@link AsyncQueue}.
3436
+ *
3437
+ * @internal
3438
+ */
3439
+ function createAsyncQueue() {
3440
+ const items = [];
3441
+ const waiters = [];
3442
+ return {
3443
+ put(item) {
3444
+ const waiter = waiters.shift();
3445
+ if (waiter) {
3446
+ waiter(item);
3447
+ }
3448
+ else {
3449
+ items.push(item);
3450
+ }
3451
+ },
3452
+ take() {
3453
+ if (items.length > 0) {
3454
+ return Promise.resolve(items.shift());
3455
+ }
3456
+ return new Promise((resolve) => {
3457
+ waiters.push(resolve);
3458
+ });
3459
+ },
3460
+ };
3461
+ }
3462
+
3463
+ /**
3464
+ * Creates a continuous polling synchronizer that periodically polls for FDv2
3465
+ * data and yields results via successive calls to `next()`.
3466
+ *
3467
+ * The first poll fires immediately. Subsequent polls are scheduled using
3468
+ * `setTimeout` after each poll completes, ensuring sequential execution and
3469
+ * preventing overlapping requests on slow networks.
3470
+ *
3471
+ * Results are buffered in an async queue. On terminal errors, polling stops
3472
+ * and the shutdown future is resolved. On `close()`, polling stops and the
3473
+ * next `next()` call returns a shutdown result.
3474
+ *
3475
+ * @internal
3476
+ */
3477
+ function createPollingSynchronizer(requestor, logger, selectorGetter, pollIntervalMs) {
3478
+ const resultQueue = createAsyncQueue();
3479
+ let shutdownResolve;
3480
+ const shutdownPromise = new Promise((resolve) => {
3481
+ shutdownResolve = resolve;
3482
+ });
3483
+ let timeoutHandle;
3484
+ let stopped = false;
3485
+ async function doPoll() {
3486
+ if (stopped) {
3487
+ return;
3488
+ }
3489
+ const startTime = Date.now();
3490
+ try {
3491
+ const result = await poll(requestor, selectorGetter(), false, logger);
3492
+ if (stopped) {
3493
+ return;
3494
+ }
3495
+ let shouldShutdown = false;
3496
+ if (result.type === 'status') {
3497
+ switch (result.state) {
3498
+ case 'terminal_error':
3499
+ stopped = true;
3500
+ shouldShutdown = true;
3501
+ break;
3502
+ case 'interrupted':
3503
+ case 'goodbye':
3504
+ // Continue polling on transient errors and goodbyes
3505
+ break;
3506
+ case 'shutdown':
3507
+ // The base poll function doesn't emit shutdown; we handle it
3508
+ // at this level via close().
3509
+ break;
3510
+ default:
3511
+ break;
3512
+ }
3513
+ }
3514
+ if (shouldShutdown) {
3515
+ shutdownResolve?.(result);
3516
+ shutdownResolve = undefined;
3517
+ }
3518
+ else {
3519
+ resultQueue.put(result);
3520
+ }
3521
+ }
3522
+ catch (err) {
3523
+ logger?.debug(`Polling error: ${err}`);
3524
+ }
3525
+ // Schedule next poll after completion, accounting for elapsed time.
3526
+ // This ensures sequential execution — no overlapping requests.
3527
+ if (!stopped) {
3528
+ const elapsed = Date.now() - startTime;
3529
+ const sleepFor = Math.min(Math.max(pollIntervalMs - elapsed, 0), pollIntervalMs);
3530
+ timeoutHandle = setTimeout(() => {
3531
+ doPoll();
3532
+ }, sleepFor);
3533
+ }
3534
+ }
3535
+ // Start polling immediately
3536
+ doPoll();
3537
+ return {
3538
+ async next() {
3539
+ return Promise.race([shutdownPromise, resultQueue.take()]);
3540
+ },
3541
+ close() {
3542
+ stopped = true;
3543
+ if (timeoutHandle !== undefined) {
3544
+ clearTimeout(timeoutHandle);
3545
+ timeoutHandle = undefined;
3546
+ }
3547
+ shutdownResolve?.(shutdown());
3548
+ shutdownResolve = undefined;
3549
+ },
3550
+ };
3551
+ }
3552
+
3553
+ /**
3554
+ * Creates a {@link SynchronizerSlot}.
3555
+ *
3556
+ * @param factory The synchronizer factory function.
3557
+ * @param options Optional configuration.
3558
+ * @param options.isFDv1Fallback Whether this slot is the FDv1 fallback adapter.
3559
+ * FDv1 slots start `'blocked'` by default.
3560
+ * @param options.initialState Override the initial state (defaults to
3561
+ * `'blocked'` for FDv1 slots, `'available'` otherwise).
3562
+ */
3563
+ function createSynchronizerSlot(factory, options) {
3564
+ const isFDv1Fallback = options?.isFDv1Fallback ?? false;
3565
+ const state = options?.initialState ?? (isFDv1Fallback ? 'blocked' : 'available');
3566
+ return { factory, isFDv1Fallback, state };
3567
+ }
3568
+
3569
+ /**
3570
+ * FDv2 event names to listen for on the EventSource. This must stay in sync
3571
+ * with the `EventType` union defined in `@launchdarkly/js-sdk-common`'s
3572
+ * `internal/fdv2/proto.ts`.
3573
+ */
3574
+ const FDV2_EVENT_NAMES = [
3575
+ 'server-intent',
3576
+ 'put-object',
3577
+ 'delete-object',
3578
+ 'payload-transferred',
3579
+ 'goodbye',
3580
+ 'error',
3581
+ 'heart-beat',
3582
+ ];
3583
+ /**
3584
+ * Creates the core streaming base for FDv2 client-side data sources.
3585
+ *
3586
+ * Manages an EventSource connection, processes FDv2 protocol events using
3587
+ * a protocol handler from the common package, detects FDv1 fallback signals,
3588
+ * handles legacy ping events, and queues results for consumption by
3589
+ * {@link createStreamingInitializer} or {@link createStreamingSynchronizer}.
3590
+ *
3591
+ * @internal
3592
+ */
3593
+ function createStreamingBase(config) {
3594
+ const resultQueue = createAsyncQueue();
3595
+ const protocolHandler = internal.createProtocolHandler({ 'flag-eval': processFlagEval }, config.logger);
3596
+ const headers = { ...config.headers };
3597
+ function buildStreamUri() {
3598
+ const params = [...config.parameters];
3599
+ const basis = config.selectorGetter?.();
3600
+ if (basis) {
3601
+ params.push({ key: 'basis', value: encodeURIComponent(basis) });
3602
+ }
3603
+ return getStreamingUri(config.serviceEndpoints, config.streamUriPath, params);
3604
+ }
3605
+ let eventSource;
3606
+ let connectionAttemptStartTime;
3607
+ let fdv1Fallback = false;
3608
+ let started = false;
3609
+ let stopped = false;
3610
+ function logConnectionAttempt() {
3611
+ connectionAttemptStartTime = Date.now();
3612
+ }
3613
+ function logConnectionResult(success) {
3614
+ if (connectionAttemptStartTime && config.diagnosticsManager) {
3615
+ config.diagnosticsManager.recordStreamInit(connectionAttemptStartTime, !success, Date.now() - connectionAttemptStartTime);
3616
+ }
3617
+ connectionAttemptStartTime = undefined;
3618
+ }
3619
+ function handleAction(action) {
3620
+ switch (action.type) {
3621
+ case 'payload':
3622
+ logConnectionResult(true);
3623
+ resultQueue.put(changeSet(action.payload, fdv1Fallback));
3624
+ break;
3625
+ case 'goodbye':
3626
+ resultQueue.put(goodbye(action.reason, fdv1Fallback));
3627
+ break;
3628
+ case 'serverError':
3629
+ resultQueue.put(interrupted(errorInfoFromUnknown(action.reason), fdv1Fallback));
3630
+ break;
3631
+ case 'error':
3632
+ // Only actionable errors are queued; informational ones (UNKNOWN_EVENT)
3633
+ // are logged by the protocol handler.
3634
+ if (action.kind === 'MISSING_PAYLOAD' || action.kind === 'PROTOCOL_ERROR') {
3635
+ resultQueue.put(interrupted(errorInfoFromInvalidData(action.message), fdv1Fallback));
3636
+ }
3637
+ break;
3638
+ }
3639
+ }
3640
+ function handleError(err) {
3641
+ // Check for FDv1 fallback header.
3642
+ if (err.headers?.['x-ld-fd-fallback'] === 'true') {
3643
+ fdv1Fallback = true;
3644
+ logConnectionResult(false);
3645
+ resultQueue.put(terminalError(errorInfoFromHttpError(err.status ?? 0), true));
3646
+ return false;
3647
+ }
3648
+ if (!shouldRetry(err)) {
3649
+ config.logger?.error(httpErrorMessage(err, 'streaming request'));
3650
+ logConnectionResult(false);
3651
+ resultQueue.put(terminalError(errorInfoFromHttpError(err.status ?? 0), fdv1Fallback));
3652
+ return false;
3653
+ }
3654
+ config.logger?.warn(httpErrorMessage(err, 'streaming request', 'will retry'));
3655
+ logConnectionResult(false);
3656
+ logConnectionAttempt();
3657
+ resultQueue.put(interrupted(errorInfoFromHttpError(err.status ?? 0), fdv1Fallback));
3658
+ return true;
3659
+ }
3660
+ function attachFDv2Listeners(es) {
3661
+ FDV2_EVENT_NAMES.forEach((eventName) => {
3662
+ es.addEventListener(eventName, (event) => {
3663
+ if (stopped) {
3664
+ config.logger?.debug(`Received ${eventName} event after processor was closed. Skipping.`);
3665
+ return;
3666
+ }
3667
+ if (!event?.data) {
3668
+ // Some events (e.g. 'error') may legitimately arrive without a body.
3669
+ if (eventName !== 'error') {
3670
+ config.logger?.warn(`Event from EventStream missing data for "${eventName}".`);
3671
+ }
3672
+ return;
3673
+ }
3674
+ config.logger?.debug(`Received ${eventName} event`);
3675
+ let parsed;
3676
+ try {
3677
+ parsed = JSON.parse(event.data);
3678
+ }
3679
+ catch {
3680
+ config.logger?.error(`Stream received data that was unable to be parsed in "${eventName}" message`);
3681
+ config.logger?.debug(`Data follows: ${event.data}`);
3682
+ resultQueue.put(interrupted(errorInfoFromInvalidData('Malformed JSON in EventStream'), fdv1Fallback));
3683
+ return;
3684
+ }
3685
+ const action = protocolHandler.processEvent({ event: eventName, data: parsed });
3686
+ handleAction(action);
3687
+ });
3688
+ });
3689
+ }
3690
+ function attachPingListener(es) {
3691
+ es.addEventListener('ping', async () => {
3692
+ if (stopped) {
3693
+ config.logger?.debug('Ping received after processor was closed. Skipping.');
3694
+ return;
3695
+ }
3696
+ config.logger?.debug('Got PING, going to poll LaunchDarkly for feature flag updates');
3697
+ if (!config.pingHandler) {
3698
+ config.logger?.warn('Ping event received but no ping handler configured.');
3699
+ return;
3700
+ }
3701
+ try {
3702
+ const result = await config.pingHandler.handlePing();
3703
+ if (stopped) {
3704
+ config.logger?.debug('Ping completed after processor was closed. Skipping processing.');
3705
+ return;
3706
+ }
3707
+ resultQueue.put(result);
3708
+ }
3709
+ catch (err) {
3710
+ if (stopped) {
3711
+ return;
3712
+ }
3713
+ config.logger?.error(`Error handling ping: ${err?.message ?? err}`);
3714
+ resultQueue.put(interrupted(errorInfoFromNetworkError(err?.message ?? 'Error during ping poll'), fdv1Fallback));
3715
+ }
3716
+ });
3717
+ }
3718
+ return {
3719
+ start() {
3720
+ if (started || stopped) {
3721
+ return;
3722
+ }
3723
+ started = true;
3724
+ logConnectionAttempt();
3725
+ const es = config.requests.createEventSource(buildStreamUri(), {
3726
+ headers,
3727
+ errorFilter: (error) => handleError(error),
3728
+ initialRetryDelayMillis: config.initialRetryDelayMillis,
3729
+ readTimeoutMillis: 5 * 60 * 1000,
3730
+ retryResetIntervalMillis: 60 * 1000,
3731
+ });
3732
+ eventSource = es;
3733
+ attachFDv2Listeners(es);
3734
+ attachPingListener(es);
3735
+ es.onclose = () => {
3736
+ config.logger?.info('Closed LaunchDarkly stream connection');
3737
+ };
3738
+ es.onerror = (err) => {
3739
+ if (stopped) {
3740
+ return;
3741
+ }
3742
+ if (err && typeof err.status === 'number') {
3743
+ // This condition will be handled by the error filter.
3744
+ return;
3745
+ }
3746
+ resultQueue.put(interrupted(errorInfoFromNetworkError(err?.message ?? 'IO Error'), fdv1Fallback));
3747
+ };
3748
+ es.onopen = () => {
3749
+ config.logger?.info('Opened LaunchDarkly stream connection');
3750
+ protocolHandler.reset();
3751
+ };
3752
+ es.onretrying = (e) => {
3753
+ config.logger?.info(`Will retry stream connection in ${e.delayMillis} milliseconds`);
3754
+ };
3755
+ },
3756
+ close() {
3757
+ if (stopped) {
3758
+ return;
3759
+ }
3760
+ stopped = true;
3761
+ eventSource?.close();
3762
+ eventSource = undefined;
3763
+ resultQueue.put(shutdown());
3764
+ },
3765
+ takeResult() {
3766
+ return resultQueue.take();
3767
+ },
3768
+ };
3769
+ }
3770
+
3771
+ /**
3772
+ * Creates a one-shot streaming initializer for FDv2.
3773
+ *
3774
+ * Connects to the FDv2 streaming endpoint, waits for the first result
3775
+ * (a change set or an error status), then disconnects. Used in browser
3776
+ * `one-shot` mode where a persistent connection is not desired.
3777
+ *
3778
+ * If `close()` is called before a result arrives, the returned promise
3779
+ * resolves with a shutdown result.
3780
+ *
3781
+ * @param base - The streaming base that manages the EventSource connection.
3782
+ * @internal
3783
+ */
3784
+ function createStreamingInitializer(base) {
3785
+ let closed = false;
3786
+ let shutdownResolve;
3787
+ const shutdownPromise = new Promise((resolve) => {
3788
+ shutdownResolve = resolve;
3789
+ });
3790
+ return {
3791
+ run() {
3792
+ if (closed) {
3793
+ return Promise.resolve(shutdown());
3794
+ }
3795
+ base.start();
3796
+ return Promise.race([
3797
+ base.takeResult().then((result) => {
3798
+ // Got our first result — close the connection.
3799
+ base.close();
3800
+ return result;
3801
+ }),
3802
+ shutdownPromise,
3803
+ ]);
3804
+ },
3805
+ close() {
3806
+ if (closed) {
3807
+ return;
3808
+ }
3809
+ closed = true;
3810
+ base.close();
3811
+ shutdownResolve?.(shutdown());
3812
+ shutdownResolve = undefined;
3813
+ },
3814
+ };
3815
+ }
3816
+
3817
+ /**
3818
+ * Creates a long-lived streaming synchronizer for FDv2.
3819
+ *
3820
+ * Maintains a persistent EventSource connection to the FDv2 streaming
3821
+ * endpoint and produces a stream of results via the pull-based `next()`
3822
+ * method. Used in streaming connection mode.
3823
+ *
3824
+ * The connection is started lazily on the first call to `next()`.
3825
+ * On `close()`, the next call to `next()` returns a shutdown result.
3826
+ *
3827
+ * @param base - The streaming base that manages the EventSource connection.
3828
+ * @internal
3829
+ */
3830
+ function createStreamingSynchronizer(base) {
3831
+ let started = false;
3832
+ let closed = false;
3833
+ let shutdownResolve;
3834
+ const shutdownPromise = new Promise((resolve) => {
3835
+ shutdownResolve = resolve;
3836
+ });
3837
+ return {
3838
+ next() {
3839
+ if (closed) {
3840
+ return Promise.resolve(shutdown());
3841
+ }
3842
+ if (!started) {
3843
+ started = true;
3844
+ base.start();
3845
+ }
3846
+ return Promise.race([base.takeResult(), shutdownPromise]);
3847
+ },
3848
+ close() {
3849
+ if (closed) {
3850
+ return;
3851
+ }
3852
+ closed = true;
3853
+ base.close();
3854
+ shutdownResolve?.(shutdown());
3855
+ shutdownResolve = undefined;
3856
+ },
3857
+ };
3858
+ }
3859
+
3860
+ function createPingHandler(requestor, selectorGetter, logger) {
3861
+ return {
3862
+ handlePing: () => poll(requestor, selectorGetter(), false, logger),
3863
+ };
3864
+ }
3865
+ /**
3866
+ * Create a {@link ServiceEndpoints} with per-entry endpoint overrides applied.
3867
+ * Returns the original endpoints if no overrides are specified.
3868
+ */
3869
+ function resolveEndpoints(ctx, endpoints) {
3870
+ if (!endpoints?.pollingBaseUri && !endpoints?.streamingBaseUri) {
3871
+ return ctx.serviceEndpoints;
3872
+ }
3873
+ return new ServiceEndpoints(endpoints.streamingBaseUri ?? ctx.serviceEndpoints.streaming, endpoints.pollingBaseUri ?? ctx.serviceEndpoints.polling, ctx.serviceEndpoints.events, ctx.serviceEndpoints.analyticsEventPath, ctx.serviceEndpoints.diagnosticEventPath, ctx.serviceEndpoints.includeAuthorizationHeader, ctx.serviceEndpoints.payloadFilterKey);
3874
+ }
3875
+ /**
3876
+ * Get the FDv2 requestor for a polling entry. If the entry has custom
3877
+ * endpoints, creates a new requestor targeting those endpoints. Otherwise
3878
+ * returns the shared requestor from the context.
3879
+ */
3880
+ function resolvePollingRequestor(ctx, endpoints) {
3881
+ if (!endpoints?.pollingBaseUri) {
3882
+ return ctx.requestor;
3883
+ }
3884
+ const overriddenEndpoints = resolveEndpoints(ctx, endpoints);
3885
+ return makeFDv2Requestor(ctx.plainContextString, overriddenEndpoints, ctx.polling.paths, ctx.requests, ctx.encoding, ctx.baseHeaders, ctx.queryParams);
3886
+ }
3887
+ /**
3888
+ * Build a streaming base instance using per-entry config with context defaults
3889
+ * as fallbacks. The `sg` selector getter is the canonical source of truth for
3890
+ * the current selector — both the stream and its ping handler use it.
3891
+ */
3892
+ function buildStreamingBase(entry, ctx, sg) {
3893
+ const entryEndpoints = resolveEndpoints(ctx, entry.endpoints);
3894
+ const requestor = resolvePollingRequestor(ctx, entry.endpoints);
3895
+ const streamUriPath = ctx.streaming.paths.pathGet(ctx.encoding, ctx.plainContextString);
3896
+ return createStreamingBase({
3897
+ requests: ctx.requests,
3898
+ serviceEndpoints: entryEndpoints,
3899
+ streamUriPath,
3900
+ parameters: ctx.queryParams,
3901
+ selectorGetter: sg,
3902
+ headers: ctx.baseHeaders,
3903
+ initialRetryDelayMillis: (entry.initialReconnectDelay ?? ctx.streaming.initialReconnectDelaySeconds) * 1000,
3904
+ logger: ctx.logger,
3905
+ pingHandler: createPingHandler(requestor, sg, ctx.logger),
3906
+ });
3907
+ }
3908
+ /**
3909
+ * Creates a {@link SourceFactoryProvider} that handles `cache`, `polling`,
3910
+ * and `streaming` data source entries.
3911
+ */
3912
+ function createDefaultSourceFactoryProvider() {
3913
+ return {
3914
+ createInitializerFactory(entry, ctx) {
3915
+ switch (entry.type) {
3916
+ case 'polling': {
3917
+ const requestor = resolvePollingRequestor(ctx, entry.endpoints);
3918
+ return (sg) => createPollingInitializer(requestor, ctx.logger, sg);
3919
+ }
3920
+ case 'streaming':
3921
+ return (sg) => createStreamingInitializer(buildStreamingBase(entry, ctx, sg));
3922
+ case 'cache':
3923
+ return createCacheInitializerFactory({
3924
+ storage: ctx.storage,
3925
+ crypto: ctx.crypto,
3926
+ environmentNamespace: ctx.environmentNamespace,
3927
+ context: ctx.context,
3928
+ logger: ctx.logger,
3929
+ });
3930
+ default:
3931
+ return undefined;
3932
+ }
3933
+ },
3934
+ createSynchronizerSlot(entry, ctx) {
3935
+ switch (entry.type) {
3936
+ case 'polling': {
3937
+ const intervalMs = (entry.pollInterval ?? ctx.polling.intervalSeconds) * 1000;
3938
+ const requestor = resolvePollingRequestor(ctx, entry.endpoints);
3939
+ const factory = (sg) => createPollingSynchronizer(requestor, ctx.logger, sg, intervalMs);
3940
+ return createSynchronizerSlot(factory);
3941
+ }
3942
+ case 'streaming': {
3943
+ const factory = (sg) => createStreamingSynchronizer(buildStreamingBase(entry, ctx, sg));
3944
+ return createSynchronizerSlot(factory);
3945
+ }
3946
+ default:
3947
+ return undefined;
3948
+ }
3949
+ },
3950
+ };
3951
+ }
3952
+
3953
+ export { BROWSER_DATA_SYSTEM_DEFAULTS, BROWSER_TRANSITION_TABLE, BaseDataManager, DESKTOP_DATA_SYSTEM_DEFAULTS, DESKTOP_TRANSITION_TABLE, DataSourceState, LDClientImpl, MOBILE_DATA_SYSTEM_DEFAULTS, MOBILE_TRANSITION_TABLE, MODE_TABLE, browserFdv1Endpoints, createDataSourceStatusManager, createDefaultSourceFactoryProvider, dataSystemValidators, fdv2Endpoints, makeRequestor, mobileFdv1Endpoints, readFlagsFromBootstrap, resolveConnectionMode, safeRegisterDebugOverridePlugins, validateOptions };
2562
3954
  //# sourceMappingURL=index.mjs.map