import { useRef } from "react"; import type { DownloadState } from "./events"; export function ArtifactDownload({ name, url, sensitive, state, onState, }: { name: string; url: string; sensitive: boolean; state?: DownloadState; onState(state: DownloadState): void; }) { const busy = useRef(false); const disabled = state === "downloading" || state === "unavailable" || (sensitive && !!state); async function download() { if (busy.current || disabled) return; busy.current = true; onState("downloading"); try { // A single GET both retrieves the bytes and detects expired/consumed files. const response = await fetch(url, { credentials: "same-origin", cache: "no-store", }); if (response.status === 410) { onState("unavailable"); return; } if (!response.ok) throw new Error(`Download failed (${response.status})`); const blob = await response.blob(); const objectUrl = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = objectUrl; link.download = name; document.body.append(link); link.click(); link.remove(); // Give the browser time to start saving before releasing the blob. setTimeout(() => URL.revokeObjectURL(objectUrl), 1000); onState("downloaded"); } catch { onState("error"); } finally { busy.current = false; } } return ( { event.preventDefault(); void download(); }} download={name} > ↓ {name} {sensitive && sensitive · one download} {state === "downloaded" && sensitive && ( Downloaded / consumed )} {state === "downloading" && Downloading…} {state === "unavailable" && no longer available} {state === "error" && ( {sensitive ? "Download failed; one-shot download may have been consumed." : "Download failed. Try again."} )} ); }