@hyperlane-xyz/utils
Version:
General utilities and types for the Hyperlane network
136 lines • 5.67 kB
TypeScript
import type { Logger } from 'pino';
/**
* Lazily initialized async value with deduplication.
* Concurrent callers share the same initialization promise.
* After successful init, returns cached value immediately.
* On error, clears state to allow retry on next call.
*/
export declare class LazyAsync<T> {
private readonly initializer;
private promise?;
private value?;
private hasValue;
private generation;
constructor(initializer: () => Promise<T>);
get(): Promise<T>;
reset(): void;
isInitialized(): boolean;
peek(): T | undefined;
private initialize;
}
/**
* Return a promise that resolves in ms milliseconds.
* @param ms Time to wait
*/
export declare function sleep(ms: number): Promise<void>;
/**
* Wait up to a given amount of time, and throw an error if the promise does not resolve in time.
* @param promise The promise to timeout on.
* @param timeoutMs How long to wait for the promise in milliseconds.
* @param message The error message if a timeout occurs.
*/
export declare function timeout<T>(promise: Promise<T>, timeoutMs?: number, message?: string): Promise<T>;
/**
* Run a callback with a timeout.
* @param timeoutMs How long to wait for the promise in milliseconds.
* @param callback The callback to run.
* @returns callback return value
* @throws Error if the timeout is reached before the callback completes
*/
export declare function runWithTimeout<T>(timeoutMs: number, callback: () => Promise<T>): Promise<T>;
/**
* Executes a fetch request that fails after a timeout via an AbortController.
* @param resource resource to fetch (e.g URL)
* @param options fetch call options object
* @param timeout timeout MS (default 10_000)
* @returns fetch response
*/
export declare function fetchWithTimeout(resource: RequestInfo, options?: RequestInit, timeout?: number): Promise<Response>;
/**
* Retries an async function with exponential backoff.
* Always executes at least once, even if `attempts` is 0 or negative.
* Stops retrying if `error.isRecoverable` is set to false.
* @param runner callback to run
* @param attempts max number of attempts (defaults to 5, minimum 1)
* @param baseRetryMs base delay between attempts in milliseconds (defaults to 50ms)
* @returns runner return value
*/
export declare function retryAsync<T>(runner: () => Promise<T> | T, attempts?: number, baseRetryMs?: number): Promise<T>;
/**
* Run a callback with a timeout, and retry if the callback throws an error.
* @param runner callback to run
* @param delayMs base delay between attempts
* @param maxAttempts maximum number of attempts
* @returns runner return value
*/
export declare function pollAsync<T>(runner: () => Promise<T>, delayMs?: number, maxAttempts?: number | undefined): Promise<T>;
/**
* An enhanced Promise.race that returns
* objects with the promise itself and index
* instead of just the resolved value.
*/
export declare function raceWithContext<T>(promises: Array<Promise<T>>): Promise<{
resolved: T;
promise: Promise<T>;
index: number;
}>;
/**
* Map an async function over a list xs with a given concurrency level
* Forked from https://github.com/celo-org/developer-tooling/blob/0c61e7e02c741fe10ecd1d733a33692d324cdc82/packages/sdk/base/src/async.ts#L128
*
* @param concurrency number of `mapFn` concurrent executions
* @param xs list of value
* @param mapFn mapping function
*/
export declare function concurrentMap<A, B>(concurrency: number, xs: A[], mapFn: (val: A, idx: number) => Promise<B>): Promise<B[]>;
/**
* Result type for mapAllSettled containing both successful results and errors.
*/
export interface AllSettledResult<K, R> {
/** Map of keys to their successfully resolved values */
fulfilled: Map<K, R>;
/** Map of keys to their rejection errors */
rejected: Map<K, Error>;
}
/**
* Maps an async function over items using Promise.allSettled semantics.
* Unlike Promise.all, this continues processing all items even if some fail.
*
* @param items - Array of items to process
* @param mapFn - Async function to apply to each item
* @param keyFn - Optional function to derive a key for each item (defaults to using index)
* @returns Object with `fulfilled` Map (successful results) and `rejected` Map (errors)
*
* @example
* ```typescript
* // Process chains and collect results/errors
* const { fulfilled, rejected } = await mapAllSettled(
* chains,
* async (chain) => deployContract(chain),
* (chain) => chain, // use chain name as key
* );
*
* // Handle errors if any
* if (rejected.size > 0) {
* const errors = [...rejected.entries()].map(([chain, err]) => `${chain}: ${err.message}`);
* throw new Error(`Deployment failed: ${errors.join('; ')}`);
* }
*
* // Use successful results
* for (const [chain, result] of fulfilled) {
* console.log(`Deployed to ${chain}: ${result}`);
* }
* ```
*/
export declare function mapAllSettled<T, R, K = number>(items: T[], mapFn: (item: T, index: number) => Promise<R>, keyFn?: (item: T, index: number) => K): Promise<AllSettledResult<K, R>>;
/**
* Wraps an async function and catches any errors, logging them instead of throwing.
* Useful for fire-and-forget operations where you want to log errors but not crash.
*
* @param fn - The async function to execute
* @param context - A description of the context for error logging
* @param logger - The logger instance to use for error logging
*/
export declare function tryFn(fn: () => Promise<void>, context: string, logger: Logger): Promise<void>;
export declare function timedAsync<T>(name: string, fn: () => Promise<T>): Promise<T>;
//# sourceMappingURL=async.d.ts.map