"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FileSystemLocalStorage = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
class FileSystemLocalStorage {
    constructor(directory) {
        this.dir = directory;
        fs_1.default.mkdirSync(this.dir, { recursive: true });
    }
    get length() {
        return this.keys().length;
    }
    key(index) {
        const keys = this.keys();
        return index >= 0 && index < keys.length ? keys[index] : null;
    }
    getItem(key) {
        const file = this.filePath(key);
        if (!fs_1.default.existsSync(file)) {
            return null;
        }
        return fs_1.default.readFileSync(file, 'utf8');
    }
    setItem(key, value) {
        const file = this.filePath(key);
        fs_1.default.writeFileSync(file, String(value), 'utf8');
    }
    removeItem(key) {
        const file = this.filePath(key);
        if (fs_1.default.existsSync(file)) {
            fs_1.default.unlinkSync(file);
        }
    }
    clear() {
        for (const key of this.keys()) {
            this.removeItem(key);
        }
    }
    keys() {
        const keys = fs_1.default
            .readdirSync(this.dir, { withFileTypes: true })
            .filter((d) => d.isFile())
            .map((d) => this.decodeKey(d.name))
            .sort();
        return keys;
    }
    filePath(key) {
        return path_1.default.join(this.dir, this.encodeKey(key));
    }
    encodeKey(key) {
        return encodeURIComponent(key);
    }
    decodeKey(filename) {
        return decodeURIComponent(filename);
    }
}
exports.FileSystemLocalStorage = FileSystemLocalStorage;
//# sourceMappingURL=localStorage.js.map