"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import type { Job, Reply } from "@/lib/hidden-path/job"; export function useProof() { const current = useRef(null); const [state, setState] = useState(null); const stop = useCallback(() => { current.current?.terminate(); current.current = null; }, []); useEffect(() => stop, [stop]); const clear = useCallback(() => { stop(); setState(null); }, [stop]); const fail = useCallback( (message: string) => { stop(); setState({ kind: "error", message }); }, [stop], ); const run = useCallback( (job: Job) => { stop(); if ( typeof Worker === "undefined" || typeof WebAssembly === "undefined" || !globalThis.crypto?.subtle ) { fail( "This device needs Web Workers, WebAssembly and Web Crypto. Open this page in a secure, current browser.", ); return; } try { const worker = new Worker( new URL("./proof.worker.ts", import.meta.url), { type: "module" }, ); current.current = worker; setState({ kind: "progress", message: "Starting the local proof engine…", }); worker.onmessage = ({ data }: MessageEvent) => { if (current.current !== worker) return; if (data.kind !== "progress") stop(); setState(data); }; worker.onerror = () => { if (current.current === worker) fail("The worker could not run. Retry or use another browser."); }; worker.postMessage(job); } catch { fail( "The browser could not start the proof worker. Retry in a secure, current browser.", ); } }, [stop, fail], ); return { state, run, clear, fail }; }