import { Emitter } from './emitter.js'; export interface AsyncResourceContext { /** currently cached value of the resource */ readonly current: T | null; /** performance.now() when the resource was fetched */ readonly currentFetchedAt: number; /** performance.now() when the resource will/did expire */ readonly currentExpiresAt: number; /** * whether the current fetch was initiated in the background * (by the swr mechanism or because of auto-reload). * this can be used to prioritize the fetch if needed */ readonly isBackground: boolean; /** abort signal that should be used to abort the fetch */ readonly abort: AbortSignal; } export interface AsyncResourceOptions { /** * if true, the resource will be automatically * reloaded after {@link autoReloadAfter} milliseconds * once the resource is expires * * (note that it will need to be fetched manually at least once) */ autoReload?: boolean; /** * time in milliseconds after which the resource will be reloaded * after expiring if {@link autoReload} is true. * can be negative to reload before expiring * * @default 0 (i.e. as soon as it expires) */ autoReloadAfter?: number; /** * if true, the resource will keep returning expired data * after it expires while the resource is being reloaded */ swr?: boolean; /** * if {@link swr} is true, this function will be called * to validate if the cached data is still valid */ swrValidator?: (ctx: AsyncResourceContext) => boolean; /** * function that will be called to fetch the resource * * @returns Promise that resolves to the resource and the number of milliseconds before it expires */ fetcher: (ctx: AsyncResourceContext) => Promise<{ data: T; expiresIn: number; }>; /** * function that will be called if {@link fetcher} throws an error * * @param err error thrown by {@link fetcher} * @default `console.error(err)` */ onError?: (err: unknown, ctx: AsyncResourceContext) => void; } export declare class AsyncResource { #private; readonly params: AsyncResourceOptions; readonly onUpdated: Emitter>; constructor(params: AsyncResourceOptions); get isStale(): boolean; setData(data: T, expiresIn: number): void; /** * update the resource * * @param force whether to force the update even if the resource hasn't expired yet */ update(force?: boolean): Promise; /** * get the resource value, refreshing it if needed * * note: this method still *might* return `null` if the resource wasn't ever cached yet, * and the underlying call to `fetcher` failed */ get(): Promise; /** * get the cached resource value immediately (if any) * note that it may be stale, which you should check separately */ getCached(): T | null; destroy(): void; }