@lifi/sdk 0.0.0-preview-dd8065ff → 0.0.0-preview-1b774eec
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 +55 -2
- package/README.md +9 -0
- package/dist/cjs/actions/getChains.js +7 -1
- package/dist/cjs/actions/getChains.js.map +1 -1
- package/dist/cjs/actions/getContractCallsQuote.js +1 -1
- package/dist/cjs/actions/getGasRecommendation.js +1 -1
- package/dist/cjs/actions/getQuote.js +1 -1
- package/dist/cjs/actions/getRelayedTransactionStatus.js +1 -1
- package/dist/cjs/actions/getRelayerQuote.js +1 -1
- package/dist/cjs/actions/getRoutes.js +1 -1
- package/dist/cjs/actions/getStatus.js +1 -1
- package/dist/cjs/actions/getToken.js +1 -1
- package/dist/cjs/actions/getTokens.js +7 -1
- package/dist/cjs/actions/getTokens.js.map +1 -1
- package/dist/cjs/actions/relayTransaction.js +1 -1
- package/dist/cjs/client/createClient.js +33 -10
- package/dist/cjs/client/createClient.js.map +1 -1
- package/dist/cjs/client/findProvider.d.ts +10 -0
- package/dist/cjs/client/findProvider.js +11 -0
- package/dist/cjs/client/findProvider.js.map +1 -0
- package/dist/cjs/core/tasks/helpers/checkBalance.js +6 -3
- package/dist/cjs/core/tasks/helpers/checkBalance.js.map +1 -1
- package/dist/cjs/index.d.ts +5 -3
- package/dist/cjs/index.js +6 -3
- package/dist/cjs/types/core.d.ts +62 -2
- package/dist/cjs/utils/abort.d.ts +6 -0
- package/dist/cjs/utils/abort.js +10 -0
- package/dist/cjs/utils/abort.js.map +1 -0
- package/dist/cjs/utils/checkPackageUpdates.js +1 -1
- package/dist/cjs/utils/convertQuoteToRoute.js +1 -1
- package/dist/cjs/utils/formatUnits.js +1 -0
- package/dist/cjs/utils/formatUnits.js.map +1 -1
- package/dist/cjs/utils/lru.d.ts +14 -0
- package/dist/cjs/utils/lru.js +35 -0
- package/dist/cjs/utils/lru.js.map +1 -0
- package/dist/cjs/utils/parseUnits.js +30 -16
- package/dist/cjs/utils/parseUnits.js.map +1 -1
- package/dist/cjs/utils/request.js +2 -2
- package/dist/cjs/utils/sleep.d.ts +7 -1
- package/dist/cjs/utils/sleep.js +22 -3
- package/dist/cjs/utils/sleep.js.map +1 -1
- package/dist/cjs/utils/waitForResult.d.ts +4 -4
- package/dist/cjs/utils/waitForResult.js +4 -4
- package/dist/cjs/utils/waitForResult.js.map +1 -1
- package/dist/cjs/utils/withDedupe.d.ts +15 -12
- package/dist/cjs/utils/withDedupe.js +69 -25
- package/dist/cjs/utils/withDedupe.js.map +1 -1
- package/dist/cjs/utils/withTimeout.js +6 -2
- package/dist/cjs/utils/withTimeout.js.map +1 -1
- package/dist/cjs/version.d.ts +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/cjs/version.js.map +1 -1
- package/dist/esm/actions/getChains.d.ts.map +1 -1
- package/dist/esm/actions/getChains.js +7 -1
- package/dist/esm/actions/getChains.js.map +1 -1
- package/dist/esm/actions/getContractCallsQuote.js +1 -1
- package/dist/esm/actions/getGasRecommendation.js +1 -1
- package/dist/esm/actions/getQuote.js +1 -1
- package/dist/esm/actions/getRelayedTransactionStatus.js +1 -1
- package/dist/esm/actions/getRelayerQuote.js +1 -1
- package/dist/esm/actions/getRoutes.d.ts.map +1 -1
- package/dist/esm/actions/getRoutes.js +1 -1
- package/dist/esm/actions/getStatus.js +1 -1
- package/dist/esm/actions/getToken.js +1 -1
- package/dist/esm/actions/getTokens.d.ts.map +1 -1
- package/dist/esm/actions/getTokens.js +7 -1
- package/dist/esm/actions/getTokens.js.map +1 -1
- package/dist/esm/actions/index.d.ts.map +1 -1
- package/dist/esm/actions/relayTransaction.js +1 -1
- package/dist/esm/client/createClient.d.ts.map +1 -1
- package/dist/esm/client/createClient.js +33 -10
- package/dist/esm/client/createClient.js.map +1 -1
- package/dist/esm/client/findProvider.d.ts +10 -0
- package/dist/esm/client/findProvider.d.ts.map +1 -0
- package/dist/esm/client/findProvider.js +10 -0
- package/dist/esm/client/findProvider.js.map +1 -0
- package/dist/esm/core/tasks/helpers/checkBalance.js +6 -3
- package/dist/esm/core/tasks/helpers/checkBalance.js.map +1 -1
- package/dist/esm/index.d.ts +5 -3
- package/dist/esm/index.js +6 -4
- package/dist/esm/types/actions.d.ts.map +1 -1
- package/dist/esm/types/core.d.ts +62 -2
- package/dist/esm/types/core.d.ts.map +1 -1
- package/dist/esm/utils/abort.d.ts +6 -0
- package/dist/esm/utils/abort.d.ts.map +1 -0
- package/dist/esm/utils/abort.js +8 -0
- package/dist/esm/utils/abort.js.map +1 -0
- package/dist/esm/utils/checkPackageUpdates.js +1 -1
- package/dist/esm/utils/convertQuoteToRoute.js +1 -1
- package/dist/esm/utils/formatUnits.js +1 -0
- package/dist/esm/utils/formatUnits.js.map +1 -1
- package/dist/esm/utils/lru.d.ts +14 -0
- package/dist/esm/utils/lru.d.ts.map +1 -0
- package/dist/esm/utils/lru.js +34 -0
- package/dist/esm/utils/lru.js.map +1 -0
- package/dist/esm/utils/parseUnits.js +30 -16
- package/dist/esm/utils/parseUnits.js.map +1 -1
- package/dist/esm/utils/request.js +2 -2
- package/dist/esm/utils/sleep.d.ts +7 -1
- package/dist/esm/utils/sleep.d.ts.map +1 -1
- package/dist/esm/utils/sleep.js +22 -3
- package/dist/esm/utils/sleep.js.map +1 -1
- package/dist/esm/utils/waitForResult.d.ts +4 -4
- package/dist/esm/utils/waitForResult.js +4 -4
- package/dist/esm/utils/waitForResult.js.map +1 -1
- package/dist/esm/utils/withDedupe.d.ts +15 -12
- package/dist/esm/utils/withDedupe.d.ts.map +1 -1
- package/dist/esm/utils/withDedupe.js +71 -25
- package/dist/esm/utils/withDedupe.js.map +1 -1
- package/dist/esm/utils/withTimeout.d.ts.map +1 -1
- package/dist/esm/utils/withTimeout.js +6 -2
- package/dist/esm/utils/withTimeout.js.map +1 -1
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/dist/esm/version.js.map +1 -1
- package/package.json +2 -2
- package/src/actions/getChains.ts +12 -4
- package/src/actions/getTokens.ts +12 -4
- package/src/client/createClient.ts +59 -7
- package/src/client/findProvider.ts +21 -0
- package/src/core/tasks/helpers/checkBalance.ts +11 -3
- package/src/index.ts +5 -1
- package/src/types/core.ts +65 -2
- package/src/utils/abort.ts +10 -0
- package/src/utils/formatUnits.ts +6 -0
- package/src/utils/lru.ts +38 -0
- package/src/utils/parseUnits.ts +53 -20
- package/src/utils/sleep.ts +27 -3
- package/src/utils/waitForResult.ts +4 -4
- package/src/utils/withDedupe.ts +121 -27
- package/src/utils/withTimeout.ts +7 -2
- package/src/version.ts +1 -1
package/dist/cjs/types/core.d.ts
CHANGED
|
@@ -19,13 +19,59 @@ export interface SDKBaseConfig {
|
|
|
19
19
|
requestInterceptor?: RequestInterceptor;
|
|
20
20
|
storage?: SDKStorage;
|
|
21
21
|
}
|
|
22
|
-
export interface SDKConfig extends Partial<Omit<SDKBaseConfig, "integrator">> {
|
|
22
|
+
export interface SDKConfig extends Partial<Omit<SDKBaseConfig, "integrator" | "rpcUrls">> {
|
|
23
23
|
integrator: string;
|
|
24
|
+
/**
|
|
25
|
+
* Per chain, one list for reads and sends, or lists by role. The client
|
|
26
|
+
* keeps the read lists in `config.rpcUrls` and serves the write and bundle
|
|
27
|
+
* lists through `getWriteRpcUrlsByChainId` and `getBundleRpcUrlsByChainId`.
|
|
28
|
+
*/
|
|
29
|
+
rpcUrls?: RPCUrlsConfig;
|
|
24
30
|
providers?: SDKProvider[];
|
|
25
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* RPC URLs for one chain, split by what they are used for.
|
|
34
|
+
*/
|
|
35
|
+
export interface RPCUrlsByRole {
|
|
36
|
+
/**
|
|
37
|
+
* Reads: balances, simulation and confirmation. Unset, the chain's own RPC
|
|
38
|
+
* URLs serve reads, as for a chain with no `rpcUrls` entry.
|
|
39
|
+
*/
|
|
40
|
+
read?: string[];
|
|
41
|
+
/**
|
|
42
|
+
* Sends. Unset or empty, the read URLs send as well. While `write` is set,
|
|
43
|
+
* nothing is sent through the read URLs: when `bundle` is unset, the write
|
|
44
|
+
* URLs that support bundles also submit bundles, and with none of them, a
|
|
45
|
+
* route that needs a bundle fails.
|
|
46
|
+
*
|
|
47
|
+
* Only `@lifi/sdk-provider-solana` uses this today; other providers ignore
|
|
48
|
+
* it.
|
|
49
|
+
*/
|
|
50
|
+
write?: string[];
|
|
51
|
+
/**
|
|
52
|
+
* Bundle submissions (Jito `sendBundle`). Unset, empty, or with no URL that
|
|
53
|
+
* supports bundles, the write URLs that do submit them. While `bundle` or
|
|
54
|
+
* `write` is set, bundles never go to the read URLs.
|
|
55
|
+
*
|
|
56
|
+
* Only `@lifi/sdk-provider-solana` uses this today; other providers ignore
|
|
57
|
+
* it.
|
|
58
|
+
*/
|
|
59
|
+
bundle?: string[];
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The `rpcUrls` option of `createClient`: per chain, either one list for reads
|
|
63
|
+
* and sends, or lists by role.
|
|
64
|
+
*/
|
|
65
|
+
export type RPCUrlsConfig = Partial<Record<ChainId, string[] | RPCUrlsByRole>>;
|
|
66
|
+
/** RPC URL lists per chain. `client.config.rpcUrls` holds the read lists. */
|
|
26
67
|
export type RPCUrls = Partial<Record<ChainId, string[]>>;
|
|
27
68
|
export interface SDKProvider {
|
|
28
69
|
readonly type: ChainType;
|
|
70
|
+
/**
|
|
71
|
+
* The chains this provider serves. Omit it to serve every chain of `type`
|
|
72
|
+
* that no other provider lists.
|
|
73
|
+
*/
|
|
74
|
+
readonly chainIds?: readonly ChainId[];
|
|
29
75
|
/**
|
|
30
76
|
* Validates a wallet address. With `chainId`, a provider whose chains use
|
|
31
77
|
* different address formats accepts only that chain's format and refuses a
|
|
@@ -46,13 +92,27 @@ export interface SDKProvider {
|
|
|
46
92
|
export interface SDKClient {
|
|
47
93
|
config: SDKBaseConfig;
|
|
48
94
|
providers: SDKProvider[];
|
|
49
|
-
getProvider(type: ChainType): SDKProvider | undefined;
|
|
95
|
+
getProvider(type: ChainType, chainId?: ChainId): SDKProvider | undefined;
|
|
50
96
|
setProviders(providers: SDKProvider[]): void;
|
|
51
97
|
setChains(chains: ExtendedChain[]): void;
|
|
52
98
|
getChains(): Promise<ExtendedChain[]>;
|
|
53
99
|
getChainById(chainId: ChainId): Promise<ExtendedChain>;
|
|
54
100
|
getRpcUrls(): Promise<RPCUrls>;
|
|
55
101
|
getRpcUrlsByChainId(chainId: ChainId): Promise<string[]>;
|
|
102
|
+
/**
|
|
103
|
+
* The chain's dedicated write RPC URLs (`rpcUrls[chainId].write`). Empty
|
|
104
|
+
* when the chain has none.
|
|
105
|
+
*
|
|
106
|
+
* Optional so clients from other SDK versions, and hand-written ones, still
|
|
107
|
+
* satisfy `SDKClient`. Providers treat a missing method as no write list.
|
|
108
|
+
*/
|
|
109
|
+
getWriteRpcUrlsByChainId?(chainId: ChainId): Promise<string[]>;
|
|
110
|
+
/**
|
|
111
|
+
* The chain's dedicated bundle RPC URLs (`rpcUrls[chainId].bundle`). Empty
|
|
112
|
+
* when the chain has none. Optional for the same reason as
|
|
113
|
+
* `getWriteRpcUrlsByChainId`.
|
|
114
|
+
*/
|
|
115
|
+
getBundleRpcUrlsByChainId?(chainId: ChainId): Promise<string[]>;
|
|
56
116
|
}
|
|
57
117
|
export interface StepExecutorOptions {
|
|
58
118
|
routeId: string;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
//#region src/utils/abort.d.ts
|
|
2
|
+
/** Older runtimes and polyfills can abort a signal without a `reason`. */
|
|
3
|
+
export declare const getAbortError: (signal: AbortSignal) => unknown;
|
|
4
|
+
export declare const isAbortError: (error: unknown) => boolean;
|
|
5
|
+
//#endregion
|
|
6
|
+
//# sourceMappingURL=abort.d.ts.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
//#region src/utils/abort.ts
|
|
3
|
+
/** Older runtimes and polyfills can abort a signal without a `reason`. */
|
|
4
|
+
const getAbortError = (signal) => signal.reason ?? Object.assign(/* @__PURE__ */ new Error("This operation was aborted"), { name: "AbortError" });
|
|
5
|
+
const isAbortError = (error) => typeof error === "object" && error !== null && "name" in error && error.name === "AbortError";
|
|
6
|
+
//#endregion
|
|
7
|
+
exports.getAbortError = getAbortError;
|
|
8
|
+
exports.isAbortError = isAbortError;
|
|
9
|
+
|
|
10
|
+
//# sourceMappingURL=abort.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"abort.js","names":[],"sources":["../../../src/utils/abort.ts"],"sourcesContent":["/** Older runtimes and polyfills can abort a signal without a `reason`. */\nexport const getAbortError = (signal: AbortSignal): unknown =>\n signal.reason ??\n Object.assign(new Error('This operation was aborted'), { name: 'AbortError' })\n\nexport const isAbortError = (error: unknown): boolean =>\n typeof error === 'object' &&\n error !== null &&\n 'name' in error &&\n error.name === 'AbortError'\n"],"mappings":";;;AACA,MAAa,iBAAiB,WAC5B,OAAO,UACP,OAAO,uBAAO,IAAI,MAAM,4BAA4B,GAAG,EAAE,MAAM,aAAa,CAAC;AAE/E,MAAa,gBAAgB,UAC3B,OAAO,UAAU,YACjB,UAAU,QACV,UAAU,SACV,MAAM,SAAS"}
|
|
@@ -5,7 +5,7 @@ const checkPackageUpdates = async (packageName, packageVersion) => {
|
|
|
5
5
|
try {
|
|
6
6
|
const pkgName = packageName ?? "@lifi/sdk";
|
|
7
7
|
const latestVersion = (await (await fetch(`https://registry.npmjs.org/${pkgName}/latest`)).json()).version;
|
|
8
|
-
const currentVersion = packageVersion ?? "0.0.0-preview-
|
|
8
|
+
const currentVersion = packageVersion ?? "0.0.0-preview-1b774eec";
|
|
9
9
|
if (latestVersion > currentVersion) console.warn(`${pkgName}: new package version is available. Please update as soon as possible to enjoy the newest features. Current version: ${currentVersion}. Latest version: ${latestVersion}.`);
|
|
10
10
|
} catch (_error) {}
|
|
11
11
|
};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_errors_errors = require("../errors/errors.js");
|
|
3
2
|
const require_errors_SDKError = require("../errors/SDKError.js");
|
|
3
|
+
const require_errors_errors = require("../errors/errors.js");
|
|
4
4
|
const require_utils_formatUnits = require("./formatUnits.js");
|
|
5
5
|
//#region src/utils/convertQuoteToRoute.ts
|
|
6
6
|
const parseBigInt = (value) => {
|
|
@@ -4,6 +4,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
4
4
|
* Divides a number by a given exponent of base 10 (10exponent), and formats it into a string representation of the number.
|
|
5
5
|
*/
|
|
6
6
|
function formatUnits(value, decimals) {
|
|
7
|
+
if (!Number.isInteger(decimals) || decimals < 0) throw new Error(`\`decimals\` must be a non-negative integer. Got \`${decimals}\`.`);
|
|
7
8
|
let display = value.toString();
|
|
8
9
|
const negative = display.startsWith("-");
|
|
9
10
|
if (negative) display = display.slice(1);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"formatUnits.js","names":[],"sources":["../../../src/utils/formatUnits.ts"],"sourcesContent":["/**\n * Divides a number by a given exponent of base 10 (10exponent), and formats it into a string representation of the number.\n */\nexport function formatUnits(value: bigint, decimals: number): string {\n let display = value.toString()\n\n const negative = display.startsWith('-')\n if (negative) {\n display = display.slice(1)\n }\n\n display = display.padStart(decimals, '0')\n\n let [integer, fraction] = [\n display.slice(0, display.length - decimals),\n display.slice(display.length - decimals),\n ]\n fraction = fraction.replace(/(0+)$/, '')\n return `${negative ? '-' : ''}${integer || '0'}${\n fraction ? `.${fraction}` : ''\n }`\n}\n"],"mappings":";;;;;AAGA,SAAgB,YAAY,OAAe,UAA0B;CACnE,IAAI,UAAU,MAAM,SAAS;CAE7B,MAAM,WAAW,QAAQ,WAAW,GAAG;CACvC,IAAI,UACF,UAAU,QAAQ,MAAM,CAAC;CAG3B,UAAU,QAAQ,SAAS,UAAU,GAAG;CAExC,IAAI,CAAC,SAAS,YAAY,CACxB,QAAQ,MAAM,GAAG,QAAQ,SAAS,QAAQ,GAC1C,QAAQ,MAAM,QAAQ,SAAS,QAAQ,CACzC;CACA,WAAW,SAAS,QAAQ,SAAS,EAAE;CACvC,OAAO,GAAG,WAAW,MAAM,KAAK,WAAW,MACzC,WAAW,IAAI,aAAa;AAEhC"}
|
|
1
|
+
{"version":3,"file":"formatUnits.js","names":[],"sources":["../../../src/utils/formatUnits.ts"],"sourcesContent":["/**\n * Divides a number by a given exponent of base 10 (10exponent), and formats it into a string representation of the number.\n */\nexport function formatUnits(value: bigint, decimals: number): string {\n if (!Number.isInteger(decimals) || decimals < 0) {\n throw new Error(\n `\\`decimals\\` must be a non-negative integer. Got \\`${decimals}\\`.`\n )\n }\n\n let display = value.toString()\n\n const negative = display.startsWith('-')\n if (negative) {\n display = display.slice(1)\n }\n\n display = display.padStart(decimals, '0')\n\n let [integer, fraction] = [\n display.slice(0, display.length - decimals),\n display.slice(display.length - decimals),\n ]\n fraction = fraction.replace(/(0+)$/, '')\n return `${negative ? '-' : ''}${integer || '0'}${\n fraction ? `.${fraction}` : ''\n }`\n}\n"],"mappings":";;;;;AAGA,SAAgB,YAAY,OAAe,UAA0B;CACnE,IAAI,CAAC,OAAO,UAAU,QAAQ,KAAK,WAAW,GAC5C,MAAM,IAAI,MACR,sDAAsD,SAAS,IACjE;CAGF,IAAI,UAAU,MAAM,SAAS;CAE7B,MAAM,WAAW,QAAQ,WAAW,GAAG;CACvC,IAAI,UACF,UAAU,QAAQ,MAAM,CAAC;CAG3B,UAAU,QAAQ,SAAS,UAAU,GAAG;CAExC,IAAI,CAAC,SAAS,YAAY,CACxB,QAAQ,MAAM,GAAG,QAAQ,SAAS,QAAQ,GAC1C,QAAQ,MAAM,QAAQ,SAAS,QAAQ,CACzC;CACA,WAAW,SAAS,QAAQ,SAAS,EAAE;CACvC,OAAO,GAAG,WAAW,MAAM,KAAK,WAAW,MACzC,WAAW,IAAI,aAAa;AAEhC"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
//#region src/utils/lru.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Map with a LRU (Least recently used) policy.
|
|
4
|
+
*
|
|
5
|
+
* https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU
|
|
6
|
+
*/
|
|
7
|
+
export declare class LruMap<value = unknown> extends Map<string, value> {
|
|
8
|
+
maxSize: number;
|
|
9
|
+
constructor(size: number);
|
|
10
|
+
override get(key: string): value | undefined;
|
|
11
|
+
override set(key: string, value: value): this;
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
14
|
+
//# sourceMappingURL=lru.d.ts.map
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
//#region src/utils/lru.ts
|
|
3
|
+
/**
|
|
4
|
+
* Map with a LRU (Least recently used) policy.
|
|
5
|
+
*
|
|
6
|
+
* https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU
|
|
7
|
+
*/
|
|
8
|
+
var LruMap = class extends Map {
|
|
9
|
+
maxSize;
|
|
10
|
+
constructor(size) {
|
|
11
|
+
super();
|
|
12
|
+
this.maxSize = size;
|
|
13
|
+
}
|
|
14
|
+
get(key) {
|
|
15
|
+
const value = super.get(key);
|
|
16
|
+
if (super.has(key)) {
|
|
17
|
+
super.delete(key);
|
|
18
|
+
super.set(key, value);
|
|
19
|
+
}
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
set(key, value) {
|
|
23
|
+
if (super.has(key)) super.delete(key);
|
|
24
|
+
super.set(key, value);
|
|
25
|
+
if (this.maxSize && this.size > this.maxSize) {
|
|
26
|
+
const firstKey = super.keys().next().value;
|
|
27
|
+
if (firstKey !== void 0) super.delete(firstKey);
|
|
28
|
+
}
|
|
29
|
+
return this;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
//#endregion
|
|
33
|
+
exports.LruMap = LruMap;
|
|
34
|
+
|
|
35
|
+
//# sourceMappingURL=lru.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lru.js","names":[],"sources":["../../../src/utils/lru.ts"],"sourcesContent":["/**\n * Map with a LRU (Least recently used) policy.\n *\n * https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n */\nexport class LruMap<value = unknown> extends Map<string, value> {\n maxSize: number\n\n constructor(size: number) {\n super()\n this.maxSize = size\n }\n\n override get(key: string): value | undefined {\n const value = super.get(key)\n if (super.has(key)) {\n super.delete(key)\n super.set(key, value as value)\n }\n return value\n }\n\n override set(key: string, value: value): this {\n if (super.has(key)) {\n super.delete(key)\n }\n super.set(key, value)\n if (this.maxSize && this.size > this.maxSize) {\n // `super.keys()`, not `this.keys()`: on iOS 18 the subclass iterator\n // can yield `undefined`, and the map then grows without limit.\n const firstKey = super.keys().next().value\n if (firstKey !== undefined) {\n super.delete(firstKey)\n }\n }\n return this\n }\n}\n"],"mappings":";;;;;;;AAKA,IAAa,SAAb,cAA6C,IAAmB;CAC9D;CAEA,YAAY,MAAc;EACxB,MAAM;EACN,KAAK,UAAU;CACjB;CAEA,IAAa,KAAgC;EAC3C,MAAM,QAAQ,MAAM,IAAI,GAAG;EAC3B,IAAI,MAAM,IAAI,GAAG,GAAG;GAClB,MAAM,OAAO,GAAG;GAChB,MAAM,IAAI,KAAK,KAAc;EAC/B;EACA,OAAO;CACT;CAEA,IAAa,KAAa,OAAoB;EAC5C,IAAI,MAAM,IAAI,GAAG,GACf,MAAM,OAAO,GAAG;EAElB,MAAM,IAAI,KAAK,KAAK;EACpB,IAAI,KAAK,WAAW,KAAK,OAAO,KAAK,SAAS;GAG5C,MAAM,WAAW,MAAM,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;GACrC,IAAI,aAAa,KAAA,GACf,MAAM,OAAO,QAAQ;EAEzB;EACA,OAAO;CACT;AACF"}
|
|
@@ -4,31 +4,45 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
4
4
|
* Multiplies a string representation of a number by a given exponent of base 10 (10exponent).
|
|
5
5
|
*/
|
|
6
6
|
function parseUnits(value, decimals) {
|
|
7
|
-
if (
|
|
8
|
-
|
|
7
|
+
if (!Number.isInteger(decimals) || decimals < 0) throw new Error(`\`decimals\` must be a non-negative integer. Got \`${decimals}\`.`);
|
|
8
|
+
if (/^-?\.?$/.test(value)) return 0n;
|
|
9
|
+
if (!/^-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/.test(value)) throw new Error(`Number \`${value}\` is not a valid decimal number.`);
|
|
10
|
+
let [integer = "", fraction = "0"] = value.split(".");
|
|
9
11
|
const negative = integer.startsWith("-");
|
|
10
12
|
if (negative) integer = integer.slice(1);
|
|
13
|
+
if (integer === "") integer = "0";
|
|
11
14
|
fraction = fraction.replace(/(0+)$/, "");
|
|
12
15
|
if (decimals === 0) {
|
|
13
|
-
if (
|
|
16
|
+
if (fraction.length > 0 && Number.parseInt(fraction[0], 10) >= 5) integer = `${BigInt(integer) + 1n}`;
|
|
14
17
|
fraction = "";
|
|
15
18
|
} else if (fraction.length > decimals) {
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
else fraction =
|
|
24
|
-
if (fraction.length > decimals) {
|
|
25
|
-
fraction = fraction.slice(1);
|
|
26
|
-
integer = `${BigInt(integer) + 1n}`;
|
|
27
|
-
}
|
|
28
|
-
fraction = fraction.slice(0, decimals);
|
|
19
|
+
const left = fraction.slice(0, decimals);
|
|
20
|
+
if (Number.parseInt(fraction.slice(decimals, decimals + 1), 10) >= 5) {
|
|
21
|
+
const carried = carry(left);
|
|
22
|
+
if (carried.length > decimals) {
|
|
23
|
+
fraction = carried.slice(1);
|
|
24
|
+
integer = `${BigInt(integer) + 1n}`;
|
|
25
|
+
} else fraction = carried;
|
|
26
|
+
} else fraction = left;
|
|
29
27
|
} else fraction = fraction.padEnd(decimals, "0");
|
|
30
28
|
return BigInt(`${negative ? "-" : ""}${integer}${fraction}`);
|
|
31
29
|
}
|
|
30
|
+
/**
|
|
31
|
+
* Adds 1 to a digit string. The result has the same length, unless the carry
|
|
32
|
+
* passes the most significant digit: then it is one digit longer.
|
|
33
|
+
*/
|
|
34
|
+
function carry(digits) {
|
|
35
|
+
const out = digits.split("");
|
|
36
|
+
for (let i = out.length - 1; i >= 0; i--) {
|
|
37
|
+
const digit = Number.parseInt(out[i], 10) + 1;
|
|
38
|
+
if (digit < 10) {
|
|
39
|
+
out[i] = String(digit);
|
|
40
|
+
return out.join("");
|
|
41
|
+
}
|
|
42
|
+
out[i] = "0";
|
|
43
|
+
}
|
|
44
|
+
return `1${out.join("")}`;
|
|
45
|
+
}
|
|
32
46
|
//#endregion
|
|
33
47
|
exports.parseUnits = parseUnits;
|
|
34
48
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parseUnits.js","names":[],"sources":["../../../src/utils/parseUnits.ts"],"sourcesContent":["/**\n * Multiplies a string representation of a number by a given exponent of base 10 (10exponent).\n */\nexport function parseUnits(value: string, decimals: number): bigint {\n if (
|
|
1
|
+
{"version":3,"file":"parseUnits.js","names":[],"sources":["../../../src/utils/parseUnits.ts"],"sourcesContent":["/**\n * Multiplies a string representation of a number by a given exponent of base 10 (10exponent).\n */\nexport function parseUnits(value: string, decimals: number): bigint {\n if (!Number.isInteger(decimals) || decimals < 0) {\n throw new Error(\n `\\`decimals\\` must be a non-negative integer. Got \\`${decimals}\\`.`\n )\n }\n\n // An input with no digit is 0n: the widget parses an empty amount field.\n if (/^-?\\.?$/.test(value)) {\n return 0n\n }\n\n if (!/^-?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)$/.test(value)) {\n throw new Error(`Number \\`${value}\\` is not a valid decimal number.`)\n }\n\n let [integer = '', fraction = '0'] = value.split('.')\n\n const negative = integer.startsWith('-')\n if (negative) {\n integer = integer.slice(1)\n }\n if (integer === '') {\n integer = '0'\n }\n\n // trim trailing zeros.\n fraction = fraction.replace(/(0+)$/, '')\n\n // round off if the fraction is larger than the number of decimals.\n if (decimals === 0) {\n // Round half away from zero by the first fractional digit.\n if (fraction.length > 0 && Number.parseInt(fraction[0], 10) >= 5) {\n integer = `${BigInt(integer) + 1n}`\n }\n fraction = ''\n } else if (fraction.length > decimals) {\n const left = fraction.slice(0, decimals)\n const roundDigit = Number.parseInt(\n fraction.slice(decimals, decimals + 1),\n 10\n )\n\n if (roundDigit >= 5) {\n // Carry in decimal space, not through a JS number: a float loses\n // precision on long fractions and can round the wrong way.\n const carried = carry(left)\n if (carried.length > decimals) {\n // The carry overflowed into the integer part.\n fraction = carried.slice(1)\n integer = `${BigInt(integer) + 1n}`\n } else {\n fraction = carried\n }\n } else {\n fraction = left\n }\n } else {\n fraction = fraction.padEnd(decimals, '0')\n }\n\n return BigInt(`${negative ? '-' : ''}${integer}${fraction}`)\n}\n\n/**\n * Adds 1 to a digit string. The result has the same length, unless the carry\n * passes the most significant digit: then it is one digit longer.\n */\nfunction carry(digits: string): string {\n const out = digits.split('')\n for (let i = out.length - 1; i >= 0; i--) {\n const digit = Number.parseInt(out[i], 10) + 1\n if (digit < 10) {\n out[i] = String(digit)\n return out.join('')\n }\n out[i] = '0'\n }\n return `1${out.join('')}`\n}\n"],"mappings":";;;;;AAGA,SAAgB,WAAW,OAAe,UAA0B;CAClE,IAAI,CAAC,OAAO,UAAU,QAAQ,KAAK,WAAW,GAC5C,MAAM,IAAI,MACR,sDAAsD,SAAS,IACjE;CAIF,IAAI,UAAU,KAAK,KAAK,GACtB,OAAO;CAGT,IAAI,CAAC,uCAAuC,KAAK,KAAK,GACpD,MAAM,IAAI,MAAM,YAAY,MAAM,kCAAkC;CAGtE,IAAI,CAAC,UAAU,IAAI,WAAW,OAAO,MAAM,MAAM,GAAG;CAEpD,MAAM,WAAW,QAAQ,WAAW,GAAG;CACvC,IAAI,UACF,UAAU,QAAQ,MAAM,CAAC;CAE3B,IAAI,YAAY,IACd,UAAU;CAIZ,WAAW,SAAS,QAAQ,SAAS,EAAE;CAGvC,IAAI,aAAa,GAAG;EAElB,IAAI,SAAS,SAAS,KAAK,OAAO,SAAS,SAAS,IAAI,EAAE,KAAK,GAC7D,UAAU,GAAG,OAAO,OAAO,IAAI;EAEjC,WAAW;CACb,OAAO,IAAI,SAAS,SAAS,UAAU;EACrC,MAAM,OAAO,SAAS,MAAM,GAAG,QAAQ;EAMvC,IALmB,OAAO,SACxB,SAAS,MAAM,UAAU,WAAW,CAAC,GACrC,EAGW,KAAK,GAAG;GAGnB,MAAM,UAAU,MAAM,IAAI;GAC1B,IAAI,QAAQ,SAAS,UAAU;IAE7B,WAAW,QAAQ,MAAM,CAAC;IAC1B,UAAU,GAAG,OAAO,OAAO,IAAI;GACjC,OACE,WAAW;EAEf,OACE,WAAW;CAEf,OACE,WAAW,SAAS,OAAO,UAAU,GAAG;CAG1C,OAAO,OAAO,GAAG,WAAW,MAAM,KAAK,UAAU,UAAU;AAC7D;;;;;AAMA,SAAS,MAAM,QAAwB;CACrC,MAAM,MAAM,OAAO,MAAM,EAAE;CAC3B,KAAK,IAAI,IAAI,IAAI,SAAS,GAAG,KAAK,GAAG,KAAK;EACxC,MAAM,QAAQ,OAAO,SAAS,IAAI,IAAI,EAAE,IAAI;EAC5C,IAAI,QAAQ,IAAI;GACd,IAAI,KAAK,OAAO,KAAK;GACrB,OAAO,IAAI,KAAK,EAAE;EACpB;EACA,IAAI,KAAK;CACX;CACA,OAAO,IAAI,IAAI,KAAK,EAAE;AACxB"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_errors_errors = require("../errors/errors.js");
|
|
3
|
-
const require_errors_httpError = require("../errors/httpError.js");
|
|
4
2
|
const require_version = require("../version.js");
|
|
5
3
|
const require_errors_SDKError = require("../errors/SDKError.js");
|
|
4
|
+
const require_errors_errors = require("../errors/errors.js");
|
|
5
|
+
const require_errors_httpError = require("../errors/httpError.js");
|
|
6
6
|
const require_utils_sleep = require("./sleep.js");
|
|
7
7
|
//#region src/utils/request.ts
|
|
8
8
|
const requestSettings = { retries: 1 };
|
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
//#region src/utils/sleep.d.ts
|
|
2
|
-
|
|
2
|
+
/**
|
|
3
|
+
* Resolves with `null` after `ms`. With a `signal`, it rejects with the abort
|
|
4
|
+
* reason as soon as the signal aborts, and clears its timer.
|
|
5
|
+
*/
|
|
6
|
+
export declare function sleep(ms: number, { signal }?: {
|
|
7
|
+
signal?: AbortSignal | undefined;
|
|
8
|
+
}): Promise<null>;
|
|
3
9
|
//#endregion
|
|
4
10
|
//# sourceMappingURL=sleep.d.ts.map
|
package/dist/cjs/utils/sleep.js
CHANGED
|
@@ -1,8 +1,27 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_utils_abort = require("./abort.js");
|
|
2
3
|
//#region src/utils/sleep.ts
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
4
|
+
/**
|
|
5
|
+
* Resolves with `null` after `ms`. With a `signal`, it rejects with the abort
|
|
6
|
+
* reason as soon as the signal aborts, and clears its timer.
|
|
7
|
+
*/
|
|
8
|
+
function sleep(ms, { signal } = {}) {
|
|
9
|
+
return new Promise((resolve, reject) => {
|
|
10
|
+
if (signal?.aborted) {
|
|
11
|
+
reject(require_utils_abort.getAbortError(signal));
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
const cleanup = () => signal?.removeEventListener("abort", onAbort);
|
|
15
|
+
const timer = setTimeout(() => {
|
|
16
|
+
cleanup();
|
|
17
|
+
resolve(null);
|
|
18
|
+
}, ms);
|
|
19
|
+
const onAbort = () => {
|
|
20
|
+
clearTimeout(timer);
|
|
21
|
+
cleanup();
|
|
22
|
+
reject(require_utils_abort.getAbortError(signal));
|
|
23
|
+
};
|
|
24
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
6
25
|
});
|
|
7
26
|
}
|
|
8
27
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sleep.js","names":[],"sources":["../../../src/utils/sleep.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"sleep.js","names":["getAbortError"],"sources":["../../../src/utils/sleep.ts"],"sourcesContent":["import { getAbortError } from './abort.js'\n\n/**\n * Resolves with `null` after `ms`. With a `signal`, it rejects with the abort\n * reason as soon as the signal aborts, and clears its timer.\n */\nexport function sleep(\n ms: number,\n { signal }: { signal?: AbortSignal | undefined } = {}\n): Promise<null> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(getAbortError(signal))\n return\n }\n\n const cleanup = (): void => signal?.removeEventListener('abort', onAbort)\n const timer = setTimeout(() => {\n cleanup()\n resolve(null)\n }, ms)\n const onAbort = (): void => {\n clearTimeout(timer)\n cleanup()\n reject(getAbortError(signal!))\n }\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n}\n"],"mappings":";;;;;;;AAMA,SAAgB,MACd,IACA,EAAE,WAAiD,CAAC,GACrC;CACf,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,IAAI,QAAQ,SAAS;GACnB,OAAOA,oBAAAA,cAAc,MAAM,CAAC;GAC5B;EACF;EAEA,MAAM,gBAAsB,QAAQ,oBAAoB,SAAS,OAAO;EACxE,MAAM,QAAQ,iBAAiB;GAC7B,QAAQ;GACR,QAAQ,IAAI;EACd,GAAG,EAAE;EACL,MAAM,gBAAsB;GAC1B,aAAa,KAAK;GAClB,QAAQ;GACR,OAAOA,oBAAAA,cAAc,MAAO,CAAC;EAC/B;EACA,QAAQ,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;CAC3D,CAAC;AACH"}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
//#region src/utils/waitForResult.d.ts
|
|
2
2
|
/**
|
|
3
|
-
* Repeatedly calls a given asynchronous function until it resolves with a value
|
|
4
|
-
* @param fn The function that should be repeated
|
|
3
|
+
* Repeatedly calls a given asynchronous function until it resolves with a truthy value
|
|
4
|
+
* @param fn The function that should be repeated. A falsy result means "no result yet" and polls again, with no limit on the number of polls
|
|
5
5
|
* @param interval The timeout in milliseconds between retries, or a function that receives the current poll count and returns the interval. Defaults to 5000
|
|
6
|
-
* @param maxRetries Maximum number of
|
|
6
|
+
* @param maxRetries Maximum number of calls that throw before the error is rethrown, defaults to 3
|
|
7
7
|
* @param shouldRetry Optional predicate to determine if an error should trigger a retry
|
|
8
8
|
* @returns The result of the fn function
|
|
9
|
-
* @throws
|
|
9
|
+
* @throws The error of fn if maximum retries is reached, or if shouldRetry returns false
|
|
10
10
|
*/
|
|
11
11
|
export declare const waitForResult: <T>(fn: () => Promise<T | undefined>, interval?: number | ((poll: number) => number), maxRetries?: number, shouldRetry?: (count: number, error: unknown) => boolean) => Promise<T>;
|
|
12
12
|
//#endregion
|
|
@@ -2,13 +2,13 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
2
2
|
const require_utils_sleep = require("./sleep.js");
|
|
3
3
|
//#region src/utils/waitForResult.ts
|
|
4
4
|
/**
|
|
5
|
-
* Repeatedly calls a given asynchronous function until it resolves with a value
|
|
6
|
-
* @param fn The function that should be repeated
|
|
5
|
+
* Repeatedly calls a given asynchronous function until it resolves with a truthy value
|
|
6
|
+
* @param fn The function that should be repeated. A falsy result means "no result yet" and polls again, with no limit on the number of polls
|
|
7
7
|
* @param interval The timeout in milliseconds between retries, or a function that receives the current poll count and returns the interval. Defaults to 5000
|
|
8
|
-
* @param maxRetries Maximum number of
|
|
8
|
+
* @param maxRetries Maximum number of calls that throw before the error is rethrown, defaults to 3
|
|
9
9
|
* @param shouldRetry Optional predicate to determine if an error should trigger a retry
|
|
10
10
|
* @returns The result of the fn function
|
|
11
|
-
* @throws
|
|
11
|
+
* @throws The error of fn if maximum retries is reached, or if shouldRetry returns false
|
|
12
12
|
*/
|
|
13
13
|
const waitForResult = async (fn, interval = 5e3, maxRetries = 3, shouldRetry = () => true) => {
|
|
14
14
|
let result;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"waitForResult.js","names":["sleep"],"sources":["../../../src/utils/waitForResult.ts"],"sourcesContent":["import { sleep } from './sleep.js'\n\n/**\n * Repeatedly calls a given asynchronous function until it resolves with a value\n * @param fn The function that should be repeated\n * @param interval The timeout in milliseconds between retries, or a function that receives the current poll count and returns the interval. Defaults to 5000\n * @param maxRetries Maximum number of
|
|
1
|
+
{"version":3,"file":"waitForResult.js","names":["sleep"],"sources":["../../../src/utils/waitForResult.ts"],"sourcesContent":["import { sleep } from './sleep.js'\n\n/**\n * Repeatedly calls a given asynchronous function until it resolves with a truthy value\n * @param fn The function that should be repeated. A falsy result means \"no result yet\" and polls again, with no limit on the number of polls\n * @param interval The timeout in milliseconds between retries, or a function that receives the current poll count and returns the interval. Defaults to 5000\n * @param maxRetries Maximum number of calls that throw before the error is rethrown, defaults to 3\n * @param shouldRetry Optional predicate to determine if an error should trigger a retry\n * @returns The result of the fn function\n * @throws The error of fn if maximum retries is reached, or if shouldRetry returns false\n */\nexport const waitForResult = async <T>(\n fn: () => Promise<T | undefined>,\n interval: number | ((poll: number) => number) = 5000,\n maxRetries = 3,\n shouldRetry: (count: number, error: unknown) => boolean = () => true\n): Promise<T> => {\n let result: T | undefined\n let attempts = 0\n let polls = 0\n\n const getInterval = typeof interval === 'function' ? interval : () => interval\n\n while (!result) {\n try {\n result = await fn()\n if (!result) {\n await sleep(getInterval(polls))\n polls++\n }\n } catch (error) {\n if (!shouldRetry(attempts, error)) {\n throw error\n }\n attempts++\n if (attempts === maxRetries) {\n throw error\n }\n await sleep(getInterval(polls))\n polls++\n }\n }\n\n return result\n}\n"],"mappings":";;;;;;;;;;;;AAWA,MAAa,gBAAgB,OAC3B,IACA,WAAgD,KAChD,aAAa,GACb,oBAAgE,SACjD;CACf,IAAI;CACJ,IAAI,WAAW;CACf,IAAI,QAAQ;CAEZ,MAAM,cAAc,OAAO,aAAa,aAAa,iBAAiB;CAEtE,OAAO,CAAC,QACN,IAAI;EACF,SAAS,MAAM,GAAG;EAClB,IAAI,CAAC,QAAQ;GACX,MAAMA,oBAAAA,MAAM,YAAY,KAAK,CAAC;GAC9B;EACF;CACF,SAAS,OAAO;EACd,IAAI,CAAC,YAAY,UAAU,KAAK,GAC9B,MAAM;EAER;EACA,IAAI,aAAa,YACf,MAAM;EAER,MAAMA,oBAAAA,MAAM,YAAY,KAAK,CAAC;EAC9B;CACF;CAGF,OAAO;AACT"}
|
|
@@ -1,19 +1,22 @@
|
|
|
1
1
|
//#region src/utils/withDedupe.d.ts
|
|
2
|
-
/**
|
|
3
|
-
* Map with a LRU (Least recently used) policy.
|
|
4
|
-
*
|
|
5
|
-
* https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU
|
|
6
|
-
*/
|
|
7
|
-
export declare class LruMap<value = unknown> extends Map<string, value> {
|
|
8
|
-
maxSize: number;
|
|
9
|
-
constructor(size: number);
|
|
10
|
-
override set(key: string, value: value): this;
|
|
11
|
-
}
|
|
12
2
|
type WithDedupeOptions = {
|
|
13
3
|
enabled?: boolean | undefined;
|
|
14
4
|
id?: string | undefined;
|
|
5
|
+
/** Lets this caller leave a shared request without aborting it for others. */
|
|
6
|
+
signal?: AbortSignal | undefined;
|
|
15
7
|
};
|
|
16
|
-
/**
|
|
17
|
-
|
|
8
|
+
/**
|
|
9
|
+
* Deduplicates in-flight promises.
|
|
10
|
+
*
|
|
11
|
+
* When the first caller passes a signal, `fn` receives the signal to hand on
|
|
12
|
+
* to its request. A caller that aborts leaves the shared request at once; the
|
|
13
|
+
* request itself is aborted only when every caller has aborted. The next
|
|
14
|
+
* caller then starts a new request, so `fn` should pass the signal on: a run
|
|
15
|
+
* that ignores it keeps going alongside the new one.
|
|
16
|
+
*/
|
|
17
|
+
export declare function withDedupe<T>(fn: (signal?: AbortSignal) => Promise<T>, options: WithDedupeOptions): Promise<T>;
|
|
18
|
+
export declare function withDedupe<T>(fn: () => Promise<T>, options: WithDedupeOptions & {
|
|
19
|
+
signal?: undefined;
|
|
20
|
+
}): Promise<T>;
|
|
18
21
|
//#endregion
|
|
19
22
|
//# sourceMappingURL=withDedupe.d.ts.map
|
|
@@ -1,34 +1,78 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_utils_abort = require("./abort.js");
|
|
2
3
|
//#region src/utils/withDedupe.ts
|
|
3
|
-
/**
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
4
|
+
/** @internal */
|
|
5
|
+
const promiseCache = /*#__PURE__*/ new (require("./lru.js")).LruMap(8192);
|
|
6
|
+
function withDedupe(fn, { enabled = true, id, signal }) {
|
|
7
|
+
if (!enabled || !id) return fn(signal);
|
|
8
|
+
if (signal?.aborted) return Promise.reject(require_utils_abort.getAbortError(signal));
|
|
9
|
+
let inFlight = promiseCache.get(id);
|
|
10
|
+
if (!inFlight) {
|
|
11
|
+
const controller = signal ? new AbortController() : void 0;
|
|
12
|
+
const promise = fn(controller?.signal).finally(() => evict(id, promise));
|
|
13
|
+
inFlight = {
|
|
14
|
+
promise,
|
|
15
|
+
controller,
|
|
16
|
+
pinned: false
|
|
17
|
+
};
|
|
18
|
+
promiseCache.set(id, inFlight);
|
|
13
19
|
}
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
20
|
+
return join(id, inFlight, signal);
|
|
21
|
+
}
|
|
22
|
+
function join(id, inFlight, signal) {
|
|
23
|
+
if (!signal) {
|
|
24
|
+
inFlight.pinned = true;
|
|
25
|
+
return inFlight.promise;
|
|
18
26
|
}
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
27
|
+
const callers = inFlight.callers ?? subscribe(inFlight);
|
|
28
|
+
return new Promise((resolve, reject) => {
|
|
29
|
+
const caller = {
|
|
30
|
+
resolve: (value) => {
|
|
31
|
+
signal.removeEventListener("abort", leave);
|
|
32
|
+
resolve(value);
|
|
33
|
+
},
|
|
34
|
+
reject: (error) => {
|
|
35
|
+
signal.removeEventListener("abort", leave);
|
|
36
|
+
reject(error);
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
const leave = () => {
|
|
40
|
+
signal.removeEventListener("abort", leave);
|
|
41
|
+
callers.delete(caller);
|
|
42
|
+
const reason = require_utils_abort.getAbortError(signal);
|
|
43
|
+
reject(reason);
|
|
44
|
+
if (!inFlight.pinned && callers.size === 0) {
|
|
45
|
+
evict(id, inFlight.promise);
|
|
46
|
+
inFlight.controller?.abort(reason);
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
callers.add(caller);
|
|
50
|
+
signal.addEventListener("abort", leave, { once: true });
|
|
51
|
+
if (signal.aborted) leave();
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Hands the result to the callers with a signal, through one reaction per
|
|
56
|
+
* request, so a caller that leaves holds nothing here. It is added only when
|
|
57
|
+
* the first such caller joins: a request shared only by callers without a
|
|
58
|
+
* signal gets no handler of ours, and a failure they all ignore is still
|
|
59
|
+
* reported as an unhandled rejection.
|
|
60
|
+
*/
|
|
61
|
+
function subscribe(inFlight) {
|
|
62
|
+
const callers = /* @__PURE__ */ new Set();
|
|
63
|
+
inFlight.callers = callers;
|
|
64
|
+
inFlight.promise.then((value) => {
|
|
65
|
+
for (const caller of callers) caller.resolve(value);
|
|
66
|
+
}, (error) => {
|
|
67
|
+
for (const caller of callers) caller.reject(error);
|
|
68
|
+
});
|
|
69
|
+
return callers;
|
|
70
|
+
}
|
|
71
|
+
/** Drops the entry for `id` only while it still holds this request. */
|
|
72
|
+
function evict(id, promise) {
|
|
73
|
+
if (promiseCache.get(id)?.promise === promise) promiseCache.delete(id);
|
|
29
74
|
}
|
|
30
75
|
//#endregion
|
|
31
|
-
exports.LruMap = LruMap;
|
|
32
76
|
exports.withDedupe = withDedupe;
|
|
33
77
|
|
|
34
78
|
//# sourceMappingURL=withDedupe.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"withDedupe.js","names":[],"sources":["../../../src/utils/withDedupe.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"withDedupe.js","names":["LruMap","getAbortError"],"sources":["../../../src/utils/withDedupe.ts"],"sourcesContent":["import { getAbortError } from './abort.js'\nimport { LruMap } from './lru.js'\n\ntype Caller = {\n resolve: (value: any) => void\n reject: (error: unknown) => void\n}\n\ntype InFlight = {\n promise: Promise<any>\n /** Absent when the first caller had no signal: then nothing can abort it. */\n controller?: AbortController | undefined\n /** Callers with a signal that are still waiting, once the first one joins. */\n callers?: Set<Caller> | undefined\n /** A caller without a signal joined, so the request must run to the end. */\n pinned: boolean\n}\n\n/** @internal */\nconst promiseCache = /*#__PURE__*/ new LruMap<InFlight>(8192)\n\ntype WithDedupeOptions = {\n enabled?: boolean | undefined\n id?: string | undefined\n /** Lets this caller leave a shared request without aborting it for others. */\n signal?: AbortSignal | undefined\n}\n\n/**\n * Deduplicates in-flight promises.\n *\n * When the first caller passes a signal, `fn` receives the signal to hand on\n * to its request. A caller that aborts leaves the shared request at once; the\n * request itself is aborted only when every caller has aborted. The next\n * caller then starts a new request, so `fn` should pass the signal on: a run\n * that ignores it keeps going alongside the new one.\n */\nexport function withDedupe<T>(\n fn: (signal?: AbortSignal) => Promise<T>,\n options: WithDedupeOptions\n): Promise<T>\nexport function withDedupe<T>(\n fn: () => Promise<T>,\n options: WithDedupeOptions & { signal?: undefined }\n): Promise<T>\nexport function withDedupe<T>(\n fn: (signal?: AbortSignal) => Promise<T>,\n { enabled = true, id, signal }: WithDedupeOptions\n): Promise<T> {\n if (!enabled || !id) {\n return fn(signal)\n }\n if (signal?.aborted) {\n return Promise.reject(getAbortError(signal))\n }\n let inFlight = promiseCache.get(id)\n if (!inFlight) {\n const controller = signal ? new AbortController() : undefined\n const promise = fn(controller?.signal).finally(() => evict(id, promise))\n inFlight = { promise, controller, pinned: false }\n promiseCache.set(id, inFlight)\n }\n return join<T>(id, inFlight, signal)\n}\n\nfunction join<T>(\n id: string,\n inFlight: InFlight,\n signal: AbortSignal | undefined\n): Promise<T> {\n if (!signal) {\n inFlight.pinned = true\n return inFlight.promise\n }\n const callers = inFlight.callers ?? subscribe(inFlight)\n return new Promise<T>((resolve, reject) => {\n // Stop listening before settling, so a later abort cannot reach the request.\n const caller: Caller = {\n resolve: (value) => {\n signal.removeEventListener('abort', leave)\n resolve(value)\n },\n reject: (error) => {\n signal.removeEventListener('abort', leave)\n reject(error)\n },\n }\n const leave = () => {\n // `leave` can run without the event, so the listener is not always gone.\n signal.removeEventListener('abort', leave)\n callers.delete(caller)\n const reason = getAbortError(signal)\n reject(reason)\n if (!inFlight.pinned && callers.size === 0) {\n // A caller arriving now must start a new request, not join this one.\n evict(id, inFlight.promise)\n inFlight.controller?.abort(reason)\n }\n }\n callers.add(caller)\n signal.addEventListener('abort', leave, { once: true })\n // `fn` runs before this listener exists and may have aborted the signal.\n if (signal.aborted) {\n leave()\n }\n })\n}\n\n/**\n * Hands the result to the callers with a signal, through one reaction per\n * request, so a caller that leaves holds nothing here. It is added only when\n * the first such caller joins: a request shared only by callers without a\n * signal gets no handler of ours, and a failure they all ignore is still\n * reported as an unhandled rejection.\n */\nfunction subscribe(inFlight: InFlight): Set<Caller> {\n const callers = new Set<Caller>()\n inFlight.callers = callers\n inFlight.promise.then(\n (value) => {\n for (const caller of callers) {\n caller.resolve(value)\n }\n },\n (error) => {\n for (const caller of callers) {\n caller.reject(error)\n }\n }\n )\n return callers\n}\n\n/** Drops the entry for `id` only while it still holds this request. */\nfunction evict(id: string, promise: Promise<unknown>): void {\n if (promiseCache.get(id)?.promise === promise) {\n promiseCache.delete(id)\n }\n}\n"],"mappings":";;;;AAmBA,MAAM,6BAA6B,uBAAIA,EAAAA,CAAAA,OAAiB,IAAI;AA0B5D,SAAgB,WACd,IACA,EAAE,UAAU,MAAM,IAAI,UACV;CACZ,IAAI,CAAC,WAAW,CAAC,IACf,OAAO,GAAG,MAAM;CAElB,IAAI,QAAQ,SACV,OAAO,QAAQ,OAAOC,oBAAAA,cAAc,MAAM,CAAC;CAE7C,IAAI,WAAW,aAAa,IAAI,EAAE;CAClC,IAAI,CAAC,UAAU;EACb,MAAM,aAAa,SAAS,IAAI,gBAAgB,IAAI,KAAA;EACpD,MAAM,UAAU,GAAG,YAAY,MAAM,CAAC,CAAC,cAAc,MAAM,IAAI,OAAO,CAAC;EACvE,WAAW;GAAE;GAAS;GAAY,QAAQ;EAAM;EAChD,aAAa,IAAI,IAAI,QAAQ;CAC/B;CACA,OAAO,KAAQ,IAAI,UAAU,MAAM;AACrC;AAEA,SAAS,KACP,IACA,UACA,QACY;CACZ,IAAI,CAAC,QAAQ;EACX,SAAS,SAAS;EAClB,OAAO,SAAS;CAClB;CACA,MAAM,UAAU,SAAS,WAAW,UAAU,QAAQ;CACtD,OAAO,IAAI,SAAY,SAAS,WAAW;EAEzC,MAAM,SAAiB;GACrB,UAAU,UAAU;IAClB,OAAO,oBAAoB,SAAS,KAAK;IACzC,QAAQ,KAAK;GACf;GACA,SAAS,UAAU;IACjB,OAAO,oBAAoB,SAAS,KAAK;IACzC,OAAO,KAAK;GACd;EACF;EACA,MAAM,cAAc;GAElB,OAAO,oBAAoB,SAAS,KAAK;GACzC,QAAQ,OAAO,MAAM;GACrB,MAAM,SAASA,oBAAAA,cAAc,MAAM;GACnC,OAAO,MAAM;GACb,IAAI,CAAC,SAAS,UAAU,QAAQ,SAAS,GAAG;IAE1C,MAAM,IAAI,SAAS,OAAO;IAC1B,SAAS,YAAY,MAAM,MAAM;GACnC;EACF;EACA,QAAQ,IAAI,MAAM;EAClB,OAAO,iBAAiB,SAAS,OAAO,EAAE,MAAM,KAAK,CAAC;EAEtD,IAAI,OAAO,SACT,MAAM;CAEV,CAAC;AACH;;;;;;;;AASA,SAAS,UAAU,UAAiC;CAClD,MAAM,0BAAU,IAAI,IAAY;CAChC,SAAS,UAAU;CACnB,SAAS,QAAQ,MACd,UAAU;EACT,KAAK,MAAM,UAAU,SACnB,OAAO,QAAQ,KAAK;CAExB,IACC,UAAU;EACT,KAAK,MAAM,UAAU,SACnB,OAAO,OAAO,KAAK;CAEvB,CACF;CACA,OAAO;AACT;;AAGA,SAAS,MAAM,IAAY,SAAiC;CAC1D,IAAI,aAAa,IAAI,EAAE,CAAC,EAAE,YAAY,SACpC,aAAa,OAAO,EAAE;AAE1B"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_utils_abort = require("./abort.js");
|
|
2
3
|
//#region src/utils/withTimeout.ts
|
|
3
4
|
/**
|
|
4
5
|
* Wraps a function in a timeout.
|
|
@@ -13,15 +14,18 @@ function withTimeout(fn, { errorInstance = /* @__PURE__ */ new Error("Timed out
|
|
|
13
14
|
return new Promise((resolve, reject) => {
|
|
14
15
|
(async () => {
|
|
15
16
|
let timeoutId;
|
|
17
|
+
const controller = new AbortController();
|
|
16
18
|
try {
|
|
17
|
-
const controller = new AbortController();
|
|
18
19
|
if (timeout > 0) timeoutId = setTimeout(() => {
|
|
19
20
|
if (signal) controller.abort();
|
|
20
21
|
else reject(errorInstance);
|
|
21
22
|
}, timeout);
|
|
22
23
|
resolve(await fn({ signal: controller?.signal || null }));
|
|
23
24
|
} catch (err) {
|
|
24
|
-
if (
|
|
25
|
+
if (controller.signal.aborted && require_utils_abort.isAbortError(err)) {
|
|
26
|
+
reject(errorInstance);
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
25
29
|
reject(err);
|
|
26
30
|
} finally {
|
|
27
31
|
clearTimeout(timeoutId);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"withTimeout.js","names":[],"sources":["../../../src/utils/withTimeout.ts"],"sourcesContent":["/**\n * Wraps a function in a timeout.\n * Based on viem's withTimeout implementation.\n * @param fn - The function to wrap.\n * @param timeout - The timeout in milliseconds.\n * @param errorInstance - The error instance to throw when the timeout is reached.\n * @param signal - Whether or not the timeout should use an abort signal.\n * @returns The result of the function.\n */\nexport function withTimeout<T>(\n fn: ({ signal }: { signal: AbortController['signal'] | null }) => Promise<T>,\n {\n errorInstance = new Error('Timed out after waiting for too long.'),\n timeout,\n signal,\n }: {\n // The error instance to throw when the timeout is reached.\n errorInstance?: Error | undefined\n // The timeout (in ms).\n timeout: number\n // Whether or not the timeout should use an abort signal.\n signal?: boolean | undefined\n }\n): Promise<T> {\n return new Promise((resolve, reject) => {\n ;(async () => {\n let timeoutId!: NodeJS.Timeout\n
|
|
1
|
+
{"version":3,"file":"withTimeout.js","names":["isAbortError"],"sources":["../../../src/utils/withTimeout.ts"],"sourcesContent":["import { isAbortError } from './abort.js'\n\n/**\n * Wraps a function in a timeout.\n * Based on viem's withTimeout implementation.\n * @param fn - The function to wrap.\n * @param timeout - The timeout in milliseconds.\n * @param errorInstance - The error instance to throw when the timeout is reached.\n * @param signal - Whether or not the timeout should use an abort signal.\n * @returns The result of the function.\n */\nexport function withTimeout<T>(\n fn: ({ signal }: { signal: AbortController['signal'] | null }) => Promise<T>,\n {\n errorInstance = new Error('Timed out after waiting for too long.'),\n timeout,\n signal,\n }: {\n // The error instance to throw when the timeout is reached.\n errorInstance?: Error | undefined\n // The timeout (in ms).\n timeout: number\n // Whether or not the timeout should use an abort signal.\n signal?: boolean | undefined\n }\n): Promise<T> {\n return new Promise((resolve, reject) => {\n ;(async () => {\n let timeoutId!: NodeJS.Timeout\n const controller = new AbortController()\n try {\n if (timeout > 0) {\n timeoutId = setTimeout(() => {\n if (signal) {\n controller.abort()\n } else {\n reject(errorInstance)\n }\n }, timeout) as NodeJS.Timeout // need to cast because bun globals.d.ts overrides @types/node\n }\n resolve(await fn({ signal: controller?.signal || null }))\n } catch (err) {\n // Only an abort from our own timeout is a timeout. Any other\n // AbortError belongs to the caller and passes through.\n if (controller.signal.aborted && isAbortError(err)) {\n reject(errorInstance)\n return\n }\n reject(err)\n } finally {\n clearTimeout(timeoutId)\n }\n })()\n })\n}\n"],"mappings":";;;;;;;;;;;;AAWA,SAAgB,YACd,IACA,EACE,gCAAgB,IAAI,MAAM,uCAAuC,GACjE,SACA,UASU;CACZ,OAAO,IAAI,SAAS,SAAS,WAAW;EACrC,CAAC,YAAY;GACZ,IAAI;GACJ,MAAM,aAAa,IAAI,gBAAgB;GACvC,IAAI;IACF,IAAI,UAAU,GACZ,YAAY,iBAAiB;KAC3B,IAAI,QACF,WAAW,MAAM;UAEjB,OAAO,aAAa;IAExB,GAAG,OAAO;IAEZ,QAAQ,MAAM,GAAG,EAAE,QAAQ,YAAY,UAAU,KAAK,CAAC,CAAC;GAC1D,SAAS,KAAK;IAGZ,IAAI,WAAW,OAAO,WAAWA,oBAAAA,aAAa,GAAG,GAAG;KAClD,OAAO,aAAa;KACpB;IACF;IACA,OAAO,GAAG;GACZ,UAAU;IACR,aAAa,SAAS;GACxB;EACF,EAAA,CAAG;CACL,CAAC;AACH"}
|