forked from mtusi2026/mtusi2026lab7
38 lines
937 B
TypeScript
38 lines
937 B
TypeScript
export type BrowserLifecyclePorts<C, R> = {
|
|
acquire: () => Promise<C>;
|
|
run: (context: C) => Promise<R>;
|
|
close: (context: C) => Promise<void>;
|
|
reportCleanupFailure: (error: unknown) => Promise<void>;
|
|
};
|
|
|
|
export function createBrowserLifecycle<C, R>(
|
|
ports: BrowserLifecyclePorts<C, R>,
|
|
) {
|
|
if (
|
|
!ports ||
|
|
[ports.acquire, ports.run, ports.close, ports.reportCleanupFailure].some(
|
|
(port) => typeof port !== "function",
|
|
)
|
|
)
|
|
throw new Error("BROWSER_LIFECYCLE_PORTS_REQUIRED");
|
|
return async () => {
|
|
const context = await ports.acquire();
|
|
let failed = false;
|
|
try {
|
|
return await ports.run(context);
|
|
} catch (error) {
|
|
failed = true;
|
|
throw error;
|
|
} finally {
|
|
try {
|
|
await ports.close(context);
|
|
} catch (error) {
|
|
try {
|
|
await ports.reportCleanupFailure(error);
|
|
} catch {}
|
|
if (!failed) throw error;
|
|
}
|
|
}
|
|
};
|
|
}
|