/** * Shenron-compatible JSONL projection for the BXC Dragon Ball crawl store. * The SQLite crawl database remains the authoritative raw HTML/JSON store; * this module creates a portable, deterministic index for downstream ingest. */ import { Database } from "bun:sqlite"; import { mkdir } from "node:fs/promises"; import { dirname } from "node:path"; export type DragonBallDocumentCategory = | "official_news" | "shenron_community" | "toei_episode" | "kanzenshuu_translation" | "jump_metrics" | "biography" | "multimedia_archive"; export interface DragonBallJsonlDocument { crawl_id: "crawl_toriyama_archive_full"; document_uid: string; canonical_url: string; source_domain: string; category: DragonBallDocumentCategory; http_status: number; payload: { title_raw: string; publication_date: string | null; authors_or_entities: string[]; structured_fields: { series_identifier: string | null; episode_or_chapter_number: number | null; toc_rank: number | null; original_print_source: string | null; dialogue_nodes: Array<{ speaker: string; content: string }>; }; body_markdown: string; embedded_media: Array<{ url: string; type: "image" | "video" | "audio"; caption: string | null }>; }; raw_checksum: string; timestamp_utc: string; } interface ScrapeRow { id?: number; url: string; status: number | null; content: string | null; metadata: string | null; json_data?: string | null; markdown: string | null; timestamp: string | null; } function sha256(value: string): string { return new Bun.CryptoHasher("sha256").update(value).digest("hex"); } function parseJson(value: string | null): Record { if (!value) return {}; try { const parsed = JSON.parse(value); return parsed && typeof parsed === "object" ? parsed as Record : {}; } catch { return {}; } } function stringOrNull(value: unknown): string | null { return typeof value === "string" && value.trim() ? value.trim() : null; } function objectValue(value: unknown): Record { return value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; } function mergedMetadata(row: ScrapeRow): Record { const structured = parseJson(row.json_data ?? null); const metadata = parseJson(row.metadata); return { ...structured, ...metadata, canonical: stringOrNull(metadata.canonical) ?? structured.canonical, openGraph: { ...objectValue(structured.openGraph), ...objectValue(metadata.openGraph) }, twitter: { ...objectValue(structured.twitter), ...objectValue(metadata.twitter) }, }; } function toeiFields(url: URL): { series: string | null; episodeNumber: number | null } { const match = url.pathname.match(/^\/ja\/tv\/([^/]+)\/episode\/(\d+)\/?$/); return match ? { series: match[1]!, episodeNumber: Number(match[2]) } : { series: null, episodeNumber: null }; } export function dragonBallCategory(url: string): DragonBallDocumentCategory { const host = new URL(url).hostname; if (host === "lineup.toei-anim.co.jp") return "toei_episode"; if (host === "www.kanzenshuu.com") return "kanzenshuu_translation"; if (host === "www.jajanken.net") return "jump_metrics"; if (host === "archive.org" || host === "web.archive.org") return "multimedia_archive"; if (host === "dragon-ball-official.com" || host.endsWith(".dragon-ball-official.com")) return "official_news"; if (host === "dragonballfr.com" || host.endsWith(".dragonballfr.com")) return "shenron_community"; return "biography"; } export function extractEmbeddedMedia( text: string, baseUrl?: string, ): DragonBallJsonlDocument["payload"]["embedded_media"] { const seen = new Set(); const output: DragonBallJsonlDocument["payload"]["embedded_media"] = []; const add = (url: string, explicitType?: "image" | "video" | "audio", caption: string | null = null): void => { let normalized = url.replace(/[),.;]+$/, ""); try { normalized = new URL(normalized, baseUrl).href; } catch { return; } if (!/^https?:/i.test(normalized) || seen.has(normalized)) return; let type: "image" | "video" | "audio" | null = explicitType ?? null; if (/\.(?:avif|gif|jpe?g|png|svg|webp)(?:[?#]|$)/i.test(normalized)) type = "image"; else if (/\.(?:m3u8|mp4|mov|webm)(?:[?#]|$)/i.test(normalized)) type = "video"; else if (/\.(?:aac|flac|m4a|mp3|ogg|wav)(?:[?#]|$)/i.test(normalized)) type = "audio"; if (!type) return; seen.add(normalized); output.push({ url: normalized, type, caption }); }; for (const match of text.matchAll(/<(img|video|audio|source)\b([^>]*)>/gi)) { const tag = match[1]!.toLowerCase(); const attributes = match[2]!; const source = attributes.match(/\b(?:src|data-src|data-original|poster)\s*=\s*["']([^"']+)["']/i)?.[1]; const caption = attributes.match(/\b(?:alt|title)\s*=\s*["']([^"']+)["']/i)?.[1]?.trim() || null; if (source) add(source, tag === "img" ? "image" : tag === "audio" ? "audio" : "video", caption); } for (const match of text.matchAll(/\bsrcset\s*=\s*["']([^"']+)["']/gi)) { for (const candidate of match[1]!.split(",")) add(candidate.trim().split(/\s+/, 1)[0]!, "image"); } for (const url of text.match(/https?:\/\/[^\s"'<>\\]+/gi) ?? []) add(url); for (const match of text.matchAll(/]*(?:property|name)\s*=\s*["'](?:og:image|twitter:image(?::src)?)["'][^>]*content\s*=\s*["']([^"']+)["'][^>]*>/gi)) add(match[1]!, "image"); for (const match of text.matchAll(/]*content\s*=\s*["']([^"']+)["'][^>]*(?:property|name)\s*=\s*["'](?:og:image|twitter:image(?::src)?)["'][^>]*>/gi)) add(match[1]!, "image"); for (const match of text.matchAll(/]*rel\s*=\s*["'](?:image_src|preload)["'][^>]*href\s*=\s*["']([^"']+)["'][^>]*>/gi)) add(match[1]!, "image"); return output; } function cleanHtml(text: string): string { return text .replace(/<[^>]*>/g, "") .replace(/’/g, "'") .replace(/‘/g, "'") .replace(/“/g, '"') .replace(/”/g, '"') .replace(/–/g, "-") .replace(/—/g, "—") .replace(/&/g, "&") .replace(/&/g, "&") .replace(/"/g, '"') .replace(/'/g, "'") .replace(/\s+/g, " ") .trim(); } export interface KanzenshuuTranslationParsed { title: string | null; originalPrintSource: string | null; publicationDate: string | null; interviewees: string[]; dialogueNodes: Array<{ speaker: string; content: string }>; } export function parseKanzenshuuTranslation(html: string, _url?: string): KanzenshuuTranslationParsed { const transIdx = html.indexOf('id="trans-content"') !== -1 ? html.indexOf('id="trans-content"') : html.indexOf("trans-content"); const section = transIdx !== -1 ? html.slice(transIdx) : html; const h2Match = section.match(/]*>([\s\S]*?)<\/h2>/i); const originalPrintSource = h2Match ? cleanHtml(h2Match[1]) : null; const h1Match = section.match(/]*>([\s\S]*?)<\/h1>/i); const title = h1Match ? cleanHtml(h1Match[1]) : null; let publicationDate: string | null = null; const dateMatch = originalPrintSource?.match(/\b(\d{1,2}\s+[A-Za-z]+\s+\d{4}|\d{4}\.\d{2}\.\d{2}|[A-Za-z]+\s+\d{4})\b/) || section.match(/\b(0?[1-9]|[12][0-9]|3[01])\s+(January|February|March|April|May|June|July|August|September|October|November|December)\s+(\d{4})\b/i); if (dateMatch) { publicationDate = dateMatch[0].trim(); } const interviewees = new Set(); const interviewerMatch = section.match(/(?:Interviewer|Interviewed by|Interviewers):\s*([^<\n]+)/i); if (interviewerMatch) { const raw = cleanHtml(interviewerMatch[1]); if (raw && !raw.startsWith("s to our amazing") && !raw.includes("archive")) { interviewees.add(raw); } } if (title && /Akira Toriyama/i.test(title)) { interviewees.add("Akira Toriyama"); } const dialogueNodes: Array<{ speaker: string; content: string }> = []; const pRegex = /([\s\S]*?)<\/div>|([\s\S]*?)<\/div>|

([\s\S]*?)<\/p>/gi; let m; while ((m = pRegex.exec(section)) !== null) { if (m[1]) { const cnt = cleanHtml(m[1]); if (cnt) dialogueNodes.push({ speaker: "Question", content: cnt }); } else if (m[2]) { const sub = m[2]; const subMatches = [...sub.matchAll(/(?:^|

)(?:<[^>]*>)*(?:\d+<\/sup>)?([^<:]+):<\/strong>([\s\S]*?)(?:<\/p>|$)/gi)]; if (subMatches.length > 0) { for (const sm of subMatches) { const spk = cleanHtml(sm[1]); const cnt = cleanHtml(sm[2]); if (spk && spk.length < 50) interviewees.add(spk); if (cnt) dialogueNodes.push({ speaker: spk || "Answer", content: cnt }); } } else { const cnt = cleanHtml(sub); if (cnt) dialogueNodes.push({ speaker: "Answer", content: cnt }); } } else if (m[3]) { const sm = m[3].match(/^(?:<[^>]*>)*(?:\d+<\/sup>)?([^<:]+):<\/strong>([\s\S]*)$/i); if (sm) { const spk = cleanHtml(sm[1]); const cnt = cleanHtml(sm[2]); if (spk && spk.length < 50) interviewees.add(spk); if (cnt) dialogueNodes.push({ speaker: spk, content: cnt }); } } } return { title, originalPrintSource, publicationDate, interviewees: [...interviewees], dialogueNodes, }; } export function toDragonBallJsonlDocument(row: ScrapeRow): DragonBallJsonlDocument { const metadata = mergedMetadata(row); const canonicalUrl = stringOrNull(metadata.canonical) ?? row.url; const url = new URL(canonicalUrl); const toei = toeiFields(url); const markdown = row.markdown ?? ""; let title = stringOrNull(metadata.title) ?? ""; let publicationDate = stringOrNull(metadata.publicationDate) ?? stringOrNull(metadata.date); let originalPrintSource = stringOrNull(metadata.originalPrintSource); const authorsOrEntities: string[] = []; const author = stringOrNull(metadata.author) ?? stringOrNull(metadata.authorName); if (author) authorsOrEntities.push(author); let dialogueNodes: Array<{ speaker: string; content: string }> = []; // If this is a Kanzenshuu translation page, extract Q&A dialogue nodes, original print source, and publication date if (url.hostname === "www.kanzenshuu.com" && url.pathname.includes("/translations/") && row.content) { const kanz = parseKanzenshuuTranslation(row.content, canonicalUrl); if (kanz.title && !title) title = kanz.title; if (kanz.originalPrintSource && !originalPrintSource) originalPrintSource = kanz.originalPrintSource; if (kanz.publicationDate && !publicationDate) publicationDate = kanz.publicationDate; for (const person of kanz.interviewees) { if (!authorsOrEntities.includes(person)) authorsOrEntities.push(person); } dialogueNodes = kanz.dialogueNodes; } const parsedTimestamp = row.timestamp ? new Date(row.timestamp) : null; const timestampUtc = parsedTimestamp && !Number.isNaN(parsedTimestamp.getTime()) ? parsedTimestamp.toISOString() : new Date().toISOString(); return { crawl_id: "crawl_toriyama_archive_full", document_uid: sha256(`${url.hostname}${canonicalUrl}`), canonical_url: canonicalUrl, source_domain: url.hostname, category: dragonBallCategory(canonicalUrl), http_status: row.status ?? 0, payload: { title_raw: title, publication_date: publicationDate, authors_or_entities: authorsOrEntities, structured_fields: { series_identifier: stringOrNull(metadata.series) ?? toei.series, episode_or_chapter_number: typeof metadata.episodeNumber === "number" ? metadata.episodeNumber : toei.episodeNumber, toc_rank: typeof metadata.tocRank === "number" ? metadata.tocRank : null, original_print_source: originalPrintSource, dialogue_nodes: dialogueNodes, }, body_markdown: markdown, embedded_media: extractEmbeddedMedia(`${row.content ?? ""}\n${markdown}\n${JSON.stringify(metadata.openGraph ?? {})}`, canonicalUrl), }, raw_checksum: sha256(markdown), timestamp_utc: timestampUtc, }; } /** Export the newest version of each canonical URL to newline-delimited JSON. */ export async function exportDragonBallJsonl(databasePath: string, outputPath: string): Promise { const database = new Database(databasePath, { readonly: true }); try { const rows = database.query(` SELECT s.id, s.url, s.status, s.content, s.metadata, s.json_data, s.markdown, s.timestamp FROM scrapes s JOIN (SELECT url, MAX(id) AS id FROM scrapes GROUP BY url) newest ON newest.id = s.id ORDER BY s.url `).all() as ScrapeRow[]; await mkdir(dirname(outputPath), { recursive: true }); const documents = new Map(); for (const row of rows) { const document = toDragonBallJsonlDocument(row); const existing = documents.get(document.canonical_url); if (!existing || (row.id ?? 0) > existing.id) documents.set(document.canonical_url, { id: row.id ?? 0, document }); } const content = [...documents.values()] .map(({ document }) => JSON.stringify(document)) .join("\n"); await Bun.write(outputPath, content ? `${content}\n` : ""); return documents.size; } finally { database.close(); } }