import { CancellationToken, CancellationTokenSource } from './cancellation.js'; import { DisposableStore, IDisposable } from './lifecycle.js'; import { MicrotaskDelay } from './symbols.js'; export declare function isThenable(obj: unknown): obj is Promise; export interface CancelablePromise extends Promise { cancel(): void; } export declare function createCancelablePromise(callback: (token: CancellationToken) => Promise): CancelablePromise; /** * Returns a promise that resolves with `undefined` as soon as the passed token is cancelled. * @see {@link raceCancellationError} */ export declare function raceCancellation(promise: Promise, token: CancellationToken): Promise; /** * Returns a promise that resolves with `defaultValue` as soon as the passed token is cancelled. * @see {@link raceCancellationError} */ export declare function raceCancellation(promise: Promise, token: CancellationToken, defaultValue: T): Promise; export interface ITask { (): T; } /** * A helper to prevent accumulation of sequential async tasks. * * Imagine a mail man with the sole task of delivering letters. As soon as * a letter submitted for delivery, he drives to the destination, delivers it * and returns to his base. Imagine that during the trip, N more letters were submitted. * When the mail man returns, he picks those N letters and delivers them all in a * single trip. Even though N+1 submissions occurred, only 2 deliveries were made. * * The throttler implements this via the queue() method, by providing it a task * factory. Following the example: * * const throttler = new Throttler(); * const letters = []; * * function deliver() { * const lettersToDeliver = letters; * letters = []; * return makeTheTrip(lettersToDeliver); * } * * function onLetterReceived(l) { * letters.push(l); * throttler.queue(deliver); * } */ export declare class Throttler implements IDisposable { private activePromise; private queuedPromise; private queuedPromiseFactory; private isDisposed; constructor(); queue(promiseFactory: ITask>): Promise; dispose(): void; } /** * A helper to delay (debounce) execution of a task that is being requested often. * * Following the throttler, now imagine the mail man wants to optimize the number of * trips proactively. The trip itself can be long, so he decides not to make the trip * as soon as a letter is submitted. Instead he waits a while, in case more * letters are submitted. After said waiting period, if no letters were submitted, he * decides to make the trip. Imagine that N more letters were submitted after the first * one, all within a short period of time between each other. Even though N+1 * submissions occurred, only 1 delivery was made. * * The delayer offers this behavior via the trigger() method, into which both the task * to be executed and the waiting period (delay) must be passed in as arguments. Following * the example: * * const delayer = new Delayer(WAITING_PERIOD); * const letters = []; * * function letterReceived(l) { * letters.push(l); * delayer.trigger(() => { return makeTheTrip(); }); * } */ export declare class Delayer implements IDisposable { defaultDelay: number | typeof MicrotaskDelay; private deferred; private completionPromise; private doResolve; private doReject; private task; constructor(defaultDelay: number | typeof MicrotaskDelay); trigger(task: ITask>, delay?: number | typeof MicrotaskDelay): Promise; isTriggered(): boolean; cancel(): void; private cancelTimeout; dispose(): void; } /** * A helper to delay execution of a task that is being requested often, while * preventing accumulation of consecutive executions, while the task runs. * * The mail man is clever and waits for a certain amount of time, before going * out to deliver letters. While the mail man is going out, more letters arrive * and can only be delivered once he is back. Once he is back the mail man will * do one more trip to deliver the letters that have accumulated while he was out. */ export declare class ThrottledDelayer { private delayer; private throttler; constructor(defaultDelay: number); trigger(promiseFactory: ITask>, delay?: number): Promise; isTriggered(): boolean; cancel(): void; dispose(): void; } export declare function timeout(millis: number): CancelablePromise; export declare function timeout(millis: number, token: CancellationToken): Promise; /** * Creates a timeout that can be disposed using its returned value. * @param handler The timeout handler. * @param timeout An optional timeout in milliseconds. * @param store An optional {@link DisposableStore} that will have the timeout disposable managed automatically. * * @example * const store = new DisposableStore; * // Call the timeout after 1000ms at which point it will be automatically * // evicted from the store. * const timeoutDisposable = disposableTimeout(() => {}, 1000, store); * * if (foo) { * // Cancel the timeout and evict it from store. * timeoutDisposable.dispose(); * } */ export declare function disposableTimeout(handler: () => void, timeout?: number, store?: DisposableStore): IDisposable; export declare function first(promiseFactories: ITask>[], shouldStop?: (t: T) => boolean, defaultValue?: T | null): Promise; export declare class TimeoutTimer implements IDisposable { private _token; private _isDisposed; constructor(); constructor(runner: () => void, timeout: number); dispose(): void; cancel(): void; cancelAndSet(runner: () => void, timeout: number): void; setIfNotSet(runner: () => void, timeout: number): void; } export declare class IntervalTimer implements IDisposable { private disposable; private isDisposed; cancel(): void; cancelAndSet(runner: () => void, interval: number, context?: typeof globalThis): void; dispose(): void; } export declare class RunOnceScheduler implements IDisposable { protected runner: ((...args: unknown[]) => void) | null; private timeoutToken; private timeout; private timeoutHandler; constructor(runner: (...args: any[]) => void, delay: number); /** * Dispose RunOnceScheduler */ dispose(): void; /** * Cancel current scheduled runner (if any). */ cancel(): void; /** * Cancel previous runner (if any) & schedule a new runner. */ schedule(delay?: number): void; get delay(): number; set delay(value: number); /** * Returns true if scheduled. */ isScheduled(): boolean; flush(): void; private onTimeout; protected doRun(): void; } export interface IdleDeadline { readonly didTimeout: boolean; timeRemaining(): number; } type IdleApi = Pick; /** * Execute the callback the next time the browser is idle, returning an * {@link IDisposable} that will cancel the callback when disposed. This wraps * [requestIdleCallback] so it will fallback to [setTimeout] if the environment * doesn't support it. * * @param callback The callback to run when idle, this includes an * [IdleDeadline] that provides the time alloted for the idle callback by the * browser. Not respecting this deadline will result in a degraded user * experience. * @param timeout A timeout at which point to queue no longer wait for an idle * callback but queue it on the regular event loop (like setTimeout). Typically * this should not be used. * * [IdleDeadline]: https://developer.mozilla.org/en-US/docs/Web/API/IdleDeadline * [requestIdleCallback]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback * [setTimeout]: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout * * **Note** that there is `dom.ts#runWhenWindowIdle` which is better suited when running inside a browser * context */ export declare let runWhenGlobalIdle: (callback: (idle: IdleDeadline) => void, timeout?: number) => IDisposable; export declare let _runWhenIdle: (targetWindow: IdleApi, callback: (idle: IdleDeadline) => void, timeout?: number) => IDisposable; export declare abstract class AbstractIdleValue { private readonly _executor; private readonly _handle; private _didRun; private _value?; private _error; constructor(targetWindow: IdleApi, executor: () => T); dispose(): void; get value(): T; get isInitialized(): boolean; } /** * An `IdleValue` that always uses the current window (which might be throttled or inactive) * * **Note** that there is `dom.ts#WindowIdleValue` which is better suited when running inside a browser * context */ export declare class GlobalIdleValue extends AbstractIdleValue { constructor(executor: () => T); } export type ValueCallback = (value: T | Promise) => void; /** * Creates a promise whose resolution or rejection can be controlled imperatively. */ export declare class DeferredPromise { private completeCallback; private errorCallback; private outcome?; get isRejected(): boolean; get isResolved(): boolean; get isSettled(): boolean; get value(): T | undefined; readonly p: Promise; constructor(); complete(value: T): Promise; error(err: unknown): Promise; cancel(): Promise; } export declare namespace Promises { /** * A drop-in replacement for `Promise.all` with the only difference * that the method awaits every promise to either fulfill or reject. * * Similar to `Promise.all`, only the first error will be returned * if any. */ function settled(promises: Promise[]): Promise; /** * A helper to create a new `Promise` with a body that is a promise * itself. By default, an error that raises from the async body will * end up as a unhandled rejection, so this utility properly awaits the * body and rejects the promise as a normal promise does without async * body. * * This method should only be used in rare cases where otherwise `async` * cannot be used (e.g. when callbacks are involved that require this). */ function withAsyncBody(bodyFn: (resolve: (value: T) => unknown, reject: (error: E) => unknown) => Promise): Promise; } /** * An object that allows to emit async values asynchronously or bring the iterable to an error state using `reject()`. * This emitter is valid only for the duration of the executor (until the promise returned by the executor settles). */ export interface AsyncIterableEmitter { /** * The value will be appended at the end. * * **NOTE** If `reject()` has already been called, this method has no effect. */ emitOne(value: T): void; /** * The values will be appended at the end. * * **NOTE** If `reject()` has already been called, this method has no effect. */ emitMany(values: T[]): void; /** * Writing an error will permanently invalidate this iterable. * The current users will receive an error thrown, as will all future users. * * **NOTE** If `reject()` have already been called, this method has no effect. */ reject(error: Error): void; } /** * An executor for the `AsyncIterableObject` that has access to an emitter. */ export interface AsyncIterableExecutor { /** * @param emitter An object that allows to emit async values valid only for the duration of the executor. */ (emitter: AsyncIterableEmitter): void | Promise; } /** * A rich implementation for an `AsyncIterable`. */ export declare class AsyncIterableObject implements AsyncIterable { static fromArray(items: T[]): AsyncIterableObject; static fromPromise(promise: Promise): AsyncIterableObject; static fromPromisesResolveOrder(promises: Promise[]): AsyncIterableObject; static merge(iterables: AsyncIterable[]): AsyncIterableObject; static EMPTY: AsyncIterableObject; private _state; private _results; private _error; private readonly _onReturn?; private readonly _onStateChanged; constructor(executor: AsyncIterableExecutor, onReturn?: () => void | Promise); [Symbol.asyncIterator](): AsyncIterator; static map(iterable: AsyncIterable, mapFn: (item: T) => R): AsyncIterableObject; map(mapFn: (item: T) => R): AsyncIterableObject; static filter(iterable: AsyncIterable, filterFn: (item: T) => boolean): AsyncIterableObject; filter(filterFn: (item: T) => boolean): AsyncIterableObject; static coalesce(iterable: AsyncIterable): AsyncIterableObject; coalesce(): AsyncIterableObject>; static toPromise(iterable: AsyncIterable): Promise; toPromise(): Promise; /** * The value will be appended at the end. * * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect. */ private emitOne; /** * The values will be appended at the end. * * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect. */ private emitMany; /** * Calling `resolve()` will mark the result array as complete. * * **NOTE** `resolve()` must be called, otherwise all consumers of this iterable will hang indefinitely, similar to a non-resolved promise. * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect. */ private resolve; /** * Writing an error will permanently invalidate this iterable. * The current users will receive an error thrown, as will all future users. * * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect. */ private reject; } export declare class CancelableAsyncIterableObject extends AsyncIterableObject { private readonly _source; constructor(_source: CancellationTokenSource, executor: AsyncIterableExecutor); cancel(): void; } export declare function createCancelableAsyncIterable(callback: (token: CancellationToken) => AsyncIterable): CancelableAsyncIterableObject; export {};