import { spawn } from "node:child_process"; import { randomUUID } from "node:crypto"; import { promises as fs } from "node:fs"; import { join } from "node:path"; import { environment } from "@raycast/api"; import { getPreferences } from "../preferences"; import { canonicalProjectPath, projectDataRoot } from "./velum-project"; import type { applyProject, prepareProject, Preview, ProjectOutput } from "./project-work"; export type AnalysisInput = { root: string; files: Parameters[2]; rules: Parameters[3]; whitelist: Parameters[4]; entityTypes: Parameters[5]; skipped: Parameters[6]; reanalyzeUnchanged: boolean; imagePolicy: Parameters[9]; fileSelectionChanged: boolean; }; export type Decision = Parameters[5]; export type JobPhase = "analysis" | "apply"; export type ProjectJobState = | { phase: JobPhase; pid: number; message: string } | { phase: "review" } | { phase: "complete"; output?: ProjectOutput; reused?: number } | { phase: "error"; message: string }; export function projectJobDirectory(root: string, support = environment.supportPath): string { return join(projectDataRoot(root, support), "active-job"); } export async function writeJobJson(directory: string, file: string, value: unknown): Promise { const target = join(directory, file); const temporary = target + "." + randomUUID(); try { await fs.writeFile(temporary, JSON.stringify(value), { flag: "wx", mode: 0o600 }); await fs.rename(temporary, target); } finally { await fs.rm(temporary, { force: true }); } } export async function readJobJson(directory: string, file: string): Promise { return JSON.parse(await fs.readFile(join(directory, file), "utf8")) as T; } export async function readProjectJob(root: string): Promise { const directory = projectJobDirectory(root); let state: ProjectJobState; try { state = await readJobJson(directory, "state.json"); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; const info = await fs.stat(directory).catch((statError: NodeJS.ErrnoException) => { if (statError.code !== "ENOENT") throw statError; }); if (info && Date.now() - info.mtimeMs > 10_000) { return { phase: "error", message: "Der Projektauftrag wurde beim Start unterbrochen." }; } return undefined; } if (state.phase === "analysis" || state.phase === "apply") { try { process.kill(state.pid, 0); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; // The worker writes its terminal state before exiting. const last = await readJobJson(directory, "state.json"); if (last.phase !== "analysis" && last.phase !== "apply") return last; return { phase: "error", message: "Der lokale Hintergrundprozess wurde beendet." }; } } return state; } export async function loadProjectReview(root: string): Promise<{ input: AnalysisInput; preview: Preview }> { const directory = projectJobDirectory(root); const [input, preview] = await Promise.all([ readJobJson(directory, "input.json"), readJobJson(directory, "preview.json"), ]); return { input, preview }; } async function launch(directory: string, phase: JobPhase): Promise { const config = JSON.stringify({ assets: environment.assetsPath, support: environment.supportPath, preferences: getPreferences(), }); const child = spawn(process.execPath, [join(environment.assetsPath, "velum-project-worker.cjs"), directory, phase], { detached: true, stdio: ["pipe", "ignore", "ignore"], cwd: directory, }); // Register a handler immediately, before doing any asynchronous filesystem IO. const started = new Promise((resolve, reject) => { child.once("error", reject); child.once("spawn", resolve); }); child.stdin.on("error", () => undefined); try { await started; await writeJobJson(directory, "state.json", { phase, pid: child.pid, message: phase === "analysis" ? "Analyse startet" : "Ausgabe wird vorbereitet" }); // Only the pipe receives credentials. Job metadata, logs and arguments are // safe to retain even after the window or worker closes. await new Promise((resolve, reject) => { child.stdin.once("error", reject); child.stdin.end(config, resolve); }); } catch (error) { child.stdin.destroy(); child.kill(); throw error; } finally { child.unref(); } } export async function startProjectAnalysis(input: AnalysisInput): Promise { const root = canonicalProjectPath(input.root); const directory = projectJobDirectory(root); await fs.mkdir(projectDataRoot(root), { recursive: true, mode: 0o700 }); await fs.mkdir(directory, { mode: 0o700 }); try { await writeJobJson(directory, "input.json", { ...input, root }); await launch(directory, "analysis"); } catch (error) { await writeJobJson(directory, "state.json", { phase: "error", message: "Der lokale Hintergrundprozess konnte nicht gestartet werden." }); throw error; } } export async function startProjectApply(root: string, decision: Decision): Promise { const directory = projectJobDirectory(root); if ((await readProjectJob(root))?.phase !== "review") { throw new Error("Dieser Projektauftrag steht nicht mehr zur Prüfung bereit."); } // Exclusive creation prevents two windows from publishing the same review. await fs.writeFile(join(directory, "decision.json"), JSON.stringify(decision), { flag: "wx", mode: 0o600 }); try { await launch(directory, "apply"); } catch (error) { await fs.rm(join(directory, "decision.json"), { force: true }); await writeJobJson(directory, "state.json", { phase: "review" }); throw error; } } export async function discardProjectJob(root: string): Promise { const state = await readProjectJob(root); if (!state || state.phase === "analysis" || state.phase === "apply") { throw new Error("Der Hintergrundauftrag läuft noch."); } const directory = projectJobDirectory(root); if (state.phase === "review") { // Mutual exclusion with the review's Apply action. await fs.writeFile(join(directory, "decision.json"), "", { flag: "wx", mode: 0o600 }); } await fs.rm(directory, { recursive: true, force: true }); }