"use strict";
/**
 * Track storage — read/write .tr files under <project>/.ccweb/tracks/.
 *
 * Mirrors backend/src/flows/store.ts but for .tr source files instead
 * of FlowDef JSON. Each track is a plain UTF-8 text file (train-lang
 * source). No schema validation here — parse errors surface from
 * train-lang when the track is run.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.sanitizeTrackFilename = sanitizeTrackFilename;
exports.listTracks = listTracks;
exports.loadTrack = loadTrack;
exports.saveTrack = saveTrack;
exports.deleteTrack = deleteTrack;
exports.resolveTrackPath = resolveTrackPath;
exports.listGlobalTracks = listGlobalTracks;
exports.loadGlobalTrack = loadGlobalTrack;
exports.saveGlobalTrack = saveGlobalTrack;
exports.deleteGlobalTrack = deleteGlobalTrack;
exports.resolveGlobalTrackPath = resolveGlobalTrackPath;
exports.saveSidecar = saveSidecar;
exports.loadSidecar = loadSidecar;
exports.deleteSidecar = deleteSidecar;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const TRACK_EXT = '.tr';
const TRACKS_DIRNAME = 'tracks';
/**
 * sanitize a user-provided filename: forbid path separators, ensure
 * .tr extension. Returns null if input is unsafe.
 */
function sanitizeTrackFilename(input) {
    if (typeof input !== 'string')
        return null;
    const trimmed = input.trim();
    if (!trimmed)
        return null;
    // No path separators or relative parents
    if (/[\\/]/.test(trimmed) || trimmed.includes('..'))
        return null;
    // No control bytes
    if (/[\x00-\x1f]/.test(trimmed))
        return null;
    // Ensure .tr extension
    const withExt = trimmed.endsWith(TRACK_EXT) ? trimmed : trimmed + TRACK_EXT;
    if (withExt.length > 200)
        return null;
    return withExt;
}
function tracksDir(projectFolder) {
    return path.join(projectFolder, '.ccweb', TRACKS_DIRNAME);
}
function trackPath(projectFolder, filename) {
    return path.join(tracksDir(projectFolder), filename);
}
function listTracks(projectFolder) {
    const dir = tracksDir(projectFolder);
    if (!fs.existsSync(dir))
        return [];
    const entries = fs.readdirSync(dir, { withFileTypes: true });
    const out = [];
    for (const e of entries) {
        if (!e.isFile() || !e.name.endsWith(TRACK_EXT))
            continue;
        const full = path.join(dir, e.name);
        try {
            const st = fs.statSync(full);
            out.push({ filename: e.name, size: st.size, mtime: st.mtimeMs });
        }
        catch {
            // skip unreadable
        }
    }
    return out.sort((a, b) => a.filename.localeCompare(b.filename));
}
/**
 * Read a track. Refuses to follow symlinks — if the on-disk entry is a
 * symlink, returns null. This prevents an attacker with write access to
 * `.ccweb/tracks/` from planting `attack.tr -> /etc/passwd` and reading
 * arbitrary files via the GET endpoint. Symmetric guard in saveTrack
 * (rejects writing to a path whose existing target is a symlink).
 */
function loadTrack(projectFolder, filename) {
    const p = trackPath(projectFolder, filename);
    try {
        const st = fs.lstatSync(p);
        if (!st.isFile())
            return null;
    }
    catch {
        return null;
    }
    try {
        return fs.readFileSync(p, 'utf8');
    }
    catch {
        return null;
    }
}
function saveTrack(projectFolder, filename, source) {
    const dir = tracksDir(projectFolder);
    try {
        fs.mkdirSync(dir, { recursive: true });
        const p = trackPath(projectFolder, filename);
        // Reject if the target already exists and is a symlink — same
        // guard as loadTrack. Without this, an attacker who can write the
        // symlink could redirect saves to arbitrary FS locations.
        try {
            const st = fs.lstatSync(p);
            if (st.isSymbolicLink())
                return false;
        }
        catch {
            // ENOENT — fine, we'll create a new file
        }
        const tmp = p + '.tmp-' + process.pid;
        fs.writeFileSync(tmp, source, 'utf8');
        fs.renameSync(tmp, p);
        return true;
    }
    catch {
        return false;
    }
}
function deleteTrack(projectFolder, filename) {
    const p = trackPath(projectFolder, filename);
    if (!fs.existsSync(p))
        return false;
    try {
        fs.unlinkSync(p);
        return true;
    }
    catch {
        return false;
    }
}
/** Absolute path used by TrackRunner when starting a run. */
function resolveTrackPath(projectFolder, filename) {
    return trackPath(projectFolder, filename);
}
// ── Global tracks (per-user templates) ──────────────────────────────────
function globalTracksDir(username) {
    return path.join(os.homedir(), '.ccweb', 'users', username, TRACKS_DIRNAME);
}
function globalTrackPath(username, filename) {
    return path.join(globalTracksDir(username), filename);
}
function listGlobalTracks(username) {
    const dir = globalTracksDir(username);
    if (!fs.existsSync(dir))
        return [];
    const entries = fs.readdirSync(dir, { withFileTypes: true });
    const out = [];
    for (const e of entries) {
        if (!e.isFile() || !e.name.endsWith(TRACK_EXT))
            continue;
        const full = path.join(dir, e.name);
        try {
            const st = fs.statSync(full);
            out.push({ filename: e.name, size: st.size, mtime: st.mtimeMs });
        }
        catch {
            // skip
        }
    }
    return out.sort((a, b) => a.filename.localeCompare(b.filename));
}
function loadGlobalTrack(username, filename) {
    const p = globalTrackPath(username, filename);
    try {
        const st = fs.lstatSync(p);
        if (!st.isFile())
            return null;
    }
    catch {
        return null;
    }
    try {
        return fs.readFileSync(p, 'utf8');
    }
    catch {
        return null;
    }
}
function saveGlobalTrack(username, filename, source) {
    const dir = globalTracksDir(username);
    try {
        fs.mkdirSync(dir, { recursive: true });
        const p = globalTrackPath(username, filename);
        try {
            const st = fs.lstatSync(p);
            if (st.isSymbolicLink())
                return false;
        }
        catch {
            // ENOENT — fine
        }
        const tmp = p + '.tmp-' + process.pid;
        fs.writeFileSync(tmp, source, 'utf8');
        fs.renameSync(tmp, p);
        return true;
    }
    catch {
        return false;
    }
}
function deleteGlobalTrack(username, filename) {
    const p = globalTrackPath(username, filename);
    if (!fs.existsSync(p))
        return false;
    try {
        fs.unlinkSync(p);
        return true;
    }
    catch {
        return false;
    }
}
function resolveGlobalTrackPath(username, filename) {
    return globalTrackPath(username, filename);
}
// ── Sidecar (graph metadata) ─────────────────────────────────────────────
function sidecarPath(projectFolder, filename) {
    const basename = filename.replace(/\.tr$/, '');
    return path.join(projectFolder, '.ccweb', 'tracks', `${basename}.tr.graph.json`);
}
function saveSidecar(projectFolder, filename, sidecar) {
    const target = sidecarPath(projectFolder, filename);
    const dir = path.dirname(target);
    try {
        fs.mkdirSync(dir, { recursive: true });
        fs.writeFileSync(target, JSON.stringify(sidecar, null, 2), 'utf8');
        return true;
    }
    catch {
        return false;
    }
}
function loadSidecar(projectFolder, filename) {
    const target = sidecarPath(projectFolder, filename);
    try {
        if (!fs.existsSync(target))
            return null;
        const raw = fs.readFileSync(target, 'utf8');
        return JSON.parse(raw);
    }
    catch {
        return null;
    }
}
function deleteSidecar(projectFolder, filename) {
    const target = sidecarPath(projectFolder, filename);
    try {
        fs.unlinkSync(target);
    }
    catch {
        // ignore — file may not exist
    }
}
//# sourceMappingURL=store.js.map