UNPKG

obsidian-dev-utils

Version:

This is the collection of useful functions that you can use for your Obsidian plugin development

318 lines (317 loc) 12.8 kB
/** * @packageDocumentation * * Contains utility functions for asynchronous operations. */ import type { Promisable } from 'type-fest'; /** * A type representing a function that resolves a {@link Promise}. * * @typeParam T - The type of the value. */ export type PromiseResolve<T> = undefined extends T ? (value?: PromiseLike<T> | T) => void : (value: PromiseLike<T> | T) => void; /** * Options for {@link retryWithTimeout}. */ export interface RetryOptions { /** * A abort signal to cancel the retry operation. */ abortSignal?: AbortSignal; /** * A delay in milliseconds between retry attempts. */ retryDelayInMilliseconds?: number; /** * Whether to retry the function on error. */ shouldRetryOnError?: boolean; /** * A maximum time in milliseconds to wait before giving up on retrying. */ timeoutInMilliseconds?: number; } /** * Adds an error handler to a {@link Promise} that catches any errors and emits an async error event. * * @param asyncFn - The asynchronous function to add an error handler to. * @param stackTrace - The stack trace of the source function. * @returns A {@link Promise} that resolves when the asynchronous function completes or emits async error event. */ export declare function addErrorHandler(asyncFn: () => Promise<unknown>, stackTrace?: string): Promise<void>; /** * Filters an array asynchronously, keeping only the elements that satisfy the provided predicate function. * * @typeParam T - The type of elements in the input array. * @param arr - The array to filter. * @param predicate - The predicate function to test each element. * @returns A {@link Promise} that resolves with an array of elements that satisfy the predicate function. */ export declare function asyncFilter<T>(arr: T[], predicate: (value: T, index: number, array: T[]) => Promisable<boolean>): Promise<T[]>; /** * Filters an array asynchronously in place, keeping only the elements that satisfy the provided predicate function. * * @typeParam T - The type of elements in the input array. * @param arr - The array to filter. * @param predicate - The predicate function to test each element. * @returns A {@link Promise} that resolves when the array is filtered. */ export declare function asyncFilterInPlace<T>(arr: T[], predicate: (value: T, index: number, array: T[]) => Promisable<boolean>): Promise<void>; /** * Maps over an array asynchronously, applying the provided callback function to each element, and then flattens the results into a single array. * * @typeParam T - The type of elements in the input array. * @typeParam U - The type of elements in the output array. * @param arr - The array to map over and flatten. * @param callback - The callback function to apply to each element. * @returns A {@link Promise} that resolves with a flattened array of the results of the callback function. */ export declare function asyncFlatMap<T, U>(arr: T[], callback: (value: T, index: number, array: T[]) => Promisable<U[]>): Promise<U[]>; /** * Maps over an array asynchronously, applying the provided callback function to each element. * * @typeParam T - The type of elements in the input array. * @typeParam U - The type of elements in the output array. * @param arr - The array to map over. * @param callback - The callback function to apply to each element. * @returns A {@link Promise} that resolves with an array of the results of the callback function. */ export declare function asyncMap<T, U>(arr: T[], callback: (value: T, index: number, array: T[]) => Promisable<U>): Promise<U[]>; /** * Converts an asynchronous function to a synchronous one by automatically handling the Promise rejection. * * @typeParam Args - The types of the arguments the function accepts. * @param asyncFunc - The asynchronous function to convert. * @param stackTrace - The stack trace of the source function. * @returns A function that wraps the asynchronous function in a synchronous interface. */ export declare function convertAsyncToSync<Args extends unknown[]>(asyncFunc: (...args: Args) => Promise<unknown>, stackTrace?: string): (...args: Args) => void; /** * Converts a synchronous function to an asynchronous one by wrapping it in a {@link Promise}. * * @typeParam Args - The types of the arguments the function accepts. * @typeParam Result - The type of the function's return value. * @param syncFn - The synchronous function to convert. * @returns A function that wraps the synchronous function in an asynchronous interface. */ export declare function convertSyncToAsync<Args extends unknown[], Result>(syncFn: (...args: Args) => Result): (...args: Args) => Promise<Result>; /** * Handles a silent error. * * @param error - The error to handle. * @returns Whether the error is a silent error. */ export declare function handleSilentError(error: unknown): boolean; /** * Ignores an error that is thrown by an asynchronous function. * * @param promise - The promise to ignore the error of. * @param fallbackValue - Always `undefined`. * @returns A {@link Promise} that resolves when the asynchronous function completes or fails. */ export declare function ignoreError(promise: Promise<unknown>, fallbackValue?: undefined): Promise<void>; /** * Invokes a {@link Promise} and safely handles any errors by catching them and emitting an async error event. * * @param asyncFn - The asynchronous function to invoke safely. * @param stackTrace - The stack trace of the source function. */ export declare function invokeAsyncSafely(asyncFn: () => Promise<unknown>, stackTrace?: string): void; /** * Invokes an asynchronous function after a delay. * * @param asyncFn - The asynchronous function to invoke. * @param delayInMilliseconds - The delay in milliseconds. * @param stackTrace - The stack trace of the source function. * @param abortSignal - The abort signal to listen to. */ export declare function invokeAsyncSafelyAfterDelay(asyncFn: (abortSignal: AbortSignal) => Promisable<void>, delayInMilliseconds?: number, stackTrace?: string, abortSignal?: AbortSignal): void; /** * Executes async functions sequentially. * * @typeParam T - The type of the value. * @param asyncFns - The async functions to execute sequentially. * @returns A {@link Promise} that resolves with an array of the results of the async functions. */ export declare function promiseAllAsyncFnsSequentially<T>(asyncFns: (() => Promisable<T>)[]): Promise<T[]>; /** * Executes promises sequentially. * * @typeParam T - The type of the value. * @param promises - The promises to execute sequentially. * @returns A {@link Promise} that resolves with an array of the results of the promises. */ export declare function promiseAllSequentially<T>(promises: Promisable<T>[]): Promise<T[]>; /** * Options for {@link retryWithTimeout}. */ export interface RetryWithTimeoutOptions { /** * The function to handle the timeout. * * @param context - The timeout context. */ onTimeout?(this: void, context: TimeoutContext): void; /** * The function to execute. * * @param abortSignal - The abort signal to listen to. * @returns The result of the function. */ operationFn(this: void, abortSignal: AbortSignal): Promisable<boolean>; /** * The name of the operation. */ operationName?: string; /** * The retry options. */ retryOptions?: RetryOptions; /** * The stack trace of the source function. */ stackTrace?: string; } /** * Options for {@link runWithTimeout}. */ export interface RunWithTimeoutOptions<Result> { /** * The context of the function. */ context?: unknown; /** * The function to handle the timeout. * * @param context - The timeout context. */ onTimeout?(this: void, context: TimeoutContext): void; /** * The operation function to execute. * * @param abortSignal - The abort signal to listen to. * @returns The result of the function. */ operationFn(this: void, abortSignal: AbortSignal): Promisable<Result>; /** * The name of the operation. */ operationName?: string; /** * The stack trace of the source function. */ stackTrace?: string | undefined; /** * The maximum time to wait in milliseconds. */ timeoutInMilliseconds: number; } /** * Context provided to the timeout handler. */ export interface TimeoutContext { /** * The duration in milliseconds since the operation started. */ duration: number; /** * Registers a callback to be invoked when the operation completes. * * @param callback - The function to call when the operation completes. */ onOperationCompleted(callback: () => void): void; /** * The name of the operation. */ operationName: string; /** * Terminates the operation that timed out. */ terminateOperation(): void; } /** * Marks an error to terminate retry logic. * * @param error - The error to mark to terminate retry logic. */ export declare function marksAsTerminateRetry(error: Error): void; /** * An async function that never ends. * * @returns A {@link Promise} that never resolves. */ export declare function neverEnds(): Promise<never>; /** * Gets the next tick. * * @returns A promise that resolves when the next tick is available. */ export declare function nextTickAsync(): Promise<void>; /** * Gets the next queue microtask. * * @returns A promise that resolves when the next queue microtask is available. */ export declare function queueMicrotaskAsync(): Promise<void>; /** * Gets the next request animation frame. * * @returns A promise that resolves when the next request animation frame is available. */ export declare function requestAnimationFrameAsync(): Promise<void>; /** * Retries the provided function until it returns true or the timeout is reached. * * @param options - The options for the function. * @returns A {@link Promise} that resolves when the function returns true or rejects when the timeout is reached. */ export declare function retryWithTimeout(options: RetryWithTimeoutOptions): Promise<void>; /** * Executes a function with a timeout. If the function does not complete within the specified time, it is considered to have timed out. * * If `DEBUG=obsidian-dev-utils:Async:runWithTimeout` is set, the execution is not terminated after the timeout and the function is allowed to run indefinitely. * * @typeParam Result - The type of the result from the asynchronous function. * @param options - The options for the function. * @returns A {@link Promise} that resolves with the result of the asynchronous function or rejects if it times out. */ export declare function runWithTimeout<Result>(options: RunWithTimeoutOptions<Result>): Promise<Result>; /** * Gets the next set immediate. * * @returns A promise that resolves when the next set immediate is available. */ export declare function setImmediateAsync(): Promise<void>; /** * Delays execution for a specified number of milliseconds. * * @param delay - The time to wait in milliseconds. * @returns A {@link Promise} that resolves after the specified delay. */ export declare function setTimeoutAsync(delay?: number): Promise<void>; /** * Delays execution for a specified number of milliseconds. * * @param milliseconds - The time to wait in milliseconds. * @param abortSignal - The abort signal to listen to. * @param shouldThrowOnAbort - Whether to throw an error if the abort signal is aborted. * @returns A {@link Promise} that resolves after the specified delay. */ export declare function sleep(milliseconds: number, abortSignal?: AbortSignal, shouldThrowOnAbort?: boolean): Promise<void>; /** * Returns a {@link Promise} that rejects after the specified timeout period. * * @param timeoutInMilliseconds - The timeout period in milliseconds. * @param abortSignal - The abort signal to listen to. * @param shouldThrowOnAbort - Whether to throw an error if the abort signal is aborted. * @returns A {@link Promise} that always rejects with a timeout error. */ export declare function timeout(timeoutInMilliseconds: number, abortSignal?: AbortSignal, shouldThrowOnAbort?: boolean): Promise<never>; /** * Converts an AsyncIterableIterator to an array by consuming all its elements. * * @typeParam T - The type of elements produced by the AsyncIterableIterator. * @param iter - The AsyncIterableIterator to convert. * @returns A {@link Promise} that resolves with an array of all the elements in the AsyncIterableIterator. */ export declare function toArray<T>(iter: AsyncIterableIterator<T>): Promise<T[]>;