repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/pulse/core.ts

Raw
File outline
import * as fs from "node:fs";
import * as path from "node:path";

export const DEFAULT_DIR_GLOB = "**/*.md";

export type PulseDocType = "file" | "dir" | "glob";

export interface PulseDoc {
    path: string;
    type?: PulseDocType;
    glob?: string;
    instruction?: string;
    model?: string;
}

export interface PulseConfig {
    documents: PulseDoc[];
    model?: string;
    interval?: number;
}

const GLOB_CHARS = /[*?[]/;
const REGEX_CHARS = /[|\\{}()[\]^$+?.]/;

export function toSlash(s: string): string {
    return s.split(path.sep).join("/");
}

export function safeRelativePath(cwd: string, input: string): string {
    if (!input || path.isAbsolute(input)) throw new Error(`unsafe path: ${input}`);
    const rel = path.relative(cwd, path.resolve(cwd, input));
    if (rel.startsWith("..") || path.isAbsolute(rel)) throw new Error(`unsafe path: ${input}`);
    return rel === "" ? "." : toSlash(rel);
}

export function assertSafeGlob(pattern: string): void {
    if (!pattern || path.isAbsolute(pattern)) throw new Error(`unsafe glob: ${pattern}`);
    for (const part of toSlash(pattern).split("/")) {
        if (part === "..") throw new Error(`unsafe glob: ${pattern}`);
    }
}

export function createFileDoc(cwd: string, filePath: string, instruction?: string): PulseDoc {
    const rel = safeRelativePath(cwd, filePath);
    const st = fs.statSync(path.join(cwd, rel));
    if (!st.isFile()) throw new Error(`not a file: ${rel}`);
    return instruction ? { path: rel, instruction } : { path: rel };
}

export function createDirDoc(cwd: string, dirPath: string, glob: string, instruction?: string): PulseDoc {
    const rel = safeRelativePath(cwd, dirPath);
    assertSafeGlob(glob);
    const st = fs.statSync(path.join(cwd, rel));
    if (!st.isDirectory()) throw new Error(`not a directory: ${rel}`);
    const doc: PulseDoc = { path: rel, type: "dir", glob: toSlash(glob) };
    if (instruction) doc.instruction = instruction;
    return doc;
}

export function createGlobDoc(pattern: string, instruction?: string): PulseDoc {
    assertSafeGlob(pattern);
    const doc: PulseDoc = { path: toSlash(pattern), type: "glob" };
    if (instruction) doc.instruction = instruction;
    return doc;
}

export function normalizeDoc(cwd: string, doc: PulseDoc): PulseDoc | null {
    if (!doc || typeof doc.path !== "string") return null;
    const type = doc.type ?? "file";
    if (type !== "file" && type !== "dir" && type !== "glob") return null;
    try {
        if (type === "glob") {
            assertSafeGlob(doc.path);
            return { ...doc, path: toSlash(doc.path), type };
        }
        const rel = safeRelativePath(cwd, doc.path);
        if (type === "dir") {
            const glob = doc.glob ?? DEFAULT_DIR_GLOB;
            assertSafeGlob(glob);
            return { ...doc, path: rel, type, glob: toSlash(glob) };
        }
        return { ...doc, path: rel };
    } catch {
        return null;
    }
}

function globBase(pattern: string): string {
    const parts = toSlash(pattern).split("/");
    const base: string[] = [];
    for (const part of parts) {
        if (GLOB_CHARS.test(part)) break;
        base.push(part);
    }
    return base.join("/") || ".";
}

export function globToRegExp(pattern: string): RegExp {
    const g = toSlash(pattern);
    let s = "^";
    for (let i = 0; i < g.length;) {
        const c = g[i];
        if (c === "*") {
            if (g[i + 1] === "*") {
                i += 2;
                if (g[i] === "/") {
                    i++;
                    s += "(?:.*/)?";
                } else {
                    s += ".*";
                }
                continue;
            }
            s += "[^/]*";
            i++;
            continue;
        }
        if (c === "?") {
            s += "[^/]";
            i++;
            continue;
        }
        s += REGEX_CHARS.test(c) ? `\\${c}` : c;
        i++;
    }
    return new RegExp(`${s}$`);
}

function collectFiles(dir: string, out: string[]): void {
    let entries: fs.Dirent[];
    try {
        entries = fs.readdirSync(dir, { withFileTypes: true });
    } catch {
        return;
    }
    for (const e of entries) {
        const p = path.join(dir, e.name);
        if (e.isFile()) {
            out.push(p);
            continue;
        }
        if (e.isDirectory()) collectFiles(p, out);
    }
}

function expandGlob(cwd: string, pattern: string): string[] {
    assertSafeGlob(pattern);
    const base = safeRelativePath(cwd, globBase(pattern));
    const baseAbs = path.join(cwd, base);
    const re = globToRegExp(pattern);
    const files: string[] = [];
    collectFiles(baseAbs, files);
    return files
        .map((f) => toSlash(path.relative(cwd, f)))
        .filter((rel) => re.test(rel))
        .sort();
}

export function expandPulseDocuments(cwd: string, docs: PulseDoc[]): PulseDoc[] {
    const out: PulseDoc[] = [];
    const seen = new Set<string>();
    const push = (doc: PulseDoc): void => {
        if (seen.has(doc.path)) return;
        seen.add(doc.path);
        out.push(doc);
    };
    for (const raw of docs) {
        const doc = normalizeDoc(cwd, raw);
        if (!doc) continue;
        const type = doc.type ?? "file";
        if (type === "glob") {
            for (const rel of expandGlob(cwd, doc.path)) push({ ...doc, path: rel, type: "file" });
            continue;
        }
        if (type === "dir") {
            for (const rel of expandGlob(cwd, `${doc.path}/${doc.glob ?? DEFAULT_DIR_GLOB}`)) push({ ...doc, path: rel, type: "file" });
            continue;
        }
        try {
            if (fs.statSync(path.join(cwd, doc.path)).isFile()) push({ ...doc, type: "file" });
        } catch {}
    }
    return out;
}

export function formatDoc(doc: PulseDoc): string {
    const type = doc.type ?? "file";
    if (type === "dir") return `${doc.path} (${doc.glob ?? DEFAULT_DIR_GLOB})`;
    if (type === "glob") return doc.path;
    return doc.path;
}