@launchdarkly/js-sdk-common 2.26.1 → 2.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,18 @@
2
2
 
3
3
  All notable changes to `@launchdarkly/js-sdk-common` will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org).
4
4
 
5
+ ## [2.27.0](https://github.com/launchdarkly/js-core/compare/js-sdk-common-v2.26.1...js-sdk-common-v2.27.0) (2026-09-29)
6
+
7
+
8
+ ### Features
9
+
10
+ * add a reusable retry state controller for RETRY-conformant backoff ([#2045](https://github.com/launchdarkly/js-core/issues/2045)) ([721b559](https://github.com/launchdarkly/js-core/commit/721b559ff15bb13e3344921de9539e2663d0f0c8))
11
+
12
+
13
+ ### Bug Fixes
14
+
15
+ * Stop format() from hanging on a trailing percent sign ([#2056](https://github.com/launchdarkly/js-core/issues/2056)) ([c5114ec](https://github.com/launchdarkly/js-core/commit/c5114ecf5dc32826f260744b0e4aa5c4a7f633d6))
16
+
5
17
  ## [2.26.1](https://github.com/launchdarkly/js-core/compare/js-sdk-common-v2.26.0...js-sdk-common-v2.26.1) (2026-09-22)
6
18
 
7
19
 
@@ -2,5 +2,6 @@ import { Backoff, DefaultBackoff } from './Backoff';
2
2
  import { CompositeDataSource } from './CompositeDataSource';
3
3
  import { DataSourceErrorKind } from './DataSourceErrorKinds';
4
4
  import { LDFileDataSourceError, LDFlagDeliveryFallbackError, LDPollingError, LDStreamingError, StreamingErrorHandler } from './errors';
5
- export { Backoff, CompositeDataSource, DefaultBackoff, DataSourceErrorKind, LDFileDataSourceError, LDFlagDeliveryFallbackError, LDPollingError, LDStreamingError, StreamingErrorHandler, };
5
+ import { createAfterConsecutiveSuccesses, createAfterHealthyFor, createRetryState, forPolling, forStreaming, ResetPolicy, RetryState, RetryStateConfig } from './retry';
6
+ export { Backoff, CompositeDataSource, createAfterConsecutiveSuccesses, createAfterHealthyFor, createRetryState, DefaultBackoff, DataSourceErrorKind, forPolling, forStreaming, LDFileDataSourceError, LDFlagDeliveryFallbackError, LDPollingError, LDStreamingError, ResetPolicy, RetryState, RetryStateConfig, StreamingErrorHandler, };
6
7
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/datasource/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EACL,qBAAqB,EACrB,2BAA2B,EAC3B,cAAc,EACd,gBAAgB,EAChB,qBAAqB,EACtB,MAAM,UAAU,CAAC;AAElB,OAAO,EACL,OAAO,EACP,mBAAmB,EACnB,cAAc,EACd,mBAAmB,EACnB,qBAAqB,EACrB,2BAA2B,EAC3B,cAAc,EACd,gBAAgB,EAChB,qBAAqB,GACtB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/datasource/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EACL,qBAAqB,EACrB,2BAA2B,EAC3B,cAAc,EACd,gBAAgB,EAChB,qBAAqB,EACtB,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,+BAA+B,EAC/B,qBAAqB,EACrB,gBAAgB,EAChB,UAAU,EACV,YAAY,EACZ,WAAW,EACX,UAAU,EACV,gBAAgB,EACjB,MAAM,SAAS,CAAC;AAEjB,OAAO,EACL,OAAO,EACP,mBAAmB,EACnB,+BAA+B,EAC/B,qBAAqB,EACrB,gBAAgB,EAChB,cAAc,EACd,mBAAmB,EACnB,UAAU,EACV,YAAY,EACZ,qBAAqB,EACrB,2BAA2B,EAC3B,cAAc,EACd,gBAAgB,EAChB,WAAW,EACX,UAAU,EACV,gBAAgB,EAChB,qBAAqB,GACtB,CAAC"}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Decides when a component has operated well enough, for long enough, that its
3
+ * retry state should reset.
4
+ */
5
+ export interface ResetPolicy {
6
+ /**
7
+ * Records that the component is operating normally.
8
+ */
9
+ noteHealthy(): void;
10
+ /**
11
+ * Records a failure, which ends any healthy stretch in progress.
12
+ */
13
+ noteFailure(): void;
14
+ /**
15
+ * Reports whether the reset condition is met.
16
+ */
17
+ isSatisfied(): boolean;
18
+ }
19
+ /**
20
+ * Creates a policy that resets once the component has operated without failing
21
+ * for the given duration. Repeated healthy reports do not move the starting
22
+ * point; only a failure clears it.
23
+ *
24
+ * @param healthyForMs How long the component must operate without failing,
25
+ * in milliseconds; must be a positive, finite number.
26
+ * @param clock The time source used to measure the healthy stretch; defaults
27
+ * to a monotonic clock. Primarily for testing.
28
+ */
29
+ export declare function createAfterHealthyFor(healthyForMs: number, clock?: () => number): ResetPolicy;
30
+ /**
31
+ * Creates a policy that resets once the given number of operations in a row
32
+ * have succeeded.
33
+ *
34
+ * @param count How many operations in a row must succeed; must be a positive
35
+ * integer.
36
+ */
37
+ export declare function createAfterConsecutiveSuccesses(count: number): ResetPolicy;
38
+ //# sourceMappingURL=ResetPolicy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ResetPolicy.d.ts","sourceRoot":"","sources":["../../../src/datasource/retry/ResetPolicy.ts"],"names":[],"mappings":"AAQA;;;GAGG;AACH,MAAM,WAAW,WAAW;IAC1B;;OAEG;IACH,WAAW,IAAI,IAAI,CAAC;IAEpB;;OAEG;IACH,WAAW,IAAI,IAAI,CAAC;IAEpB;;OAEG;IACH,WAAW,IAAI,OAAO,CAAC;CACxB;AAED;;;;;;;;;GASG;AACH,wBAAgB,qBAAqB,CACnC,YAAY,EAAE,MAAM,EACpB,KAAK,GAAE,MAAM,MAAuB,GACnC,WAAW,CAkBb;AAED;;;;;;GAMG;AACH,wBAAgB,+BAA+B,CAAC,KAAK,EAAE,MAAM,GAAG,WAAW,CAgB1E"}
@@ -0,0 +1,119 @@
1
+ import { LDLogger } from '../../api/logging/LDLogger';
2
+ import { FailureKind } from '../../errors';
3
+ import { ResetPolicy } from './ResetPolicy';
4
+ /**
5
+ * Configuration for a {@link RetryState}.
6
+ *
7
+ * Values are trusted, not validated: each delay bound must be a positive,
8
+ * finite number of milliseconds, and the operating cadence a non-negative,
9
+ * finite one. The factories ({@link forStreaming}, {@link forPolling}) are the
10
+ * validated entry points for anything user-configurable; a caller constructing
11
+ * directly is expected to supply known-good values.
12
+ */
13
+ export interface RetryStateConfig {
14
+ /** The delay before the first retry in the normal regime, in milliseconds. */
15
+ normalInitialDelayMs: number;
16
+ /** The longest normal-regime delay, in milliseconds. */
17
+ normalCeilingMs: number;
18
+ /** The delay before the first retry in the extended regime, in milliseconds. */
19
+ extendedInitialDelayMs: number;
20
+ /**
21
+ * The longest extended-regime delay, in milliseconds; never less than the
22
+ * extended initial delay.
23
+ */
24
+ extendedCeilingMs: number;
25
+ /** Decides when the retry state resets. */
26
+ resetPolicy: ResetPolicy;
27
+ /**
28
+ * The wait between healthy operations, in milliseconds. No wait is ever
29
+ * shorter than this. Zero (the default) for a component that operates
30
+ * continuously.
31
+ */
32
+ operatingCadenceMs?: number;
33
+ /** The random source used for jitter. */
34
+ random?: () => number;
35
+ }
36
+ /**
37
+ * Tracks how long a data source, or another long-running component, should
38
+ * wait before its next attempt.
39
+ *
40
+ * Recording a failure advances the state and decides the next wait, which
41
+ * {@link RetryState.nextDelay} reports: the delay doubles with each
42
+ * consecutive failure, from the current regime's initial delay up to its
43
+ * ceiling, less a random jitter of up to half of it, and never less than the
44
+ * operating cadence. An unexpected failure moves the state to the extended
45
+ * regime, which raises both bounds; a normal failure that follows cannot lower
46
+ * them. The bounds stay raised until the reset policy is satisfied. A
47
+ * server-directed retry time, once applied, replaces the regime's initial
48
+ * delay as the base of the computation; the ceiling continues to apply.
49
+ *
50
+ * Recording a success sets the next wait back to the operating cadence, even
51
+ * while the retry state is raised, because a backoff wait applies to a retry
52
+ * and not to every operation.
53
+ *
54
+ * A retry state never starts timers, performs I/O, or logs; callers schedule
55
+ * the waits it computes. Use one instance per component; instances are never
56
+ * shared between components.
57
+ */
58
+ export interface RetryState {
59
+ /**
60
+ * The wait, in milliseconds, before the next operation, as the last
61
+ * recorded outcome decided it. Reading it has no side effects.
62
+ */
63
+ readonly nextDelay: number;
64
+ /**
65
+ * Records a failed attempt and decides the wait before the next one.
66
+ *
67
+ * The state advances before the wait is computed, so {@link RetryState.nextDelay}
68
+ * always reflects the failure just recorded. Callers should read it in the
69
+ * same turn, before any other outcome is recorded.
70
+ */
71
+ recordFailure(kind: FailureKind): void;
72
+ /**
73
+ * Records a successful operation and resets the retry state if that is now
74
+ * enough to satisfy the reset policy.
75
+ */
76
+ recordSuccess(): void;
77
+ /**
78
+ * Applies a server-directed retry time.
79
+ *
80
+ * The value replaces the base of the delay computation and restarts the
81
+ * doubling sequence, taking precedence over the current regime's initial
82
+ * delay — including the extended regime's. The computed delay is still
83
+ * bounded by the regime's ceiling. The value stays in effect until another
84
+ * one arrives, including across a reset. Non-finite or negative values are
85
+ * ignored; callers are expected to have validated and capped the value at
86
+ * its point of entry.
87
+ */
88
+ applyServerDirectedRetry(delayMs: number): void;
89
+ }
90
+ /**
91
+ * Builds a retry state from explicit bounds. See {@link RetryStateConfig} for
92
+ * the contract on the values.
93
+ */
94
+ export declare function createRetryState(config: RetryStateConfig): RetryState;
95
+ /**
96
+ * Builds the retry state for a streaming data source: no wait during healthy
97
+ * operation, a normal regime running from the configured initial delay up to
98
+ * a 30 second ceiling, an extended regime of 5 minutes up to 1 hour, and a
99
+ * reset once a connection has been healthy for 60 seconds.
100
+ *
101
+ * The initial delay is validated here; the documented default of 1 second
102
+ * stands in for anything that is not a positive, finite number. A configured
103
+ * delay above the normal ceiling is clamped to it, while the extended regime
104
+ * never starts below the configured delay.
105
+ */
106
+ export declare function forStreaming(initialReconnectDelayMs: number, logger?: LDLogger): RetryState;
107
+ /**
108
+ * Builds the retry state for a polling data source: the poll interval is the
109
+ * operating cadence, so no wait is ever shorter than it; in the normal regime
110
+ * both bounds are the interval itself, so a normal failure simply polls again
111
+ * on schedule; the extended regime runs from 5 minutes (or the interval, if
112
+ * longer) up to 1 hour (or the interval, if longer); and the state resets
113
+ * after two successful polls in a row.
114
+ *
115
+ * The poll interval is validated here; the documented default of 30 seconds
116
+ * stands in for anything that is not a positive, finite number.
117
+ */
118
+ export declare function forPolling(pollIntervalMs: number, logger?: LDLogger): RetryState;
119
+ //# sourceMappingURL=RetryState.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RetryState.d.ts","sourceRoot":"","sources":["../../../src/datasource/retry/RetryState.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAA0D,WAAW,EAAE,MAAM,eAAe,CAAC;AAgCpG;;;;;;;;GAQG;AACH,MAAM,WAAW,gBAAgB;IAC/B,8EAA8E;IAC9E,oBAAoB,EAAE,MAAM,CAAC;IAE7B,wDAAwD;IACxD,eAAe,EAAE,MAAM,CAAC;IAExB,gFAAgF;IAChF,sBAAsB,EAAE,MAAM,CAAC;IAE/B;;;OAGG;IACH,iBAAiB,EAAE,MAAM,CAAC;IAE1B,2CAA2C;IAC3C,WAAW,EAAE,WAAW,CAAC;IAEzB;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAE5B,yCAAyC;IACzC,MAAM,CAAC,EAAE,MAAM,MAAM,CAAC;CACvB;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,WAAW,UAAU;IACzB;;;OAGG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAE3B;;;;;;OAMG;IACH,aAAa,CAAC,IAAI,EAAE,WAAW,GAAG,IAAI,CAAC;IAEvC;;;OAGG;IACH,aAAa,IAAI,IAAI,CAAC;IAEtB;;;;;;;;;;OAUG;IACH,wBAAwB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CACjD;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,gBAAgB,GAAG,UAAU,CAgFrE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,YAAY,CAAC,uBAAuB,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,QAAQ,GAAG,UAAU,CAe3F;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,UAAU,CAAC,cAAc,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,QAAQ,GAAG,UAAU,CAehF"}
@@ -0,0 +1,4 @@
1
+ import { createAfterConsecutiveSuccesses, createAfterHealthyFor, ResetPolicy } from './ResetPolicy';
2
+ import { createRetryState, forPolling, forStreaming, RetryState, RetryStateConfig } from './RetryState';
3
+ export { createAfterConsecutiveSuccesses, createAfterHealthyFor, createRetryState, forPolling, forStreaming, ResetPolicy, RetryState, RetryStateConfig, };
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/datasource/retry/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,+BAA+B,EAAE,qBAAqB,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACpG,OAAO,EACL,gBAAgB,EAChB,UAAU,EACV,YAAY,EACZ,UAAU,EACV,gBAAgB,EACjB,MAAM,cAAc,CAAC;AAEtB,OAAO,EACL,+BAA+B,EAC/B,qBAAqB,EACrB,gBAAgB,EAChB,UAAU,EACV,YAAY,EACZ,WAAW,EACX,UAAU,EACV,gBAAgB,GACjB,CAAC"}
@@ -7,11 +7,43 @@ export declare class LDClientError extends Error {
7
7
  export declare class LDTimeoutError extends Error {
8
8
  constructor(message: string);
9
9
  }
10
+ /**
11
+ * How a failure is classified, which decides how long the next wait is.
12
+ *
13
+ * A 'normal' failure is one the service is expected to recover from without
14
+ * intervention, so the wait stays short. An 'unexpected' failure suggests a
15
+ * problem that requires a person to fix, such as a rejected credential, so the
16
+ * wait becomes much longer. Neither classification ever means giving up; there
17
+ * is always a next attempt.
18
+ */
19
+ export type FailureKind = 'normal' | 'unexpected';
20
+ /**
21
+ * Classifies an HTTP status.
22
+ *
23
+ * 400, 408, and 429 are normal, as is any 5xx. Every other 4xx, including 401
24
+ * and 403, is unexpected. Anything outside the error ranges, including 0 for
25
+ * "no response", is normal.
26
+ */
27
+ export declare function classifyHttpStatus(status: number): FailureKind;
28
+ /**
29
+ * Classifies a transport-level failure (connection refused or dropped, DNS
30
+ * failure, timeout, TLS negotiation failure).
31
+ *
32
+ * Always normal: in an all-HTTPS system every transport error surfaces through
33
+ * the TLS layer, so a certificate misconfiguration cannot be reliably
34
+ * distinguished from a transient network fault, and treating transient faults
35
+ * as unexpected would hold ordinary recoveries to multi-minute waits.
36
+ */
37
+ export declare function classifyTransportFailure(): FailureKind;
10
38
  /**
11
39
  * Check if the HTTP error is recoverable. This will return false if a request
12
40
  * made with any payload could not recover. If the reason for the failure
13
41
  * is payload specific, for instance a payload that is too large, then
14
42
  * it could recover with a different payload.
43
+ *
44
+ * Superseded by {@link classifyHttpStatus}, which this delegates to. It is
45
+ * retained for the event-delivery pathway and is expected to be deprecated
46
+ * once that pathway migrates to failure classification.
15
47
  */
16
48
  export declare function isHttpRecoverable(status: number): boolean;
17
49
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAGA,qBAAa,yBAA0B,SAAQ,KAAK;gBACtC,OAAO,EAAE,MAAM;CAI5B;AAED,qBAAa,aAAc,SAAQ,KAAK;gBAC1B,OAAO,EAAE,MAAM;CAI5B;AAED,qBAAa,cAAe,SAAQ,KAAK;gBAC3B,OAAO,EAAE,MAAM;CAI5B;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,WAK/C;AAED;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,MAAM,WAKtD"}
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAGA,qBAAa,yBAA0B,SAAQ,KAAK;gBACtC,OAAO,EAAE,MAAM;CAI5B;AAED,qBAAa,aAAc,SAAQ,KAAK;gBAC1B,OAAO,EAAE,MAAM;CAI5B;AAED,qBAAa,cAAe,SAAQ,KAAK;gBAC3B,OAAO,EAAE,MAAM;CAI5B;AAED;;;;;;;;GAQG;AACH,MAAM,MAAM,WAAW,GAAG,QAAQ,GAAG,YAAY,CAAC;AAMlD;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,WAAW,CAK9D;AAED;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,IAAI,WAAW,CAEtD;AAED;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,WAE/C;AAED;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,MAAM,WAKtD"}
@@ -1482,6 +1482,203 @@ exports.DataSourceErrorKind = void 0;
1482
1482
  DataSourceErrorKind["InvalidData"] = "INVALID_DATA";
1483
1483
  })(exports.DataSourceErrorKind || (exports.DataSourceErrorKind = {}));
1484
1484
 
1485
+ function defaultClock() {
1486
+ const perf = globalThis?.performance;
1487
+ if (perf && typeof perf.now === 'function') {
1488
+ return () => perf.now();
1489
+ }
1490
+ return () => Date.now();
1491
+ }
1492
+ /**
1493
+ * Creates a policy that resets once the component has operated without failing
1494
+ * for the given duration. Repeated healthy reports do not move the starting
1495
+ * point; only a failure clears it.
1496
+ *
1497
+ * @param healthyForMs How long the component must operate without failing,
1498
+ * in milliseconds; must be a positive, finite number.
1499
+ * @param clock The time source used to measure the healthy stretch; defaults
1500
+ * to a monotonic clock. Primarily for testing.
1501
+ */
1502
+ function createAfterHealthyFor(healthyForMs, clock = defaultClock()) {
1503
+ let healthySinceMs;
1504
+ return {
1505
+ noteHealthy() {
1506
+ if (healthySinceMs === undefined) {
1507
+ healthySinceMs = clock();
1508
+ }
1509
+ },
1510
+ noteFailure() {
1511
+ healthySinceMs = undefined;
1512
+ },
1513
+ isSatisfied() {
1514
+ return healthySinceMs !== undefined && clock() - healthySinceMs >= healthyForMs;
1515
+ },
1516
+ };
1517
+ }
1518
+ /**
1519
+ * Creates a policy that resets once the given number of operations in a row
1520
+ * have succeeded.
1521
+ *
1522
+ * @param count How many operations in a row must succeed; must be a positive
1523
+ * integer.
1524
+ */
1525
+ function createAfterConsecutiveSuccesses(count) {
1526
+ let successes = 0;
1527
+ return {
1528
+ noteHealthy() {
1529
+ successes += 1;
1530
+ },
1531
+ noteFailure() {
1532
+ successes = 0;
1533
+ },
1534
+ isSatisfied() {
1535
+ return successes >= count;
1536
+ },
1537
+ };
1538
+ }
1539
+
1540
+ // The delay bounds of the extended regime, in milliseconds. A component enters
1541
+ // the extended regime after an unexpected failure and leaves it when its reset
1542
+ // policy is satisfied.
1543
+ const EXTENDED_INITIAL_DELAY_MS = 5 * 60 * 1000;
1544
+ const EXTENDED_CEILING_MS = 60 * 60 * 1000;
1545
+ // The bounds, reset window, and default initial delay of streaming's normal regime.
1546
+ const STREAMING_NORMAL_CEILING_MS = 30 * 1000;
1547
+ const STREAMING_RESET_INTERVAL_MS = 60 * 1000;
1548
+ const DEFAULT_STREAMING_INITIAL_DELAY_MS = 1000;
1549
+ // Polling's reset condition and default cadence.
1550
+ const POLLING_RESET_SUCCESSES = 2;
1551
+ const DEFAULT_POLL_INTERVAL_MS = 30 * 1000;
1552
+ function positiveFiniteOrDefault(value, defaultValueMs, name, logger) {
1553
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
1554
+ return value;
1555
+ }
1556
+ logger?.warn(`${name} must be a positive, finite number of milliseconds; using the default of ${defaultValueMs}`);
1557
+ return defaultValueMs;
1558
+ }
1559
+ /**
1560
+ * Builds a retry state from explicit bounds. See {@link RetryStateConfig} for
1561
+ * the contract on the values.
1562
+ */
1563
+ function createRetryState(config) {
1564
+ const normalInitialDelayMs = config.normalInitialDelayMs;
1565
+ const normalCeilingMs = config.normalCeilingMs;
1566
+ const extendedInitialDelayMs = config.extendedInitialDelayMs;
1567
+ const extendedCeilingMs = config.extendedCeilingMs;
1568
+ const operatingCadenceMs = config.operatingCadenceMs ?? 0;
1569
+ const { resetPolicy } = config;
1570
+ const random = config.random ?? Math.random;
1571
+ let attempts = 0;
1572
+ let extended = false;
1573
+ let minDelayMs = normalInitialDelayMs;
1574
+ let maxDelayMs = normalCeilingMs;
1575
+ let serverDirectedBaseMs;
1576
+ // Before any outcome is recorded, the next wait is the ordinary interval.
1577
+ let nextDelayMs = operatingCadenceMs;
1578
+ function resetIfDue() {
1579
+ if (!resetPolicy.isSatisfied()) {
1580
+ return;
1581
+ }
1582
+ attempts = 0;
1583
+ extended = false;
1584
+ minDelayMs = normalInitialDelayMs;
1585
+ maxDelayMs = normalCeilingMs;
1586
+ }
1587
+ return {
1588
+ get nextDelay() {
1589
+ return nextDelayMs;
1590
+ },
1591
+ recordFailure(kind) {
1592
+ // A reset that fell due during healthy operation is applied before the
1593
+ // new failure is counted, so the failure computes from a fresh sequence.
1594
+ resetIfDue();
1595
+ resetPolicy.noteFailure();
1596
+ if (kind === 'unexpected' && !extended) {
1597
+ // Moving to the extended regime raises both bounds and starts the delay
1598
+ // sequence over. Only the move does this: a later unexpected failure
1599
+ // keeps counting up rather than re-pinning the initial delay.
1600
+ extended = true;
1601
+ minDelayMs = extendedInitialDelayMs;
1602
+ maxDelayMs = Math.max(extendedCeilingMs, extendedInitialDelayMs);
1603
+ attempts = 1;
1604
+ }
1605
+ else {
1606
+ attempts += 1;
1607
+ }
1608
+ const base = serverDirectedBaseMs ?? minDelayMs;
1609
+ // Compare against the ceiling scaled down rather than the base scaled up, so
1610
+ // the computed value can never overflow the ceiling. A base of zero doubles
1611
+ // to zero forever, so it short-circuits.
1612
+ let target = 0;
1613
+ if (base > 0) {
1614
+ const exponent = attempts - 1;
1615
+ target = base >= maxDelayMs / 2 ** exponent ? maxDelayMs : base * 2 ** exponent;
1616
+ }
1617
+ const jitter = (random() * target) / 2;
1618
+ nextDelayMs = Math.max(target - jitter, operatingCadenceMs);
1619
+ },
1620
+ recordSuccess() {
1621
+ resetPolicy.noteHealthy();
1622
+ resetIfDue();
1623
+ // A backoff wait applies to a retry, not to every operation, so after a
1624
+ // success the next wait is the ordinary interval even while the retry
1625
+ // state is raised.
1626
+ nextDelayMs = operatingCadenceMs;
1627
+ },
1628
+ applyServerDirectedRetry(delayMs) {
1629
+ if (typeof delayMs !== 'number' || !Number.isFinite(delayMs) || delayMs < 0) {
1630
+ return;
1631
+ }
1632
+ serverDirectedBaseMs = delayMs;
1633
+ attempts = 0;
1634
+ },
1635
+ };
1636
+ }
1637
+ /**
1638
+ * Builds the retry state for a streaming data source: no wait during healthy
1639
+ * operation, a normal regime running from the configured initial delay up to
1640
+ * a 30 second ceiling, an extended regime of 5 minutes up to 1 hour, and a
1641
+ * reset once a connection has been healthy for 60 seconds.
1642
+ *
1643
+ * The initial delay is validated here; the documented default of 1 second
1644
+ * stands in for anything that is not a positive, finite number. A configured
1645
+ * delay above the normal ceiling is clamped to it, while the extended regime
1646
+ * never starts below the configured delay.
1647
+ */
1648
+ function forStreaming(initialReconnectDelayMs, logger) {
1649
+ const validated = positiveFiniteOrDefault(initialReconnectDelayMs, DEFAULT_STREAMING_INITIAL_DELAY_MS, 'initialReconnectDelayMs', logger);
1650
+ return createRetryState({
1651
+ normalInitialDelayMs: validated,
1652
+ normalCeilingMs: STREAMING_NORMAL_CEILING_MS,
1653
+ extendedInitialDelayMs: Math.max(EXTENDED_INITIAL_DELAY_MS, validated),
1654
+ extendedCeilingMs: EXTENDED_CEILING_MS,
1655
+ resetPolicy: createAfterHealthyFor(STREAMING_RESET_INTERVAL_MS),
1656
+ operatingCadenceMs: 0,
1657
+ });
1658
+ }
1659
+ /**
1660
+ * Builds the retry state for a polling data source: the poll interval is the
1661
+ * operating cadence, so no wait is ever shorter than it; in the normal regime
1662
+ * both bounds are the interval itself, so a normal failure simply polls again
1663
+ * on schedule; the extended regime runs from 5 minutes (or the interval, if
1664
+ * longer) up to 1 hour (or the interval, if longer); and the state resets
1665
+ * after two successful polls in a row.
1666
+ *
1667
+ * The poll interval is validated here; the documented default of 30 seconds
1668
+ * stands in for anything that is not a positive, finite number.
1669
+ */
1670
+ function forPolling(pollIntervalMs, logger) {
1671
+ const validated = positiveFiniteOrDefault(pollIntervalMs, DEFAULT_POLL_INTERVAL_MS, 'pollIntervalMs', logger);
1672
+ return createRetryState({
1673
+ normalInitialDelayMs: validated,
1674
+ normalCeilingMs: validated,
1675
+ extendedInitialDelayMs: Math.max(EXTENDED_INITIAL_DELAY_MS, validated),
1676
+ extendedCeilingMs: EXTENDED_CEILING_MS,
1677
+ resetPolicy: createAfterConsecutiveSuccesses(POLLING_RESET_SUCCESSES),
1678
+ operatingCadenceMs: validated,
1679
+ });
1680
+ }
1681
+
1485
1682
  /**
1486
1683
  * Enable / disable Auto environment attributes. When enabled, the SDK will automatically
1487
1684
  * provide data about the mobile environment where the application is running. This data makes it simpler to target
@@ -1647,6 +1844,11 @@ function format(...args) {
1647
1844
  }
1648
1845
  i += 2;
1649
1846
  }
1847
+ else {
1848
+ // A trailing '%' has nothing to escape, so keep it as-is.
1849
+ out += '%';
1850
+ i += 1;
1851
+ }
1650
1852
  }
1651
1853
  else {
1652
1854
  out += char;
@@ -2031,17 +2233,46 @@ class LDTimeoutError extends Error {
2031
2233
  this.name = 'LaunchDarklyTimeoutError';
2032
2234
  }
2033
2235
  }
2236
+ // HTTP statuses in the 4xx range that are still normal failures. Every other
2237
+ // 4xx is unexpected.
2238
+ const NORMAL_4XX_STATUSES = [400, 408, 429];
2239
+ /**
2240
+ * Classifies an HTTP status.
2241
+ *
2242
+ * 400, 408, and 429 are normal, as is any 5xx. Every other 4xx, including 401
2243
+ * and 403, is unexpected. Anything outside the error ranges, including 0 for
2244
+ * "no response", is normal.
2245
+ */
2246
+ function classifyHttpStatus(status) {
2247
+ if (status >= 400 && status < 500 && !NORMAL_4XX_STATUSES.includes(status)) {
2248
+ return 'unexpected';
2249
+ }
2250
+ return 'normal';
2251
+ }
2252
+ /**
2253
+ * Classifies a transport-level failure (connection refused or dropped, DNS
2254
+ * failure, timeout, TLS negotiation failure).
2255
+ *
2256
+ * Always normal: in an all-HTTPS system every transport error surfaces through
2257
+ * the TLS layer, so a certificate misconfiguration cannot be reliably
2258
+ * distinguished from a transient network fault, and treating transient faults
2259
+ * as unexpected would hold ordinary recoveries to multi-minute waits.
2260
+ */
2261
+ function classifyTransportFailure() {
2262
+ return 'normal';
2263
+ }
2034
2264
  /**
2035
2265
  * Check if the HTTP error is recoverable. This will return false if a request
2036
2266
  * made with any payload could not recover. If the reason for the failure
2037
2267
  * is payload specific, for instance a payload that is too large, then
2038
2268
  * it could recover with a different payload.
2269
+ *
2270
+ * Superseded by {@link classifyHttpStatus}, which this delegates to. It is
2271
+ * retained for the event-delivery pathway and is expected to be deprecated
2272
+ * once that pathway migrates to failure classification.
2039
2273
  */
2040
2274
  function isHttpRecoverable(status) {
2041
- if (status >= 400 && status < 500) {
2042
- return status === 400 || status === 408 || status === 429;
2043
- }
2044
- return true;
2275
+ return classifyHttpStatus(status) === 'normal';
2045
2276
  }
2046
2277
  /**
2047
2278
  * Returns true if the status could recover for a different payload.
@@ -3530,12 +3761,19 @@ exports.TypeArray = TypeArray;
3530
3761
  exports.TypeValidators = TypeValidators;
3531
3762
  exports.base64UrlEncode = base64UrlEncode;
3532
3763
  exports.cancelableTimedPromise = cancelableTimedPromise;
3764
+ exports.classifyHttpStatus = classifyHttpStatus;
3765
+ exports.classifyTransportFailure = classifyTransportFailure;
3533
3766
  exports.clone = clone;
3767
+ exports.createAfterConsecutiveSuccesses = createAfterConsecutiveSuccesses;
3768
+ exports.createAfterHealthyFor = createAfterHealthyFor;
3769
+ exports.createRetryState = createRetryState;
3534
3770
  exports.createSafeLogger = createSafeLogger;
3535
3771
  exports.debounce = debounce;
3536
3772
  exports.deepCompact = deepCompact;
3537
3773
  exports.defaultHeaders = defaultHeaders;
3538
3774
  exports.fastDeepEqual = fastDeepEqual;
3775
+ exports.forPolling = forPolling;
3776
+ exports.forStreaming = forStreaming;
3539
3777
  exports.getEventsUri = getEventsUri;
3540
3778
  exports.getPollingUri = getPollingUri;
3541
3779
  exports.getStreamingUri = getStreamingUri;