Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

closingTerminals.ts

29 lines1.2 KB

1import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2import type { ScopedThreadRef } from "@t3tools/contracts";
3​
4// Lifecycle commands run in order, so a queued close ends whichever shell holds its ID by then.
5const closingIdsByThread = new Map<string, Map<string, number>>();
6​
7/** IDs a new terminal must not take until their pending closes settle. */
8export function closingTerminalIds(threadRef: ScopedThreadRef): ReadonlyArray<string> {
9 return [...(closingIdsByThread.get(scopedThreadKey(threadRef))?.keys() ?? [])];
11​
12export async function holdTerminalIdWhileClosing<A>(
13 threadRef: ScopedThreadRef,
14 terminalId: string,
15 close: () => Promise<A>,
16): Promise<A> {
17 const key = scopedThreadKey(threadRef);
18 const closing = closingIdsByThread.get(key) ?? new Map<string, number>();
19 closingIdsByThread.set(key, closing);
20 closing.set(terminalId, (closing.get(terminalId) ?? 0) + 1);
21 try {
22 return await close();
23 } finally {
24 const remaining = (closing.get(terminalId) ?? 1) - 1;
25 if (remaining > 0) closing.set(terminalId, remaining);
26 else closing.delete(terminalId);
27 if (closing.size === 0) closingIdsByThread.delete(key);
28 }