import { ASYNC, AsyncContext } from "../async/index.js"; import { captureSelf, TeardownHook } from "../core/index.js"; export interface AsyncTestContext { asyncCtx: AsyncContext; use: (fn: () => T) => T; } export type AsyncTestFn = (ctx: AsyncTestContext) => Promise; export async function runAsyncTest(fn: AsyncTestFn): Promise { const teardown: TeardownHook[] = []; const asyncCtx = new AsyncContext(); async function cleanup() { for (let i = teardown.length - 1; i >= 0; i--) { teardown[i](); } return asyncCtx.complete(); } try { const result = await fn({ asyncCtx, use: fn => captureSelf(dispose => { teardown.push(dispose); return ASYNC.provide(asyncCtx, fn); }), }); await cleanup(); return result; } catch (error) { try { await cleanup(); } catch {} throw error; } }