UNPKG

histoire

Version:

A fast story book powered by Vite

68 lines (67 loc) • 2.99 kB
/** Teardown failed or timed out; project ownership cannot be safely transferred. */ export class RuntimeCleanupError extends AggregateError { /** Stable marker survives duplicate module instances and worker serialization. */ code = 'HISTOIRE_RUNTIME_CLEANUP_FAILED'; /** Preserves original failures while marking unconfirmed resource release. */ constructor(errors, message) { super(errors, message); this.name = 'RuntimeCleanupError'; } } /** Finds unconfirmed teardown even when startup preserved it in an aggregate. */ export function hasUnconfirmedCleanup(error) { return error instanceof RuntimeCleanupError || (typeof error === 'object' && error !== null && 'code' in error && (error.code === 'HISTOIRE_RUNTIME_CLEANUP_FAILED' || error.code === 'CLEANUP_UNCONFIRMED')) || (error instanceof AggregateError && error.errors.some(hasUnconfirmedCleanup)); } /** Bounds owned resource teardown without leaving an unobserved rejection. */ export async function withCleanupDeadline(promise, timeout = 10_000) { let timer; try { return await Promise.race([ promise, new Promise((_, reject) => { timer = setTimeout(() => reject(new RuntimeCleanupError([], 'Project runtime cleanup timed out')), timeout); }), ]); } finally { clearTimeout(timer); } } /** Closes every acquired resource in reverse dependency order, including after failures. */ export function createCleanupStack() { const cleanups = []; let closing; return { /** Shutdown admission fence, visible before asynchronous disposers finish. */ get isClosing() { return closing !== undefined; }, /** Registers an owned resource while acquisition is still active. */ add(cleanup) { if (closing) { throw new Error('Cannot acquire resource after runtime cleanup started'); } cleanups.push(cleanup); }, /** Invokes disposers once; all attempts occur even when a disposer throws. */ close() { return closing ??= (async () => { const deadline = Date.now() + 10_000; const errors = []; for (const cleanup of cleanups.splice(0).reverse()) { // Plugin cleanup may still need Vite. Await each disposer before // releasing earlier-acquired resources, while bounding total teardown. try { await withCleanupDeadline(Promise.resolve().then(cleanup), Math.max(1, deadline - Date.now())); } catch (error) { errors.push(error); } } if (errors.length) { throw new RuntimeCleanupError(errors, errors.map(error => String(error)).join('; ')); } })(); }, }; }