"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const index = require("./index-skt9-lu6.cjs");
index.u();
var $ = "state.txt", G = "data", T = { DIR: 16384, FILE: 32768 }, H, v, F, M, y, b, m, x, P, D, S, n, C, O, k, w, f, I, W, j, L = class extends index.cr {
  constructor(e, { initialPoolSize: t = 1e3, maintainedPoolSize: o = 100, debug: i = false } = {}) {
    super(e, { debug: i });
    index.R(this, n);
    index.R(this, H);
    index.R(this, v);
    index.R(this, F);
    index.R(this, M);
    index.R(this, y);
    index.R(this, b, /* @__PURE__ */ new Map());
    index.R(this, m, /* @__PURE__ */ new Map());
    index.R(this, x, 0);
    index.R(this, P, /* @__PURE__ */ new Map());
    index.R(this, D, /* @__PURE__ */ new Map());
    this.lastCheckpoint = 0;
    this.checkpointInterval = 1e3 * 60;
    this.poolCounter = 0;
    index.R(this, S, /* @__PURE__ */ new Set());
    this.initialPoolSize = t, this.maintainedPoolSize = o;
  }
  async init(e, t) {
    return await index.T(this, n, C).call(this), super.init(e, t);
  }
  async syncToFs(e = false) {
    await this.maybeCheckpointState(), await this.maintainPool(), e || this.flush();
  }
  async closeFs() {
    for (let e of index.h(this, m).values()) e.close();
    index.h(this, y).flush(), index.h(this, y).close(), this.pg.Module.FS.quit();
  }
  async maintainPool(e) {
    e = e || this.maintainedPoolSize;
    let t = e - this.state.pool.length, o = [];
    for (let i = 0; i < t; i++) o.push(new Promise(async (c) => {
      ++this.poolCounter;
      let a = `${(Date.now() - 1704063600).toString(16).padStart(8, "0")}-${this.poolCounter.toString(16).padStart(8, "0")}`, h = await index.h(this, F).getFileHandle(a, { create: true }), d = await h.createSyncAccessHandle();
      index.h(this, b).set(a, h), index.h(this, m).set(a, d), index.T(this, n, k).call(this, { opp: "createPoolFile", args: [a] }), this.state.pool.push(a), c();
    }));
    for (let i = 0; i > t; i--) o.push(new Promise(async (c) => {
      var _a;
      let a = this.state.pool.pop();
      index.T(this, n, k).call(this, { opp: "deletePoolFile", args: [a] });
      let h = index.h(this, b).get(a);
      (_a = index.h(this, m).get(a)) == null ? void 0 : _a.close(), await index.h(this, F).removeEntry(h.name), index.h(this, b).delete(a), index.h(this, m).delete(a), c();
    }));
    await Promise.all(o);
  }
  _createPoolFileState(e) {
    this.state.pool.push(e);
  }
  _deletePoolFileState(e) {
    let t = this.state.pool.indexOf(e);
    t > -1 && this.state.pool.splice(t, 1);
  }
  async maybeCheckpointState() {
    Date.now() - this.lastCheckpoint > this.checkpointInterval && await this.checkpointState();
  }
  async checkpointState() {
    let e = new TextEncoder().encode(JSON.stringify(this.state));
    index.h(this, y).truncate(0), index.h(this, y).write(e, { at: 0 }), index.h(this, y).flush(), this.lastCheckpoint = Date.now();
  }
  flush() {
    for (let e of index.h(this, S)) try {
      e.flush();
    } catch {
    }
    index.h(this, S).clear();
  }
  chmod(e, t) {
    index.T(this, n, O).call(this, { opp: "chmod", args: [e, t] }, () => {
      this._chmodState(e, t);
    });
  }
  _chmodState(e, t) {
    let o = index.T(this, n, f).call(this, e);
    o.mode = t;
  }
  close(e) {
    let t = index.T(this, n, I).call(this, e);
    index.h(this, P).delete(e), index.h(this, D).delete(t);
  }
  fstat(e) {
    let t = index.T(this, n, I).call(this, e);
    return this.lstat(t);
  }
  lstat(e) {
    let t = index.T(this, n, f).call(this, e), o = t.type === "file" ? index.h(this, m).get(t.backingFilename).getSize() : 0, i = 4096;
    return { dev: 0, ino: 0, mode: t.mode, nlink: 1, uid: 0, gid: 0, rdev: 0, size: o, blksize: i, blocks: Math.ceil(o / i), atime: t.lastModified, mtime: t.lastModified, ctime: t.lastModified };
  }
  mkdir(e, t) {
    index.T(this, n, O).call(this, { opp: "mkdir", args: [e, t] }, () => {
      this._mkdirState(e, t);
    });
  }
  _mkdirState(e, t) {
    let o = index.T(this, n, w).call(this, e), i = o.pop(), c = [], a = this.state.root;
    for (let d of o) {
      if (c.push(e), !Object.prototype.hasOwnProperty.call(a.children, d)) if (t == null ? void 0 : t.recursive) this.mkdir(c.join("/"));
      else throw new p("ENOENT", "No such file or directory");
      if (a.children[d].type !== "directory") throw new p("ENOTDIR", "Not a directory");
      a = a.children[d];
    }
    if (Object.prototype.hasOwnProperty.call(a.children, i)) throw new p("EEXIST", "File exists");
    let h = { type: "directory", lastModified: Date.now(), mode: (t == null ? void 0 : t.mode) || T.DIR, children: {} };
    a.children[i] = h;
  }
  open(e, t, o) {
    if (index.T(this, n, f).call(this, e).type !== "file") throw new p("EISDIR", "Is a directory");
    let c = index.T(this, n, W).call(this);
    return index.h(this, P).set(c, e), index.h(this, D).set(e, c), c;
  }
  readdir(e) {
    let t = index.T(this, n, f).call(this, e);
    if (t.type !== "directory") throw new p("ENOTDIR", "Not a directory");
    return Object.keys(t.children);
  }
  read(e, t, o, i, c) {
    let a = index.T(this, n, I).call(this, e), h = index.T(this, n, f).call(this, a);
    if (h.type !== "file") throw new p("EISDIR", "Is a directory");
    return index.h(this, m).get(h.backingFilename).read(new Uint8Array(t.buffer, o, i), { at: c });
  }
  rename(e, t) {
    index.T(this, n, O).call(this, { opp: "rename", args: [e, t] }, () => {
      this._renameState(e, t, true);
    });
  }
  _renameState(e, t, o = false) {
    let i = index.T(this, n, w).call(this, e), c = i.pop(), a = index.T(this, n, f).call(this, i.join("/"));
    if (!Object.prototype.hasOwnProperty.call(a.children, c)) throw new p("ENOENT", "No such file or directory");
    let h = index.T(this, n, w).call(this, t), d = h.pop(), l = index.T(this, n, f).call(this, h.join("/"));
    if (o && Object.prototype.hasOwnProperty.call(l.children, d)) {
      let u = l.children[d];
      index.h(this, m).get(u.backingFilename).truncate(0), this.state.pool.push(u.backingFilename);
    }
    l.children[d] = a.children[c], delete a.children[c];
  }
  rmdir(e) {
    index.T(this, n, O).call(this, { opp: "rmdir", args: [e] }, () => {
      this._rmdirState(e);
    });
  }
  _rmdirState(e) {
    let t = index.T(this, n, w).call(this, e), o = t.pop(), i = index.T(this, n, f).call(this, t.join("/"));
    if (!Object.prototype.hasOwnProperty.call(i.children, o)) throw new p("ENOENT", "No such file or directory");
    let c = i.children[o];
    if (c.type !== "directory") throw new p("ENOTDIR", "Not a directory");
    if (Object.keys(c.children).length > 0) throw new p("ENOTEMPTY", "Directory not empty");
    delete i.children[o];
  }
  truncate(e, t = 0) {
    let o = index.T(this, n, f).call(this, e);
    if (o.type !== "file") throw new p("EISDIR", "Is a directory");
    let i = index.h(this, m).get(o.backingFilename);
    if (!i) throw new p("ENOENT", "No such file or directory");
    i.truncate(t), index.h(this, S).add(i);
  }
  unlink(e) {
    index.T(this, n, O).call(this, { opp: "unlink", args: [e] }, () => {
      this._unlinkState(e, true);
    });
  }
  _unlinkState(e, t = false) {
    let o = index.T(this, n, w).call(this, e), i = o.pop(), c = index.T(this, n, f).call(this, o.join("/"));
    if (!Object.prototype.hasOwnProperty.call(c.children, i)) throw new p("ENOENT", "No such file or directory");
    let a = c.children[i];
    if (a.type !== "file") throw new p("EISDIR", "Is a directory");
    if (delete c.children[i], t) {
      let h = index.h(this, m).get(a.backingFilename);
      h == null ? void 0 : h.truncate(0), index.h(this, S).add(h), index.h(this, D).has(e) && (index.h(this, P).delete(index.h(this, D).get(e)), index.h(this, D).delete(e));
    }
    this.state.pool.push(a.backingFilename);
  }
  utimes(e, t, o) {
    index.T(this, n, O).call(this, { opp: "utimes", args: [e, t, o] }, () => {
      this._utimesState(e, t, o);
    });
  }
  _utimesState(e, t, o) {
    let i = index.T(this, n, f).call(this, e);
    i.lastModified = o;
  }
  writeFile(e, t, o) {
    let i = index.T(this, n, w).call(this, e), c = i.pop(), a = index.T(this, n, f).call(this, i.join("/"));
    if (Object.prototype.hasOwnProperty.call(a.children, c)) {
      let l = a.children[c];
      l.lastModified = Date.now(), index.T(this, n, k).call(this, { opp: "setLastModified", args: [e, l.lastModified] });
    } else {
      if (this.state.pool.length === 0) throw new Error("No more file handles available in the pool");
      let l = { type: "file", lastModified: Date.now(), mode: (o == null ? void 0 : o.mode) || T.FILE, backingFilename: this.state.pool.pop() };
      a.children[c] = l, index.T(this, n, k).call(this, { opp: "createFileNode", args: [e, l] });
    }
    let h = a.children[c], d = index.h(this, m).get(h.backingFilename);
    t.length > 0 && (d.write(typeof t == "string" ? new TextEncoder().encode(t) : new Uint8Array(t), { at: 0 }), e.startsWith("/pg_wal") && index.h(this, S).add(d));
  }
  _createFileNodeState(e, t) {
    let o = index.T(this, n, w).call(this, e), i = o.pop(), c = index.T(this, n, f).call(this, o.join("/"));
    c.children[i] = t;
    let a = this.state.pool.indexOf(t.backingFilename);
    return a > -1 && this.state.pool.splice(a, 1), t;
  }
  _setLastModifiedState(e, t) {
    let o = index.T(this, n, f).call(this, e);
    o.lastModified = t;
  }
  write(e, t, o, i, c) {
    let a = index.T(this, n, I).call(this, e), h = index.T(this, n, f).call(this, a);
    if (h.type !== "file") throw new p("EISDIR", "Is a directory");
    let d = index.h(this, m).get(h.backingFilename);
    if (!d) throw new p("EBADF", "Bad file descriptor");
    let l = d.write(new Uint8Array(t, o, i), { at: c });
    return a.startsWith("/pg_wal") && index.h(this, S).add(d), l;
  }
};
H = /* @__PURE__ */ new WeakMap(), v = /* @__PURE__ */ new WeakMap(), F = /* @__PURE__ */ new WeakMap(), M = /* @__PURE__ */ new WeakMap(), y = /* @__PURE__ */ new WeakMap(), b = /* @__PURE__ */ new WeakMap(), m = /* @__PURE__ */ new WeakMap(), x = /* @__PURE__ */ new WeakMap(), P = /* @__PURE__ */ new WeakMap(), D = /* @__PURE__ */ new WeakMap(), S = /* @__PURE__ */ new WeakMap(), n = /* @__PURE__ */ new WeakSet(), C = async function() {
  index.x(this, H, await navigator.storage.getDirectory()), index.x(this, v, await index.T(this, n, j).call(this, this.dataDir, { create: true })), index.x(this, F, await index.T(this, n, j).call(this, G, { from: index.h(this, v), create: true })), index.x(this, M, await index.h(this, v).getFileHandle($, { create: true })), index.x(this, y, await index.h(this, M).createSyncAccessHandle());
  let e = new ArrayBuffer(index.h(this, y).getSize());
  index.h(this, y).read(e, { at: 0 });
  let t, o = new TextDecoder().decode(e).split(`
`), i = false;
  try {
    t = JSON.parse(o[0]);
  } catch {
    t = { root: { type: "directory", lastModified: Date.now(), mode: T.DIR, children: {} }, pool: [] }, index.h(this, y).truncate(0), index.h(this, y).write(new TextEncoder().encode(JSON.stringify(t)), { at: 0 }), i = true;
  }
  this.state = t;
  let c = o.slice(1).filter(Boolean).map((l) => JSON.parse(l));
  for (let l of c) {
    let u = `_${l.opp}State`;
    if (typeof this[u] == "function") try {
      this[u].bind(this)(...l.args);
    } catch (N) {
      console.warn("Error applying OPFS AHP WAL entry", l, N);
    }
  }
  let a = [], h = async (l) => {
    if (l.type === "file") try {
      let u = await index.h(this, F).getFileHandle(l.backingFilename), N = await u.createSyncAccessHandle();
      index.h(this, b).set(l.backingFilename, u), index.h(this, m).set(l.backingFilename, N);
    } catch (u) {
      console.error("Error opening file handle for node", l, u);
    }
    else for (let u of Object.values(l.children)) a.push(h(u));
  };
  await h(this.state.root);
  let d = [];
  for (let l of this.state.pool) d.push(new Promise(async (u) => {
    index.h(this, b).has(l) && console.warn("File handle already exists for pool file", l);
    let N = await index.h(this, F).getFileHandle(l), U = await N.createSyncAccessHandle();
    index.h(this, b).set(l, N), index.h(this, m).set(l, U), u();
  }));
  await Promise.all([...a, ...d]), await this.maintainPool(i ? this.initialPoolSize : this.maintainedPoolSize);
}, O = function(e, t) {
  let o = index.T(this, n, k).call(this, e);
  try {
    t();
  } catch (i) {
    throw index.h(this, y).truncate(o), i;
  }
}, k = function(e) {
  let t = JSON.stringify(e), o = new TextEncoder().encode(`
${t}`), i = index.h(this, y).getSize();
  return index.h(this, y).write(o, { at: i }), index.h(this, S).add(index.h(this, y)), i;
}, w = function(e) {
  return e.split("/").filter(Boolean);
}, f = function(e, t) {
  let o = index.T(this, n, w).call(this, e), i = t || this.state.root;
  for (let c of o) {
    if (i.type !== "directory") throw new p("ENOTDIR", "Not a directory");
    if (!Object.prototype.hasOwnProperty.call(i.children, c)) throw new p("ENOENT", "No such file or directory");
    i = i.children[c];
  }
  return i;
}, I = function(e) {
  let t = index.h(this, P).get(e);
  if (!t) throw new p("EBADF", "Bad file descriptor");
  return t;
}, W = function() {
  let e = ++index.U(this, x)._;
  for (; index.h(this, P).has(e); ) index.U(this, x)._++;
  return e;
}, j = async function(e, t) {
  let o = index.T(this, n, w).call(this, e), i = (t == null ? void 0 : t.from) || index.h(this, H);
  for (let c of o) i = await i.getDirectoryHandle(c, { create: t == null ? void 0 : t.create });
  return i;
};
var p = class extends Error {
  constructor(A, e) {
    super(e), typeof A == "number" ? this.code = A : typeof A == "string" && (this.code = index.pr[A]);
  }
};
exports.OpfsAhpFS = L;
//# sourceMappingURL=opfs-ahp-Dl5DbHFn.cjs.map
