var __defProp = Object.defineProperty;
var __publicField = (obj, key, value) => {
  if (typeof key !== "symbol")
    key += "";
  if (key in obj)
    return __defProp(obj, key, {enumerable: true, configurable: true, writable: true, value});
  return obj[key] = value;
};
var _a;
import "/error/node:fs?from=flat-cache";
;
import {CacheableMemory} from "/-/cacheable@v2.3.4-6GAADUoFtbM8xccxRhpF/dist=es2019,mode=imports/optimized/cacheable.js";
import {parse, stringify} from "/new/flatted@v3.4.2/dist=es2019,mode=imports?from=flatted";
import {Hookified} from "/-/hookified@v1.15.1-pPPPUB3iC7T1vU6yEZ3J/dist=es2019,mode=imports/optimized/hookified.js";
function normalizeArray(parts, allowAboveRoot) {
  var up = 0;
  for (var i = parts.length - 1; i >= 0; i--) {
    var last = parts[i];
    if (last === ".") {
      parts.splice(i, 1);
    } else if (last === "..") {
      parts.splice(i, 1);
      up++;
    } else if (up) {
      parts.splice(i, 1);
      up--;
    }
  }
  if (allowAboveRoot) {
    for (; up--; up) {
      parts.unshift("..");
    }
  }
  return parts;
}
var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function(filename) {
  return splitPathRe.exec(filename).slice(1);
};
function resolve() {
  var resolvedPath = "", resolvedAbsolute = false;
  for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    var path2 = i >= 0 ? arguments[i] : "/";
    if (typeof path2 !== "string") {
      throw new TypeError("Arguments to path.resolve must be strings");
    } else if (!path2) {
      continue;
    }
    resolvedPath = path2 + "/" + resolvedPath;
    resolvedAbsolute = path2.charAt(0) === "/";
  }
  resolvedPath = normalizeArray(filter(resolvedPath.split("/"), function(p) {
    return !!p;
  }), !resolvedAbsolute).join("/");
  return (resolvedAbsolute ? "/" : "") + resolvedPath || ".";
}
function normalize(path2) {
  var isPathAbsolute = isAbsolute(path2), trailingSlash = substr(path2, -1) === "/";
  path2 = normalizeArray(filter(path2.split("/"), function(p) {
    return !!p;
  }), !isPathAbsolute).join("/");
  if (!path2 && !isPathAbsolute) {
    path2 = ".";
  }
  if (path2 && trailingSlash) {
    path2 += "/";
  }
  return (isPathAbsolute ? "/" : "") + path2;
}
function isAbsolute(path2) {
  return path2.charAt(0) === "/";
}
function join() {
  var paths = Array.prototype.slice.call(arguments, 0);
  return normalize(filter(paths, function(p, index) {
    if (typeof p !== "string") {
      throw new TypeError("Arguments to path.join must be strings");
    }
    return p;
  }).join("/"));
}
function relative(from, to) {
  from = resolve(from).substr(1);
  to = resolve(to).substr(1);
  function trim(arr) {
    var start = 0;
    for (; start < arr.length; start++) {
      if (arr[start] !== "")
        break;
    }
    var end = arr.length - 1;
    for (; end >= 0; end--) {
      if (arr[end] !== "")
        break;
    }
    if (start > end)
      return [];
    return arr.slice(start, end - start + 1);
  }
  var fromParts = trim(from.split("/"));
  var toParts = trim(to.split("/"));
  var length = Math.min(fromParts.length, toParts.length);
  var samePartsLength = length;
  for (var i = 0; i < length; i++) {
    if (fromParts[i] !== toParts[i]) {
      samePartsLength = i;
      break;
    }
  }
  var outputParts = [];
  for (var i = samePartsLength; i < fromParts.length; i++) {
    outputParts.push("..");
  }
  outputParts = outputParts.concat(toParts.slice(samePartsLength));
  return outputParts.join("/");
}
var sep = "/";
var delimiter = ":";
function dirname(path2) {
  var result = splitPath(path2), root = result[0], dir = result[1];
  if (!root && !dir) {
    return ".";
  }
  if (dir) {
    dir = dir.substr(0, dir.length - 1);
  }
  return root + dir;
}
function basename(path2, ext) {
  var f = splitPath(path2)[2];
  if (ext && f.substr(-1 * ext.length) === ext) {
    f = f.substr(0, f.length - ext.length);
  }
  return f;
}
function extname(path2) {
  return splitPath(path2)[3];
}
var path = {
  extname,
  basename,
  dirname,
  sep,
  delimiter,
  relative,
  join,
  isAbsolute,
  normalize,
  resolve
};
function filter(xs, f) {
  if (xs.filter)
    return xs.filter(f);
  var res = [];
  for (var i = 0; i < xs.length; i++) {
    if (f(xs[i], i, xs))
      res.push(xs[i]);
  }
  return res;
}
var substr = "ab".substr(-1) === "b" ? function(str, start, len) {
  return str.substr(start, len);
} : function(str, start, len) {
  if (start < 0)
    start = str.length + start;
  return str.substr(start, len);
};
var FlatCacheEvents = /* @__PURE__ */ ((FlatCacheEvents2) => {
  FlatCacheEvents2["SAVE"] = "save";
  FlatCacheEvents2["LOAD"] = "load";
  FlatCacheEvents2["DELETE"] = "delete";
  FlatCacheEvents2["CLEAR"] = "clear";
  FlatCacheEvents2["DESTROY"] = "destroy";
  FlatCacheEvents2["ERROR"] = "error";
  FlatCacheEvents2["EXPIRED"] = "expired";
  return FlatCacheEvents2;
})(FlatCacheEvents || {});
var FlatCache = class extends Hookified {
  constructor(options) {
    super();
    __publicField(this, "_cache", new CacheableMemory());
    __publicField(this, "_cacheDir", ".cache");
    __publicField(this, "_cacheId", "cache1");
    __publicField(this, "_persistInterval", 0);
    __publicField(this, "_persistTimer");
    __publicField(this, "_changesSinceLastSave", false);
    __publicField(this, "_parse", parse);
    __publicField(this, "_stringify", stringify);
    if (options) {
      this._cache = new CacheableMemory({
        ttl: options.ttl,
        useClone: options.useClone,
        lruSize: options.lruSize,
        checkInterval: options.expirationInterval
      });
    }
    if (options == null ? void 0 : options.cacheDir) {
      this._cacheDir = options.cacheDir;
    }
    if (options == null ? void 0 : options.cacheId) {
      this._cacheId = options.cacheId;
    }
    if (options == null ? void 0 : options.persistInterval) {
      this._persistInterval = options.persistInterval;
      this.startAutoPersist();
    }
    if (options == null ? void 0 : options.deserialize) {
      this._parse = options.deserialize;
    }
    if (options == null ? void 0 : options.serialize) {
      this._stringify = options.serialize;
    }
  }
  get cache() {
    return this._cache;
  }
  get cacheDir() {
    return this._cacheDir;
  }
  set cacheDir(value) {
    this._cacheDir = value;
  }
  get cacheId() {
    return this._cacheId;
  }
  set cacheId(value) {
    this._cacheId = value;
  }
  get changesSinceLastSave() {
    return this._changesSinceLastSave;
  }
  get persistInterval() {
    return this._persistInterval;
  }
  set persistInterval(value) {
    this._persistInterval = value;
  }
  load(cacheId, cacheDir) {
    try {
      const filePath = path.resolve(`${cacheDir != null ? cacheDir : this._cacheDir}/${cacheId != null ? cacheId : this._cacheId}`);
      this.loadFile(filePath);
      this.emit("load");
    } catch (error) {
      this.emit("error", error);
    }
  }
  loadFile(pathToFile) {
    if (fs.existsSync(pathToFile)) {
      const data = fs.readFileSync(pathToFile, "utf8");
      const items = this._parse(data);
      if (Array.isArray(items)) {
        for (const item of items) {
          if (item && typeof item === "object" && "key" in item) {
            if (item.expires) {
              this._cache.set(item.key, item.value, {expire: item.expires});
            } else if (item.timestamp) {
              this._cache.set(item.key, item.value, {expire: item.timestamp});
            } else {
              this._cache.set(item.key, item.value);
            }
          }
        }
      } else {
        for (const key of Object.keys(items)) {
          const item = items[key];
          if (item && typeof item === "object" && "key" in item) {
            this._cache.set(item.key, item.value, {
              expire: item.expires
            });
          } else {
            if (item && typeof item === "object" && item.timestamp) {
              this._cache.set(key, item, {expire: item.timestamp});
            } else {
              this._cache.set(key, item);
            }
          }
        }
      }
      this._changesSinceLastSave = true;
    }
  }
  loadFileStream(pathToFile, onProgress, onEnd, onError) {
    if (fs.existsSync(pathToFile)) {
      const stats = fs.statSync(pathToFile);
      const total = stats.size;
      let loaded = 0;
      let streamData = "";
      const readStream = fs.createReadStream(pathToFile, {encoding: "utf8"});
      readStream.on("data", (chunk) => {
        loaded += chunk.length;
        streamData += chunk;
        onProgress(loaded, total);
      });
      readStream.on("end", () => {
        const items = this._parse(streamData);
        for (const key of Object.keys(items)) {
          this._cache.set(items[key].key, items[key].value, {
            expire: items[key].expires
          });
        }
        this._changesSinceLastSave = true;
        onEnd();
      });
      readStream.on("error", (error) => {
        this.emit("error", error);
        if (onError) {
          onError(error);
        }
      });
    } else {
      const error = new Error(`Cache file ${pathToFile} does not exist`);
      this.emit("error", error);
      if (onError) {
        onError(error);
      }
    }
  }
  all() {
    const result = {};
    const items = [...this._cache.items];
    for (const item of items) {
      result[item.key] = item.value;
    }
    return result;
  }
  get items() {
    return [...this._cache.items];
  }
  get cacheFilePath() {
    return path.resolve(`${this._cacheDir}/${this._cacheId}`);
  }
  get cacheDirPath() {
    return path.resolve(this._cacheDir);
  }
  keys() {
    return [...this._cache.keys];
  }
  setKey(key, value, ttl) {
    this.set(key, value, ttl);
  }
  set(key, value, ttl) {
    this._cache.set(key, value, ttl);
    this._changesSinceLastSave = true;
  }
  removeKey(key) {
    this.delete(key);
  }
  delete(key) {
    this._cache.delete(key);
    this._changesSinceLastSave = true;
    this.emit("delete", key);
  }
  getKey(key) {
    return this.get(key);
  }
  get(key) {
    return this._cache.get(key);
  }
  clear() {
    try {
      this._cache.clear();
      this._changesSinceLastSave = true;
      this.save();
      this.emit("clear");
    } catch (error) {
      this.emit("error", error);
    }
  }
  save(force = false) {
    try {
      if (this._changesSinceLastSave || force) {
        const filePath = this.cacheFilePath;
        const items = [...this._cache.items];
        const data = this._stringify(items);
        if (!fs.existsSync(this._cacheDir)) {
          fs.mkdirSync(this._cacheDir, {recursive: true});
        }
        fs.writeFileSync(filePath, data);
        this._changesSinceLastSave = false;
        this.emit("save");
      }
    } catch (error) {
      this.emit("error", error);
    }
  }
  removeCacheFile() {
    try {
      if (fs.existsSync(this.cacheFilePath)) {
        fs.rmSync(this.cacheFilePath);
        return true;
      }
    } catch (error) {
      this.emit("error", error);
    }
    return false;
  }
  destroy(includeCacheDirectory = false) {
    try {
      this._cache.clear();
      this.stopAutoPersist();
      if (includeCacheDirectory) {
        fs.rmSync(this.cacheDirPath, {recursive: true, force: true});
      } else {
        fs.rmSync(this.cacheFilePath, {recursive: true, force: true});
      }
      this._changesSinceLastSave = false;
      this.emit("destroy");
    } catch (error) {
      this.emit("error", error);
    }
  }
  startAutoPersist() {
    if (this._persistInterval > 0) {
      if (this._persistTimer) {
        clearInterval(this._persistTimer);
        this._persistTimer = void 0;
      }
      this._persistTimer = setInterval(() => {
        this.save();
      }, this._persistInterval);
    }
  }
  stopAutoPersist() {
    if (this._persistTimer) {
      clearInterval(this._persistTimer);
      this._persistTimer = void 0;
    }
  }
};
var FlatCacheDefault = (_a = class {
}, __publicField(_a, "create", create), __publicField(_a, "createFromFile", createFromFile), __publicField(_a, "clearCacheById", clearCacheById), __publicField(_a, "clearAll", clearAll), _a);
function create(options) {
  const cache = new FlatCache(options);
  cache.load();
  return cache;
}
function createFromFile(filePath, options) {
  const cache = new FlatCache(options);
  cache.loadFile(filePath);
  return cache;
}
function clearCacheById(cacheId, cacheDirectory) {
  const cache = new FlatCache({cacheId, cacheDir: cacheDirectory});
  cache.destroy();
}
function clearAll(cacheDirectory) {
  fs.rmSync(cacheDirectory != null ? cacheDirectory : ".cache", {recursive: true, force: true});
}
/* v8 ignore next -- @preserve */
export default FlatCacheDefault;
export {FlatCache, FlatCacheEvents, clearAll, clearCacheById, create, createFromFile};
