| 1 | // @effect-diagnostics globalTimers:off -- The child-process shutdown watchdog runs at a worker callback boundary outside any Effect fiber. |
| 2 | // @effect-diagnostics nodeBuiltinImport:off -- This desktop-only helper owns a Node child process for global shortcut capture. |
| 3 | |
| 4 | import * as NodeChildProcess from "node:child_process"; |
| 5 | |
| 6 | import type { SnapShotModifier } from "@t3tools/contracts"; |
| 7 | |
| 8 | export function startGlobalShiftShortcutProcess( |
| 9 | workerPath: string, |
| 10 | modifier: SnapShotModifier, |
| 11 | onTrigger: () => void, |
| 12 | onFailure: (error: Error) => void, |
| 13 | ): Promise<() => void> { |
| 14 | const worker = NodeChildProcess.fork(workerPath, [modifier], { |
| 15 | env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" }, |
| 16 | execArgv: [], |
| 17 | stdio: ["ignore", "ignore", "inherit", "ipc"], |
| 18 | }); |
| 19 | |
| 20 | return new Promise((resolve, reject) => { |
| 21 | let settled = false; |
| 22 | let stopped = false; |
| 23 | const stop = () => { |
| 24 | if (stopped) return; |
| 25 | stopped = true; |
| 26 | worker.kill(); |
| 27 | const forceKill = setTimeout(() => worker.kill("SIGKILL"), 1_000); |
| 28 | forceKill.unref?.(); |
| 29 | worker.once("exit", () => clearTimeout(forceKill)); |
| 30 | }; |
| 31 | const fail = (error: Error) => { |
| 32 | if (stopped) return; |
| 33 | if (settled) { |
| 34 | stop(); |
| 35 | onFailure(error); |
| 36 | return; |
| 37 | } |
| 38 | settled = true; |
| 39 | stop(); |
| 40 | reject(error); |
| 41 | }; |
| 42 | |
| 43 | worker.on("message", (message) => { |
| 44 | if (message === "ready" && !settled) { |
| 45 | settled = true; |
| 46 | resolve(stop); |
| 47 | return; |
| 48 | } |
| 49 | if (message !== "trigger" || !settled || stopped) return; |
| 50 | try { |
| 51 | onTrigger(); |
| 52 | } catch {} |
| 53 | }); |
| 54 | worker.once("error", (error) => { |
| 55 | fail(error); |
| 56 | }); |
| 57 | worker.once("exit", (code) => { |
| 58 | fail(new Error(`Snapshot shortcut helper exited with code ${code}`)); |
| 59 | }); |
| 60 | }); |
| 61 | } |