#!/usr/bin/env node
import { createRequire as createRequire_BATI_CLI } from 'module';
const require = createRequire_BATI_CLI(import.meta.url);

import {
  n
} from "./chunk-IAWYWZSL.js";
import "./chunk-IHX3I5SM.js";

// ../core/dist/src-5HGZFBZ3.js
import { createRequire as BATI_core_createRequire } from "module";
import { fileURLToPath as BATI_fileURLToPath } from "url";
import { dirname as BATI_dirname } from "path";
import E from "path";
import X from "fs/promises";
import { fileURLToPath as g } from "url";
var require2 = BATI_core_createRequire(import.meta.url);
var __filename = BATI_fileURLToPath(import.meta.url);
var __dirname = BATI_dirname(__filename);
function o(s) {
  if (!s || !(s instanceof URL) && typeof s != "string") throw new TypeError("Path must be a non-empty string or URL.");
}
function M(s) {
  if (typeof s != "string" && !(s instanceof ArrayBuffer) && !ArrayBuffer.isView(s)) throw new TypeError("File contents must be a string, ArrayBuffer, or ArrayBuffer view.");
}
function U(s) {
  if (s instanceof Uint8Array) return s;
  if (typeof s == "string") return C.encode(s);
  if (s instanceof ArrayBuffer) return new Uint8Array(s);
  if (ArrayBuffer.isView(s)) {
    let t = s.buffer.slice(s.byteOffset, s.byteOffset + s.byteLength);
    return new Uint8Array(t);
  }
  throw new TypeError("Invalid contents type. Expected string or ArrayBuffer.");
}
var L;
var C;
var T;
var A;
var b;
var x;
var y;
var N = n(() => {
  "use strict";
  L = new TextDecoder(), C = new TextEncoder(), T = class extends Error {
    constructor(t) {
      super(`Method "${t}" does not exist on impl.`);
    }
  }, A = class extends Error {
    constructor(t) {
      super(`Method "${t}" is not supported on this impl.`);
    }
  }, b = class extends Error {
    constructor() {
      super("Implementation already set.");
    }
  };
  x = class {
    type;
    data;
    timestamp = Date.now();
    constructor(t, e) {
      this.type = t, this.data = e;
    }
  }, y = class {
    #t;
    #e;
    #s = /* @__PURE__ */ new Map();
    constructor({ impl: t }) {
      this.#t = t, this.#e = t;
    }
    #i(t, ...e) {
      for (let r of this.#s.values()) r.push(new x("call", { methodName: t, args: e }));
    }
    logStart(t) {
      if (!t || typeof t != "string") throw new TypeError("Log name must be a non-empty string.");
      if (this.#s.has(t)) throw new Error(`Log "${t}" already exists.`);
      this.#s.set(t, []);
    }
    logEnd(t) {
      if (this.#s.has(t)) {
        let e = this.#s.get(t);
        return this.#s.delete(t), e;
      }
      throw new Error(`Log "${t}" does not exist.`);
    }
    isBaseImpl() {
      return this.#e === this.#t;
    }
    setImpl(t) {
      if (this.#i("implSet", t), this.#e !== this.#t) throw new b();
      this.#e = t;
    }
    resetImpl() {
      this.#i("implReset"), this.#e = this.#t;
    }
    #o(t) {
      if (typeof this.#e[t] != "function") throw new T(t);
    }
    #a(t, e) {
      if (typeof this.#e[t] != "function") throw new A(e);
    }
    #r(t, ...e) {
      return this.#i(t, ...e), this.#o(t), this.#e[t](...e);
    }
    #n(t, ...e) {
      return this.#o(t), this.#e[t](...e);
    }
    #c(t, e, ...r) {
      return this.#i(e, ...r), this.#a(t, e), this.#e[t](...r);
    }
    async text(t) {
      o(t);
      let e = await this.#c("bytes", "text", t);
      return e ? L.decode(e) : void 0;
    }
    async json(t) {
      o(t);
      let e = await this.#c("bytes", "json", t);
      return e ? JSON.parse(L.decode(e)) : void 0;
    }
    async arrayBuffer(t) {
      return o(t), (await this.#c("bytes", "arrayBuffer", t))?.buffer;
    }
    async bytes(t) {
      return o(t), this.#r("bytes", t);
    }
    async write(t, e) {
      o(t), M(e), this.#i("write", t, e);
      let r = U(e);
      return this.#n("write", t, r);
    }
    async append(t, e) {
      o(t), M(e), this.#i("append", t, e);
      let r = U(e);
      return this.#n("append", t, r);
    }
    async isFile(t) {
      return o(t), this.#r("isFile", t);
    }
    async isDirectory(t) {
      return o(t), this.#r("isDirectory", t);
    }
    async createDirectory(t) {
      return o(t), this.#r("createDirectory", t);
    }
    async delete(t) {
      return o(t), this.#r("delete", t);
    }
    async deleteAll(t) {
      return o(t), this.#r("deleteAll", t);
    }
    async *list(t) {
      o(t), yield* await this.#r("list", t);
    }
    async *walk(t, { directoryFilter: e = () => true, entryFilter: r = () => true } = {}) {
      o(t), this.#i("walk", t, { directoryFilter: e, entryFilter: r });
      let n2 = async function* (i, { directoryFilter: h, entryFilter: a, parentPath: f = "", depth: S = 1 }) {
        let I;
        try {
          I = await this.#n("list", i);
        } catch (u) {
          if (u.code === "ENOENT") return;
          throw u;
        }
        for await (let u of I) {
          let p = { path: u.name, depth: S, ...u };
          f && (p.path = `${f}/${p.path}`);
          let w = a(p);
          if (w.then && (w = await w), w && (yield p), u.isDirectory) {
            let d = h(p);
            if (d.then && (d = await d), !d) continue;
            let z = i instanceof URL ? new URL(u.name, i.href.endsWith("/") ? i.href : `${i.href}/`) : `${i.endsWith("/") ? i : `${i}/`}${u.name}`;
            yield* n2(z, { directoryFilter: h, entryFilter: a, parentPath: p.path, depth: S + 1 });
          }
        }
      }.bind(this);
      yield* n2(t, { directoryFilter: e, entryFilter: r });
    }
    async size(t) {
      return o(t), this.#r("size", t);
    }
    async lastModified(t) {
      return o(t), this.#r("lastModified", t);
    }
    async copy(t, e) {
      return o(t), o(e), this.#r("copy", t, e);
    }
    async copyAll(t, e) {
      return o(t), o(e), this.#r("copyAll", t, e);
    }
    async move(t, e) {
      return o(t), o(e), this.#r("move", t, e);
    }
    async moveAll(t, e) {
      return o(t), o(e), this.#r("moveAll", t, e);
    }
  };
});
var O = n(() => {
  "use strict";
});
var F = n(() => {
  "use strict";
});
var R = n(() => {
  "use strict";
  N();
  O();
  F();
});
function c(s) {
  globalThis?.process?.env.DEBUG === "@hwc/retry" && console.debug(s);
}
function _(s, t) {
  let e = Date.now() - s.lastAttempt, r = Math.max(s.lastAttempt - s.timestamp, 1), n2 = Math.min(r * 1.2, t);
  return e >= n2;
}
function W(s, t) {
  return s.age > t;
}
function Y() {
  if (Promise.withResolvers) return Promise.withResolvers();
  let s, t, e = new Promise((r, n2) => {
    s = r, t = n2;
  });
  if (s === void 0 || t === void 0) throw new Error("Promise executor did not initialize resolve or reject.");
  return { promise: e, resolve: s, reject: t };
}
var k;
var m;
var B = n(() => {
  "use strict";
  k = class {
    id = Math.random().toString(36).slice(2);
    fn;
    error;
    timestamp = Date.now();
    lastAttempt = this.timestamp;
    resolve;
    reject;
    signal;
    constructor(t, e, r, n2, i) {
      this.fn = t, this.error = e, this.timestamp = Date.now(), this.lastAttempt = Date.now(), this.resolve = r, this.reject = n2, this.signal = i;
    }
    get age() {
      return Date.now() - this.timestamp;
    }
  }, m = class {
    #t = [];
    #e = [];
    #s = 0;
    #i;
    #o;
    #a;
    #r;
    #n;
    constructor(t, { timeout: e = 6e4, maxDelay: r = 100, concurrency: n2 = 1e3 } = {}) {
      if (typeof t != "function") throw new Error("Missing function to check errors");
      this.#r = t, this.#i = e, this.#o = r, this.#n = n2;
    }
    get retrying() {
      return this.#t.length;
    }
    get pending() {
      return this.#e.length;
    }
    get working() {
      return this.#s;
    }
    #c(t, { signal: e, promise: r, resolve: n2, reject: i }) {
      let h;
      try {
        h = t();
      } catch (a) {
        return i(new Error(`Synchronous error: ${a.message}`, { cause: a })), r;
      }
      return !h || typeof h.then != "function" ? (i(new Error("Result is not a promise.")), r) : (this.#s++, r.finally(() => {
        this.#s--, this.#h();
      }).catch(() => {
      }), Promise.resolve(h).then((a) => {
        c("Function called successfully without retry."), n2(a);
      }).catch((a) => {
        if (!this.#r(a)) {
          i(a);
          return;
        }
        let f = new k(t, a, n2, i, e);
        c(`Function failed, queuing for retry with task ${f.id}.`), this.#t.push(f), e?.addEventListener("abort", () => {
          c(`Task ${f.id} was aborted due to AbortSignal.`), i(e.reason);
        }), this.#l();
      }), r);
    }
    retry(t, { signal: e } = {}) {
      e?.throwIfAborted();
      let { promise: r, resolve: n2, reject: i } = Y();
      return this.#e.push(() => this.#c(t, { signal: e, promise: r, resolve: n2, reject: i })), this.#h(), r;
    }
    #u() {
      this.pending && this.#h(), this.retrying && this.#l();
    }
    #h() {
      c(`Processing pending tasks: ${this.pending} pending, ${this.working} working.`);
      let t = this.#n - this.working;
      if (t <= 0) return;
      let e = Math.min(this.pending, t);
      for (let r = 0; r < e; r++) this.#e.shift()?.();
      c(`Processed pending tasks: ${this.pending} pending, ${this.working} working.`);
    }
    #l() {
      clearTimeout(this.#a), this.#a = void 0, c(`Processing retry queue: ${this.retrying} retrying, ${this.working} working.`);
      let t = () => {
        this.#a = setTimeout(() => this.#u(), 0);
      }, e = this.#t.shift();
      if (!e) {
        c("Queue is empty, exiting."), this.pending && t();
        return;
      }
      if (W(e, this.#i)) {
        c(`Task ${e.id} was abandoned due to timeout.`), e.reject(e.error), t();
        return;
      }
      if (!_(e, this.#o)) {
        c(`Task ${e.id} is not ready to retry, skipping.`), this.#t.push(e), t();
        return;
      }
      e.lastAttempt = Date.now(), Promise.resolve(e.fn()).then((r) => {
        c(`Task ${e.id} succeeded after ${e.age}ms.`), e.resolve(r);
      }).catch((r) => {
        if (!this.#r(r)) {
          c(`Task ${e.id} failed with non-retryable error: ${r.message}.`), e.reject(r);
          return;
        }
        e.lastAttempt = Date.now(), this.#t.push(e), c(`Task ${e.id} failed, requeueing to try again.`);
      }).finally(() => {
        this.#u();
      });
    }
  };
});
var V;
var $;
var v;
var D;
var at;
var j = n(() => {
  "use strict";
  R();
  B();
  V = /* @__PURE__ */ new Set(["ENFILE", "EMFILE"]), $ = class {
    name;
    isFile;
    isDirectory;
    isSymlink;
    constructor(t) {
      this.name = t.name, this.isFile = t.isFile(), this.isDirectory = t.isDirectory(), this.isSymlink = t.isSymbolicLink();
    }
  }, v = class {
    #t;
    #e;
    constructor({ fsp: t = X } = {}) {
      this.#t = t, this.#e = new m((e) => V.has(e.code));
    }
    bytes(t) {
      return this.#e.retry(() => this.#t.readFile(t)).then((e) => new Uint8Array(e.buffer)).catch((e) => {
        if (e.code !== "ENOENT") throw e;
      });
    }
    async write(t, e) {
      let r = Buffer.from(e);
      return this.#e.retry(() => this.#t.writeFile(t, r)).catch((n2) => {
        if (n2.code === "ENOENT") {
          let i = E.dirname(t instanceof URL ? g(t) : t);
          return this.#t.mkdir(i, { recursive: true }).then(() => this.#t.writeFile(t, r));
        }
        throw n2;
      });
    }
    async append(t, e) {
      let r = Buffer.from(e);
      return this.#e.retry(() => this.#t.appendFile(t, r)).catch((n2) => {
        if (n2.code === "ENOENT") {
          let i = E.dirname(t instanceof URL ? g(t) : t);
          return this.#t.mkdir(i, { recursive: true }).then(() => this.#t.appendFile(t, r));
        }
        throw n2;
      });
    }
    isFile(t) {
      return this.#t.stat(t).then((e) => e.isFile()).catch((e) => {
        if (e.code === "ENOENT") return false;
        throw e;
      });
    }
    isDirectory(t) {
      return this.#t.stat(t).then((e) => e.isDirectory()).catch((e) => {
        if (e.code === "ENOENT") return false;
        throw e;
      });
    }
    async createDirectory(t) {
      await this.#t.mkdir(t, { recursive: true });
    }
    delete(t) {
      return this.#t.rm(t).then(() => true).catch((e) => {
        if (e.code === "ERR_FS_EISDIR") return this.#t.rmdir(t).then(() => true);
        if (e.code === "ENOENT") return false;
        throw e;
      });
    }
    deleteAll(t) {
      return this.#t.rm(t, { recursive: true }).then(() => true).catch((e) => {
        if (e.code === "ENOENT") return false;
        throw e;
      });
    }
    async *list(t) {
      let e = await this.#t.readdir(t, { withFileTypes: true });
      for (let r of e) yield new $(r);
    }
    size(t) {
      return this.#t.stat(t).then((e) => e.size).catch((e) => {
        if (e.code !== "ENOENT") throw e;
      });
    }
    lastModified(t) {
      return this.#t.stat(t).then((e) => e.mtime).catch((e) => {
        if (e.code !== "ENOENT") throw e;
      });
    }
    copy(t, e) {
      return this.#t.copyFile(t, e);
    }
    async copyAll(t, e) {
      if (await this.isFile(t)) return this.copy(t, e);
      let r = t instanceof URL ? g(t) : t, n2 = e instanceof URL ? g(e) : e;
      await this.createDirectory(e);
      for await (let i of this.list(t)) {
        let h = E.join(r, i.name), a = E.join(n2, i.name);
        i.isDirectory ? await this.copyAll(h, a) : await this.copy(h, a);
      }
    }
    move(t, e) {
      return this.#t.stat(t).then((r) => {
        if (r.isDirectory()) throw new Error(`EISDIR: illegal operation on a directory, move '${t}' -> '${e}'`);
        return this.#t.rename(t, e);
      });
    }
    async moveAll(t, e) {
      return this.#t.rename(t, e);
    }
  }, D = class extends y {
    constructor({ fsp: t } = {}) {
      super({ impl: new v({ fsp: t }) });
    }
  }, at = new D();
});
var K = n(() => {
  j();
  R();
});
K();
export {
  y as Hfs,
  D as NodeHfs,
  v as NodeHfsImpl,
  at as hfs
};
