import { writeFile, mkdir } from "node:fs/promises";
const base = "https://api.prefetch.io";
const headers = { "X-API-Key": process.env.PREFETCH_API_KEY, "Content-Type": "application/json" };
// 1. List the docs URLs
const map = await (await fetch(`${base}/map?url=https://docs.example.com&limit=5000`, { headers })).json();
const urls = map.data.links.map((l) => l.url).filter((u) => !u.includes("/changelog/")).slice(0, 500);
// 2. Scrape them as one job
const { data: job } = await (await fetch(`${base}/batch/scrape`, {
method: "POST",
headers,
body: JSON.stringify({ urls, scrape_options: { formats: ["markdown"], only_main_content: true } }),
})).json();
// 3. Wait, then read every page of results
let status;
do {
await new Promise((r) => setTimeout(r, 5000));
({ data: status } = await (await fetch(`${base}/batch/scrape/${job.id}`, { headers })).json());
} while (status.status === "pending" || status.status === "running");
const pages = [...status.data];
for (let next = status.next; next; ) {
const { data } = await (await fetch(base + next, { headers })).json();
pages.push(...data.data);
next = data.next;
}
// 4. Save one markdown file per page
await mkdir("docs", { recursive: true });
for (const p of pages.filter((p) => p.ok)) {
const name = new URL(p.url).pathname.replace(/^\/|\/$/g, "").replaceAll("/", "__") || "index";
await writeFile(`docs/${name}.md`, `<!-- ${p.url} -->\n${p.markdown.content}`);
}