// lib/directus.ts // Central Directus helpers used by API routes. (user bearer only) const BASE = (process.env.DIRECTUS_URL || "").replace(/\/$/, ""); const TOKEN_ADMIN_REGISTER = process.env.DIRECTUS_TOKEN_ADMIN_REGISTER || ""; // server-only const ROLE_MEMBER_NAME = process.env.DIRECTUS_ROLE_MEMBER_NAME || "Users"; const PROJECTS_COLLECTION = process.env.DIRECTUS_PROJECTS_COLLECTION || "projects"; if (!BASE) console.warn("[directus] Missing DIRECTUS_URL"); if (!TOKEN_ADMIN_REGISTER) console.warn("[directus] Missing DIRECTUS_TOKEN_ADMIN_REGISTER (used for registration)"); export function bytesFromMB(mb: number) { return Math.round(mb * 1024 * 1024); } // Extract a user's bearer (ma_at) from a Next.js Request (server routes) export function getUserBearerFromRequest(req: Request): string | null { const cookieHeader = req.headers.get("cookie") ?? ""; const m = cookieHeader.match(/(?:^|;\s*)ma_at=([^;]+)/); return m?.[1] ?? null; } // ───────────────────────────────────────────────────────────── // Low-level helpers (bearer REQUIRED; no fallbacks) // ───────────────────────────────────────────────────────────── function authHeaders(bearer: string, extra?: HeadersInit): HeadersInit { return { Accept: "application/json", Authorization: `Bearer ${bearer}`, ...extra }; } async function parseJsonSafe(res: Response) { const text = await res.text(); let json: any = null; try { json = text ? JSON.parse(text) : null; } catch {} return { json, text }; } async function throwIfNotOk(res: Response) { const { json, text } = await parseJsonSafe(res); if (!res.ok) { const err: any = new Error(`Directus ${res.status}: ${text || res.statusText}`); err.status = res.status; err.detail = json ?? text; throw err; } return json; } export async function dxGET(path: string, bearer: string): Promise { const res = await fetch(`${BASE}${path}`, { headers: authHeaders(bearer), cache: "no-store" }); return (await throwIfNotOk(res)) as T; } export async function dxPOST(path: string, bearer: string, body: any): Promise { const res = await fetch(`${BASE}${path}`, { method: "POST", headers: authHeaders(bearer, { "content-type": "application/json" }), body: JSON.stringify(body), cache: "no-store", }); return (await throwIfNotOk(res)) as T; } export async function dxPATCH(path: string, bearer: string, body: any): Promise { const res = await fetch(`${BASE}${path}`, { method: "PATCH", headers: authHeaders(bearer, { "content-type": "application/json" }), body: JSON.stringify(body), cache: "no-store", }); return (await throwIfNotOk(res)) as T; } export async function dxDELETE(path: string, bearer: string): Promise { const res = await fetch(`${BASE}${path}`, { method: "DELETE", headers: authHeaders(bearer), cache: "no-store", }); return (await throwIfNotOk(res)) as T; } // ───────────────────────────────────────────────────────────── /** Server-only admin fetch (registration flows, etc.) */ export async function directusAdminFetch(path: string, init?: RequestInit): Promise { if (!TOKEN_ADMIN_REGISTER) throw new Error("Missing DIRECTUS_TOKEN_ADMIN_REGISTER"); const res = await fetch(`${BASE}${path}`, { ...init, headers: { Accept: "application/json", Authorization: `Bearer ${TOKEN_ADMIN_REGISTER}`, ...(init?.headers || {}) }, cache: "no-store", }); return (await throwIfNotOk(res)) as T; } // ───────────────────────────────────────────────────────────── // Optional folder lookup (server-only if using admin token) // ───────────────────────────────────────────────────────────── type FolderItem = { id: string; name: string; parent?: { id?: string; name?: string } | null }; const folderCache = new Map(); let folderListCache: FolderItem[] | null = null; let folderListCacheAt = 0; async function fetchAllFolders(): Promise { try { const q = `/folders?fields=id,name,parent.id,parent.name&limit=500`; const res = await directusAdminFetch<{ data: FolderItem[] }>(q); return res?.data ?? []; } catch (e: any) { console.warn("[directus] fetchAllFolders failed:", e?.message || e); return null; } } async function getFolderIdByPath(path: string): Promise { if (!path) return undefined; if (folderCache.has(path)) return folderCache.get(path); const now = Date.now(); const freshForMs = 60_000; if (!folderListCache || now - folderListCacheAt > freshForMs) { folderListCache = await fetchAllFolders(); folderListCacheAt = now; } const list = folderListCache; if (!list) { folderCache.set(path, undefined); return undefined; } const parts = path.split("/").map((s) => s.trim()).filter(Boolean); const [parentName, childName] = parts; const eq = (a?: string | null, b?: string | null) => String(a ?? "").toLowerCase() === String(b ?? "").toLowerCase(); let match: FolderItem | undefined; if (parts.length >= 2) { match = list.find((f) => eq(f.name, childName) && eq(f.parent?.name ?? "", parentName)); } else { match = list.find((f) => eq(f.name, parts[0])); } const id = match?.id ? String(match.id) : undefined; folderCache.set(path, id); return id; } // ───────────────────────────────────────────────────────────── // Files & items — user bearer ONLY // ───────────────────────────────────────────────────────────── export async function uploadFile( file: Blob | File, filename: string, bearer: string, options?: { folderId?: string; folderNamePath?: string; title?: string } ): Promise<{ id: string }> { const form = new FormData(); form.set("file", file, filename); form.set("filename_download", filename); if (options?.title) form.set("title", options.title); let folderId = options?.folderId; if (!folderId && options?.folderNamePath) { try { folderId = await getFolderIdByPath(options.folderNamePath); } catch {} } if (folderId) form.set("folder", folderId); const res = await fetch(`${BASE}/files`, { method: "POST", headers: authHeaders(bearer), body: form, cache: "no-store", }); const json = await throwIfNotOk(res); const id = json?.data?.id ?? json?.id; if (!id) throw new Error("File upload succeeded but no id returned"); return { id: String(id) }; } export async function createSettingsItem( collection: string, payload: any, bearer: string ): Promise<{ data: { id: string } }> { return dxPOST<{ data: { id: string } }>(`/items/${collection}`, bearer, payload); } export async function createProjectRow( payload: any, bearer: string ): Promise<{ data: { id: string } }> { return dxPOST<{ data: { id: string } }>(`/items/${PROJECTS_COLLECTION}`, bearer, payload); } export async function patchProject( id: string | number, payload: any, bearer: string ): Promise<{ data: { id: string } }> { return dxPATCH<{ data: { id: string } }>(`/items/${PROJECTS_COLLECTION}/${id}`, bearer, payload); } // ───────────────────────────────────────────────────────────── // Auth helpers (registration / login support) // ───────────────────────────────────────────────────────────── export async function resolveMemberRoleId(): Promise { const name = ROLE_MEMBER_NAME; const q = `/roles?filter[name][_eq]=${encodeURIComponent(name)}&fields=id,name&limit=1`; const { data } = await directusAdminFetch<{ data: Array<{ id: string }> }>(q); const hit = data?.[0]?.id; if (!hit) throw new Error(`Role not found: ${name}`); return hit; } /** Registrations always create a 'Users' role account. No overrides. */ export async function createDirectusUser(input: { username: string; password: string; email?: string; }): Promise<{ id: string }> { const role = await resolveMemberRoleId(); // If email is omitted, create a stable placeholder so login can still work. const email = input.email && input.email.trim() ? input.email.trim() : `${input.username}@noemail.local`; const res = await directusAdminFetch<{ data: { id: string } }>(`/users`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ status: "active", role, username: input.username, email, password: input.password, }), }); return { id: String(res?.data?.id) }; } export async function emailForUsername(username: string): Promise { const q = `/users?filter[username][_eq]=${encodeURIComponent(username)}&fields=email&limit=1`; const { data } = await directusAdminFetch<{ data: Array<{ email?: string }> }>(q); const em = data?.[0]?.email; return em ? String(em) : null; } export async function loginDirectus(email: string, password: string) { const res = await fetch(`${BASE}/auth/login`, { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify({ email, password }), cache: "no-store", }); const json = await throwIfNotOk(res); // Directus typically returns { data: { access_token, refresh_token, expires } } return json?.data ?? json; }