const MUTATING = new Set(["POST", "PUT", "PATCH", "DELETE"]); /** Read the CSRF token injected by the admin layout ``. */ export function getCsrfToken(): string | null { if (typeof document === "undefined") return null; return ( document .querySelector('meta[name="csrf-token"]') ?.getAttribute("content") ?? null ); } /** * Same-origin fetch for admin APIs. Attaches `x-csrf-token` on mutating methods. */ export function adminFetch( input: RequestInfo | URL, init?: RequestInit, ): Promise { const method = (init?.method ?? "GET").toUpperCase(); const headers = new Headers(init?.headers); if (MUTATING.has(method)) { const token = getCsrfToken(); if (token) headers.set("x-csrf-token", token); } return fetch(input, { ...init, headers, credentials: init?.credentials ?? "same-origin", }); }