@launchdarkly/js-sdk-common 2.28.1 → 2.30.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 +14 -0
- package/dist/cjs/api/platform/Requests.d.ts +85 -0
- package/dist/cjs/api/platform/Requests.d.ts.map +1 -1
- package/dist/cjs/datasource/retry/ResetPolicy.d.ts.map +1 -1
- package/dist/cjs/index.cjs +1074 -924
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/internal/fetch/StreamingResponse.d.ts +83 -0
- package/dist/cjs/internal/fetch/StreamingResponse.d.ts.map +1 -0
- package/dist/cjs/internal/fetch/index.d.ts +3 -0
- package/dist/cjs/internal/fetch/index.d.ts.map +1 -0
- package/dist/cjs/internal/fetch/toRequestInit.d.ts +12 -0
- package/dist/cjs/internal/fetch/toRequestInit.d.ts.map +1 -0
- package/dist/cjs/internal/index.d.ts +1 -0
- package/dist/cjs/internal/index.d.ts.map +1 -1
- package/dist/cjs/utils/index.d.ts +2 -1
- package/dist/cjs/utils/index.d.ts.map +1 -1
- package/dist/cjs/utils/time.d.ts +16 -0
- package/dist/cjs/utils/time.d.ts.map +1 -0
- package/dist/esm/api/platform/Requests.d.ts +85 -0
- package/dist/esm/api/platform/Requests.d.ts.map +1 -1
- package/dist/esm/datasource/retry/ResetPolicy.d.ts.map +1 -1
- package/dist/esm/index.mjs +1074 -925
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/internal/fetch/StreamingResponse.d.ts +83 -0
- package/dist/esm/internal/fetch/StreamingResponse.d.ts.map +1 -0
- package/dist/esm/internal/fetch/index.d.ts +3 -0
- package/dist/esm/internal/fetch/index.d.ts.map +1 -0
- package/dist/esm/internal/fetch/toRequestInit.d.ts +12 -0
- package/dist/esm/internal/fetch/toRequestInit.d.ts.map +1 -0
- package/dist/esm/internal/index.d.ts +1 -0
- package/dist/esm/internal/index.d.ts.map +1 -1
- package/dist/esm/utils/index.d.ts +2 -1
- package/dist/esm/utils/index.d.ts.map +1 -1
- package/dist/esm/utils/time.d.ts +16 -0
- package/dist/esm/utils/time.d.ts.map +1 -0
- package/package.json +1 -1
package/dist/esm/index.mjs
CHANGED
|
@@ -1480,1059 +1480,1076 @@ var DataSourceErrorKind;
|
|
|
1480
1480
|
DataSourceErrorKind["InvalidData"] = "INVALID_DATA";
|
|
1481
1481
|
})(DataSourceErrorKind || (DataSourceErrorKind = {}));
|
|
1482
1482
|
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1483
|
+
// These classes are of trivial complexity. If they become
|
|
1484
|
+
// more complex, then they could be independent files.
|
|
1485
|
+
class LDUnexpectedResponseError extends Error {
|
|
1486
|
+
constructor(message) {
|
|
1487
|
+
super(message);
|
|
1488
|
+
this.name = 'LaunchDarklyUnexpectedResponseError';
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
class LDClientError extends Error {
|
|
1492
|
+
constructor(message) {
|
|
1493
|
+
super(message);
|
|
1494
|
+
this.name = 'LaunchDarklyClientError';
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
class LDTimeoutError extends Error {
|
|
1498
|
+
constructor(message) {
|
|
1499
|
+
super(message);
|
|
1500
|
+
this.name = 'LaunchDarklyTimeoutError';
|
|
1487
1501
|
}
|
|
1488
|
-
return () => Date.now();
|
|
1489
1502
|
}
|
|
1503
|
+
// HTTP statuses in the 4xx range that are still normal failures. Every other
|
|
1504
|
+
// 4xx is unexpected.
|
|
1505
|
+
const NORMAL_4XX_STATUSES = [400, 408, 429];
|
|
1490
1506
|
/**
|
|
1491
|
-
*
|
|
1492
|
-
* for the given duration. Repeated healthy reports do not move the starting
|
|
1493
|
-
* point; only a failure clears it.
|
|
1507
|
+
* Classifies an HTTP status.
|
|
1494
1508
|
*
|
|
1495
|
-
*
|
|
1496
|
-
*
|
|
1497
|
-
*
|
|
1498
|
-
* to a monotonic clock. Primarily for testing.
|
|
1509
|
+
* 400, 408, and 429 are normal, as is any 5xx. Every other 4xx, including 401
|
|
1510
|
+
* and 403, is unexpected. Anything outside the error ranges, including 0 for
|
|
1511
|
+
* "no response", is normal.
|
|
1499
1512
|
*/
|
|
1500
|
-
function
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
healthySinceMs = clock();
|
|
1506
|
-
}
|
|
1507
|
-
},
|
|
1508
|
-
noteFailure() {
|
|
1509
|
-
healthySinceMs = undefined;
|
|
1510
|
-
},
|
|
1511
|
-
isSatisfied() {
|
|
1512
|
-
return healthySinceMs !== undefined && clock() - healthySinceMs >= healthyForMs;
|
|
1513
|
-
},
|
|
1514
|
-
};
|
|
1513
|
+
function classifyHttpStatus(status) {
|
|
1514
|
+
if (status >= 400 && status < 500 && !NORMAL_4XX_STATUSES.includes(status)) {
|
|
1515
|
+
return 'unexpected';
|
|
1516
|
+
}
|
|
1517
|
+
return 'normal';
|
|
1515
1518
|
}
|
|
1516
1519
|
/**
|
|
1517
|
-
*
|
|
1518
|
-
*
|
|
1520
|
+
* Classifies a transport-level failure (connection refused or dropped, DNS
|
|
1521
|
+
* failure, timeout, TLS negotiation failure).
|
|
1519
1522
|
*
|
|
1520
|
-
*
|
|
1521
|
-
*
|
|
1523
|
+
* Always normal: in an all-HTTPS system every transport error surfaces through
|
|
1524
|
+
* the TLS layer, so a certificate misconfiguration cannot be reliably
|
|
1525
|
+
* distinguished from a transient network fault, and treating transient faults
|
|
1526
|
+
* as unexpected would hold ordinary recoveries to multi-minute waits.
|
|
1522
1527
|
*/
|
|
1523
|
-
function
|
|
1524
|
-
|
|
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;
|
|
1528
|
+
function classifyTransportFailure() {
|
|
1529
|
+
return 'normal';
|
|
1556
1530
|
}
|
|
1557
1531
|
/**
|
|
1558
|
-
*
|
|
1559
|
-
* the
|
|
1532
|
+
* Check if the HTTP error is recoverable. This will return false if a request
|
|
1533
|
+
* made with any payload could not recover. If the reason for the failure
|
|
1534
|
+
* is payload specific, for instance a payload that is too large, then
|
|
1535
|
+
* it could recover with a different payload.
|
|
1536
|
+
*
|
|
1537
|
+
* Superseded by {@link classifyHttpStatus}, which this delegates to. It is
|
|
1538
|
+
* retained for the event-delivery pathway and is expected to be deprecated
|
|
1539
|
+
* once that pathway migrates to failure classification.
|
|
1560
1540
|
*/
|
|
1561
|
-
function
|
|
1562
|
-
|
|
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
|
-
};
|
|
1541
|
+
function isHttpRecoverable(status) {
|
|
1542
|
+
return classifyHttpStatus(status) === 'normal';
|
|
1634
1543
|
}
|
|
1635
1544
|
/**
|
|
1636
|
-
*
|
|
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.
|
|
1545
|
+
* Returns true if the status could recover for a different payload.
|
|
1640
1546
|
*
|
|
1641
|
-
*
|
|
1642
|
-
*
|
|
1643
|
-
*
|
|
1644
|
-
* never starts below the configured delay.
|
|
1547
|
+
* When used with event processing this indicates that we should discard
|
|
1548
|
+
* the payload, but that a subsequent payload may succeed. Therefore we should
|
|
1549
|
+
* not stop event processing.
|
|
1645
1550
|
*/
|
|
1646
|
-
function
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
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
|
-
});
|
|
1551
|
+
function isHttpLocallyRecoverable(status) {
|
|
1552
|
+
if (status === 413) {
|
|
1553
|
+
return true;
|
|
1554
|
+
}
|
|
1555
|
+
return isHttpRecoverable(status);
|
|
1656
1556
|
}
|
|
1557
|
+
|
|
1657
1558
|
/**
|
|
1658
|
-
*
|
|
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.
|
|
1559
|
+
* Returns a promise which errors after t seconds.
|
|
1664
1560
|
*
|
|
1665
|
-
*
|
|
1666
|
-
*
|
|
1561
|
+
* @param t Timeout in seconds.
|
|
1562
|
+
* @param taskName Name of task being timed for logging and error reporting.
|
|
1667
1563
|
*/
|
|
1668
|
-
function
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1564
|
+
function cancelableTimedPromise(t, taskName) {
|
|
1565
|
+
let timeout;
|
|
1566
|
+
let resolve;
|
|
1567
|
+
const promise = new Promise((_res, reject) => {
|
|
1568
|
+
resolve = _res;
|
|
1569
|
+
timeout = setTimeout(() => {
|
|
1570
|
+
const e = `${taskName} timed out after ${t} seconds.`;
|
|
1571
|
+
reject(new LDTimeoutError(e));
|
|
1572
|
+
}, t * 1000);
|
|
1677
1573
|
});
|
|
1574
|
+
return {
|
|
1575
|
+
promise,
|
|
1576
|
+
cancel: () => {
|
|
1577
|
+
resolve();
|
|
1578
|
+
clearTimeout(timeout);
|
|
1579
|
+
},
|
|
1580
|
+
};
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
function clone(obj) {
|
|
1584
|
+
if (obj === undefined || obj === null) {
|
|
1585
|
+
return obj;
|
|
1586
|
+
}
|
|
1587
|
+
return JSON.parse(JSON.stringify(obj));
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
function secondsToMillis(sec) {
|
|
1591
|
+
return Math.trunc(sec * 1000);
|
|
1678
1592
|
}
|
|
1679
1593
|
|
|
1680
1594
|
/**
|
|
1681
|
-
*
|
|
1682
|
-
*
|
|
1683
|
-
*
|
|
1684
|
-
*
|
|
1685
|
-
*
|
|
1686
|
-
*
|
|
1595
|
+
* Wait before calling the same function. Useful for expensive calls.
|
|
1596
|
+
* Adapted from https://amitd.co/code/typescript/debounce.
|
|
1597
|
+
*
|
|
1598
|
+
* @return The debounced function.
|
|
1599
|
+
*
|
|
1600
|
+
* @example
|
|
1601
|
+
*
|
|
1602
|
+
* ```js
|
|
1603
|
+
* const debouncedFunction = debounce(e => {
|
|
1604
|
+
* console.log(e);
|
|
1605
|
+
* }, 5000);
|
|
1606
|
+
*
|
|
1607
|
+
* // Console logs 'Hello world again ' after 5 seconds
|
|
1608
|
+
* debouncedFunction('Hello world');
|
|
1609
|
+
* debouncedFunction('Hello world again');
|
|
1610
|
+
* ```
|
|
1611
|
+
* @param fn The function to be debounced.
|
|
1612
|
+
* @param delayMs Defaults to 5 seconds.
|
|
1687
1613
|
*/
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
LDEventType[LDEventType["DiagnosticEvent"] = 1] = "DiagnosticEvent";
|
|
1698
|
-
})(LDEventType || (LDEventType = {}));
|
|
1699
|
-
var LDDeliveryStatus;
|
|
1700
|
-
(function (LDDeliveryStatus) {
|
|
1701
|
-
LDDeliveryStatus[LDDeliveryStatus["Succeeded"] = 0] = "Succeeded";
|
|
1702
|
-
LDDeliveryStatus[LDDeliveryStatus["Failed"] = 1] = "Failed";
|
|
1703
|
-
LDDeliveryStatus[LDDeliveryStatus["FailedAndMustShutDown"] = 2] = "FailedAndMustShutDown";
|
|
1704
|
-
})(LDDeliveryStatus || (LDDeliveryStatus = {}));
|
|
1614
|
+
const debounce = (fn, delayMs = 5000) => {
|
|
1615
|
+
let timer;
|
|
1616
|
+
return (...args) => {
|
|
1617
|
+
clearTimeout(timer);
|
|
1618
|
+
timer = setTimeout(() => {
|
|
1619
|
+
fn(...args);
|
|
1620
|
+
}, delayMs);
|
|
1621
|
+
};
|
|
1622
|
+
};
|
|
1705
1623
|
|
|
1706
|
-
|
|
1707
|
-
__proto__: null,
|
|
1708
|
-
get DataSourceState () { return DataSourceState; },
|
|
1709
|
-
get LDDeliveryStatus () { return LDDeliveryStatus; },
|
|
1710
|
-
get LDEventType () { return LDEventType; }
|
|
1711
|
-
});
|
|
1624
|
+
const isEmptyObject = (obj) => JSON.stringify(obj) === '{}';
|
|
1712
1625
|
|
|
1713
1626
|
/**
|
|
1714
|
-
*
|
|
1715
|
-
*
|
|
1716
|
-
*
|
|
1717
|
-
*
|
|
1718
|
-
* @param
|
|
1719
|
-
* @
|
|
1627
|
+
* Strips all falsy and empty {} from a given object. Returns a new object with only truthy values.
|
|
1628
|
+
* Sourced from below but modified to include checks for empty object and ignoring keys.
|
|
1629
|
+
* https://www.w3resource.com/javascript-exercises/javascript-array-exercise-47.php
|
|
1630
|
+
*
|
|
1631
|
+
* @param obj
|
|
1632
|
+
* @param ignoreKeys
|
|
1720
1633
|
*/
|
|
1721
|
-
|
|
1722
|
-
if (
|
|
1723
|
-
return
|
|
1724
|
-
}
|
|
1725
|
-
if (val === undefined) {
|
|
1726
|
-
return 'undefined';
|
|
1727
|
-
}
|
|
1728
|
-
if (val === null) {
|
|
1729
|
-
return 'null';
|
|
1634
|
+
const deepCompact = (obj, ignoreKeys) => {
|
|
1635
|
+
if (!obj) {
|
|
1636
|
+
return obj;
|
|
1730
1637
|
}
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1638
|
+
return Object.entries(obj).reduce((acc, [key, value]) => {
|
|
1639
|
+
if (Boolean(value) && !isEmptyObject(value) && !ignoreKeys?.includes(key)) {
|
|
1640
|
+
acc[key] = typeof value === 'object' ? deepCompact(value, ignoreKeys) : value;
|
|
1734
1641
|
}
|
|
1735
|
-
|
|
1736
|
-
|
|
1642
|
+
return acc;
|
|
1643
|
+
}, {});
|
|
1644
|
+
};
|
|
1645
|
+
|
|
1646
|
+
/* eslint-disable */
|
|
1647
|
+
// Ripped from https://github.com/epoberezkin/fast-deep-fastDeepEqual
|
|
1648
|
+
// {{? it.es6 }}
|
|
1649
|
+
// var envHasBigInt64Array = typeof BigInt64Array !== 'undefined';
|
|
1650
|
+
// {{?}}
|
|
1651
|
+
function fastDeepEqual(a, b) {
|
|
1652
|
+
if (a === b)
|
|
1653
|
+
return true;
|
|
1654
|
+
if (a && b && typeof a == 'object' && typeof b == 'object') {
|
|
1655
|
+
if (a.constructor !== b.constructor)
|
|
1656
|
+
return false;
|
|
1657
|
+
var length, i, keys;
|
|
1658
|
+
if (Array.isArray(a)) {
|
|
1659
|
+
length = a.length;
|
|
1660
|
+
if (length != b.length)
|
|
1661
|
+
return false;
|
|
1662
|
+
for (i = length; i-- !== 0;)
|
|
1663
|
+
if (!fastDeepEqual(a[i], b[i]))
|
|
1664
|
+
return false;
|
|
1665
|
+
return true;
|
|
1737
1666
|
}
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1667
|
+
// {{? it.es6 }}
|
|
1668
|
+
if (a instanceof Map && b instanceof Map) {
|
|
1669
|
+
if (a.size !== b.size)
|
|
1670
|
+
return false;
|
|
1671
|
+
for (i of a.entries())
|
|
1672
|
+
if (!b.has(i[0]))
|
|
1673
|
+
return false;
|
|
1674
|
+
for (i of a.entries())
|
|
1675
|
+
if (!fastDeepEqual(i[1], b.get(i[0])))
|
|
1676
|
+
return false;
|
|
1677
|
+
return true;
|
|
1748
1678
|
}
|
|
1749
|
-
|
|
1679
|
+
if (a instanceof Set && b instanceof Set) {
|
|
1680
|
+
if (a.size !== b.size)
|
|
1681
|
+
return false;
|
|
1682
|
+
for (i of a.entries())
|
|
1683
|
+
if (!b.has(i[0]))
|
|
1684
|
+
return false;
|
|
1685
|
+
return true;
|
|
1686
|
+
}
|
|
1687
|
+
if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
|
|
1688
|
+
// @ts-ignore
|
|
1689
|
+
length = a.length;
|
|
1690
|
+
// @ts-ignore
|
|
1691
|
+
if (length != b.length)
|
|
1692
|
+
return false;
|
|
1693
|
+
for (i = length; i-- !== 0;) {
|
|
1694
|
+
// @ts-ignore
|
|
1695
|
+
if (a[i] !== b[i])
|
|
1696
|
+
return false;
|
|
1697
|
+
}
|
|
1698
|
+
return true;
|
|
1699
|
+
}
|
|
1700
|
+
// {{?}}
|
|
1701
|
+
if (a.constructor === RegExp)
|
|
1702
|
+
return a.source === b.source && a.flags === b.flags;
|
|
1703
|
+
if (a.valueOf !== Object.prototype.valueOf)
|
|
1704
|
+
return a.valueOf() === b.valueOf();
|
|
1705
|
+
if (a.toString !== Object.prototype.toString)
|
|
1706
|
+
return a.toString() === b.toString();
|
|
1707
|
+
keys = Object.keys(a);
|
|
1708
|
+
length = keys.length;
|
|
1709
|
+
if (length !== Object.keys(b).length)
|
|
1710
|
+
return false;
|
|
1711
|
+
for (i = length; i-- !== 0;)
|
|
1712
|
+
if (!Object.prototype.hasOwnProperty.call(b, keys[i]))
|
|
1713
|
+
return false;
|
|
1714
|
+
for (i = length; i-- !== 0;) {
|
|
1715
|
+
var key = keys[i];
|
|
1716
|
+
// {{? it.react }}
|
|
1717
|
+
// if (key === '_owner' && a.$$typeof) {
|
|
1718
|
+
// // React-specific: avoid traversing React elements' _owner.
|
|
1719
|
+
// // _owner contains circular references
|
|
1720
|
+
// // and is not needed when comparing the actual elements (and not their owners)
|
|
1721
|
+
// continue;
|
|
1722
|
+
// }
|
|
1723
|
+
// {{?}}
|
|
1724
|
+
if (!fastDeepEqual(a[key], b[key]))
|
|
1725
|
+
return false;
|
|
1726
|
+
}
|
|
1727
|
+
return true;
|
|
1750
1728
|
}
|
|
1729
|
+
// true if both NaN, false otherwise
|
|
1730
|
+
return a !== a && b !== b;
|
|
1751
1731
|
}
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
//
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
return 'NaN';
|
|
1732
|
+
|
|
1733
|
+
function defaultHeaders(sdkKey, info, tags, includeAuthorizationHeader = true, userAgentHeaderName = 'user-agent', instanceId) {
|
|
1734
|
+
const { userAgentBase, version, wrapperName, wrapperVersion } = info.sdkData();
|
|
1735
|
+
const headers = {
|
|
1736
|
+
[userAgentHeaderName]: `${userAgentBase ?? 'NodeJSClient'}/${version}`,
|
|
1737
|
+
};
|
|
1738
|
+
// edge sdks sets this to false because they use the clientSideID
|
|
1739
|
+
// and they don't need the authorization header
|
|
1740
|
+
if (includeAuthorizationHeader) {
|
|
1741
|
+
headers.authorization = sdkKey;
|
|
1763
1742
|
}
|
|
1764
|
-
if (
|
|
1765
|
-
|
|
1743
|
+
if (wrapperName) {
|
|
1744
|
+
headers['x-launchdarkly-wrapper'] = wrapperVersion
|
|
1745
|
+
? `${wrapperName}/${wrapperVersion}`
|
|
1746
|
+
: wrapperName;
|
|
1766
1747
|
}
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
/**
|
|
1770
|
-
* Attempt to produce an integer representation.
|
|
1771
|
-
* BigInts have an `n` suffix.
|
|
1772
|
-
* @param val
|
|
1773
|
-
* @returns The integer representation or 'NaN' if not numeric.
|
|
1774
|
-
*/
|
|
1775
|
-
function toInt(val) {
|
|
1776
|
-
if (typeof val === 'symbol') {
|
|
1777
|
-
return 'NaN';
|
|
1748
|
+
if (tags?.value) {
|
|
1749
|
+
headers['x-launchdarkly-tags'] = tags.value;
|
|
1778
1750
|
}
|
|
1779
|
-
|
|
1780
|
-
|
|
1751
|
+
// Per SCMP-server-connection-minutes-polling (spec section 1.1), server SDKs include a
|
|
1752
|
+
// per-instance v4 GUID on every polling request. The caller (a server SDK) is responsible
|
|
1753
|
+
// for generating the GUID once per SDK instance and passing it here, so that it rides on
|
|
1754
|
+
// every outbound request via this shared default-headers map. Client/edge SDKs do not pass
|
|
1755
|
+
// this value, so the header is omitted for them.
|
|
1756
|
+
if (instanceId) {
|
|
1757
|
+
headers['x-launchdarkly-instance-id'] = instanceId;
|
|
1781
1758
|
}
|
|
1782
|
-
return
|
|
1759
|
+
return headers;
|
|
1783
1760
|
}
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
* @returns The integer representation or 'NaN' if not numeric.
|
|
1789
|
-
*/
|
|
1790
|
-
function toFloat(val) {
|
|
1791
|
-
if (typeof val === 'symbol') {
|
|
1792
|
-
return 'NaN';
|
|
1761
|
+
function httpErrorMessage(err, context, retryMessage) {
|
|
1762
|
+
let desc;
|
|
1763
|
+
if (err.status) {
|
|
1764
|
+
desc = `error ${err.status}${err.status === 401 ? ' (invalid SDK key)' : ''}`;
|
|
1793
1765
|
}
|
|
1794
|
-
|
|
1766
|
+
else {
|
|
1767
|
+
desc = `I/O error (${err.message || 'unknown error'})`;
|
|
1768
|
+
}
|
|
1769
|
+
const action = retryMessage ?? 'giving up permanently';
|
|
1770
|
+
return `Received ${desc} for ${context} - ${action}`;
|
|
1771
|
+
}
|
|
1772
|
+
function shouldRetry({ status }) {
|
|
1773
|
+
return status ? isHttpRecoverable(status) : true;
|
|
1795
1774
|
}
|
|
1796
|
-
// Based on:
|
|
1797
|
-
// https://nodejs.org/api/util.html#utilformatformat-args
|
|
1798
|
-
// The result will not match node exactly, but it should get the
|
|
1799
|
-
// right information through.
|
|
1800
|
-
const escapes = {
|
|
1801
|
-
s: (val) => tryStringify(val),
|
|
1802
|
-
d: (val) => toNumber(val),
|
|
1803
|
-
i: (val) => toInt(val),
|
|
1804
|
-
f: (val) => toFloat(val),
|
|
1805
|
-
j: (val) => tryStringify(val),
|
|
1806
|
-
o: (val) => tryStringify(val),
|
|
1807
|
-
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
1808
|
-
O: (val) => tryStringify(val),
|
|
1809
|
-
c: () => '',
|
|
1810
|
-
};
|
|
1811
1775
|
/**
|
|
1812
|
-
*
|
|
1813
|
-
*
|
|
1814
|
-
*
|
|
1776
|
+
* In react-native use base64-js to polyfill btoa. This is safe
|
|
1777
|
+
* because the react-native repo uses it too. Set the global.btoa to the encode
|
|
1778
|
+
* function of base64-js.
|
|
1779
|
+
* https://github.com/beatgammit/base64-js
|
|
1780
|
+
* https://github.com/axios/axios/issues/2235#issuecomment-512204616
|
|
1815
1781
|
*
|
|
1816
|
-
*
|
|
1782
|
+
* Ripped from https://thewoods.blog/base64url/
|
|
1783
|
+
*/
|
|
1784
|
+
const base64UrlEncode = (s, encoding) => encoding.btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
1785
|
+
|
|
1786
|
+
var noop = () => { };
|
|
1787
|
+
|
|
1788
|
+
const sleep = async (delayMillis = 1000) => new Promise((resolve) => {
|
|
1789
|
+
setTimeout(resolve, delayMillis);
|
|
1790
|
+
});
|
|
1791
|
+
|
|
1792
|
+
let useWallClock;
|
|
1793
|
+
/**
|
|
1794
|
+
* Milliseconds from a monotonic clock when the runtime provides one.
|
|
1817
1795
|
*
|
|
1818
|
-
*
|
|
1819
|
-
*
|
|
1796
|
+
* Deadlines and embargoes compare differences of these values. A wall clock can
|
|
1797
|
+
* step backward, for example through an NTP correction, and a deadline armed
|
|
1798
|
+
* against it would then never pass. Values from this function are not epoch
|
|
1799
|
+
* times and must only be compared with each other.
|
|
1800
|
+
*
|
|
1801
|
+
* The time source is selected on the first call and never changes after that.
|
|
1802
|
+
* Monotonic values and wall-clock values have different origins, so a switch
|
|
1803
|
+
* between sources would corrupt in-flight measurements. A runtime without a
|
|
1804
|
+
* performance global at the first call uses the wall clock from then on, even
|
|
1805
|
+
* if a polyfill appears later.
|
|
1820
1806
|
*/
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
if (
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
let i = 0;
|
|
1827
|
-
while (i < formatString.length) {
|
|
1828
|
-
const char = formatString.charAt(i);
|
|
1829
|
-
if (char === '%') {
|
|
1830
|
-
const nextIndex = i + 1;
|
|
1831
|
-
if (nextIndex < formatString.length) {
|
|
1832
|
-
const nextChar = formatString.charAt(i + 1);
|
|
1833
|
-
if (nextChar in escapes && args.length) {
|
|
1834
|
-
const value = args.shift();
|
|
1835
|
-
// This rule is for math.
|
|
1836
|
-
out += escapes[nextChar]?.(value);
|
|
1837
|
-
}
|
|
1838
|
-
else if (nextChar === '%') {
|
|
1839
|
-
out += '%';
|
|
1840
|
-
}
|
|
1841
|
-
else {
|
|
1842
|
-
out += `%${nextChar}`;
|
|
1843
|
-
}
|
|
1844
|
-
i += 2;
|
|
1845
|
-
}
|
|
1846
|
-
else {
|
|
1847
|
-
// A trailing '%' has nothing to escape, so keep it as-is.
|
|
1848
|
-
out += '%';
|
|
1849
|
-
i += 1;
|
|
1850
|
-
}
|
|
1851
|
-
}
|
|
1852
|
-
else {
|
|
1853
|
-
out += char;
|
|
1854
|
-
i += 1;
|
|
1855
|
-
}
|
|
1856
|
-
}
|
|
1857
|
-
// If there are any args left after we exhaust the format string
|
|
1858
|
-
// then just stick those on the end.
|
|
1859
|
-
if (args.length) {
|
|
1860
|
-
if (out.length) {
|
|
1861
|
-
out += ' ';
|
|
1862
|
-
}
|
|
1863
|
-
out += args.map(tryStringify).join(' ');
|
|
1864
|
-
}
|
|
1865
|
-
return out;
|
|
1807
|
+
// eslint-disable-next-line import/prefer-default-export
|
|
1808
|
+
function monotonicNow() {
|
|
1809
|
+
if (useWallClock === undefined) {
|
|
1810
|
+
const perf = globalThis?.performance;
|
|
1811
|
+
useWallClock = !(perf && typeof perf.now === 'function');
|
|
1866
1812
|
}
|
|
1867
|
-
return
|
|
1813
|
+
return useWallClock ? Date.now() : globalThis.performance.now();
|
|
1868
1814
|
}
|
|
1869
1815
|
|
|
1870
|
-
var LogPriority;
|
|
1871
|
-
(function (LogPriority) {
|
|
1872
|
-
LogPriority[LogPriority["debug"] = 0] = "debug";
|
|
1873
|
-
LogPriority[LogPriority["info"] = 1] = "info";
|
|
1874
|
-
LogPriority[LogPriority["warn"] = 2] = "warn";
|
|
1875
|
-
LogPriority[LogPriority["error"] = 3] = "error";
|
|
1876
|
-
LogPriority[LogPriority["none"] = 4] = "none";
|
|
1877
|
-
})(LogPriority || (LogPriority = {}));
|
|
1878
|
-
const LEVEL_NAMES = ['debug', 'info', 'warn', 'error', 'none'];
|
|
1879
1816
|
/**
|
|
1880
|
-
*
|
|
1817
|
+
* Returns a promise which errors after t seconds.
|
|
1881
1818
|
*
|
|
1882
|
-
*
|
|
1883
|
-
*
|
|
1884
|
-
|
|
1885
|
-
|
|
1819
|
+
* @param t Timeout in seconds.
|
|
1820
|
+
* @param taskName Name of task being timed for logging and error reporting.
|
|
1821
|
+
*/
|
|
1822
|
+
const timedPromise = (t, taskName) => new Promise((_res, reject) => {
|
|
1823
|
+
setTimeout(() => {
|
|
1824
|
+
const e = `${taskName} timed out after ${t} seconds.`;
|
|
1825
|
+
reject(new LDTimeoutError(e));
|
|
1826
|
+
}, t * 1000);
|
|
1827
|
+
});
|
|
1828
|
+
|
|
1829
|
+
/**
|
|
1830
|
+
* Creates a policy that resets once the component has operated without failing
|
|
1831
|
+
* for the given duration. Repeated healthy reports do not move the starting
|
|
1832
|
+
* point; only a failure clears it.
|
|
1886
1833
|
*
|
|
1887
|
-
*
|
|
1888
|
-
*
|
|
1834
|
+
* @param healthyForMs How long the component must operate without failing,
|
|
1835
|
+
* in milliseconds; must be a positive, finite number.
|
|
1836
|
+
* @param clock The time source used to measure the healthy stretch; defaults
|
|
1837
|
+
* to a monotonic clock. Primarily for testing.
|
|
1889
1838
|
*/
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
static get() {
|
|
1897
|
-
return new BasicLogger({});
|
|
1898
|
-
}
|
|
1899
|
-
constructor(options) {
|
|
1900
|
-
this._logLevel = LogPriority[options.level ?? 'info'] ?? LogPriority.info;
|
|
1901
|
-
this._name = options.name ?? 'LaunchDarkly';
|
|
1902
|
-
this._formatter = options.formatter;
|
|
1903
|
-
if (typeof options.destination === 'object') {
|
|
1904
|
-
this._destinations = {
|
|
1905
|
-
[LogPriority.debug]: options.destination.debug,
|
|
1906
|
-
[LogPriority.info]: options.destination.info,
|
|
1907
|
-
[LogPriority.warn]: options.destination.warn,
|
|
1908
|
-
[LogPriority.error]: options.destination.error,
|
|
1909
|
-
};
|
|
1910
|
-
}
|
|
1911
|
-
else if (typeof options.destination === 'function') {
|
|
1912
|
-
const { destination } = options;
|
|
1913
|
-
this._destinations = {
|
|
1914
|
-
[LogPriority.debug]: destination,
|
|
1915
|
-
[LogPriority.info]: destination,
|
|
1916
|
-
[LogPriority.warn]: destination,
|
|
1917
|
-
[LogPriority.error]: destination,
|
|
1918
|
-
};
|
|
1919
|
-
}
|
|
1920
|
-
}
|
|
1921
|
-
_tryFormat(...args) {
|
|
1922
|
-
try {
|
|
1923
|
-
if (this._formatter) {
|
|
1924
|
-
// In case the provided formatter fails.
|
|
1925
|
-
return this._formatter?.(...args);
|
|
1926
|
-
}
|
|
1927
|
-
return format(...args);
|
|
1928
|
-
}
|
|
1929
|
-
catch {
|
|
1930
|
-
return format(...args);
|
|
1931
|
-
}
|
|
1932
|
-
}
|
|
1933
|
-
_tryWrite(destination, msg) {
|
|
1934
|
-
try {
|
|
1935
|
-
destination(msg);
|
|
1936
|
-
}
|
|
1937
|
-
catch {
|
|
1938
|
-
// eslint-disable-next-line no-console
|
|
1939
|
-
console.error(msg);
|
|
1940
|
-
}
|
|
1941
|
-
}
|
|
1942
|
-
_log(level, args) {
|
|
1943
|
-
if (level >= this._logLevel) {
|
|
1944
|
-
const prefix = `${LEVEL_NAMES[level]}: [${this._name}]`;
|
|
1945
|
-
try {
|
|
1946
|
-
const destination = this._destinations?.[level];
|
|
1947
|
-
if (destination) {
|
|
1948
|
-
this._tryWrite(destination, `${prefix} ${this._tryFormat(...args)}`);
|
|
1949
|
-
}
|
|
1950
|
-
else {
|
|
1951
|
-
// `console.error` has its own formatter.
|
|
1952
|
-
// So we don't need to do anything.
|
|
1953
|
-
// eslint-disable-next-line no-console
|
|
1954
|
-
console.error(...args);
|
|
1955
|
-
}
|
|
1956
|
-
}
|
|
1957
|
-
catch {
|
|
1958
|
-
// If all else fails do not break.
|
|
1959
|
-
// eslint-disable-next-line no-console
|
|
1960
|
-
console.error(...args);
|
|
1839
|
+
function createAfterHealthyFor(healthyForMs, clock = monotonicNow) {
|
|
1840
|
+
let healthySinceMs;
|
|
1841
|
+
return {
|
|
1842
|
+
noteHealthy() {
|
|
1843
|
+
if (healthySinceMs === undefined) {
|
|
1844
|
+
healthySinceMs = clock();
|
|
1961
1845
|
}
|
|
1962
|
-
}
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
}
|
|
1970
|
-
info(...args) {
|
|
1971
|
-
this._log(LogPriority.info, args);
|
|
1972
|
-
}
|
|
1973
|
-
debug(...args) {
|
|
1974
|
-
this._log(LogPriority.debug, args);
|
|
1975
|
-
}
|
|
1846
|
+
},
|
|
1847
|
+
noteFailure() {
|
|
1848
|
+
healthySinceMs = undefined;
|
|
1849
|
+
},
|
|
1850
|
+
isSatisfied() {
|
|
1851
|
+
return healthySinceMs !== undefined && clock() - healthySinceMs >= healthyForMs;
|
|
1852
|
+
},
|
|
1853
|
+
};
|
|
1976
1854
|
}
|
|
1977
|
-
|
|
1978
|
-
const loggerRequirements = {
|
|
1979
|
-
error: TypeValidators.Function,
|
|
1980
|
-
warn: TypeValidators.Function,
|
|
1981
|
-
info: TypeValidators.Function,
|
|
1982
|
-
debug: TypeValidators.Function,
|
|
1983
|
-
};
|
|
1984
1855
|
/**
|
|
1985
|
-
*
|
|
1986
|
-
*
|
|
1987
|
-
*
|
|
1988
|
-
*
|
|
1989
|
-
*
|
|
1990
|
-
* all but some other kind of object; the former is handled by a catch block that logs an error
|
|
1991
|
-
* message to the SDK's default logger, and we can at least partly guard against the latter by
|
|
1992
|
-
* checking for the presence of required methods at configuration time.
|
|
1856
|
+
* Creates a policy that resets once the given number of operations in a row
|
|
1857
|
+
* have succeeded.
|
|
1858
|
+
*
|
|
1859
|
+
* @param count How many operations in a row must succeed; must be a positive
|
|
1860
|
+
* integer.
|
|
1993
1861
|
*/
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
1862
|
+
function createAfterConsecutiveSuccesses(count) {
|
|
1863
|
+
let successes = 0;
|
|
1864
|
+
return {
|
|
1865
|
+
noteHealthy() {
|
|
1866
|
+
successes += 1;
|
|
1867
|
+
},
|
|
1868
|
+
noteFailure() {
|
|
1869
|
+
successes = 0;
|
|
1870
|
+
},
|
|
1871
|
+
isSatisfied() {
|
|
1872
|
+
return successes >= count;
|
|
1873
|
+
},
|
|
1874
|
+
};
|
|
1875
|
+
}
|
|
1876
|
+
|
|
1877
|
+
// The delay bounds of the extended regime, in milliseconds. A component enters
|
|
1878
|
+
// the extended regime after an unexpected failure and leaves it when its reset
|
|
1879
|
+
// policy is satisfied.
|
|
1880
|
+
const EXTENDED_INITIAL_DELAY_MS = 5 * 60 * 1000;
|
|
1881
|
+
const EXTENDED_CEILING_MS = 60 * 60 * 1000;
|
|
1882
|
+
// The bounds, reset window, and default initial delay of streaming's normal regime.
|
|
1883
|
+
const STREAMING_NORMAL_CEILING_MS = 30 * 1000;
|
|
1884
|
+
const STREAMING_RESET_INTERVAL_MS = 60 * 1000;
|
|
1885
|
+
const DEFAULT_STREAMING_INITIAL_DELAY_MS = 1000;
|
|
1886
|
+
// Polling's reset condition and default cadence.
|
|
1887
|
+
const POLLING_RESET_SUCCESSES = 2;
|
|
1888
|
+
const DEFAULT_POLL_INTERVAL_MS = 30 * 1000;
|
|
1889
|
+
function positiveFiniteOrDefault(value, defaultValueMs, name, logger) {
|
|
1890
|
+
if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
|
|
1891
|
+
return value;
|
|
2013
1892
|
}
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
1893
|
+
logger?.warn(`${name} must be a positive, finite number of milliseconds; using the default of ${defaultValueMs}`);
|
|
1894
|
+
return defaultValueMs;
|
|
1895
|
+
}
|
|
1896
|
+
/**
|
|
1897
|
+
* Builds a retry state from explicit bounds. See {@link RetryStateConfig} for
|
|
1898
|
+
* the contract on the values.
|
|
1899
|
+
*/
|
|
1900
|
+
function createRetryState(config) {
|
|
1901
|
+
const normalInitialDelayMs = config.normalInitialDelayMs;
|
|
1902
|
+
const normalCeilingMs = config.normalCeilingMs;
|
|
1903
|
+
const extendedInitialDelayMs = config.extendedInitialDelayMs;
|
|
1904
|
+
const extendedCeilingMs = config.extendedCeilingMs;
|
|
1905
|
+
const operatingCadenceMs = config.operatingCadenceMs ?? 0;
|
|
1906
|
+
const { resetPolicy } = config;
|
|
1907
|
+
const random = config.random ?? Math.random;
|
|
1908
|
+
let attempts = 0;
|
|
1909
|
+
let extended = false;
|
|
1910
|
+
let minDelayMs = normalInitialDelayMs;
|
|
1911
|
+
let maxDelayMs = normalCeilingMs;
|
|
1912
|
+
let serverDirectedBaseMs;
|
|
1913
|
+
// Before any outcome is recorded, the next wait is the ordinary interval.
|
|
1914
|
+
let nextDelayMs = operatingCadenceMs;
|
|
1915
|
+
function resetIfDue() {
|
|
1916
|
+
if (!resetPolicy.isSatisfied()) {
|
|
1917
|
+
return;
|
|
2021
1918
|
}
|
|
1919
|
+
attempts = 0;
|
|
1920
|
+
extended = false;
|
|
1921
|
+
minDelayMs = normalInitialDelayMs;
|
|
1922
|
+
maxDelayMs = normalCeilingMs;
|
|
2022
1923
|
}
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
1924
|
+
return {
|
|
1925
|
+
get nextDelay() {
|
|
1926
|
+
return nextDelayMs;
|
|
1927
|
+
},
|
|
1928
|
+
recordFailure(kind) {
|
|
1929
|
+
// A reset that fell due during healthy operation is applied before the
|
|
1930
|
+
// new failure is counted, so the failure computes from a fresh sequence.
|
|
1931
|
+
resetIfDue();
|
|
1932
|
+
resetPolicy.noteFailure();
|
|
1933
|
+
if (kind === 'unexpected' && !extended) {
|
|
1934
|
+
// Moving to the extended regime raises both bounds and starts the delay
|
|
1935
|
+
// sequence over. Only the move does this: a later unexpected failure
|
|
1936
|
+
// keeps counting up rather than re-pinning the initial delay.
|
|
1937
|
+
extended = true;
|
|
1938
|
+
minDelayMs = extendedInitialDelayMs;
|
|
1939
|
+
maxDelayMs = Math.max(extendedCeilingMs, extendedInitialDelayMs);
|
|
1940
|
+
attempts = 1;
|
|
1941
|
+
}
|
|
1942
|
+
else {
|
|
1943
|
+
attempts += 1;
|
|
1944
|
+
}
|
|
1945
|
+
const base = serverDirectedBaseMs ?? minDelayMs;
|
|
1946
|
+
// Compare against the ceiling scaled down rather than the base scaled up, so
|
|
1947
|
+
// the computed value can never overflow the ceiling. A base of zero doubles
|
|
1948
|
+
// to zero forever, so it short-circuits.
|
|
1949
|
+
let target = 0;
|
|
1950
|
+
if (base > 0) {
|
|
1951
|
+
const exponent = attempts - 1;
|
|
1952
|
+
target = base >= maxDelayMs / 2 ** exponent ? maxDelayMs : base * 2 ** exponent;
|
|
1953
|
+
}
|
|
1954
|
+
const jitter = (random() * target) / 2;
|
|
1955
|
+
nextDelayMs = Math.max(target - jitter, operatingCadenceMs);
|
|
1956
|
+
},
|
|
1957
|
+
recordSuccess() {
|
|
1958
|
+
resetPolicy.noteHealthy();
|
|
1959
|
+
resetIfDue();
|
|
1960
|
+
// A backoff wait applies to a retry, not to every operation, so after a
|
|
1961
|
+
// success the next wait is the ordinary interval even while the retry
|
|
1962
|
+
// state is raised.
|
|
1963
|
+
nextDelayMs = operatingCadenceMs;
|
|
1964
|
+
},
|
|
1965
|
+
applyServerDirectedRetry(delayMs) {
|
|
1966
|
+
if (typeof delayMs !== 'number' || !Number.isFinite(delayMs) || delayMs < 0) {
|
|
1967
|
+
return;
|
|
1968
|
+
}
|
|
1969
|
+
serverDirectedBaseMs = delayMs;
|
|
1970
|
+
attempts = 0;
|
|
1971
|
+
},
|
|
1972
|
+
};
|
|
2035
1973
|
}
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
1974
|
+
/**
|
|
1975
|
+
* Builds the retry state for a streaming data source: no wait during healthy
|
|
1976
|
+
* operation, a normal regime running from the configured initial delay up to
|
|
1977
|
+
* a 30 second ceiling, an extended regime of 5 minutes up to 1 hour, and a
|
|
1978
|
+
* reset once a connection has been healthy for 60 seconds.
|
|
1979
|
+
*
|
|
1980
|
+
* The initial delay is validated here; the documented default of 1 second
|
|
1981
|
+
* stands in for anything that is not a positive, finite number. A configured
|
|
1982
|
+
* delay above the normal ceiling is clamped to it, while the extended regime
|
|
1983
|
+
* never starts below the configured delay.
|
|
1984
|
+
*/
|
|
1985
|
+
function forStreaming(initialReconnectDelayMs, logger) {
|
|
1986
|
+
const validated = positiveFiniteOrDefault(initialReconnectDelayMs, DEFAULT_STREAMING_INITIAL_DELAY_MS, 'initialReconnectDelayMs', logger);
|
|
1987
|
+
return createRetryState({
|
|
1988
|
+
normalInitialDelayMs: validated,
|
|
1989
|
+
normalCeilingMs: STREAMING_NORMAL_CEILING_MS,
|
|
1990
|
+
extendedInitialDelayMs: Math.max(EXTENDED_INITIAL_DELAY_MS, validated),
|
|
1991
|
+
extendedCeilingMs: EXTENDED_CEILING_MS,
|
|
1992
|
+
resetPolicy: createAfterHealthyFor(STREAMING_RESET_INTERVAL_MS),
|
|
1993
|
+
operatingCadenceMs: 0,
|
|
2043
1994
|
});
|
|
2044
|
-
|
|
2045
|
-
};
|
|
2046
|
-
|
|
1995
|
+
}
|
|
2047
1996
|
/**
|
|
2048
|
-
*
|
|
1997
|
+
* Builds the retry state for a polling data source: the poll interval is the
|
|
1998
|
+
* operating cadence, so no wait is ever shorter than it; in the normal regime
|
|
1999
|
+
* both bounds are the interval itself, so a normal failure simply polls again
|
|
2000
|
+
* on schedule; the extended regime runs from 5 minutes (or the interval, if
|
|
2001
|
+
* longer) up to 1 hour (or the interval, if longer); and the state resets
|
|
2002
|
+
* after two successful polls in a row.
|
|
2003
|
+
*
|
|
2004
|
+
* The poll interval is validated here; the documented default of 30 seconds
|
|
2005
|
+
* stands in for anything that is not a positive, finite number.
|
|
2049
2006
|
*/
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
}
|
|
2060
|
-
static wrongOptionType(name, expectedType, actualType) {
|
|
2061
|
-
return `Config option "${name}" should be of type ${expectedType}, got ${actualType}, using default value`;
|
|
2062
|
-
}
|
|
2063
|
-
static wrongOptionTypeBoolean(name, actualType) {
|
|
2064
|
-
return `Config option "${name}" should be a boolean, got ${actualType}, converting to boolean`;
|
|
2065
|
-
}
|
|
2066
|
-
static invalidTagValue(name) {
|
|
2067
|
-
return `Config option "${name}" must only contain letters, numbers, ., _ or -.`;
|
|
2068
|
-
}
|
|
2069
|
-
static tagValueTooLong(name) {
|
|
2070
|
-
return `Value of "${name}" was longer than 64 characters and was discarded.`;
|
|
2071
|
-
}
|
|
2072
|
-
static partialEndpoint(name) {
|
|
2073
|
-
return `You have set custom uris without specifying the ${name} URI; connections may not work properly`;
|
|
2074
|
-
}
|
|
2007
|
+
function forPolling(pollIntervalMs, logger) {
|
|
2008
|
+
const validated = positiveFiniteOrDefault(pollIntervalMs, DEFAULT_POLL_INTERVAL_MS, 'pollIntervalMs', logger);
|
|
2009
|
+
return createRetryState({
|
|
2010
|
+
normalInitialDelayMs: validated,
|
|
2011
|
+
normalCeilingMs: validated,
|
|
2012
|
+
extendedInitialDelayMs: Math.max(EXTENDED_INITIAL_DELAY_MS, validated),
|
|
2013
|
+
extendedCeilingMs: EXTENDED_CEILING_MS,
|
|
2014
|
+
resetPolicy: createAfterConsecutiveSuccesses(POLLING_RESET_SUCCESSES),
|
|
2015
|
+
operatingCadenceMs: validated,
|
|
2016
|
+
});
|
|
2075
2017
|
}
|
|
2076
2018
|
|
|
2077
2019
|
/**
|
|
2078
|
-
*
|
|
2020
|
+
* Enable / disable Auto environment attributes. When enabled, the SDK will automatically
|
|
2021
|
+
* provide data about the mobile environment where the application is running. This data makes it simpler to target
|
|
2022
|
+
* your mobile customers based on application name or version, or on device characteristics including manufacturer,
|
|
2023
|
+
* model, operating system, locale, and so on. We recommend enabling this when you configure the SDK. To learn more,
|
|
2024
|
+
* read [Automatic environment attributes](https://docs.launchdarkly.com/sdk/features/environment-attributes).
|
|
2025
|
+
* for more documentation.
|
|
2079
2026
|
*/
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2027
|
+
var AutoEnvAttributes;
|
|
2028
|
+
(function (AutoEnvAttributes) {
|
|
2029
|
+
AutoEnvAttributes[AutoEnvAttributes["Disabled"] = 0] = "Disabled";
|
|
2030
|
+
AutoEnvAttributes[AutoEnvAttributes["Enabled"] = 1] = "Enabled";
|
|
2031
|
+
})(AutoEnvAttributes || (AutoEnvAttributes = {}));
|
|
2032
|
+
|
|
2033
|
+
var LDEventType;
|
|
2034
|
+
(function (LDEventType) {
|
|
2035
|
+
LDEventType[LDEventType["AnalyticsEvents"] = 0] = "AnalyticsEvents";
|
|
2036
|
+
LDEventType[LDEventType["DiagnosticEvent"] = 1] = "DiagnosticEvent";
|
|
2037
|
+
})(LDEventType || (LDEventType = {}));
|
|
2038
|
+
var LDDeliveryStatus;
|
|
2039
|
+
(function (LDDeliveryStatus) {
|
|
2040
|
+
LDDeliveryStatus[LDDeliveryStatus["Succeeded"] = 0] = "Succeeded";
|
|
2041
|
+
LDDeliveryStatus[LDDeliveryStatus["Failed"] = 1] = "Failed";
|
|
2042
|
+
LDDeliveryStatus[LDDeliveryStatus["FailedAndMustShutDown"] = 2] = "FailedAndMustShutDown";
|
|
2043
|
+
})(LDDeliveryStatus || (LDDeliveryStatus = {}));
|
|
2044
|
+
|
|
2045
|
+
var index$1 = /*#__PURE__*/Object.freeze({
|
|
2046
|
+
__proto__: null,
|
|
2047
|
+
get DataSourceState () { return DataSourceState; },
|
|
2048
|
+
get LDDeliveryStatus () { return LDDeliveryStatus; },
|
|
2049
|
+
get LDEventType () { return LDEventType; }
|
|
2050
|
+
});
|
|
2051
|
+
|
|
2093
2052
|
/**
|
|
2094
|
-
*
|
|
2053
|
+
* Attempt to produce a string representation of a value.
|
|
2054
|
+
* The format should be roughly comparable to `util.format`
|
|
2055
|
+
* aside from object which will be JSON versus the `util.inspect`
|
|
2056
|
+
* format.
|
|
2057
|
+
* @param val
|
|
2058
|
+
* @returns A string representation of the value if possible.
|
|
2095
2059
|
*/
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
tags[`application-version-name`] = [value];
|
|
2110
|
-
}
|
|
2111
|
-
else {
|
|
2112
|
-
tags[`application-${key}`] = [value];
|
|
2113
|
-
}
|
|
2114
|
-
}
|
|
2115
|
-
});
|
|
2060
|
+
function tryStringify(val) {
|
|
2061
|
+
if (typeof val === 'string') {
|
|
2062
|
+
return val;
|
|
2063
|
+
}
|
|
2064
|
+
if (val === undefined) {
|
|
2065
|
+
return 'undefined';
|
|
2066
|
+
}
|
|
2067
|
+
if (val === null) {
|
|
2068
|
+
return 'null';
|
|
2069
|
+
}
|
|
2070
|
+
if (Object.prototype.hasOwnProperty.call(val, 'toString')) {
|
|
2071
|
+
try {
|
|
2072
|
+
return val.toString();
|
|
2116
2073
|
}
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
this.value = tagKeys
|
|
2120
|
-
.sort()
|
|
2121
|
-
.flatMap((key) => tags[key].sort().map((value) => `${key}/${value}`))
|
|
2122
|
-
.join(' ');
|
|
2074
|
+
catch {
|
|
2075
|
+
/* Keep going */
|
|
2123
2076
|
}
|
|
2124
2077
|
}
|
|
2078
|
+
if (typeof val === 'bigint') {
|
|
2079
|
+
return `${val}n`;
|
|
2080
|
+
}
|
|
2081
|
+
try {
|
|
2082
|
+
return JSON.stringify(val);
|
|
2083
|
+
}
|
|
2084
|
+
catch (error) {
|
|
2085
|
+
if (error instanceof TypeError && error.message.indexOf('circular') >= 0) {
|
|
2086
|
+
return '[Circular]';
|
|
2087
|
+
}
|
|
2088
|
+
return '[Not Stringifiable]';
|
|
2089
|
+
}
|
|
2125
2090
|
}
|
|
2126
|
-
|
|
2127
2091
|
/**
|
|
2128
|
-
*
|
|
2129
|
-
*
|
|
2092
|
+
* Attempt to produce a numeric representation.
|
|
2093
|
+
* BigInts have an `n` suffix.
|
|
2094
|
+
* @param val
|
|
2095
|
+
* @returns The numeric representation or 'NaN' if not numeric.
|
|
2130
2096
|
*/
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
logger: configuration.logger,
|
|
2137
|
-
offline: configuration.offline,
|
|
2138
|
-
serviceEndpoints: configuration.serviceEndpoints,
|
|
2139
|
-
sdkKey,
|
|
2140
|
-
};
|
|
2097
|
+
function toNumber(val) {
|
|
2098
|
+
// Symbol has to be treated special because it will
|
|
2099
|
+
// throw an exception if an attempt is made to convert it.
|
|
2100
|
+
if (typeof val === 'symbol') {
|
|
2101
|
+
return 'NaN';
|
|
2141
2102
|
}
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
return
|
|
2146
|
-
}
|
|
2147
|
-
function canonicalizePath(path) {
|
|
2148
|
-
return path.replace(/^\/+/, '').replace(/\?$/, '');
|
|
2103
|
+
if (typeof val === 'bigint') {
|
|
2104
|
+
return `${val}n`;
|
|
2105
|
+
}
|
|
2106
|
+
return String(Number(val));
|
|
2149
2107
|
}
|
|
2150
2108
|
/**
|
|
2151
|
-
*
|
|
2109
|
+
* Attempt to produce an integer representation.
|
|
2110
|
+
* BigInts have an `n` suffix.
|
|
2111
|
+
* @param val
|
|
2112
|
+
* @returns The integer representation or 'NaN' if not numeric.
|
|
2152
2113
|
*/
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
this.polling = canonicalizeUri(polling);
|
|
2157
|
-
this.events = canonicalizeUri(events);
|
|
2158
|
-
this.analyticsEventPath = analyticsEventPath;
|
|
2159
|
-
this.diagnosticEventPath = diagnosticEventPath;
|
|
2160
|
-
this.includeAuthorizationHeader = includeAuthorizationHeader;
|
|
2161
|
-
this.payloadFilterKey = payloadFilterKey;
|
|
2114
|
+
function toInt(val) {
|
|
2115
|
+
if (typeof val === 'symbol') {
|
|
2116
|
+
return 'NaN';
|
|
2162
2117
|
}
|
|
2163
|
-
|
|
2164
|
-
|
|
2165
|
-
ServiceEndpoints.DEFAULT_EVENTS = 'https://events.launchdarkly.com';
|
|
2166
|
-
function getWithParams(uri, parameters = []) {
|
|
2167
|
-
if (parameters.length === 0) {
|
|
2168
|
-
return uri;
|
|
2118
|
+
if (typeof val === 'bigint') {
|
|
2119
|
+
return `${val}n`;
|
|
2169
2120
|
}
|
|
2170
|
-
|
|
2171
|
-
return `${uri}?${parts.join('&')}`;
|
|
2121
|
+
return String(parseInt(val, 10));
|
|
2172
2122
|
}
|
|
2173
2123
|
/**
|
|
2174
|
-
*
|
|
2175
|
-
*
|
|
2176
|
-
* @param
|
|
2177
|
-
* @
|
|
2178
|
-
* @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.
|
|
2124
|
+
* Attempt to produce a float representation.
|
|
2125
|
+
* BigInts have an `n` suffix.
|
|
2126
|
+
* @param val
|
|
2127
|
+
* @returns The integer representation or 'NaN' if not numeric.
|
|
2179
2128
|
*/
|
|
2180
|
-
function
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
if (endpoints.payloadFilterKey) {
|
|
2184
|
-
combinedParameters.push({ key: 'filter', value: endpoints.payloadFilterKey });
|
|
2129
|
+
function toFloat(val) {
|
|
2130
|
+
if (typeof val === 'symbol') {
|
|
2131
|
+
return 'NaN';
|
|
2185
2132
|
}
|
|
2186
|
-
return
|
|
2133
|
+
return String(parseFloat(val));
|
|
2187
2134
|
}
|
|
2135
|
+
// Based on:
|
|
2136
|
+
// https://nodejs.org/api/util.html#utilformatformat-args
|
|
2137
|
+
// The result will not match node exactly, but it should get the
|
|
2138
|
+
// right information through.
|
|
2139
|
+
const escapes = {
|
|
2140
|
+
s: (val) => tryStringify(val),
|
|
2141
|
+
d: (val) => toNumber(val),
|
|
2142
|
+
i: (val) => toInt(val),
|
|
2143
|
+
f: (val) => toFloat(val),
|
|
2144
|
+
j: (val) => tryStringify(val),
|
|
2145
|
+
o: (val) => tryStringify(val),
|
|
2146
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
2147
|
+
O: (val) => tryStringify(val),
|
|
2148
|
+
c: () => '',
|
|
2149
|
+
};
|
|
2188
2150
|
/**
|
|
2189
|
-
*
|
|
2151
|
+
* A basic formatted for use where `util.format` is not available.
|
|
2152
|
+
* This will not be as performant, but it will produce formatted
|
|
2153
|
+
* messages.
|
|
2190
2154
|
*
|
|
2191
|
-
* @
|
|
2192
|
-
*
|
|
2193
|
-
* @param
|
|
2155
|
+
* @internal
|
|
2156
|
+
*
|
|
2157
|
+
* @param args
|
|
2158
|
+
* @returns Formatted string.
|
|
2194
2159
|
*/
|
|
2195
|
-
function
|
|
2196
|
-
const
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2160
|
+
function format(...args) {
|
|
2161
|
+
const formatString = args[0];
|
|
2162
|
+
if (TypeValidators.String.is(formatString)) {
|
|
2163
|
+
args.shift();
|
|
2164
|
+
let out = '';
|
|
2165
|
+
let i = 0;
|
|
2166
|
+
while (i < formatString.length) {
|
|
2167
|
+
const char = formatString.charAt(i);
|
|
2168
|
+
if (char === '%') {
|
|
2169
|
+
const nextIndex = i + 1;
|
|
2170
|
+
if (nextIndex < formatString.length) {
|
|
2171
|
+
const nextChar = formatString.charAt(i + 1);
|
|
2172
|
+
if (nextChar in escapes && args.length) {
|
|
2173
|
+
const value = args.shift();
|
|
2174
|
+
// This rule is for math.
|
|
2175
|
+
out += escapes[nextChar]?.(value);
|
|
2176
|
+
}
|
|
2177
|
+
else if (nextChar === '%') {
|
|
2178
|
+
out += '%';
|
|
2179
|
+
}
|
|
2180
|
+
else {
|
|
2181
|
+
out += `%${nextChar}`;
|
|
2182
|
+
}
|
|
2183
|
+
i += 2;
|
|
2184
|
+
}
|
|
2185
|
+
else {
|
|
2186
|
+
// A trailing '%' has nothing to escape, so keep it as-is.
|
|
2187
|
+
out += '%';
|
|
2188
|
+
i += 1;
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
else {
|
|
2192
|
+
out += char;
|
|
2193
|
+
i += 1;
|
|
2194
|
+
}
|
|
2195
|
+
}
|
|
2196
|
+
// If there are any args left after we exhaust the format string
|
|
2197
|
+
// then just stick those on the end.
|
|
2198
|
+
if (args.length) {
|
|
2199
|
+
if (out.length) {
|
|
2200
|
+
out += ' ';
|
|
2201
|
+
}
|
|
2202
|
+
out += args.map(tryStringify).join(' ');
|
|
2203
|
+
}
|
|
2204
|
+
return out;
|
|
2200
2205
|
}
|
|
2201
|
-
return
|
|
2206
|
+
return args.map(tryStringify).join(' ');
|
|
2202
2207
|
}
|
|
2208
|
+
|
|
2209
|
+
var LogPriority;
|
|
2210
|
+
(function (LogPriority) {
|
|
2211
|
+
LogPriority[LogPriority["debug"] = 0] = "debug";
|
|
2212
|
+
LogPriority[LogPriority["info"] = 1] = "info";
|
|
2213
|
+
LogPriority[LogPriority["warn"] = 2] = "warn";
|
|
2214
|
+
LogPriority[LogPriority["error"] = 3] = "error";
|
|
2215
|
+
LogPriority[LogPriority["none"] = 4] = "none";
|
|
2216
|
+
})(LogPriority || (LogPriority = {}));
|
|
2217
|
+
const LEVEL_NAMES = ['debug', 'info', 'warn', 'error', 'none'];
|
|
2203
2218
|
/**
|
|
2204
|
-
*
|
|
2219
|
+
* A basic logger which handles filtering by level.
|
|
2205
2220
|
*
|
|
2206
|
-
*
|
|
2207
|
-
*
|
|
2208
|
-
*
|
|
2221
|
+
* With the default options it will write to `console.error`
|
|
2222
|
+
* and it will use the formatting provided by `console.error`.
|
|
2223
|
+
* If the destination is overwritten, then it will use an included
|
|
2224
|
+
* formatter similar to `util.format`.
|
|
2225
|
+
*
|
|
2226
|
+
* If a formatter is available, then that should be overridden
|
|
2227
|
+
* as well for performance.
|
|
2209
2228
|
*/
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
constructor(message) {
|
|
2219
|
-
super(message);
|
|
2220
|
-
this.name = 'LaunchDarklyUnexpectedResponseError';
|
|
2229
|
+
class BasicLogger {
|
|
2230
|
+
/**
|
|
2231
|
+
* This should only be used as a default fallback and not as a convenient
|
|
2232
|
+
* solution. In most cases you should construct a new instance with the
|
|
2233
|
+
* appropriate options for your specific needs.
|
|
2234
|
+
*/
|
|
2235
|
+
static get() {
|
|
2236
|
+
return new BasicLogger({});
|
|
2221
2237
|
}
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2238
|
+
constructor(options) {
|
|
2239
|
+
this._logLevel = LogPriority[options.level ?? 'info'] ?? LogPriority.info;
|
|
2240
|
+
this._name = options.name ?? 'LaunchDarkly';
|
|
2241
|
+
this._formatter = options.formatter;
|
|
2242
|
+
if (typeof options.destination === 'object') {
|
|
2243
|
+
this._destinations = {
|
|
2244
|
+
[LogPriority.debug]: options.destination.debug,
|
|
2245
|
+
[LogPriority.info]: options.destination.info,
|
|
2246
|
+
[LogPriority.warn]: options.destination.warn,
|
|
2247
|
+
[LogPriority.error]: options.destination.error,
|
|
2248
|
+
};
|
|
2249
|
+
}
|
|
2250
|
+
else if (typeof options.destination === 'function') {
|
|
2251
|
+
const { destination } = options;
|
|
2252
|
+
this._destinations = {
|
|
2253
|
+
[LogPriority.debug]: destination,
|
|
2254
|
+
[LogPriority.info]: destination,
|
|
2255
|
+
[LogPriority.warn]: destination,
|
|
2256
|
+
[LogPriority.error]: destination,
|
|
2257
|
+
};
|
|
2258
|
+
}
|
|
2227
2259
|
}
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2260
|
+
_tryFormat(...args) {
|
|
2261
|
+
try {
|
|
2262
|
+
if (this._formatter) {
|
|
2263
|
+
// In case the provided formatter fails.
|
|
2264
|
+
return this._formatter?.(...args);
|
|
2265
|
+
}
|
|
2266
|
+
return format(...args);
|
|
2267
|
+
}
|
|
2268
|
+
catch {
|
|
2269
|
+
return format(...args);
|
|
2270
|
+
}
|
|
2233
2271
|
}
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
|
|
2272
|
+
_tryWrite(destination, msg) {
|
|
2273
|
+
try {
|
|
2274
|
+
destination(msg);
|
|
2275
|
+
}
|
|
2276
|
+
catch {
|
|
2277
|
+
// eslint-disable-next-line no-console
|
|
2278
|
+
console.error(msg);
|
|
2279
|
+
}
|
|
2280
|
+
}
|
|
2281
|
+
_log(level, args) {
|
|
2282
|
+
if (level >= this._logLevel) {
|
|
2283
|
+
const prefix = `${LEVEL_NAMES[level]}: [${this._name}]`;
|
|
2284
|
+
try {
|
|
2285
|
+
const destination = this._destinations?.[level];
|
|
2286
|
+
if (destination) {
|
|
2287
|
+
this._tryWrite(destination, `${prefix} ${this._tryFormat(...args)}`);
|
|
2288
|
+
}
|
|
2289
|
+
else {
|
|
2290
|
+
// `console.error` has its own formatter.
|
|
2291
|
+
// So we don't need to do anything.
|
|
2292
|
+
// eslint-disable-next-line no-console
|
|
2293
|
+
console.error(...args);
|
|
2294
|
+
}
|
|
2295
|
+
}
|
|
2296
|
+
catch {
|
|
2297
|
+
// If all else fails do not break.
|
|
2298
|
+
// eslint-disable-next-line no-console
|
|
2299
|
+
console.error(...args);
|
|
2300
|
+
}
|
|
2301
|
+
}
|
|
2302
|
+
}
|
|
2303
|
+
error(...args) {
|
|
2304
|
+
this._log(LogPriority.error, args);
|
|
2248
2305
|
}
|
|
2249
|
-
|
|
2250
|
-
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
|
|
2254
|
-
|
|
2255
|
-
|
|
2256
|
-
|
|
2257
|
-
* distinguished from a transient network fault, and treating transient faults
|
|
2258
|
-
* as unexpected would hold ordinary recoveries to multi-minute waits.
|
|
2259
|
-
*/
|
|
2260
|
-
function classifyTransportFailure() {
|
|
2261
|
-
return 'normal';
|
|
2262
|
-
}
|
|
2263
|
-
/**
|
|
2264
|
-
* Check if the HTTP error is recoverable. This will return false if a request
|
|
2265
|
-
* made with any payload could not recover. If the reason for the failure
|
|
2266
|
-
* is payload specific, for instance a payload that is too large, then
|
|
2267
|
-
* it could recover with a different payload.
|
|
2268
|
-
*
|
|
2269
|
-
* Superseded by {@link classifyHttpStatus}, which this delegates to. It is
|
|
2270
|
-
* retained for the event-delivery pathway and is expected to be deprecated
|
|
2271
|
-
* once that pathway migrates to failure classification.
|
|
2272
|
-
*/
|
|
2273
|
-
function isHttpRecoverable(status) {
|
|
2274
|
-
return classifyHttpStatus(status) === 'normal';
|
|
2275
|
-
}
|
|
2276
|
-
/**
|
|
2277
|
-
* Returns true if the status could recover for a different payload.
|
|
2278
|
-
*
|
|
2279
|
-
* When used with event processing this indicates that we should discard
|
|
2280
|
-
* the payload, but that a subsequent payload may succeed. Therefore we should
|
|
2281
|
-
* not stop event processing.
|
|
2282
|
-
*/
|
|
2283
|
-
function isHttpLocallyRecoverable(status) {
|
|
2284
|
-
if (status === 413) {
|
|
2285
|
-
return true;
|
|
2306
|
+
warn(...args) {
|
|
2307
|
+
this._log(LogPriority.warn, args);
|
|
2308
|
+
}
|
|
2309
|
+
info(...args) {
|
|
2310
|
+
this._log(LogPriority.info, args);
|
|
2311
|
+
}
|
|
2312
|
+
debug(...args) {
|
|
2313
|
+
this._log(LogPriority.debug, args);
|
|
2286
2314
|
}
|
|
2287
|
-
return isHttpRecoverable(status);
|
|
2288
2315
|
}
|
|
2289
2316
|
|
|
2317
|
+
const loggerRequirements = {
|
|
2318
|
+
error: TypeValidators.Function,
|
|
2319
|
+
warn: TypeValidators.Function,
|
|
2320
|
+
info: TypeValidators.Function,
|
|
2321
|
+
debug: TypeValidators.Function,
|
|
2322
|
+
};
|
|
2290
2323
|
/**
|
|
2291
|
-
*
|
|
2292
|
-
*
|
|
2293
|
-
*
|
|
2294
|
-
*
|
|
2324
|
+
* The safeLogger logic exists because we allow the application to pass in a custom logger, but
|
|
2325
|
+
* there is no guarantee that the logger works correctly and if it ever throws exceptions there
|
|
2326
|
+
* could be serious consequences (e.g. an uncaught exception within an error event handler, due
|
|
2327
|
+
* to the SDK trying to log the error, can terminate the application). An exception could result
|
|
2328
|
+
* from faulty logic in the logger implementation, or it could be that this is not a logger at
|
|
2329
|
+
* all but some other kind of object; the former is handled by a catch block that logs an error
|
|
2330
|
+
* message to the SDK's default logger, and we can at least partly guard against the latter by
|
|
2331
|
+
* checking for the presence of required methods at configuration time.
|
|
2295
2332
|
*/
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2333
|
+
class SafeLogger {
|
|
2334
|
+
/**
|
|
2335
|
+
* Construct a safe logger with the specified logger.
|
|
2336
|
+
* @param logger The logger to use.
|
|
2337
|
+
* @param fallback A fallback logger to use in case an issue is encountered using
|
|
2338
|
+
* the provided logger.
|
|
2339
|
+
*/
|
|
2340
|
+
constructor(logger, fallback) {
|
|
2341
|
+
Object.entries(loggerRequirements).forEach(([level, validator]) => {
|
|
2342
|
+
if (!validator.is(logger[level])) {
|
|
2343
|
+
throw new Error(`Provided logger instance must support logger.${level}(...) method`);
|
|
2344
|
+
// Note that the SDK normally does not throw exceptions to the application, but that rule
|
|
2345
|
+
// does not apply to LDClient.init() which will throw an exception if the parameters are so
|
|
2346
|
+
// invalid that we cannot proceed with creating the client. An invalid logger meets those
|
|
2347
|
+
// criteria since the SDK calls the logger during nearly all of its operations.
|
|
2348
|
+
}
|
|
2349
|
+
});
|
|
2350
|
+
this._logger = logger;
|
|
2351
|
+
this._fallback = fallback;
|
|
2352
|
+
}
|
|
2353
|
+
_log(level, args) {
|
|
2354
|
+
try {
|
|
2355
|
+
this._logger[level](...args);
|
|
2356
|
+
}
|
|
2357
|
+
catch {
|
|
2358
|
+
// If all else fails do not break.
|
|
2359
|
+
this._fallback[level](...args);
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
error(...args) {
|
|
2363
|
+
this._log('error', args);
|
|
2364
|
+
}
|
|
2365
|
+
warn(...args) {
|
|
2366
|
+
this._log('warn', args);
|
|
2367
|
+
}
|
|
2368
|
+
info(...args) {
|
|
2369
|
+
this._log('info', args);
|
|
2370
|
+
}
|
|
2371
|
+
debug(...args) {
|
|
2372
|
+
this._log('debug', args);
|
|
2318
2373
|
}
|
|
2319
|
-
return JSON.parse(JSON.stringify(obj));
|
|
2320
|
-
}
|
|
2321
|
-
|
|
2322
|
-
function secondsToMillis(sec) {
|
|
2323
|
-
return Math.trunc(sec * 1000);
|
|
2324
2374
|
}
|
|
2325
2375
|
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
* ```js
|
|
2335
|
-
* const debouncedFunction = debounce(e => {
|
|
2336
|
-
* console.log(e);
|
|
2337
|
-
* }, 5000);
|
|
2338
|
-
*
|
|
2339
|
-
* // Console logs 'Hello world again ' after 5 seconds
|
|
2340
|
-
* debouncedFunction('Hello world');
|
|
2341
|
-
* debouncedFunction('Hello world again');
|
|
2342
|
-
* ```
|
|
2343
|
-
* @param fn The function to be debounced.
|
|
2344
|
-
* @param delayMs Defaults to 5 seconds.
|
|
2345
|
-
*/
|
|
2346
|
-
const debounce = (fn, delayMs = 5000) => {
|
|
2347
|
-
let timer;
|
|
2348
|
-
return (...args) => {
|
|
2349
|
-
clearTimeout(timer);
|
|
2350
|
-
timer = setTimeout(() => {
|
|
2351
|
-
fn(...args);
|
|
2352
|
-
}, delayMs);
|
|
2353
|
-
};
|
|
2376
|
+
const createSafeLogger = (logger) => {
|
|
2377
|
+
const basicLogger = new BasicLogger({
|
|
2378
|
+
level: 'info',
|
|
2379
|
+
// eslint-disable-next-line no-console
|
|
2380
|
+
destination: console.error,
|
|
2381
|
+
formatter: format,
|
|
2382
|
+
});
|
|
2383
|
+
return logger ? new SafeLogger(logger, basicLogger) : basicLogger;
|
|
2354
2384
|
};
|
|
2355
2385
|
|
|
2356
|
-
const isEmptyObject = (obj) => JSON.stringify(obj) === '{}';
|
|
2357
|
-
|
|
2358
2386
|
/**
|
|
2359
|
-
*
|
|
2360
|
-
* Sourced from below but modified to include checks for empty object and ignoring keys.
|
|
2361
|
-
* https://www.w3resource.com/javascript-exercises/javascript-array-exercise-47.php
|
|
2362
|
-
*
|
|
2363
|
-
* @param obj
|
|
2364
|
-
* @param ignoreKeys
|
|
2387
|
+
* Messages for issues which can be encountered from processing the configuration options.
|
|
2365
2388
|
*/
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
return
|
|
2389
|
+
class OptionMessages {
|
|
2390
|
+
static deprecated(oldName, newName) {
|
|
2391
|
+
return `"${oldName}" is deprecated, please use "${newName}"`;
|
|
2369
2392
|
}
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
return
|
|
2375
|
-
}
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
if (
|
|
2401
|
-
if (
|
|
2402
|
-
return false;
|
|
2403
|
-
for (i of a.entries())
|
|
2404
|
-
if (!b.has(i[0]))
|
|
2405
|
-
return false;
|
|
2406
|
-
for (i of a.entries())
|
|
2407
|
-
if (!fastDeepEqual(i[1], b.get(i[0])))
|
|
2408
|
-
return false;
|
|
2409
|
-
return true;
|
|
2410
|
-
}
|
|
2411
|
-
if (a instanceof Set && b instanceof Set) {
|
|
2412
|
-
if (a.size !== b.size)
|
|
2413
|
-
return false;
|
|
2414
|
-
for (i of a.entries())
|
|
2415
|
-
if (!b.has(i[0]))
|
|
2416
|
-
return false;
|
|
2417
|
-
return true;
|
|
2418
|
-
}
|
|
2419
|
-
if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
|
|
2420
|
-
// @ts-ignore
|
|
2421
|
-
length = a.length;
|
|
2422
|
-
// @ts-ignore
|
|
2423
|
-
if (length != b.length)
|
|
2424
|
-
return false;
|
|
2425
|
-
for (i = length; i-- !== 0;) {
|
|
2426
|
-
// @ts-ignore
|
|
2427
|
-
if (a[i] !== b[i])
|
|
2428
|
-
return false;
|
|
2393
|
+
static optionBelowMinimum(name, value, min) {
|
|
2394
|
+
return `Config option "${name}" had invalid value of ${value}, using minimum of ${min} instead`;
|
|
2395
|
+
}
|
|
2396
|
+
static unknownOption(name) {
|
|
2397
|
+
return `Ignoring unknown config option "${name}"`;
|
|
2398
|
+
}
|
|
2399
|
+
static wrongOptionType(name, expectedType, actualType) {
|
|
2400
|
+
return `Config option "${name}" should be of type ${expectedType}, got ${actualType}, using default value`;
|
|
2401
|
+
}
|
|
2402
|
+
static wrongOptionTypeBoolean(name, actualType) {
|
|
2403
|
+
return `Config option "${name}" should be a boolean, got ${actualType}, converting to boolean`;
|
|
2404
|
+
}
|
|
2405
|
+
static invalidTagValue(name) {
|
|
2406
|
+
return `Config option "${name}" must only contain letters, numbers, ., _ or -.`;
|
|
2407
|
+
}
|
|
2408
|
+
static tagValueTooLong(name) {
|
|
2409
|
+
return `Value of "${name}" was longer than 64 characters and was discarded.`;
|
|
2410
|
+
}
|
|
2411
|
+
static partialEndpoint(name) {
|
|
2412
|
+
return `You have set custom uris without specifying the ${name} URI; connections may not work properly`;
|
|
2413
|
+
}
|
|
2414
|
+
}
|
|
2415
|
+
|
|
2416
|
+
/**
|
|
2417
|
+
* Expression to validate characters that are allowed in tag keys and values.
|
|
2418
|
+
*/
|
|
2419
|
+
const allowedTagCharacters = /^(\w|\.|-)+$/;
|
|
2420
|
+
const regexValidator = TypeValidators.stringMatchingRegex(allowedTagCharacters);
|
|
2421
|
+
const tagValidator = {
|
|
2422
|
+
is: (u, name) => {
|
|
2423
|
+
if (regexValidator.is(u)) {
|
|
2424
|
+
if (u.length > 64) {
|
|
2425
|
+
return { valid: false, message: OptionMessages.tagValueTooLong(name) };
|
|
2429
2426
|
}
|
|
2430
|
-
return true;
|
|
2427
|
+
return { valid: true };
|
|
2431
2428
|
}
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
|
|
2443
|
-
|
|
2444
|
-
|
|
2445
|
-
|
|
2446
|
-
|
|
2447
|
-
|
|
2448
|
-
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2429
|
+
return { valid: false, message: OptionMessages.invalidTagValue(name) };
|
|
2430
|
+
},
|
|
2431
|
+
};
|
|
2432
|
+
/**
|
|
2433
|
+
* Class for managing tags.
|
|
2434
|
+
*/
|
|
2435
|
+
class ApplicationTags {
|
|
2436
|
+
constructor(options) {
|
|
2437
|
+
const tags = {};
|
|
2438
|
+
const application = options?.application;
|
|
2439
|
+
const logger = options?.logger;
|
|
2440
|
+
if (application) {
|
|
2441
|
+
Object.entries(application).forEach(([key, value]) => {
|
|
2442
|
+
if (value !== null && value !== undefined) {
|
|
2443
|
+
const { valid, message } = tagValidator.is(value, `application.${key}`);
|
|
2444
|
+
if (!valid) {
|
|
2445
|
+
logger?.warn(message);
|
|
2446
|
+
}
|
|
2447
|
+
else if (key === 'versionName') {
|
|
2448
|
+
tags[`application-version-name`] = [value];
|
|
2449
|
+
}
|
|
2450
|
+
else {
|
|
2451
|
+
tags[`application-${key}`] = [value];
|
|
2452
|
+
}
|
|
2453
|
+
}
|
|
2454
|
+
});
|
|
2455
|
+
}
|
|
2456
|
+
const tagKeys = Object.keys(tags);
|
|
2457
|
+
if (tagKeys.length) {
|
|
2458
|
+
this.value = tagKeys
|
|
2459
|
+
.sort()
|
|
2460
|
+
.flatMap((key) => tags[key].sort().map((value) => `${key}/${value}`))
|
|
2461
|
+
.join(' ');
|
|
2458
2462
|
}
|
|
2459
|
-
return true;
|
|
2460
2463
|
}
|
|
2461
|
-
// true if both NaN, false otherwise
|
|
2462
|
-
return a !== a && b !== b;
|
|
2463
2464
|
}
|
|
2464
2465
|
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
}
|
|
2480
|
-
if (tags?.value) {
|
|
2481
|
-
headers['x-launchdarkly-tags'] = tags.value;
|
|
2482
|
-
}
|
|
2483
|
-
// Per SCMP-server-connection-minutes-polling (spec section 1.1), server SDKs include a
|
|
2484
|
-
// per-instance v4 GUID on every polling request. The caller (a server SDK) is responsible
|
|
2485
|
-
// for generating the GUID once per SDK instance and passing it here, so that it rides on
|
|
2486
|
-
// every outbound request via this shared default-headers map. Client/edge SDKs do not pass
|
|
2487
|
-
// this value, so the header is omitted for them.
|
|
2488
|
-
if (instanceId) {
|
|
2489
|
-
headers['x-launchdarkly-instance-id'] = instanceId;
|
|
2466
|
+
/**
|
|
2467
|
+
* The client context provides basic configuration and platform support which are required
|
|
2468
|
+
* when building SDK components.
|
|
2469
|
+
*/
|
|
2470
|
+
class ClientContext {
|
|
2471
|
+
constructor(sdkKey, configuration, platform) {
|
|
2472
|
+
this.platform = platform;
|
|
2473
|
+
this.basicConfiguration = {
|
|
2474
|
+
tags: configuration.tags,
|
|
2475
|
+
logger: configuration.logger,
|
|
2476
|
+
offline: configuration.offline,
|
|
2477
|
+
serviceEndpoints: configuration.serviceEndpoints,
|
|
2478
|
+
sdkKey,
|
|
2479
|
+
};
|
|
2490
2480
|
}
|
|
2491
|
-
return headers;
|
|
2492
2481
|
}
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
|
|
2482
|
+
|
|
2483
|
+
function canonicalizeUri(uri) {
|
|
2484
|
+
return uri.replace(/\/+$/, '');
|
|
2485
|
+
}
|
|
2486
|
+
function canonicalizePath(path) {
|
|
2487
|
+
return path.replace(/^\/+/, '').replace(/\?$/, '');
|
|
2488
|
+
}
|
|
2489
|
+
/**
|
|
2490
|
+
* Specifies the base service URIs used by SDK components.
|
|
2491
|
+
*/
|
|
2492
|
+
class ServiceEndpoints {
|
|
2493
|
+
constructor(streaming, polling, events = ServiceEndpoints.DEFAULT_EVENTS, analyticsEventPath = '/bulk', diagnosticEventPath = '/diagnostic', includeAuthorizationHeader = true, payloadFilterKey) {
|
|
2494
|
+
this.streaming = canonicalizeUri(streaming);
|
|
2495
|
+
this.polling = canonicalizeUri(polling);
|
|
2496
|
+
this.events = canonicalizeUri(events);
|
|
2497
|
+
this.analyticsEventPath = analyticsEventPath;
|
|
2498
|
+
this.diagnosticEventPath = diagnosticEventPath;
|
|
2499
|
+
this.includeAuthorizationHeader = includeAuthorizationHeader;
|
|
2500
|
+
this.payloadFilterKey = payloadFilterKey;
|
|
2497
2501
|
}
|
|
2498
|
-
|
|
2499
|
-
|
|
2502
|
+
}
|
|
2503
|
+
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
2504
|
+
ServiceEndpoints.DEFAULT_EVENTS = 'https://events.launchdarkly.com';
|
|
2505
|
+
function getWithParams(uri, parameters = []) {
|
|
2506
|
+
if (parameters.length === 0) {
|
|
2507
|
+
return uri;
|
|
2500
2508
|
}
|
|
2501
|
-
const
|
|
2502
|
-
return
|
|
2509
|
+
const parts = parameters.map(({ key, value }) => `${key}=${value}`);
|
|
2510
|
+
return `${uri}?${parts.join('&')}`;
|
|
2503
2511
|
}
|
|
2504
|
-
|
|
2505
|
-
|
|
2512
|
+
/**
|
|
2513
|
+
* Get the URI for the streaming endpoint.
|
|
2514
|
+
*
|
|
2515
|
+
* @param endpoints The service endpoints.
|
|
2516
|
+
* @param path The path to the resource, devoid of any query parameters or hrefs.
|
|
2517
|
+
* @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.
|
|
2518
|
+
*/
|
|
2519
|
+
function getStreamingUri(endpoints, path, parameters) {
|
|
2520
|
+
const canonicalizedPath = canonicalizePath(path);
|
|
2521
|
+
const combinedParameters = [...parameters];
|
|
2522
|
+
if (endpoints.payloadFilterKey) {
|
|
2523
|
+
combinedParameters.push({ key: 'filter', value: endpoints.payloadFilterKey });
|
|
2524
|
+
}
|
|
2525
|
+
return getWithParams(`${endpoints.streaming}/${canonicalizedPath}`, combinedParameters);
|
|
2506
2526
|
}
|
|
2507
2527
|
/**
|
|
2508
|
-
*
|
|
2509
|
-
* because the react-native repo uses it too. Set the global.btoa to the encode
|
|
2510
|
-
* function of base64-js.
|
|
2511
|
-
* https://github.com/beatgammit/base64-js
|
|
2512
|
-
* https://github.com/axios/axios/issues/2235#issuecomment-512204616
|
|
2528
|
+
* Get the URI for the polling endpoint.
|
|
2513
2529
|
*
|
|
2514
|
-
*
|
|
2530
|
+
* @param endpoints The service endpoints.
|
|
2531
|
+
* @param path The path to the resource, devoid of any query parameters or hrefs.
|
|
2532
|
+
* @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.
|
|
2515
2533
|
*/
|
|
2516
|
-
|
|
2517
|
-
|
|
2518
|
-
|
|
2519
|
-
|
|
2520
|
-
|
|
2521
|
-
|
|
2522
|
-
});
|
|
2523
|
-
|
|
2534
|
+
function getPollingUri(endpoints, path, parameters = []) {
|
|
2535
|
+
const canonicalizedPath = canonicalizePath(path);
|
|
2536
|
+
const combinedParameters = [...parameters];
|
|
2537
|
+
if (endpoints.payloadFilterKey) {
|
|
2538
|
+
combinedParameters.push({ key: 'filter', value: endpoints.payloadFilterKey });
|
|
2539
|
+
}
|
|
2540
|
+
return getWithParams(`${endpoints.polling}/${canonicalizedPath}`, combinedParameters);
|
|
2541
|
+
}
|
|
2524
2542
|
/**
|
|
2525
|
-
*
|
|
2543
|
+
* Get the URI for the events endpoint.
|
|
2526
2544
|
*
|
|
2527
|
-
* @param
|
|
2528
|
-
* @param
|
|
2545
|
+
* @param endpoints The service endpoints.
|
|
2546
|
+
* @param path The path to the resource, devoid of any query parameters or hrefs.
|
|
2547
|
+
* @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.
|
|
2529
2548
|
*/
|
|
2530
|
-
|
|
2531
|
-
|
|
2532
|
-
|
|
2533
|
-
|
|
2534
|
-
}, t * 1000);
|
|
2535
|
-
});
|
|
2549
|
+
function getEventsUri(endpoints, path, parameters = []) {
|
|
2550
|
+
const canonicalizedPath = canonicalizePath(path);
|
|
2551
|
+
return getWithParams(`${endpoints.events}/${canonicalizedPath}`, parameters);
|
|
2552
|
+
}
|
|
2536
2553
|
|
|
2537
2554
|
class DiagnosticsManager {
|
|
2538
2555
|
constructor(sdkKey, _platform, _diagnosticInitConfig) {
|
|
@@ -3642,6 +3659,136 @@ class PayloadStreamReader {
|
|
|
3642
3659
|
}
|
|
3643
3660
|
}
|
|
3644
3661
|
|
|
3662
|
+
/**
|
|
3663
|
+
* Wraps the raw headers in the fetch `Headers` shape. Lookups are case-insensitive.
|
|
3664
|
+
* Multi-value headers are joined with ", ", names that differ only by case merge into one
|
|
3665
|
+
* joined value, and names without a value are skipped.
|
|
3666
|
+
*/
|
|
3667
|
+
function wrapRawHeaders(headers) {
|
|
3668
|
+
const normalized = new Map();
|
|
3669
|
+
Object.keys(headers).forEach((key) => {
|
|
3670
|
+
const val = headers[key];
|
|
3671
|
+
if (val !== undefined && val !== null) {
|
|
3672
|
+
const name = key.toLowerCase();
|
|
3673
|
+
const joined = Array.isArray(val) ? val.join(', ') : val;
|
|
3674
|
+
const existing = normalized.get(name);
|
|
3675
|
+
normalized.set(name, existing === undefined ? joined : `${existing}, ${joined}`);
|
|
3676
|
+
}
|
|
3677
|
+
});
|
|
3678
|
+
return {
|
|
3679
|
+
get: (name) => normalized.get(name.toLowerCase()) ?? null,
|
|
3680
|
+
keys: () => normalized.keys(),
|
|
3681
|
+
values: () => normalized.values(),
|
|
3682
|
+
entries: () => normalized.entries(),
|
|
3683
|
+
forEach: (callback) => {
|
|
3684
|
+
normalized.forEach((value, key) => callback(value, key));
|
|
3685
|
+
},
|
|
3686
|
+
has: (name) => normalized.has(name.toLowerCase()),
|
|
3687
|
+
};
|
|
3688
|
+
}
|
|
3689
|
+
/**
|
|
3690
|
+
* Creates a response for a streaming request. The response does not buffer the body. Each
|
|
3691
|
+
* read hands out the next chunk from the source iterator. The body does not enforce a
|
|
3692
|
+
* consumer lock: every `getReader`, `text`, and `json` call reads from the same iterator,
|
|
3693
|
+
* so the caller uses one consumer per response. The `cancel` methods on the body and the
|
|
3694
|
+
* reader call every release function the source provides: they destroy the source when it
|
|
3695
|
+
* has a `destroy` method, and they also call the iterator's `return` method when one
|
|
3696
|
+
* exists. The body passes through as-is, so the caller decodes any content encoding first.
|
|
3697
|
+
*
|
|
3698
|
+
* @param source The raw platform response, for example a Node `IncomingMessage`. A missing
|
|
3699
|
+
* status code maps to 0, and a missing status message maps to an empty string.
|
|
3700
|
+
*/
|
|
3701
|
+
function createStreamingResponse(source) {
|
|
3702
|
+
// A consumer compiled without `Symbol.asyncIterator` in its lib can pass a source that
|
|
3703
|
+
// lacks the iterator without a compile error. The check turns that mistake into a named
|
|
3704
|
+
// failure instead of a bare member-access TypeError.
|
|
3705
|
+
if (typeof source[Symbol.asyncIterator] !== 'function') {
|
|
3706
|
+
throw new TypeError('the streaming response source does not provide an async iterator');
|
|
3707
|
+
}
|
|
3708
|
+
const iterator = source[Symbol.asyncIterator]();
|
|
3709
|
+
const cancel = async () => {
|
|
3710
|
+
// Destroy the stream first. That rejects a pending read and unblocks a queued return
|
|
3711
|
+
// call. A Node readable iterator queues the return call behind a pending read, and on
|
|
3712
|
+
// a stream that was never read it completes without a destroy, so the return call
|
|
3713
|
+
// alone cannot release the connection. Do not await it for the same reason. Each
|
|
3714
|
+
// release call is guarded on its own, so a release function that throws, or a return
|
|
3715
|
+
// that resolves synchronously, does not skip the other release path or reject cancel.
|
|
3716
|
+
try {
|
|
3717
|
+
source.destroy?.();
|
|
3718
|
+
}
|
|
3719
|
+
catch {
|
|
3720
|
+
// A throwing destroy has nothing left to release.
|
|
3721
|
+
}
|
|
3722
|
+
try {
|
|
3723
|
+
Promise.resolve(iterator.return?.()).catch(() => { });
|
|
3724
|
+
}
|
|
3725
|
+
catch {
|
|
3726
|
+
// A throwing return has nothing left to release.
|
|
3727
|
+
}
|
|
3728
|
+
};
|
|
3729
|
+
async function text() {
|
|
3730
|
+
const decoder = new TextDecoder();
|
|
3731
|
+
let result = '';
|
|
3732
|
+
try {
|
|
3733
|
+
let next = await iterator.next();
|
|
3734
|
+
while (!next.done) {
|
|
3735
|
+
if (next.value !== undefined) {
|
|
3736
|
+
try {
|
|
3737
|
+
result += decoder.decode(next.value, { stream: true });
|
|
3738
|
+
}
|
|
3739
|
+
catch {
|
|
3740
|
+
// decode() rejects a chunk that is not a BufferSource. The fixed message keeps
|
|
3741
|
+
// chunk contents out of error messages.
|
|
3742
|
+
throw new TypeError('the source supplied a chunk that is not a BufferSource');
|
|
3743
|
+
}
|
|
3744
|
+
}
|
|
3745
|
+
// The stream provides the chunks in sequence, so the reads cannot run in parallel.
|
|
3746
|
+
// oxlint-disable-next-line no-await-in-loop
|
|
3747
|
+
next = await iterator.next();
|
|
3748
|
+
}
|
|
3749
|
+
}
|
|
3750
|
+
catch (err) {
|
|
3751
|
+
// text() owns the body, so any failed read must release the source itself. This
|
|
3752
|
+
// covers a rejecting next() as well as a bad chunk.
|
|
3753
|
+
cancel();
|
|
3754
|
+
throw err;
|
|
3755
|
+
}
|
|
3756
|
+
// The final decode flushes a trailing partial multi-byte sequence.
|
|
3757
|
+
return result + decoder.decode();
|
|
3758
|
+
}
|
|
3759
|
+
return {
|
|
3760
|
+
headers: wrapRawHeaders(source.headers),
|
|
3761
|
+
status: source.statusCode ?? 0,
|
|
3762
|
+
statusText: source.statusMessage ?? '',
|
|
3763
|
+
body: {
|
|
3764
|
+
getReader: () => ({
|
|
3765
|
+
read: async () => {
|
|
3766
|
+
const next = await iterator.next();
|
|
3767
|
+
if (next.done) {
|
|
3768
|
+
return { done: true };
|
|
3769
|
+
}
|
|
3770
|
+
return { done: false, value: next.value };
|
|
3771
|
+
},
|
|
3772
|
+
cancel,
|
|
3773
|
+
}),
|
|
3774
|
+
cancel,
|
|
3775
|
+
},
|
|
3776
|
+
text,
|
|
3777
|
+
json: async () => JSON.parse(await text()),
|
|
3778
|
+
};
|
|
3779
|
+
}
|
|
3780
|
+
|
|
3781
|
+
/**
|
|
3782
|
+
* Converts the request options into the init shape a platform's native `fetch` accepts. A
|
|
3783
|
+
* platform can declare its `AbortSignal` as a lexical class, which `AbortSignalLike`
|
|
3784
|
+
* cannot resolve to, so the `signal` member widens here. The caller must pass a signal
|
|
3785
|
+
* created by the running platform. The widening then only restores the type the runtime
|
|
3786
|
+
* already has.
|
|
3787
|
+
*/
|
|
3788
|
+
function toRequestInit(options) {
|
|
3789
|
+
return options;
|
|
3790
|
+
}
|
|
3791
|
+
|
|
3645
3792
|
/**
|
|
3646
3793
|
* Creates an InitMetadata object from initialization headers.
|
|
3647
3794
|
*
|
|
@@ -3717,6 +3864,7 @@ var index = /*#__PURE__*/Object.freeze({
|
|
|
3717
3864
|
PayloadStreamReader: PayloadStreamReader,
|
|
3718
3865
|
canonicalize: canonicalize,
|
|
3719
3866
|
createProtocolHandler: createProtocolHandler,
|
|
3867
|
+
createStreamingResponse: createStreamingResponse,
|
|
3720
3868
|
initMetadataFromHeaders: initMetadataFromHeaders,
|
|
3721
3869
|
isLegacyUser: isLegacyUser,
|
|
3722
3870
|
isMultiKind: isMultiKind,
|
|
@@ -3726,8 +3874,9 @@ var index = /*#__PURE__*/Object.freeze({
|
|
|
3726
3874
|
safeGetHooks: safeGetHooks,
|
|
3727
3875
|
safeGetName: safeGetName,
|
|
3728
3876
|
safeRegisterPlugins: safeRegisterPlugins,
|
|
3729
|
-
shouldSample: shouldSample
|
|
3877
|
+
shouldSample: shouldSample,
|
|
3878
|
+
toRequestInit: toRequestInit
|
|
3730
3879
|
});
|
|
3731
3880
|
|
|
3732
|
-
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 };
|
|
3881
|
+
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, monotonicNow, noop, secondsToMillis, shouldRetry, sleep, index$1 as subsystem, timedPromise };
|
|
3733
3882
|
//# sourceMappingURL=index.mjs.map
|