spb/note-spboucher-ai
Public
1/** Text extraction for attachments (PDF, DOCX, Markdown/TXT/CSV). Returns null for unsupported types. */2export async function extractText(buf: Buffer, mime: string, filename: string): Promise<{ text: string; pages?: number } | null> {3 const ext = filename.toLowerCase().split(".").pop() ?? "";4 try {5 if (mime === "application/pdf" || ext === "pdf") { const { PDFParse } = await import("pdf-parse"); const p = new PDFParse({ data: new Uint8Array(buf) }); const r = await p.getText(); await p.destroy().catch(() => {}); return { text: r.text ?? "", pages: r.total ?? undefined }; }6 if (ext === "docx" || mime.includes("wordprocessingml")) { const mammoth = await import("mammoth"); const r = await mammoth.extractRawText({ buffer: buf }); return { text: r.value }; }7 if (/^text\//.test(mime) || ["md", "markdown", "txt", "csv", "json", "bib", "tex", "py", "ts", "js", "r", "sql"].includes(ext)) return { text: buf.toString("utf8").slice(0, 2_000_000) };8 } catch (e) { console.error("extract failed", filename, e); }9 return null;10}11