/** * Internet Archive and Wayback Machine client. * * This module deliberately uses the documented HTTP APIs directly. It offers * the useful high-level ergonomics of `internetarchive`/`iajs` while keeping * BXC dependency-free and usable from Bun, Node-compatible runtimes, and MCP. */ export const ARCHIVE_ORG = "https://archive.org"; export const WAYBACK_CDX = "https://web.archive.org/cdx/search/cdx"; export interface ArchiveFile { name: string; source?: string; format?: string; mtime?: string; size?: string; sha1?: string; md5?: string; [key: string]: unknown; } export interface ArchiveItem { created: number; d1: string; d2: string; dir: string; files: ArchiveFile[]; files_count: number; item_last_updated: number; item_size: number; metadata: Record; server: string; uniq: number; workable_servers: string[]; } export interface ArchiveSearchOptions { fields?: string[]; rows?: number; page?: number; sort?: string | string[]; facet?: string | string[]; and?: boolean; } export interface ArchiveSearchResult { response: { numFound: number; start: number; docs: Record[]; }; facets?: Record; } export interface CdxCapture { urlkey?: string; timestamp: string; original: string; mimetype?: string; statuscode?: string; digest?: string; length?: string; [key: string]: string | undefined; } export interface WaybackOptions { matchType?: "exact" | "prefix" | "host" | "domain"; from?: string; to?: string; filter?: string | string[]; collapse?: string; limit?: number; fl?: string[]; showResumeKey?: boolean; } export interface ArchiveCredentials { accessKey: string; secretKey: string; } export interface UploadOptions { metadata?: Record; collection?: string | string[]; mediatype?: string; headers?: HeadersInit; credentials: ArchiveCredentials; } /** Deliberately narrower than Bun's augmented `typeof fetch`, making it easy to mock. */ export type ArchiveFetch = ( input: RequestInfo | URL, init?: RequestInit, ) => Promise; export class ArchiveHttpError extends Error { constructor( public readonly response: Response, message?: string, ) { super( message ?? `Internet Archive request failed: HTTP ${response.status}`, ); this.name = "ArchiveHttpError"; } } function appendMany( params: URLSearchParams, key: string, values?: string | string[], ) { if (!values) return; for (const value of Array.isArray(values) ? values : [values]) params.append(key, value); } async function expectJson(response: Response): Promise { if (!response.ok) { const detail = (await response.text()).slice(0, 500); throw new ArchiveHttpError( response, `Internet Archive request failed: HTTP ${response.status}${detail ? ` — ${detail}` : ""}`, ); } return response.json() as Promise; } /** Build a stable, safely encoded public file URL without fetching it. */ export function archiveDownloadUrl( identifier: string, filename: string, ): string { return `${ARCHIVE_ORG}/download/${encodeURIComponent(identifier)}/${filename.split("/").map(encodeURIComponent).join("/")}`; } /** Build the playable embedded BookReader URL for an Archive.org identifier. */ export function archiveEmbedUrl(identifier: string): string { return `${ARCHIVE_ORG}/embed/${encodeURIComponent(identifier)}`; } export class ArchiveClient { constructor( private readonly fetchImpl: ArchiveFetch = fetch, private readonly baseUrl = ARCHIVE_ORG, private readonly cdxUrl = WAYBACK_CDX, ) {} async getItem( identifier: string, signal?: AbortSignal, ): Promise { return expectJson( await this.fetchImpl( `${this.baseUrl}/metadata/${encodeURIComponent(identifier)}`, { signal }, ), ); } async search( query: string, options: ArchiveSearchOptions = {}, signal?: AbortSignal, ): Promise { const params = new URLSearchParams({ q: query, output: "json", rows: String(Math.min(Math.max(options.rows ?? 50, 1), 1000)), page: String(Math.max(options.page ?? 1, 1)), }); for (const field of options.fields ?? [ "identifier", "title", "creator", "date", "mediatype", "collection", "downloads", "description", ]) params.append("fl[]", field); appendMany(params, "sort[]", options.sort); appendMany(params, "facet[]", options.facet); if (options.and) params.set("and[]", "true"); return expectJson( await this.fetchImpl(`${this.baseUrl}/advancedsearch.php?${params}`, { signal, }), ); } async listFiles( identifier: string, signal?: AbortSignal, ): Promise { return (await this.getItem(identifier, signal)).files ?? []; } async download( identifier: string, filename: string, signal?: AbortSignal, ): Promise { const response = await this.fetchImpl( archiveDownloadUrl(identifier, filename), { signal }, ); if (!response.ok) throw new ArchiveHttpError(response); return response; } async cdx( url: string, options: WaybackOptions = {}, signal?: AbortSignal, ): Promise { const params = new URLSearchParams({ url, output: "json" }); if (options.matchType) params.set("matchType", options.matchType); if (options.from) params.set("from", options.from); if (options.to) params.set("to", options.to); if (options.collapse) params.set("collapse", options.collapse); if (options.limit !== undefined) params.set("limit", String(options.limit)); if (options.showResumeKey) params.set("showResumeKey", "true"); appendMany(params, "filter", options.filter); if (options.fl?.length) params.set("fl", options.fl.join(",")); const data = await expectJson( await this.fetchImpl(`${this.cdxUrl}?${params}`, { signal }), ); if (data.length === 0) return []; const [columns, ...rows] = data; return rows.map( (row) => Object.fromEntries( columns.map((column, index) => [column, row[index] ?? ""]), ) as CdxCapture, ); } /** Returns the archived replay URL for a specific CDX capture. */ replayUrl(capture: Pick): string { return `https://web.archive.org/web/${capture.timestamp}id_/${capture.original}`; } /** * Upload a file using Internet Archive's S3-compatible, LOW-signed API. * Credentials are only used in-memory and are never persisted by BXC. */ async upload( identifier: string, filename: string, body: BodyInit, options: UploadOptions, ): Promise { const date = new Date().toUTCString(); const headers = new Headers(options.headers); headers.set("Date", date); headers.set("x-archive-auto-make-bucket", "1"); if (options.collection) headers.set( "x-archive-meta-collection", Array.isArray(options.collection) ? options.collection.join(",") : options.collection, ); if (options.mediatype) headers.set("x-archive-meta-mediatype", options.mediatype); for (const [key, value] of Object.entries(options.metadata ?? {})) headers.set(`x-archive-meta-${key.toLowerCase()}`, String(value)); const contentType = headers.get("Content-Type") ?? ""; const canonicalAmz = [...headers] .filter(([key]) => key.toLowerCase().startsWith("x-archive-")) .map(([key, value]) => `${key.toLowerCase()}:${value.trim()}\n`) .sort() .join(""); const path = `/${identifier}/${filename}`; const signature = await hmacSha1Base64( options.credentials.secretKey, `PUT\n\n${contentType}\n${date}\n${canonicalAmz}${path}`, ); headers.set( "Authorization", `LOW ${options.credentials.accessKey}:${signature}`, ); const response = await this.fetchImpl( `${this.baseUrl}/${encodeURIComponent(identifier)}/${filename.split("/").map(encodeURIComponent).join("/")}`, { method: "PUT", headers, body }, ); if (!response.ok) throw new ArchiveHttpError(response); return response; } } async function hmacSha1Base64(secret: string, value: string): Promise { const key = await crypto.subtle.importKey( "raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-1" }, false, ["sign"], ); const signature = await crypto.subtle.sign( "HMAC", key, new TextEncoder().encode(value), ); return btoa(String.fromCharCode(...new Uint8Array(signature))); } export const archive = new ArchiveClient(); export * from "./shenron.ts";