dist / fileSearch / store.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DocumentStore = exports.validId = exports.MissingSearchDataError = void 0;
const node_crypto_1 = require("node:crypto");
const promises_1 = require("node:fs/promises");
const node_path_1 = require("node:path");
const documents_1 = require("./documents");
const json_1 = require("./json");
class MissingSearchDataError extends Error {
    kind;
    id;
    constructor(kind, id) {
        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.kind = kind;
        this.id = id;
        this.name = "MissingSearchDataError";
    }
}
exports.MissingSearchDataError = MissingSearchDataError;
const validId = (value) => /^[a-f0-9]{32}$/.test(value);
exports.validId = validId;
const newId = () => (0, node_crypto_1.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".
class DocumentStore {
    root;
    constructor(workingDirectory) { this.root = (0, node_path_1.join)(workingDirectory, ".rag-search"); }
    path(kind, id) {
        if (!(0, exports.validId)(id))
            throw new Error("Invalid search ID.");
        return (0, node_path_1.join)(this.root, kind, `${id}.json`);
    }
    async write(kind, id, value) {
        await (0, promises_1.mkdir)((0, node_path_1.join)(this.root, kind), { recursive: true });
        const target = this.path(kind, id);
        const temporary = `${target}.${newId()}.tmp`;
        const file = await (0, promises_1.open)(temporary, "wx", 0o600);
        try {
            await file.writeFile(JSON.stringify(value));
        }
        finally {
            await file.close();
        }
        await (0, promises_1.rename)(temporary, target);
    }
    async imported(key) {
        try {
            const path = this.path("imports", key);
            if ((await (0, promises_1.stat)(path)).size > 1024)
                throw new Error("Invalid import receipt.");
            const { collectionId } = JSON.parse(await (0, promises_1.readFile)(path, "utf8"));
            return await this.collection(collectionId);
        }
        catch (error) {
            if (error.code === "ENOENT" || error instanceof MissingSearchDataError && error.kind === "collection")
                return undefined;
            throw error;
        }
    }
    async rememberImport(key, collection) {
        await this.write("imports", key, { collectionId: collection.id });
    }
    async collection(id) {
        const path = this.path("collections", id);
        let raw;
        try {
            if ((await (0, promises_1.stat)(path)).size > 2 * 1024 * 1024)
                throw new Error("Invalid collection size.");
            raw = await (0, promises_1.readFile)(path, "utf8");
        }
        catch (error) {
            if (error.code === "ENOENT")
                throw new MissingSearchDataError("collection", id);
            throw error;
        }
        const value = JSON.parse(raw);
        if (value.version !== 1 || value.id !== id || !Array.isArray(value.documents) || value.documents.length > documents_1.MAX_DOCUMENTS)
            throw new Error("Invalid collection.");
        return value;
    }
    async document(collection, id, signal) {
        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;
        try {
            if ((await (0, promises_1.stat)(path)).size > documents_1.MAX_FILE_BYTES * 7)
                throw new Error("Invalid stored document size.");
            raw = await (0, promises_1.readFile)(path, { encoding: "utf8", signal });
        }
        catch (error) {
            if (error.code === "ENOENT")
                throw new MissingSearchDataError("document", id);
            throw error;
        }
        const value = JSON.parse(raw);
        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 = (0, json_1.parseJson)(value.text);
        return value;
    }
    async add(previous, inputs, signal, encoding = "auto") {
        const documents = [...(previous?.documents ?? [])];
        for (const input of inputs) {
            signal?.throwIfAborted();
            const name = input.name.slice(0, 512);
            const extracted = (0, documents_1.extractDocument)(name, input.bytes, input.encoding ?? encoding, input.sourceUrl);
            const text = extracted.text;
            const sourceKind = input.sourceKind ?? "attachment";
            const hash = (0, node_crypto_1.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 >= documents_1.MAX_DOCUMENTS || documents.reduce((sum, d) => sum + d.bytes, 0) + bytes > documents_1.MAX_COLLECTION_BYTES)
                throw new Error("Collection exceeds 200 documents or 128 MiB of extracted text.");
            const info = { 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 = { version: 1, id: newId(), documents };
        signal?.throwIfAborted();
        await this.write("collections", collection.id, collection);
        return collection;
    }
}
exports.DocumentStore = DocumentStore;