src / store.ts

import { createHash, randomBytes } from "node:crypto";
import { mkdir, open, readFile, rename, stat } from "node:fs/promises";
import { join } from "node:path";
import { extractDocument, MAX_COLLECTION_BYTES, MAX_DOCUMENTS, MAX_FILE_BYTES } from "./documents";
import type { DocumentEncoding, EncodingSource } from "./encoding";
import { parseJson, type JsonIndex, type JsonType } from "./json";
import type { HtmlIndex } from "./web/html";

export interface DocumentInfo {
  id: string; name: string; hash: string; bytes: number; lines: number;
  sourceKind: "attachment" | "conversation" | "web";
  encoding?: Exclude<DocumentEncoding, "auto">;
  encodingSource?: EncodingSource;
  format?: "text" | "html" | "json";
  jsonRootType?: JsonType;
  jsonNodes?: number;
  htmlBlocks?: number;
  title?: string; sourceUrl?: string; retrievedAt?: string; sourceEncoding?: string;
}
export interface Document extends DocumentInfo { text: string; json?: JsonIndex; sourceHtml?: string; html?: HtmlIndex; }
export interface Collection { version: 1; id: string; documents: DocumentInfo[]; }
export class MissingSearchDataError extends Error {
  constructor(readonly kind: "collection" | "document", readonly id: string) {
    super(kind === "collection" ? "The requested collection ID does not exist in local search storage." : "The document is registered in this collection, but its stored content is missing.");
    this.name = "MissingSearchDataError";
  }
}
export const validId = (value: string): boolean => /^[a-f0-9]{32}$/.test(value);
const newId = () => randomBytes(16).toString("hex");

// Storage is independent of the attachment API. A future conversation archiver can
// feed UTF-8 text into add() using sourceKind="conversation".
export class DocumentStore {
  readonly root: string;
  constructor(workingDirectory: string) { this.root = join(workingDirectory, ".rag-search"); }

  private path(kind: "collections" | "documents" | "imports", id: string): string {
    if (!validId(id)) throw new Error("Invalid search ID.");
    return join(this.root, kind, `${id}.json`);
  }

  private async write(kind: "collections" | "documents" | "imports", id: string, value: unknown): Promise<void> {
    await mkdir(join(this.root, kind), { recursive: true });
    const target = this.path(kind, id);
    const temporary = `${target}.${newId()}.tmp`;
    const file = await open(temporary, "wx", 0o600);
    try { await file.writeFile(JSON.stringify(value)); } finally { await file.close(); }
    await rename(temporary, target);
  }

  async imported(key: string): Promise<Collection | undefined> {
    try {
      const path = this.path("imports", key);
      if ((await stat(path)).size > 1024) throw new Error("Invalid import receipt.");
      const { collectionId } = JSON.parse(await readFile(path, "utf8"));
      return await this.collection(collectionId);
    } catch (error) {
      if ((error as NodeJS.ErrnoException).code === "ENOENT" || error instanceof MissingSearchDataError && error.kind === "collection") return undefined;
      throw error;
    }
  }

  async rememberImport(key: string, collection: Collection): Promise<void> {
    await this.write("imports", key, { collectionId: collection.id });
  }

  async collection(id: string): Promise<Collection> {
    const path = this.path("collections", id);
    let raw: string;
    try {
      if ((await stat(path)).size > 2 * 1024 * 1024) throw new Error("Invalid collection size.");
      raw = await readFile(path, "utf8");
    } catch (error) {
      if ((error as NodeJS.ErrnoException).code === "ENOENT") throw new MissingSearchDataError("collection", id);
      throw error;
    }
    const value = JSON.parse(raw) as Collection;
    if (value.version !== 1 || value.id !== id || !Array.isArray(value.documents) || value.documents.length > MAX_DOCUMENTS) throw new Error("Invalid collection.");
    return value;
  }

  async document(collection: Collection, id: string, signal?: AbortSignal): Promise<Document> {
    if (!collection.documents.some(d => d.id === id)) throw new Error("Document is not in this collection.");
    signal?.throwIfAborted();
    const path = this.path("documents", id);
    let raw: string;
    try {
      if ((await stat(path)).size > MAX_FILE_BYTES * 7) throw new Error("Invalid stored document size.");
      raw = await readFile(path, {encoding: "utf8", signal});
    } catch (error) {
      if ((error as NodeJS.ErrnoException).code === "ENOENT") throw new MissingSearchDataError("document", id);
      throw error;
    }
    const value = JSON.parse(raw) as Document;
    if (value.id !== id || typeof value.text !== "string") throw new Error("Invalid stored document.");
    // Old uploads remain usable without modifying their original stored text.
    if (/\.json$/i.test(value.name) && !value.json) value.json = parseJson(value.text);
    return value;
  }

  async add(previous: Collection | undefined, inputs: {name: string; bytes: Buffer; sourceKind?: DocumentInfo["sourceKind"]; encoding?: DocumentEncoding; sourceUrl?: string; retrievedAt?: string; sourceEncoding?: string}[], signal?: AbortSignal, encoding: DocumentEncoding = "auto"): Promise<Collection> {
    const documents = [...(previous?.documents ?? [])];
    for (const input of inputs) {
      signal?.throwIfAborted();
      const name = input.name.slice(0, 512);
      const extracted = extractDocument(name, input.bytes, input.encoding ?? encoding, input.sourceUrl);
      const text = extracted.text;
      const sourceKind = input.sourceKind ?? "attachment";
      const hash = createHash("sha256").update(text).digest("hex");
      if (documents.some(d => d.hash === hash && d.name === name && d.sourceKind === sourceKind && (!extracted.html || d.htmlBlocks !== undefined))) continue;
      const bytes = Buffer.byteLength(text);
      if (documents.length >= MAX_DOCUMENTS || documents.reduce((sum, d) => sum + d.bytes, 0) + bytes > MAX_COLLECTION_BYTES) throw new Error("Collection exceeds 200 documents or 128 MiB of extracted text.");
      const info: DocumentInfo = { id: newId(), name, hash, bytes, lines: text.split("\n").length, sourceKind,
        encoding: extracted.encoding, encodingSource: extracted.encodingSource,
        format: extracted.json ? "json" : /\.html?$/i.test(name) ? "html" : "text",
        ...(extracted.json ? {jsonRootType: extracted.json.nodes[0].type, jsonNodes: extracted.json.nodes.length} : {}),
        ...(extracted.html ? {htmlBlocks: extracted.html.blocks.length, title: extracted.html.title} : {}),
        sourceUrl: input.sourceUrl, retrievedAt: input.retrievedAt, sourceEncoding: input.sourceEncoding };
      await this.write("documents", info.id, { ...info, text, json: extracted.json, sourceHtml: extracted.sourceHtml, html: extracted.html });
      documents.push(info);
    }
    if (previous && documents.length === previous.documents.length) return previous;
    const collection: Collection = { version: 1, id: newId(), documents };
    signal?.throwIfAborted();
    await this.write("collections", collection.id, collection);
    return collection;
  }
}