@launchdarkly/js-sdk-common 2.26.0 → 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.
Files changed (32) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/cjs/datasource/index.d.ts +2 -1
  3. package/dist/cjs/datasource/index.d.ts.map +1 -1
  4. package/dist/cjs/datasource/retry/ResetPolicy.d.ts +38 -0
  5. package/dist/cjs/datasource/retry/ResetPolicy.d.ts.map +1 -0
  6. package/dist/cjs/datasource/retry/RetryState.d.ts +119 -0
  7. package/dist/cjs/datasource/retry/RetryState.d.ts.map +1 -0
  8. package/dist/cjs/datasource/retry/index.d.ts +4 -0
  9. package/dist/cjs/datasource/retry/index.d.ts.map +1 -0
  10. package/dist/cjs/errors.d.ts +32 -0
  11. package/dist/cjs/errors.d.ts.map +1 -1
  12. package/dist/cjs/index.cjs +246 -5
  13. package/dist/cjs/index.cjs.map +1 -1
  14. package/dist/cjs/index.d.ts +2 -2
  15. package/dist/cjs/index.d.ts.map +1 -1
  16. package/dist/cjs/internal/fdv2/payloadStreamReader.d.ts.map +1 -1
  17. package/dist/esm/datasource/index.d.ts +2 -1
  18. package/dist/esm/datasource/index.d.ts.map +1 -1
  19. package/dist/esm/datasource/retry/ResetPolicy.d.ts +38 -0
  20. package/dist/esm/datasource/retry/ResetPolicy.d.ts.map +1 -0
  21. package/dist/esm/datasource/retry/RetryState.d.ts +119 -0
  22. package/dist/esm/datasource/retry/RetryState.d.ts.map +1 -0
  23. package/dist/esm/datasource/retry/index.d.ts +4 -0
  24. package/dist/esm/datasource/retry/index.d.ts.map +1 -0
  25. package/dist/esm/errors.d.ts +32 -0
  26. package/dist/esm/errors.d.ts.map +1 -1
  27. package/dist/esm/index.d.ts +2 -2
  28. package/dist/esm/index.d.ts.map +1 -1
  29. package/dist/esm/index.mjs +240 -6
  30. package/dist/esm/index.mjs.map +1 -1
  31. package/dist/esm/internal/fdv2/payloadStreamReader.d.ts.map +1 -1
  32. package/package.json +1 -1
@@ -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"}
@@ -1,7 +1,7 @@
1
1
  import AttributeReference from './AttributeReference';
2
2
  import Context from './Context';
3
3
  import ContextFilter from './ContextFilter';
4
- import { Backoff, CompositeDataSource, DataSourceErrorKind, DefaultBackoff, LDFileDataSourceError, LDFlagDeliveryFallbackError, LDPollingError, LDStreamingError, StreamingErrorHandler } from './datasource';
4
+ import { Backoff, CompositeDataSource, createAfterConsecutiveSuccesses, createAfterHealthyFor, createRetryState, DataSourceErrorKind, DefaultBackoff, forPolling, forStreaming, LDFileDataSourceError, LDFlagDeliveryFallbackError, LDPollingError, LDStreamingError, ResetPolicy, RetryState, RetryStateConfig, StreamingErrorHandler } from './datasource';
5
5
  export * from './api';
6
6
  export * from './validators';
7
7
  export * from './logging';
@@ -9,5 +9,5 @@ export * from './options';
9
9
  export * from './utils';
10
10
  export * as internal from './internal';
11
11
  export * from './errors';
12
- export { AttributeReference, Context, ContextFilter, CompositeDataSource, DataSourceErrorKind, Backoff, DefaultBackoff, LDPollingError, LDStreamingError, StreamingErrorHandler, LDFileDataSourceError, LDFlagDeliveryFallbackError, };
12
+ export { AttributeReference, Context, ContextFilter, CompositeDataSource, DataSourceErrorKind, Backoff, DefaultBackoff, LDPollingError, LDStreamingError, StreamingErrorHandler, LDFileDataSourceError, LDFlagDeliveryFallbackError, createAfterConsecutiveSuccesses, createAfterHealthyFor, createRetryState, forPolling, forStreaming, ResetPolicy, RetryState, RetryStateConfig, };
13
13
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,kBAAkB,MAAM,sBAAsB,CAAC;AACtD,OAAO,OAAO,MAAM,WAAW,CAAC;AAChC,OAAO,aAAa,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EACL,OAAO,EACP,mBAAmB,EACnB,mBAAmB,EACnB,cAAc,EACd,qBAAqB,EACrB,2BAA2B,EAC3B,cAAc,EACd,gBAAgB,EAChB,qBAAqB,EACtB,MAAM,cAAc,CAAC;AAEtB,cAAc,OAAO,CAAC;AACtB,cAAc,cAAc,CAAC;AAC7B,cAAc,WAAW,CAAC;AAC1B,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC;AAExB,OAAO,KAAK,QAAQ,MAAM,YAAY,CAAC;AACvC,cAAc,UAAU,CAAC;AAEzB,OAAO,EACL,kBAAkB,EAClB,OAAO,EACP,aAAa,EACb,mBAAmB,EACnB,mBAAmB,EACnB,OAAO,EACP,cAAc,EACd,cAAc,EACd,gBAAgB,EAChB,qBAAqB,EACrB,qBAAqB,EACrB,2BAA2B,GAC5B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,kBAAkB,MAAM,sBAAsB,CAAC;AACtD,OAAO,OAAO,MAAM,WAAW,CAAC;AAChC,OAAO,aAAa,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EACL,OAAO,EACP,mBAAmB,EACnB,+BAA+B,EAC/B,qBAAqB,EACrB,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,UAAU,EACV,YAAY,EACZ,qBAAqB,EACrB,2BAA2B,EAC3B,cAAc,EACd,gBAAgB,EAChB,WAAW,EACX,UAAU,EACV,gBAAgB,EAChB,qBAAqB,EACtB,MAAM,cAAc,CAAC;AAEtB,cAAc,OAAO,CAAC;AACtB,cAAc,cAAc,CAAC;AAC7B,cAAc,WAAW,CAAC;AAC1B,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC;AAExB,OAAO,KAAK,QAAQ,MAAM,YAAY,CAAC;AACvC,cAAc,UAAU,CAAC;AAEzB,OAAO,EACL,kBAAkB,EAClB,OAAO,EACP,aAAa,EACb,mBAAmB,EACnB,mBAAmB,EACnB,OAAO,EACP,cAAc,EACd,cAAc,EACd,gBAAgB,EAChB,qBAAqB,EACrB,qBAAqB,EACrB,2BAA2B,EAC3B,+BAA+B,EAC/B,qBAAqB,EACrB,gBAAgB,EAChB,UAAU,EACV,YAAY,EACZ,WAAW,EACX,UAAU,EACV,gBAAgB,GACjB,CAAC"}
@@ -1480,6 +1480,203 @@ var DataSourceErrorKind;
1480
1480
  DataSourceErrorKind["InvalidData"] = "INVALID_DATA";
1481
1481
  })(DataSourceErrorKind || (DataSourceErrorKind = {}));
1482
1482
 
1483
+ function defaultClock() {
1484
+ const perf = globalThis?.performance;
1485
+ if (perf && typeof perf.now === 'function') {
1486
+ return () => perf.now();
1487
+ }
1488
+ return () => Date.now();
1489
+ }
1490
+ /**
1491
+ * Creates a policy that resets once the component has operated without failing
1492
+ * for the given duration. Repeated healthy reports do not move the starting
1493
+ * point; only a failure clears it.
1494
+ *
1495
+ * @param healthyForMs How long the component must operate without failing,
1496
+ * in milliseconds; must be a positive, finite number.
1497
+ * @param clock The time source used to measure the healthy stretch; defaults
1498
+ * to a monotonic clock. Primarily for testing.
1499
+ */
1500
+ function createAfterHealthyFor(healthyForMs, clock = defaultClock()) {
1501
+ let healthySinceMs;
1502
+ return {
1503
+ noteHealthy() {
1504
+ if (healthySinceMs === undefined) {
1505
+ healthySinceMs = clock();
1506
+ }
1507
+ },
1508
+ noteFailure() {
1509
+ healthySinceMs = undefined;
1510
+ },
1511
+ isSatisfied() {
1512
+ return healthySinceMs !== undefined && clock() - healthySinceMs >= healthyForMs;
1513
+ },
1514
+ };
1515
+ }
1516
+ /**
1517
+ * Creates a policy that resets once the given number of operations in a row
1518
+ * have succeeded.
1519
+ *
1520
+ * @param count How many operations in a row must succeed; must be a positive
1521
+ * integer.
1522
+ */
1523
+ function createAfterConsecutiveSuccesses(count) {
1524
+ let successes = 0;
1525
+ return {
1526
+ noteHealthy() {
1527
+ successes += 1;
1528
+ },
1529
+ noteFailure() {
1530
+ successes = 0;
1531
+ },
1532
+ isSatisfied() {
1533
+ return successes >= count;
1534
+ },
1535
+ };
1536
+ }
1537
+
1538
+ // The delay bounds of the extended regime, in milliseconds. A component enters
1539
+ // the extended regime after an unexpected failure and leaves it when its reset
1540
+ // policy is satisfied.
1541
+ const EXTENDED_INITIAL_DELAY_MS = 5 * 60 * 1000;
1542
+ const EXTENDED_CEILING_MS = 60 * 60 * 1000;
1543
+ // The bounds, reset window, and default initial delay of streaming's normal regime.
1544
+ const STREAMING_NORMAL_CEILING_MS = 30 * 1000;
1545
+ const STREAMING_RESET_INTERVAL_MS = 60 * 1000;
1546
+ const DEFAULT_STREAMING_INITIAL_DELAY_MS = 1000;
1547
+ // Polling's reset condition and default cadence.
1548
+ const POLLING_RESET_SUCCESSES = 2;
1549
+ const DEFAULT_POLL_INTERVAL_MS = 30 * 1000;
1550
+ function positiveFiniteOrDefault(value, defaultValueMs, name, logger) {
1551
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
1552
+ return value;
1553
+ }
1554
+ logger?.warn(`${name} must be a positive, finite number of milliseconds; using the default of ${defaultValueMs}`);
1555
+ return defaultValueMs;
1556
+ }
1557
+ /**
1558
+ * Builds a retry state from explicit bounds. See {@link RetryStateConfig} for
1559
+ * the contract on the values.
1560
+ */
1561
+ function createRetryState(config) {
1562
+ const normalInitialDelayMs = config.normalInitialDelayMs;
1563
+ const normalCeilingMs = config.normalCeilingMs;
1564
+ const extendedInitialDelayMs = config.extendedInitialDelayMs;
1565
+ const extendedCeilingMs = config.extendedCeilingMs;
1566
+ const operatingCadenceMs = config.operatingCadenceMs ?? 0;
1567
+ const { resetPolicy } = config;
1568
+ const random = config.random ?? Math.random;
1569
+ let attempts = 0;
1570
+ let extended = false;
1571
+ let minDelayMs = normalInitialDelayMs;
1572
+ let maxDelayMs = normalCeilingMs;
1573
+ let serverDirectedBaseMs;
1574
+ // Before any outcome is recorded, the next wait is the ordinary interval.
1575
+ let nextDelayMs = operatingCadenceMs;
1576
+ function resetIfDue() {
1577
+ if (!resetPolicy.isSatisfied()) {
1578
+ return;
1579
+ }
1580
+ attempts = 0;
1581
+ extended = false;
1582
+ minDelayMs = normalInitialDelayMs;
1583
+ maxDelayMs = normalCeilingMs;
1584
+ }
1585
+ return {
1586
+ get nextDelay() {
1587
+ return nextDelayMs;
1588
+ },
1589
+ recordFailure(kind) {
1590
+ // A reset that fell due during healthy operation is applied before the
1591
+ // new failure is counted, so the failure computes from a fresh sequence.
1592
+ resetIfDue();
1593
+ resetPolicy.noteFailure();
1594
+ if (kind === 'unexpected' && !extended) {
1595
+ // Moving to the extended regime raises both bounds and starts the delay
1596
+ // sequence over. Only the move does this: a later unexpected failure
1597
+ // keeps counting up rather than re-pinning the initial delay.
1598
+ extended = true;
1599
+ minDelayMs = extendedInitialDelayMs;
1600
+ maxDelayMs = Math.max(extendedCeilingMs, extendedInitialDelayMs);
1601
+ attempts = 1;
1602
+ }
1603
+ else {
1604
+ attempts += 1;
1605
+ }
1606
+ const base = serverDirectedBaseMs ?? minDelayMs;
1607
+ // Compare against the ceiling scaled down rather than the base scaled up, so
1608
+ // the computed value can never overflow the ceiling. A base of zero doubles
1609
+ // to zero forever, so it short-circuits.
1610
+ let target = 0;
1611
+ if (base > 0) {
1612
+ const exponent = attempts - 1;
1613
+ target = base >= maxDelayMs / 2 ** exponent ? maxDelayMs : base * 2 ** exponent;
1614
+ }
1615
+ const jitter = (random() * target) / 2;
1616
+ nextDelayMs = Math.max(target - jitter, operatingCadenceMs);
1617
+ },
1618
+ recordSuccess() {
1619
+ resetPolicy.noteHealthy();
1620
+ resetIfDue();
1621
+ // A backoff wait applies to a retry, not to every operation, so after a
1622
+ // success the next wait is the ordinary interval even while the retry
1623
+ // state is raised.
1624
+ nextDelayMs = operatingCadenceMs;
1625
+ },
1626
+ applyServerDirectedRetry(delayMs) {
1627
+ if (typeof delayMs !== 'number' || !Number.isFinite(delayMs) || delayMs < 0) {
1628
+ return;
1629
+ }
1630
+ serverDirectedBaseMs = delayMs;
1631
+ attempts = 0;
1632
+ },
1633
+ };
1634
+ }
1635
+ /**
1636
+ * Builds the retry state for a streaming data source: no wait during healthy
1637
+ * operation, a normal regime running from the configured initial delay up to
1638
+ * a 30 second ceiling, an extended regime of 5 minutes up to 1 hour, and a
1639
+ * reset once a connection has been healthy for 60 seconds.
1640
+ *
1641
+ * The initial delay is validated here; the documented default of 1 second
1642
+ * stands in for anything that is not a positive, finite number. A configured
1643
+ * delay above the normal ceiling is clamped to it, while the extended regime
1644
+ * never starts below the configured delay.
1645
+ */
1646
+ function forStreaming(initialReconnectDelayMs, logger) {
1647
+ const validated = positiveFiniteOrDefault(initialReconnectDelayMs, DEFAULT_STREAMING_INITIAL_DELAY_MS, 'initialReconnectDelayMs', logger);
1648
+ return createRetryState({
1649
+ normalInitialDelayMs: validated,
1650
+ normalCeilingMs: STREAMING_NORMAL_CEILING_MS,
1651
+ extendedInitialDelayMs: Math.max(EXTENDED_INITIAL_DELAY_MS, validated),
1652
+ extendedCeilingMs: EXTENDED_CEILING_MS,
1653
+ resetPolicy: createAfterHealthyFor(STREAMING_RESET_INTERVAL_MS),
1654
+ operatingCadenceMs: 0,
1655
+ });
1656
+ }
1657
+ /**
1658
+ * Builds the retry state for a polling data source: the poll interval is the
1659
+ * operating cadence, so no wait is ever shorter than it; in the normal regime
1660
+ * both bounds are the interval itself, so a normal failure simply polls again
1661
+ * on schedule; the extended regime runs from 5 minutes (or the interval, if
1662
+ * longer) up to 1 hour (or the interval, if longer); and the state resets
1663
+ * after two successful polls in a row.
1664
+ *
1665
+ * The poll interval is validated here; the documented default of 30 seconds
1666
+ * stands in for anything that is not a positive, finite number.
1667
+ */
1668
+ function forPolling(pollIntervalMs, logger) {
1669
+ const validated = positiveFiniteOrDefault(pollIntervalMs, DEFAULT_POLL_INTERVAL_MS, 'pollIntervalMs', logger);
1670
+ return createRetryState({
1671
+ normalInitialDelayMs: validated,
1672
+ normalCeilingMs: validated,
1673
+ extendedInitialDelayMs: Math.max(EXTENDED_INITIAL_DELAY_MS, validated),
1674
+ extendedCeilingMs: EXTENDED_CEILING_MS,
1675
+ resetPolicy: createAfterConsecutiveSuccesses(POLLING_RESET_SUCCESSES),
1676
+ operatingCadenceMs: validated,
1677
+ });
1678
+ }
1679
+
1483
1680
  /**
1484
1681
  * Enable / disable Auto environment attributes. When enabled, the SDK will automatically
1485
1682
  * provide data about the mobile environment where the application is running. This data makes it simpler to target
@@ -1645,6 +1842,11 @@ function format(...args) {
1645
1842
  }
1646
1843
  i += 2;
1647
1844
  }
1845
+ else {
1846
+ // A trailing '%' has nothing to escape, so keep it as-is.
1847
+ out += '%';
1848
+ i += 1;
1849
+ }
1648
1850
  }
1649
1851
  else {
1650
1852
  out += char;
@@ -2029,17 +2231,46 @@ class LDTimeoutError extends Error {
2029
2231
  this.name = 'LaunchDarklyTimeoutError';
2030
2232
  }
2031
2233
  }
2234
+ // HTTP statuses in the 4xx range that are still normal failures. Every other
2235
+ // 4xx is unexpected.
2236
+ const NORMAL_4XX_STATUSES = [400, 408, 429];
2237
+ /**
2238
+ * Classifies an HTTP status.
2239
+ *
2240
+ * 400, 408, and 429 are normal, as is any 5xx. Every other 4xx, including 401
2241
+ * and 403, is unexpected. Anything outside the error ranges, including 0 for
2242
+ * "no response", is normal.
2243
+ */
2244
+ function classifyHttpStatus(status) {
2245
+ if (status >= 400 && status < 500 && !NORMAL_4XX_STATUSES.includes(status)) {
2246
+ return 'unexpected';
2247
+ }
2248
+ return 'normal';
2249
+ }
2250
+ /**
2251
+ * Classifies a transport-level failure (connection refused or dropped, DNS
2252
+ * failure, timeout, TLS negotiation failure).
2253
+ *
2254
+ * Always normal: in an all-HTTPS system every transport error surfaces through
2255
+ * the TLS layer, so a certificate misconfiguration cannot be reliably
2256
+ * distinguished from a transient network fault, and treating transient faults
2257
+ * as unexpected would hold ordinary recoveries to multi-minute waits.
2258
+ */
2259
+ function classifyTransportFailure() {
2260
+ return 'normal';
2261
+ }
2032
2262
  /**
2033
2263
  * Check if the HTTP error is recoverable. This will return false if a request
2034
2264
  * made with any payload could not recover. If the reason for the failure
2035
2265
  * is payload specific, for instance a payload that is too large, then
2036
2266
  * it could recover with a different payload.
2267
+ *
2268
+ * Superseded by {@link classifyHttpStatus}, which this delegates to. It is
2269
+ * retained for the event-delivery pathway and is expected to be deprecated
2270
+ * once that pathway migrates to failure classification.
2037
2271
  */
2038
2272
  function isHttpRecoverable(status) {
2039
- if (status >= 400 && status < 500) {
2040
- return status === 400 || status === 408 || status === 429;
2041
- }
2042
- return true;
2273
+ return classifyHttpStatus(status) === 'normal';
2043
2274
  }
2044
2275
  /**
2045
2276
  * Returns true if the status could recover for a different payload.
@@ -3400,7 +3631,10 @@ class PayloadStreamReader {
3400
3631
  this._errorHandler?.(DataSourceErrorKind.InvalidData, 'Malformed data in EventStream.');
3401
3632
  }
3402
3633
  }
3403
- else {
3634
+ else if (eventName !== 'error') {
3635
+ // Missing data is a protocol violation for every type except 'error': a connection
3636
+ // failure also dispatches under 'error', without data, and the transport owner handles
3637
+ // it. Only a server-sent error frame carries data.
3404
3638
  this._errorHandler?.(DataSourceErrorKind.Unknown, 'Event from EventStream missing data.');
3405
3639
  }
3406
3640
  });
@@ -3494,5 +3728,5 @@ var index = /*#__PURE__*/Object.freeze({
3494
3728
  shouldSample: shouldSample
3495
3729
  });
3496
3730
 
3497
- export { ApplicationTags, AttributeReference, AutoEnvAttributes, BasicLogger, ClientContext, CompositeDataSource, Context, ContextFilter, DataSourceErrorKind, DateValidator, DefaultBackoff, FactoryOrInstance, Function, KindValidator, LDClientError, LDFileDataSourceError, LDFlagDeliveryFallbackError, LDPollingError, LDStreamingError, LDTimeoutError, LDUnexpectedResponseError, NullableBoolean, NumberWithMinimum, OneOf, OptionMessages, SafeLogger, ServiceEndpoints, StringMatchingRegex, Type, TypeArray, TypeValidators, base64UrlEncode, cancelableTimedPromise, clone, createSafeLogger, debounce, deepCompact, defaultHeaders, fastDeepEqual, getEventsUri, getPollingUri, getStreamingUri, httpErrorMessage, index as internal, isHttpLocallyRecoverable, isHttpRecoverable, isNullish, noop, secondsToMillis, shouldRetry, sleep, index$1 as subsystem, timedPromise };
3731
+ export { ApplicationTags, AttributeReference, AutoEnvAttributes, BasicLogger, ClientContext, CompositeDataSource, Context, ContextFilter, DataSourceErrorKind, DateValidator, DefaultBackoff, FactoryOrInstance, Function, KindValidator, LDClientError, LDFileDataSourceError, LDFlagDeliveryFallbackError, LDPollingError, LDStreamingError, LDTimeoutError, LDUnexpectedResponseError, NullableBoolean, NumberWithMinimum, OneOf, OptionMessages, SafeLogger, ServiceEndpoints, StringMatchingRegex, Type, TypeArray, TypeValidators, base64UrlEncode, cancelableTimedPromise, classifyHttpStatus, classifyTransportFailure, clone, createAfterConsecutiveSuccesses, createAfterHealthyFor, createRetryState, createSafeLogger, debounce, deepCompact, defaultHeaders, fastDeepEqual, forPolling, forStreaming, getEventsUri, getPollingUri, getStreamingUri, httpErrorMessage, index as internal, isHttpLocallyRecoverable, isHttpRecoverable, isNullish, noop, secondsToMillis, shouldRetry, sleep, index$1 as subsystem, timedPromise };
3498
3732
  //# sourceMappingURL=index.mjs.map