opfs-worker 1.2.1 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { wrap as u } from "comlink";
2
2
  import { i as c, d as l, e as h } from "./helpers-CkNHswLp.js";
3
- import { E as x, D as S, F as P, O as F, b as O, a as A, P as T, c as I, S as R, T as $, h as C, v as _, u as N, B as D, g as z, x as k, t as M, f as L, C as j, k as W, q as U, p as H, j as B, m as G, o as q, l as V, n as Y, y as X, r as Z, A as J, s as K, z as Q, w as nn } from "./helpers-CkNHswLp.js";
3
+ import { E as x, D as S, F as P, O as F, b as O, a as A, P as T, c as I, S as R, T as $, h as _, v as C, u as N, B as D, g as z, x as k, t as M, f as L, C as j, k as W, q as U, p as H, j as B, m as G, o as q, l as V, n as Y, y as X, r as Z, A as J, s as K, z as Q, w as nn } from "./helpers-CkNHswLp.js";
4
4
  const f = `/**
5
5
  * @license
6
6
  * Copyright 2019 Google LLC
@@ -15,7 +15,7 @@ const pt = Symbol("Comlink.proxy"), Ct = Symbol("Comlink.endpoint"), Tt = Symbol
15
15
  deserialize(s) {
16
16
  return s.start(), Rt(s);
17
17
  }
18
- }, Pt = {
18
+ }, It = {
19
19
  canHandle: (s) => gt(s) && z in s,
20
20
  serialize({ value: s }) {
21
21
  let t;
@@ -33,9 +33,9 @@ const pt = Symbol("Comlink.proxy"), Ct = Symbol("Comlink.endpoint"), Tt = Symbol
33
33
  }
34
34
  }, wt = /* @__PURE__ */ new Map([
35
35
  ["proxy", Mt],
36
- ["throw", Pt]
36
+ ["throw", It]
37
37
  ]);
38
- function It(s, t) {
38
+ function Pt(s, t) {
39
39
  for (const e of s)
40
40
  if (t === e || e === "*" || e instanceof RegExp && e.test(t))
41
41
  return !0;
@@ -45,7 +45,7 @@ function K(s, t = globalThis, e = ["*"]) {
45
45
  t.addEventListener("message", function n(i) {
46
46
  if (!i || !i.data)
47
47
  return;
48
- if (!It(e, i.origin)) {
48
+ if (!Pt(e, i.origin)) {
49
49
  console.warn(\`Invalid origin '\${i.origin}' for comlink proxy\`);
50
50
  return;
51
51
  }
@@ -85,10 +85,10 @@ function K(s, t = globalThis, e = ["*"]) {
85
85
  h = { value: c, [z]: 0 };
86
86
  }
87
87
  Promise.resolve(h).catch((c) => ({ value: c, [z]: 0 })).then((c) => {
88
- const [f, u] = B(c);
89
- t.postMessage(Object.assign(Object.assign({}, f), { id: r }), u), o === "RELEASE" && (t.removeEventListener("message", n), yt(t), q in s && typeof s[q] == "function" && s[q]());
88
+ const [f, u] = U(c);
89
+ t.postMessage(Object.assign(Object.assign({}, f), { id: r }), u), o === "RELEASE" && (t.removeEventListener("message", n), mt(t), q in s && typeof s[q] == "function" && s[q]());
90
90
  }).catch((c) => {
91
- const [f, u] = B({
91
+ const [f, u] = U({
92
92
  value: new TypeError("Unserializable return value"),
93
93
  [z]: 0
94
94
  });
@@ -99,7 +99,7 @@ function K(s, t = globalThis, e = ["*"]) {
99
99
  function kt(s) {
100
100
  return s.constructor.name === "MessagePort";
101
101
  }
102
- function yt(s) {
102
+ function mt(s) {
103
103
  kt(s) && s.close();
104
104
  }
105
105
  function Rt(s, t) {
@@ -121,16 +121,16 @@ function k(s) {
121
121
  if (s)
122
122
  throw new Error("Proxy has been released and is not useable");
123
123
  }
124
- function mt(s) {
124
+ function yt(s) {
125
125
  return N(s, /* @__PURE__ */ new Map(), {
126
126
  type: "RELEASE"
127
127
  }).then(() => {
128
- yt(s);
128
+ mt(s);
129
129
  });
130
130
  }
131
131
  const _ = /* @__PURE__ */ new WeakMap(), j = "FinalizationRegistry" in globalThis && new FinalizationRegistry((s) => {
132
132
  const t = (_.get(s) || 0) - 1;
133
- _.set(s, t), t === 0 && mt(s);
133
+ _.set(s, t), t === 0 && yt(s);
134
134
  });
135
135
  function Lt(s, t) {
136
136
  const e = (_.get(t) || 0) + 1;
@@ -146,7 +146,7 @@ function Z(s, t, e = [], n = function() {
146
146
  get(o, a) {
147
147
  if (k(i), a === Tt)
148
148
  return () => {
149
- zt(r), mt(s), t.clear(), i = !0;
149
+ zt(r), yt(s), t.clear(), i = !0;
150
150
  };
151
151
  if (a === "then") {
152
152
  if (e.length === 0)
@@ -161,7 +161,7 @@ function Z(s, t, e = [], n = function() {
161
161
  },
162
162
  set(o, a, l) {
163
163
  k(i);
164
- const [h, c] = B(l);
164
+ const [h, c] = U(l);
165
165
  return N(s, t, {
166
166
  type: "SET",
167
167
  path: [...e, a].map((f) => f.toString()),
@@ -200,7 +200,7 @@ function Ht(s) {
200
200
  return Array.prototype.concat.apply([], s);
201
201
  }
202
202
  function st(s) {
203
- const t = s.map(B);
203
+ const t = s.map(U);
204
204
  return [t.map((e) => e[0]), Ht(t.map((e) => e[1]))];
205
205
  }
206
206
  const Et = /* @__PURE__ */ new WeakMap();
@@ -210,7 +210,7 @@ function H(s, t) {
210
210
  function Wt(s) {
211
211
  return Object.assign(s, { [pt]: !0 });
212
212
  }
213
- function B(s) {
213
+ function U(s) {
214
214
  for (const [t, e] of wt)
215
215
  if (e.canHandle(s)) {
216
216
  const [n, i] = e.serialize(s);
@@ -258,7 +258,7 @@ class jt extends p {
258
258
  super("OPFS is not supported in this browser", "OPFS_NOT_SUPPORTED", void 0, t);
259
259
  }
260
260
  }
261
- class Bt extends p {
261
+ class Ut extends p {
262
262
  constructor(t, e, n) {
263
263
  super(t, "INVALID_PATH", e, n);
264
264
  }
@@ -272,7 +272,7 @@ function R(s, t, e, n) {
272
272
  const i = \`\${s.toUpperCase()}_FAILED\`;
273
273
  return new p(\`Failed to \${s} file descriptor: \${t}\`, i, e, n);
274
274
  }
275
- function Ut(s, t) {
275
+ function Bt(s, t) {
276
276
  const e = t?.path;
277
277
  switch (s.name) {
278
278
  case "InvalidStateError":
@@ -391,17 +391,17 @@ function T(s, t) {
391
391
  const O = c.some(oe);
392
392
  f = [];
393
393
  for (let x = u; S(x, d); x += g) {
394
- let y;
394
+ let m;
395
395
  if (a)
396
- y = String.fromCharCode(x), y === "\\\\" && (y = "");
397
- else if (y = String(x), O) {
398
- const $ = w - y.length;
396
+ m = String.fromCharCode(x), m === "\\\\" && (m = "");
397
+ else if (m = String(x), O) {
398
+ const $ = w - m.length;
399
399
  if ($ > 0) {
400
- const I = new Array($ + 1).join("0");
401
- x < 0 ? y = "-" + I + y.slice(1) : y = I + y;
400
+ const P = new Array($ + 1).join("0");
401
+ x < 0 ? m = "-" + P + m.slice(1) : m = P + m;
402
402
  }
403
403
  }
404
- f.push(y);
404
+ f.push(m);
405
405
  }
406
406
  } else {
407
407
  f = [];
@@ -416,7 +416,7 @@ function T(s, t) {
416
416
  }
417
417
  return e;
418
418
  }
419
- const le = 1024 * 64, U = (s) => {
419
+ const le = 1024 * 64, B = (s) => {
420
420
  if (typeof s != "string")
421
421
  throw new TypeError("invalid pattern");
422
422
  if (s.length > le)
@@ -489,7 +489,7 @@ const le = 1024 * 64, U = (s) => {
489
489
  }
490
490
  const u = "[" + (h ? "^" : "") + rt(n) + "]", d = "[" + (h ? "" : "^") + rt(i) + "]";
491
491
  return [n.length && i.length ? "(" + u + "|" + d + ")" : n.length ? u : d, a, c - e, !0];
492
- }, M = (s, { windowsPathsNoEscape: t = !1 } = {}) => t ? s.replace(/\\[([^\\/\\\\])\\]/g, "$1") : s.replace(/((?!\\\\).|^)\\[([^\\/\\\\])\\]/g, "$1$2").replace(/\\\\([^\\/])/g, "$1"), de = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]), ot = (s) => de.has(s), pe = "(?!(?:^|/)\\\\.\\\\.?(?:$|/))", L = "(?!\\\\.)", ge = /* @__PURE__ */ new Set(["[", "."]), we = /* @__PURE__ */ new Set(["..", "."]), ye = new Set("().*{}+?[]^$\\\\!"), me = (s) => s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, "\\\\$&"), tt = "[^/]", at = tt + "*?", ct = tt + "+?";
492
+ }, M = (s, { windowsPathsNoEscape: t = !1 } = {}) => t ? s.replace(/\\[([^\\/\\\\])\\]/g, "$1") : s.replace(/((?!\\\\).|^)\\[([^\\/\\\\])\\]/g, "$1$2").replace(/\\\\([^\\/])/g, "$1"), de = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]), ot = (s) => de.has(s), pe = "(?!(?:^|/)\\\\.\\\\.?(?:$|/))", L = "(?!\\\\.)", ge = /* @__PURE__ */ new Set(["[", "."]), we = /* @__PURE__ */ new Set(["..", "."]), me = new Set("().*{}+?[]^$\\\\!"), ye = (s) => s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, "\\\\$&"), tt = "[^/]", at = tt + "*?", ct = tt + "+?";
493
493
  class E {
494
494
  type;
495
495
  #s;
@@ -801,7 +801,7 @@ class E {
801
801
  for (let a = 0; a < t.length; a++) {
802
802
  const l = t.charAt(a);
803
803
  if (i) {
804
- i = !1, r += (ye.has(l) ? "\\\\" : "") + l;
804
+ i = !1, r += (me.has(l) ? "\\\\" : "") + l;
805
805
  continue;
806
806
  }
807
807
  if (l === "\\\\") {
@@ -823,12 +823,12 @@ class E {
823
823
  r += tt, e = !0;
824
824
  continue;
825
825
  }
826
- r += me(l);
826
+ r += ye(l);
827
827
  }
828
828
  return [r, M(t), !!e, o];
829
829
  }
830
830
  }
831
- const Ee = (s, { windowsPathsNoEscape: t = !1 } = {}) => t ? s.replace(/[?*()[\\]]/g, "[$&]") : s.replace(/[?*()[\\]\\\\]/g, "\\\\$&"), m = (s, t, e = {}) => (U(t), !e.nocomment && t.charAt(0) === "#" ? !1 : new G(t, e).match(s)), Se = /^\\*+([^+@!?\\*\\[\\(]*)$/, xe = (s) => (t) => !t.startsWith(".") && t.endsWith(s), be = (s) => (t) => t.endsWith(s), ve = (s) => (s = s.toLowerCase(), (t) => !t.startsWith(".") && t.toLowerCase().endsWith(s)), Ae = (s) => (s = s.toLowerCase(), (t) => t.toLowerCase().endsWith(s)), Fe = /^\\*+\\.\\*+$/, Ne = (s) => !s.startsWith(".") && s.includes("."), De = (s) => s !== "." && s !== ".." && s.includes("."), Oe = /^\\.\\*+$/, $e = (s) => s !== "." && s !== ".." && s.startsWith("."), Ce = /^\\*+$/, Te = (s) => s.length !== 0 && !s.startsWith("."), Me = (s) => s.length !== 0 && s !== "." && s !== "..", Pe = /^\\?+([^+@!?\\*\\[\\(]*)?$/, Ie = ([s, t = ""]) => {
831
+ const Ee = (s, { windowsPathsNoEscape: t = !1 } = {}) => t ? s.replace(/[?*()[\\]]/g, "[$&]") : s.replace(/[?*()[\\]\\\\]/g, "\\\\$&"), y = (s, t, e = {}) => (B(t), !e.nocomment && t.charAt(0) === "#" ? !1 : new G(t, e).match(s)), Se = /^\\*+([^+@!?\\*\\[\\(]*)$/, xe = (s) => (t) => !t.startsWith(".") && t.endsWith(s), be = (s) => (t) => t.endsWith(s), ve = (s) => (s = s.toLowerCase(), (t) => !t.startsWith(".") && t.toLowerCase().endsWith(s)), Ae = (s) => (s = s.toLowerCase(), (t) => t.toLowerCase().endsWith(s)), Fe = /^\\*+\\.\\*+$/, Ne = (s) => !s.startsWith(".") && s.includes("."), De = (s) => s !== "." && s !== ".." && s.includes("."), Oe = /^\\.\\*+$/, $e = (s) => s !== "." && s !== ".." && s.startsWith("."), Ce = /^\\*+$/, Te = (s) => s.length !== 0 && !s.startsWith("."), Me = (s) => s.length !== 0 && s !== "." && s !== "..", Ie = /^\\?+([^+@!?\\*\\[\\(]*)?$/, Pe = ([s, t = ""]) => {
832
832
  const e = Nt([s]);
833
833
  return t ? (t = t.toLowerCase(), (n) => e(n) && n.toLowerCase().endsWith(t)) : e;
834
834
  }, ke = ([s, t = ""]) => {
@@ -850,15 +850,15 @@ const Ee = (s, { windowsPathsNoEscape: t = !1 } = {}) => t ? s.replace(/[?*()[\\
850
850
  win32: { sep: "\\\\" },
851
851
  posix: { sep: "/" }
852
852
  }, ze = Ot === "win32" ? lt.win32.sep : lt.posix.sep;
853
- m.sep = ze;
853
+ y.sep = ze;
854
854
  const v = Symbol("globstar **");
855
- m.GLOBSTAR = v;
856
- const He = "[^/]", We = He + "*?", _e = "(?:(?!(?:\\\\/|^)(?:\\\\.{1,2})($|\\\\/)).)*?", je = "(?:(?!(?:\\\\/|^)\\\\.).)*?", Be = (s, t = {}) => (e) => m(e, s, t);
857
- m.filter = Be;
858
- const b = (s, t = {}) => Object.assign({}, s, t), Ue = (s) => {
855
+ y.GLOBSTAR = v;
856
+ const He = "[^/]", We = He + "*?", _e = "(?:(?!(?:\\\\/|^)(?:\\\\.{1,2})($|\\\\/)).)*?", je = "(?:(?!(?:\\\\/|^)\\\\.).)*?", Ue = (s, t = {}) => (e) => y(e, s, t);
857
+ y.filter = Ue;
858
+ const b = (s, t = {}) => Object.assign({}, s, t), Be = (s) => {
859
859
  if (!s || typeof s != "object" || !Object.keys(s).length)
860
- return m;
861
- const t = m;
860
+ return y;
861
+ const t = y;
862
862
  return Object.assign((n, i, r = {}) => t(n, i, b(s, r)), {
863
863
  Minimatch: class extends t.Minimatch {
864
864
  constructor(i, r = {}) {
@@ -889,16 +889,16 @@ const b = (s, t = {}) => Object.assign({}, s, t), Ue = (s) => {
889
889
  GLOBSTAR: v
890
890
  });
891
891
  };
892
- m.defaults = Ue;
893
- const $t = (s, t = {}) => (U(s), t.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(s) ? [s] : ie(s));
894
- m.braceExpand = $t;
892
+ y.defaults = Be;
893
+ const $t = (s, t = {}) => (B(s), t.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(s) ? [s] : ie(s));
894
+ y.braceExpand = $t;
895
895
  const Ge = (s, t = {}) => new G(s, t).makeRe();
896
- m.makeRe = Ge;
896
+ y.makeRe = Ge;
897
897
  const qe = (s, t, e = {}) => {
898
898
  const n = new G(t, e);
899
899
  return s = s.filter((i) => n.match(i)), n.options.nonull && !s.length && s.push(t), s;
900
900
  };
901
- m.match = qe;
901
+ y.match = qe;
902
902
  const ht = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/, Ve = (s) => s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, "\\\\$&");
903
903
  class G {
904
904
  options;
@@ -919,7 +919,7 @@ class G {
919
919
  windowsNoMagicRoot;
920
920
  regexp;
921
921
  constructor(t, e = {}) {
922
- U(t), e = e || {}, this.options = e, this.pattern = t, this.platform = e.platform || Ot, this.isWindows = this.platform === "win32", this.windowsPathsNoEscape = !!e.windowsPathsNoEscape || e.allowWindowsEscape === !1, this.windowsPathsNoEscape && (this.pattern = this.pattern.replace(/\\\\/g, "/")), this.preserveMultipleSlashes = !!e.preserveMultipleSlashes, this.regexp = null, this.negate = !1, this.nonegate = !!e.nonegate, this.comment = !1, this.empty = !1, this.partial = !!e.partial, this.nocase = !!this.options.nocase, this.windowsNoMagicRoot = e.windowsNoMagicRoot !== void 0 ? e.windowsNoMagicRoot : !!(this.isWindows && this.nocase), this.globSet = [], this.globParts = [], this.set = [], this.make();
922
+ B(t), e = e || {}, this.options = e, this.pattern = t, this.platform = e.platform || Ot, this.isWindows = this.platform === "win32", this.windowsPathsNoEscape = !!e.windowsPathsNoEscape || e.allowWindowsEscape === !1, this.windowsPathsNoEscape && (this.pattern = this.pattern.replace(/\\\\/g, "/")), this.preserveMultipleSlashes = !!e.preserveMultipleSlashes, this.regexp = null, this.negate = !1, this.nonegate = !!e.nonegate, this.comment = !1, this.empty = !1, this.partial = !!e.partial, this.nocase = !!this.options.nocase, this.windowsNoMagicRoot = e.windowsNoMagicRoot !== void 0 ? e.windowsNoMagicRoot : !!(this.isWindows && this.nocase), this.globSet = [], this.globParts = [], this.set = [], this.make();
923
923
  }
924
924
  hasMagic() {
925
925
  if (this.options.magicalBraces && this.set.length > 1)
@@ -1127,10 +1127,10 @@ class G {
1127
1127
  matchOne(t, e, n = !1) {
1128
1128
  const i = this.options;
1129
1129
  if (this.isWindows) {
1130
- const g = typeof t[0] == "string" && /^[a-z]:$/i.test(t[0]), S = !g && t[0] === "" && t[1] === "" && t[2] === "?" && /^[a-z]:$/i.test(t[3]), A = typeof e[0] == "string" && /^[a-z]:$/i.test(e[0]), O = !A && e[0] === "" && e[1] === "" && e[2] === "?" && typeof e[3] == "string" && /^[a-z]:$/i.test(e[3]), x = S ? 3 : g ? 0 : void 0, y = O ? 3 : A ? 0 : void 0;
1131
- if (typeof x == "number" && typeof y == "number") {
1132
- const [$, I] = [t[x], e[y]];
1133
- $.toLowerCase() === I.toLowerCase() && (e[y] = $, y > x ? e = e.slice(y) : x > y && (t = t.slice(x)));
1130
+ const g = typeof t[0] == "string" && /^[a-z]:$/i.test(t[0]), S = !g && t[0] === "" && t[1] === "" && t[2] === "?" && /^[a-z]:$/i.test(t[3]), A = typeof e[0] == "string" && /^[a-z]:$/i.test(e[0]), O = !A && e[0] === "" && e[1] === "" && e[2] === "?" && typeof e[3] == "string" && /^[a-z]:$/i.test(e[3]), x = S ? 3 : g ? 0 : void 0, m = O ? 3 : A ? 0 : void 0;
1131
+ if (typeof x == "number" && typeof m == "number") {
1132
+ const [$, P] = [t[x], e[m]];
1133
+ $.toLowerCase() === P.toLowerCase() && (e[m] = $, m > x ? e = e.slice(m) : x > m && (t = t.slice(x)));
1134
1134
  }
1135
1135
  }
1136
1136
  const { optimizationLevel: r = 1 } = this.options;
@@ -1179,14 +1179,14 @@ globstar while\`, t, u, e, d, w), this.matchOne(t.slice(u), e.slice(d), n))
1179
1179
  return $t(this.pattern, this.options);
1180
1180
  }
1181
1181
  parse(t) {
1182
- U(t);
1182
+ B(t);
1183
1183
  const e = this.options;
1184
1184
  if (t === "**")
1185
1185
  return v;
1186
1186
  if (t === "")
1187
1187
  return "";
1188
1188
  let n, i = null;
1189
- (n = t.match(Ce)) ? i = e.dot ? Me : Te : (n = t.match(Se)) ? i = (e.nocase ? e.dot ? Ae : ve : e.dot ? be : xe)(n[1]) : (n = t.match(Pe)) ? i = (e.nocase ? e.dot ? ke : Ie : e.dot ? Re : Le)(n) : (n = t.match(Fe)) ? i = e.dot ? De : Ne : (n = t.match(Oe)) && (i = $e);
1189
+ (n = t.match(Ce)) ? i = e.dot ? Me : Te : (n = t.match(Se)) ? i = (e.nocase ? e.dot ? Ae : ve : e.dot ? be : xe)(n[1]) : (n = t.match(Ie)) ? i = (e.nocase ? e.dot ? ke : Pe : e.dot ? Re : Le)(n) : (n = t.match(Fe)) ? i = e.dot ? De : Ne : (n = t.match(Oe)) && (i = $e);
1190
1190
  const r = E.fromGlob(t, this.options).toMMPattern();
1191
1191
  return i && typeof r == "object" && Reflect.defineProperty(r, "test", { value: i }), r;
1192
1192
  }
@@ -1247,18 +1247,18 @@ globstar while\`, t, u, e, d, w), this.matchOne(t.slice(u), e.slice(d), n))
1247
1247
  return n.flipNegate ? !1 : this.negate;
1248
1248
  }
1249
1249
  static defaults(t) {
1250
- return m.defaults(t).Minimatch;
1250
+ return y.defaults(t).Minimatch;
1251
1251
  }
1252
1252
  }
1253
- m.AST = E;
1254
- m.Minimatch = G;
1255
- m.escape = Ee;
1256
- m.unescape = M;
1253
+ y.AST = E;
1254
+ y.Minimatch = G;
1255
+ y.escape = Ee;
1256
+ y.unescape = M;
1257
1257
  function Xe() {
1258
1258
  if (!("storage" in navigator) || !("getDirectory" in navigator.storage))
1259
1259
  throw new jt();
1260
1260
  }
1261
- async function P(s, t, e) {
1261
+ async function I(s, t, e) {
1262
1262
  return typeof navigator < "u" && navigator.locks?.request ? navigator.locks.request(\`opfs:\${s.replace(/\\/+/g, "/")}\`, { mode: t }, e) : e();
1263
1263
  }
1264
1264
  function D(s) {
@@ -1282,7 +1282,7 @@ function Ye(s, t = !1) {
1282
1282
  return s = s.replace(/\\/$/, ""), t && !s.includes("*") ? \`\${s}/**\` : s;
1283
1283
  }
1284
1284
  function Y(s, t) {
1285
- return m(s, t, {
1285
+ return y(s, t, {
1286
1286
  dot: !0,
1287
1287
  matchBase: !0
1288
1288
  });
@@ -1311,7 +1311,7 @@ async function Je(s) {
1311
1311
  }
1312
1312
  async function Ke(s, t, e = {}) {
1313
1313
  const n = J(t);
1314
- return P(t, "exclusive", async () => {
1314
+ return I(t, "exclusive", async () => {
1315
1315
  const i = e.recursive ?? !1, r = e.force ?? !1;
1316
1316
  e.useTrash;
1317
1317
  try {
@@ -1351,7 +1351,7 @@ async function ts(s, t) {
1351
1351
  try {
1352
1352
  return await s.createSyncAccessHandle();
1353
1353
  } catch (e) {
1354
- throw Ut(e, { path: t });
1354
+ throw Bt(e, { path: t });
1355
1355
  }
1356
1356
  }
1357
1357
  class es {
@@ -1526,7 +1526,7 @@ class es {
1526
1526
  async getFileHandle(t, e = !1, n = this.root) {
1527
1527
  const i = D(t);
1528
1528
  if (i.length === 0)
1529
- throw new Bt("Path must not be empty", Array.isArray(t) ? t.join("/") : t);
1529
+ throw new Ut("Path must not be empty", Array.isArray(t) ? t.join("/") : t);
1530
1530
  const r = i.pop();
1531
1531
  return (await this.getDirectoryHandle(i, e, n)).getFileHandle(r, { create: e });
1532
1532
  }
@@ -1593,7 +1593,7 @@ class es {
1593
1593
  async readFile(t) {
1594
1594
  await this.mount();
1595
1595
  try {
1596
- return await P(t, "shared", async () => {
1596
+ return await I(t, "shared", async () => {
1597
1597
  const e = await this.open(t);
1598
1598
  try {
1599
1599
  const { size: n } = await this.fstat(e), i = new Uint8Array(n);
@@ -1631,7 +1631,7 @@ class es {
1631
1631
  async writeFile(t, e) {
1632
1632
  await this.mount();
1633
1633
  const n = e instanceof Uint8Array ? e : new Uint8Array(e);
1634
- await P(t, "exclusive", async () => {
1634
+ await I(t, "exclusive", async () => {
1635
1635
  const i = await this.exists(t), r = await this.open(t, { create: !0, truncate: !0 });
1636
1636
  try {
1637
1637
  await this.write(r, n, 0, n.length, null, !1), await this.fsync(r);
@@ -1666,7 +1666,7 @@ class es {
1666
1666
  async appendFile(t, e) {
1667
1667
  await this.mount();
1668
1668
  const n = e instanceof Uint8Array ? e : new Uint8Array(e);
1669
- await P(t, "exclusive", async () => {
1669
+ await I(t, "exclusive", async () => {
1670
1670
  const i = await this.open(t, { create: !0 });
1671
1671
  try {
1672
1672
  const { size: r } = await this.fstat(i);
@@ -2103,7 +2103,7 @@ class es {
2103
2103
  await this.mount();
2104
2104
  const { create: n = !1, exclusive: i = !1, truncate: r = !1 } = e || {}, o = W(ut(t));
2105
2105
  try {
2106
- return n && i ? await P(o, "exclusive", async () => {
2106
+ return n && i ? await I(o, "exclusive", async () => {
2107
2107
  if (await this.exists(o))
2108
2108
  throw new p(\`File already exists: \${o}\`, "EEXIST", o);
2109
2109
  return this._openFile(o, n, r);
@@ -2329,22 +2329,21 @@ class es {
2329
2329
  * await fs.sync(entries, { cleanBefore: true });
2330
2330
  * \`\`\`
2331
2331
  */
2332
- async sync(t, e) {
2332
+ async createIndex(t) {
2333
2333
  await this.mount();
2334
2334
  try {
2335
- (e?.cleanBefore ?? !1) && await this.clear("/");
2336
- for (const [i, r] of t) {
2337
- const o = W(i);
2338
- let a;
2339
- r instanceof Blob ? a = await Je(r) : typeof r == "string" ? a = new TextEncoder().encode(r) : a = r, await this.writeFile(o, a);
2335
+ for (const [e, n] of t) {
2336
+ const i = W(e);
2337
+ let r;
2338
+ n instanceof Blob ? r = await Je(n) : typeof n == "string" ? r = new TextEncoder().encode(n) : r = n, await this.writeFile(i, r);
2340
2339
  }
2341
- } catch (n) {
2342
- throw n instanceof p ? n : new p("Failed to sync file system", "SYNC_FAILED", void 0, n);
2340
+ } catch (e) {
2341
+ throw e instanceof p ? e : new p("Failed to sync file system", "SYNC_FAILED", void 0, e);
2343
2342
  }
2344
2343
  }
2345
2344
  }
2346
2345
  typeof globalThis < "u" && globalThis.constructor.name === "DedicatedWorkerGlobalScope" && K(new es());
2347
- //# sourceMappingURL=worker-CLvhwwfc.js.map
2346
+ //# sourceMappingURL=worker-BuPeqKqw.js.map
2348
2347
  `, p = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", f], { type: "text/javascript;charset=utf-8" });
2349
2348
  function m(a) {
2350
2349
  let n;
@@ -2551,9 +2550,9 @@ class w {
2551
2550
  /**
2552
2551
  * Synchronize the file system with external data
2553
2552
  */
2554
- async sync(n, t) {
2555
- const e = n.map(([r, i]) => [s(r), i]);
2556
- return this.#n.sync(e, t);
2553
+ async createIndex(n) {
2554
+ const t = n.map(([e, r]) => [s(e), r]);
2555
+ return this.#n.createIndex(t);
2557
2556
  }
2558
2557
  /**
2559
2558
  * Read a file as text with automatic encoding detection
@@ -2592,8 +2591,8 @@ export {
2592
2591
  I as PermissionError,
2593
2592
  R as StorageError,
2594
2593
  $ as TimeoutError,
2595
- C as basename,
2596
- _ as buffersEqual,
2594
+ _ as basename,
2595
+ C as buffersEqual,
2597
2596
  N as calculateFileHash,
2598
2597
  D as calculateReadLength,
2599
2598
  z as checkOPFSSupport,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/facade.ts","../src/index.ts"],"sourcesContent":["import { wrap } from 'comlink';\n\nimport { decodeBuffer, encodeString, isBinaryFileExtension } from './utils/encoder';\nimport WorkerCtor from './worker?worker&inline';\n\nimport type {\n DirentData,\n Encoding,\n FileOpenOptions,\n FileStat,\n OPFSOptions,\n PathLike,\n RemoteOPFSWorker,\n RenameOptions,\n WatchOptions\n} from './types';\n\n/**\n * Utility function to convert a PathLike to a string path\n * If it's a URI, extracts the pathname; otherwise returns the string as-is\n */\nfunction normalizePath(path: PathLike): string {\n if (path instanceof URL) {\n return path.pathname;\n }\n\n return path;\n}\n\n/**\n * Facade class that provides a clean interface for communicating with the OPFS worker\n * while hiding Comlink implementation details.\n */\nexport class OPFSFileSystem {\n #worker: RemoteOPFSWorker;\n\n constructor(options?: OPFSOptions) {\n const wrapped = wrap<RemoteOPFSWorker>(new WorkerCtor());\n\n this.#worker = wrapped;\n\n // Set up options if provided\n if (options) {\n // We can't pass a BroadcastChannel instance to the worker, so we need to convert it to a string first\n if (options.broadcastChannel && options.broadcastChannel instanceof BroadcastChannel) {\n options.broadcastChannel = options.broadcastChannel.name;\n }\n\n // Initialize options asynchronously\n void this.setOptions(options);\n }\n }\n\n /**\n * Update configuration options\n */\n async setOptions(options: OPFSOptions) {\n return this.#worker.setOptions(options);\n }\n\n /**\n * Get a complete index of all files and directories in the file system\n */\n async index(): Promise<Map<string, FileStat>> {\n return this.#worker.index();\n }\n\n /**\n * Read a file from the file system\n */\n async readFile(path: PathLike, encoding: 'binary'): Promise<Uint8Array>;\n async readFile(path: PathLike, encoding: Encoding): Promise<string>;\n async readFile(path: PathLike, encoding?: Encoding | 'binary'): Promise<string | Uint8Array>;\n async readFile(\n path: PathLike,\n encoding?: any\n ): Promise<string | Uint8Array> {\n const normalizedPath = normalizePath(path);\n // Get binary data from worker\n const buffer = await this.#worker.readFile(normalizedPath);\n\n // If no encoding specified, auto-detect based on file extension\n if (!encoding) {\n encoding = isBinaryFileExtension(normalizedPath) ? 'binary' : 'utf-8';\n }\n\n // Return binary data or decode to string\n return (encoding === 'binary') ? buffer : decodeBuffer(buffer, encoding);\n }\n\n /**\n * Write data to a file\n */\n async writeFile(\n path: PathLike,\n data: string | Uint8Array | ArrayBuffer,\n encoding?: Encoding\n ): Promise<void> {\n const normalizedPath = normalizePath(path);\n\n // If no encoding specified, auto-detect based on file extension\n if (!encoding) {\n encoding = (typeof data !== 'string' || isBinaryFileExtension(normalizedPath)) ? 'binary' : 'utf-8';\n }\n\n // Convert data to Uint8Array\n const buffer = typeof data === 'string'\n ? encodeString(data, encoding)\n : (data instanceof Uint8Array ? data : new Uint8Array(data));\n\n return this.#worker.writeFile(normalizedPath, buffer);\n }\n\n /**\n * Append data to a file\n */\n async appendFile(\n path: PathLike,\n data: string | Uint8Array | ArrayBuffer,\n encoding?: Encoding\n ): Promise<void> {\n const normalizedPath = normalizePath(path);\n\n // If no encoding specified, auto-detect based on file extension\n if (!encoding) {\n encoding = (typeof data !== 'string' || isBinaryFileExtension(normalizedPath)) ? 'binary' : 'utf-8';\n }\n\n // Convert data to Uint8Array\n const buffer = typeof data === 'string'\n ? encodeString(data, encoding)\n : (data instanceof Uint8Array ? data : new Uint8Array(data));\n\n return this.#worker.appendFile(normalizedPath, buffer);\n }\n\n /**\n * Create a directory\n */\n async mkdir(path: PathLike, options?: { recursive?: boolean }): Promise<void> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.mkdir(normalizedPath, options);\n }\n\n /**\n * Get file or directory statistics\n */\n async stat(path: PathLike): Promise<FileStat> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.stat(normalizedPath);\n }\n\n /**\n * Read a directory's contents\n */\n async readDir(path: PathLike): Promise<DirentData[]> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.readDir(normalizedPath);\n }\n\n /**\n * Check if a file or directory exists\n */\n async exists(path: PathLike): Promise<boolean> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.exists(normalizedPath);\n }\n\n /**\n * Clear all contents of a directory without removing the directory itself\n */\n async clear(path?: PathLike): Promise<void> {\n const normalizedPath = path ? normalizePath(path) : undefined;\n\n return this.#worker.clear(normalizedPath);\n }\n\n /**\n * Remove files and directories\n */\n async remove(path: PathLike, options?: { recursive?: boolean; force?: boolean }): Promise<void> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.remove(normalizedPath, options);\n }\n\n /**\n * Resolve a path to an absolute path\n */\n async realpath(path: PathLike): Promise<string> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.realpath(normalizedPath);\n }\n\n /**\n * Rename a file or directory\n */\n async rename(oldPath: PathLike, newPath: PathLike, options?: RenameOptions): Promise<void> {\n const normalizedOldPath = normalizePath(oldPath);\n const normalizedNewPath = normalizePath(newPath);\n\n return this.#worker.rename(normalizedOldPath, normalizedNewPath, options);\n }\n\n /**\n * Copy files and directories\n */\n async copy(source: PathLike, destination: PathLike, options?: { recursive?: boolean; overwrite?: boolean }): Promise<void> {\n const normalizedSource = normalizePath(source);\n const normalizedDestination = normalizePath(destination);\n\n return this.#worker.copy(normalizedSource, normalizedDestination, options);\n }\n\n /**\n * Start watching a file or directory for changes\n */\n watch(path: PathLike, options?: WatchOptions): () => void {\n const normalizedPath = normalizePath(path);\n\n void this.#worker.watch(normalizedPath, options);\n\n return () => this.unwatch(normalizedPath);\n }\n\n /**\n * Stop watching a previously watched path\n */\n unwatch(path: PathLike) {\n const normalizedPath = normalizePath(path);\n\n void this.#worker.unwatch(normalizedPath);\n }\n\n /**\n * Open a file and return a file descriptor\n */\n async open(path: PathLike, options?: FileOpenOptions): Promise<number> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.open(normalizedPath, options);\n }\n\n /**\n * Close a file descriptor\n */\n async close(fd: number): Promise<void> {\n return this.#worker.close(fd);\n }\n\n /**\n * Read data from a file descriptor\n * \n * This method requires special handling due to Comlink transfer requirements.\n * The buffer is transferred to the worker and back, so the original buffer\n * becomes unusable after the call.\n */\n async read(\n fd: number,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position?: number | null | undefined\n ): Promise<{ bytesRead: number; buffer: Uint8Array }> {\n const { bytesRead, buffer: transferred } = await this.#worker.read(\n fd,\n // Temp buffer to preserve the original buffer\n new Uint8Array(length),\n 0,\n length,\n position\n );\n\n // Copy the data from the transferred buffer to the original buffer\n if (bytesRead > 0) {\n buffer.set(transferred.subarray(0, bytesRead), offset);\n }\n\n return { bytesRead, buffer };\n }\n\n /**\n * Write data to a file descriptor\n */\n async write(\n fd: number,\n buffer: Uint8Array,\n offset?: number,\n length?: number,\n position?: number | null | undefined,\n emitEvent?: boolean\n ): Promise<number> {\n return this.#worker.write(fd, buffer, offset, length, position, emitEvent);\n }\n\n /**\n * Get file status information by file descriptor\n */\n async fstat(fd: number): Promise<FileStat> {\n return this.#worker.fstat(fd);\n }\n\n /**\n * Truncate file to specified size\n */\n async ftruncate(fd: number, size?: number): Promise<void> {\n return this.#worker.ftruncate(fd, size);\n }\n\n /**\n * Synchronize file data to storage (fsync equivalent)\n */\n async fsync(fd: number): Promise<void> {\n return this.#worker.fsync(fd);\n }\n\n /**\n * Dispose of resources and clean up the file system instance\n */\n dispose() {\n void this.#worker.dispose();\n }\n\n /**\n * Synchronize the file system with external data\n */\n async sync(entries: [PathLike, string | Uint8Array | Blob][], options?: { cleanBefore?: boolean }): Promise<void> {\n const normalizedEntries = entries.map(([path, data]) => [normalizePath(path), data] as [string, string | Uint8Array | Blob]);\n\n return this.#worker.sync(normalizedEntries, options);\n }\n\n /**\n * Read a file as text with automatic encoding detection\n */\n async readText(path: PathLike, encoding: Encoding = 'utf-8'): Promise<string> {\n const normalizedPath = normalizePath(path);\n const buffer = await this.#worker.readFile(normalizedPath);\n\n return decodeBuffer(buffer, encoding);\n }\n\n /**\n * Write text to a file with specified encoding\n */\n async writeText(path: PathLike, text: string, encoding: Encoding = 'utf-8'): Promise<void> {\n const normalizedPath = normalizePath(path);\n const buffer = encodeString(text, encoding);\n\n return this.#worker.writeFile(normalizedPath, buffer);\n }\n\n /**\n * Append text to a file with specified encoding\n */\n async appendText(path: PathLike, text: string, encoding: Encoding = 'utf-8'): Promise<void> {\n const normalizedPath = normalizePath(path);\n const buffer = encodeString(text, encoding);\n\n return this.#worker.appendFile(normalizedPath, buffer);\n }\n}\n","import { OPFSFileSystem } from './facade';\n\nimport type { OPFSOptions } from './types';\n\nexport * from './types';\nexport * from './utils/errors';\nexport * from './utils/helpers';\nexport * from './utils/encoder';\nexport * from './facade';\n\n/**\n * Creates a new file system instance with inline worker\n * @param options - Optional configuration options\n * @returns Promise resolving to the file system interface\n */\nexport function createWorker(\n options?: OPFSOptions\n): OPFSFileSystem {\n return new OPFSFileSystem(options);\n}\n"],"names":["normalizePath","path","OPFSFileSystem","#worker","options","wrapped","wrap","WorkerCtor","encoding","normalizedPath","buffer","isBinaryFileExtension","decodeBuffer","data","encodeString","oldPath","newPath","normalizedOldPath","normalizedNewPath","source","destination","normalizedSource","normalizedDestination","fd","offset","length","position","bytesRead","transferred","emitEvent","size","entries","normalizedEntries","text","createWorker"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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O;AAAA,EACvD;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,SAASH,GAAgBO,IAAqB,SAA0B;AAC1E,UAAMC,IAAiBT,EAAcC,CAAI,GACnCS,IAAS,MAAM,KAAKP,GAAQ,SAASM,CAAc;AAEzD,WAAOG,EAAaF,GAAQF,CAAQ;AAAA,EACxC;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,UAAUP,GAAgBgC,GAAczB,IAAqB,SAAwB;AACvF,UAAMC,IAAiBT,EAAcC,CAAI,GACnCS,IAASI,EAAamB,GAAMzB,CAAQ;AAE1C,WAAO,KAAKL,GAAQ,UAAUM,GAAgBC,CAAM;AAAA,EACxD;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,WAAWT,GAAgBgC,GAAczB,IAAqB,SAAwB;AACxF,UAAMC,IAAiBT,EAAcC,CAAI,GACnCS,IAASI,EAAamB,GAAMzB,CAAQ;AAE1C,WAAO,KAAKL,GAAQ,WAAWM,GAAgBC,CAAM;AAAA,EACzD;AACJ;AC/VO,SAASwB,EACZ9B,GACc;AACd,SAAO,IAAIF,EAAeE,CAAO;AACrC;"}
1
+ {"version":3,"file":"index.js","sources":["../src/facade.ts","../src/index.ts"],"sourcesContent":["import { wrap } from 'comlink';\n\nimport { decodeBuffer, encodeString, isBinaryFileExtension } from './utils/encoder';\nimport WorkerCtor from './worker?worker&inline';\n\nimport type {\n DirentData,\n Encoding,\n FileOpenOptions,\n FileStat,\n OPFSOptions,\n PathLike,\n RemoteOPFSWorker,\n RenameOptions,\n WatchOptions\n} from './types';\n\n/**\n * Utility function to convert a PathLike to a string path\n * If it's a URI, extracts the pathname; otherwise returns the string as-is\n */\nfunction normalizePath(path: PathLike): string {\n if (path instanceof URL) {\n return path.pathname;\n }\n\n return path;\n}\n\n/**\n * Facade class that provides a clean interface for communicating with the OPFS worker\n * while hiding Comlink implementation details.\n */\nexport class OPFSFileSystem {\n #worker: RemoteOPFSWorker;\n\n constructor(options?: OPFSOptions) {\n const wrapped = wrap<RemoteOPFSWorker>(new WorkerCtor());\n\n this.#worker = wrapped;\n\n // Set up options if provided\n if (options) {\n // We can't pass a BroadcastChannel instance to the worker, so we need to convert it to a string first\n if (options.broadcastChannel && options.broadcastChannel instanceof BroadcastChannel) {\n options.broadcastChannel = options.broadcastChannel.name;\n }\n\n // Initialize options asynchronously\n void this.setOptions(options);\n }\n }\n\n /**\n * Update configuration options\n */\n async setOptions(options: OPFSOptions) {\n return this.#worker.setOptions(options);\n }\n\n /**\n * Get a complete index of all files and directories in the file system\n */\n async index(): Promise<Map<string, FileStat>> {\n return this.#worker.index();\n }\n\n /**\n * Read a file from the file system\n */\n async readFile(path: PathLike, encoding: 'binary'): Promise<Uint8Array>;\n async readFile(path: PathLike, encoding: Encoding): Promise<string>;\n async readFile(path: PathLike, encoding?: Encoding | 'binary'): Promise<string | Uint8Array>;\n async readFile(\n path: PathLike,\n encoding?: any\n ): Promise<string | Uint8Array> {\n const normalizedPath = normalizePath(path);\n // Get binary data from worker\n const buffer = await this.#worker.readFile(normalizedPath);\n\n // If no encoding specified, auto-detect based on file extension\n if (!encoding) {\n encoding = isBinaryFileExtension(normalizedPath) ? 'binary' : 'utf-8';\n }\n\n // Return binary data or decode to string\n return (encoding === 'binary') ? buffer : decodeBuffer(buffer, encoding);\n }\n\n /**\n * Write data to a file\n */\n async writeFile(\n path: PathLike,\n data: string | Uint8Array | ArrayBuffer,\n encoding?: Encoding\n ): Promise<void> {\n const normalizedPath = normalizePath(path);\n\n // If no encoding specified, auto-detect based on file extension\n if (!encoding) {\n encoding = (typeof data !== 'string' || isBinaryFileExtension(normalizedPath)) ? 'binary' : 'utf-8';\n }\n\n // Convert data to Uint8Array\n const buffer = typeof data === 'string'\n ? encodeString(data, encoding)\n : (data instanceof Uint8Array ? data : new Uint8Array(data));\n\n return this.#worker.writeFile(normalizedPath, buffer);\n }\n\n /**\n * Append data to a file\n */\n async appendFile(\n path: PathLike,\n data: string | Uint8Array | ArrayBuffer,\n encoding?: Encoding\n ): Promise<void> {\n const normalizedPath = normalizePath(path);\n\n // If no encoding specified, auto-detect based on file extension\n if (!encoding) {\n encoding = (typeof data !== 'string' || isBinaryFileExtension(normalizedPath)) ? 'binary' : 'utf-8';\n }\n\n // Convert data to Uint8Array\n const buffer = typeof data === 'string'\n ? encodeString(data, encoding)\n : (data instanceof Uint8Array ? data : new Uint8Array(data));\n\n return this.#worker.appendFile(normalizedPath, buffer);\n }\n\n /**\n * Create a directory\n */\n async mkdir(path: PathLike, options?: { recursive?: boolean }): Promise<void> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.mkdir(normalizedPath, options);\n }\n\n /**\n * Get file or directory statistics\n */\n async stat(path: PathLike): Promise<FileStat> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.stat(normalizedPath);\n }\n\n /**\n * Read a directory's contents\n */\n async readDir(path: PathLike): Promise<DirentData[]> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.readDir(normalizedPath);\n }\n\n /**\n * Check if a file or directory exists\n */\n async exists(path: PathLike): Promise<boolean> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.exists(normalizedPath);\n }\n\n /**\n * Clear all contents of a directory without removing the directory itself\n */\n async clear(path?: PathLike): Promise<void> {\n const normalizedPath = path ? normalizePath(path) : undefined;\n\n return this.#worker.clear(normalizedPath);\n }\n\n /**\n * Remove files and directories\n */\n async remove(path: PathLike, options?: { recursive?: boolean; force?: boolean }): Promise<void> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.remove(normalizedPath, options);\n }\n\n /**\n * Resolve a path to an absolute path\n */\n async realpath(path: PathLike): Promise<string> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.realpath(normalizedPath);\n }\n\n /**\n * Rename a file or directory\n */\n async rename(oldPath: PathLike, newPath: PathLike, options?: RenameOptions): Promise<void> {\n const normalizedOldPath = normalizePath(oldPath);\n const normalizedNewPath = normalizePath(newPath);\n\n return this.#worker.rename(normalizedOldPath, normalizedNewPath, options);\n }\n\n /**\n * Copy files and directories\n */\n async copy(source: PathLike, destination: PathLike, options?: { recursive?: boolean; overwrite?: boolean }): Promise<void> {\n const normalizedSource = normalizePath(source);\n const normalizedDestination = normalizePath(destination);\n\n return this.#worker.copy(normalizedSource, normalizedDestination, options);\n }\n\n /**\n * Start watching a file or directory for changes\n */\n watch(path: PathLike, options?: WatchOptions): () => void {\n const normalizedPath = normalizePath(path);\n\n void this.#worker.watch(normalizedPath, options);\n\n return () => this.unwatch(normalizedPath);\n }\n\n /**\n * Stop watching a previously watched path\n */\n unwatch(path: PathLike) {\n const normalizedPath = normalizePath(path);\n\n void this.#worker.unwatch(normalizedPath);\n }\n\n /**\n * Open a file and return a file descriptor\n */\n async open(path: PathLike, options?: FileOpenOptions): Promise<number> {\n const normalizedPath = normalizePath(path);\n\n return this.#worker.open(normalizedPath, options);\n }\n\n /**\n * Close a file descriptor\n */\n async close(fd: number): Promise<void> {\n return this.#worker.close(fd);\n }\n\n /**\n * Read data from a file descriptor\n * \n * This method requires special handling due to Comlink transfer requirements.\n * The buffer is transferred to the worker and back, so the original buffer\n * becomes unusable after the call.\n */\n async read(\n fd: number,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position?: number | null | undefined\n ): Promise<{ bytesRead: number; buffer: Uint8Array }> {\n const { bytesRead, buffer: transferred } = await this.#worker.read(\n fd,\n // Temp buffer to preserve the original buffer\n new Uint8Array(length),\n 0,\n length,\n position\n );\n\n // Copy the data from the transferred buffer to the original buffer\n if (bytesRead > 0) {\n buffer.set(transferred.subarray(0, bytesRead), offset);\n }\n\n return { bytesRead, buffer };\n }\n\n /**\n * Write data to a file descriptor\n */\n async write(\n fd: number,\n buffer: Uint8Array,\n offset?: number,\n length?: number,\n position?: number | null | undefined,\n emitEvent?: boolean\n ): Promise<number> {\n return this.#worker.write(fd, buffer, offset, length, position, emitEvent);\n }\n\n /**\n * Get file status information by file descriptor\n */\n async fstat(fd: number): Promise<FileStat> {\n return this.#worker.fstat(fd);\n }\n\n /**\n * Truncate file to specified size\n */\n async ftruncate(fd: number, size?: number): Promise<void> {\n return this.#worker.ftruncate(fd, size);\n }\n\n /**\n * Synchronize file data to storage (fsync equivalent)\n */\n async fsync(fd: number): Promise<void> {\n return this.#worker.fsync(fd);\n }\n\n /**\n * Dispose of resources and clean up the file system instance\n */\n dispose() {\n void this.#worker.dispose();\n }\n\n /**\n * Synchronize the file system with external data\n */\n async createIndex(entries: [PathLike, string | Uint8Array | Blob][]): Promise<void> {\n const normalizedEntries = entries.map(([path, data]) => [normalizePath(path), data] as [string, string | Uint8Array | Blob]);\n\n return this.#worker.createIndex(normalizedEntries);\n }\n\n /**\n * Read a file as text with automatic encoding detection\n */\n async readText(path: PathLike, encoding: Encoding = 'utf-8'): Promise<string> {\n const normalizedPath = normalizePath(path);\n const buffer = await this.#worker.readFile(normalizedPath);\n\n return decodeBuffer(buffer, encoding);\n }\n\n /**\n * Write text to a file with specified encoding\n */\n async writeText(path: PathLike, text: string, encoding: Encoding = 'utf-8'): Promise<void> {\n const normalizedPath = normalizePath(path);\n const buffer = encodeString(text, encoding);\n\n return this.#worker.writeFile(normalizedPath, buffer);\n }\n\n /**\n * Append text to a file with specified encoding\n */\n async appendText(path: PathLike, text: string, encoding: Encoding = 'utf-8'): Promise<void> {\n const normalizedPath = normalizePath(path);\n const buffer = encodeString(text, encoding);\n\n return this.#worker.appendFile(normalizedPath, buffer);\n }\n}\n","import { OPFSFileSystem } from './facade';\n\nimport type { OPFSOptions } from './types';\n\nexport * from './types';\nexport * from './utils/errors';\nexport * from './utils/helpers';\nexport * from './utils/encoder';\nexport * from './facade';\n\n/**\n * Creates a new file system instance with inline worker\n * @param options - Optional configuration options\n * @returns Promise resolving to the file system interface\n */\nexport function createWorker(\n options?: OPFSOptions\n): OPFSFileSystem {\n return new OPFSFileSystem(options);\n}\n"],"names":["normalizePath","path","OPFSFileSystem","#worker","options","wrapped","wrap","WorkerCtor","encoding","normalizedPath","buffer","isBinaryFileExtension","decodeBuffer","data","encodeString","oldPath","newPath","normalizedOldPath","normalizedNewPath","source","destination","normalizedSource","normalizedDestination","fd","offset","length","position","bytesRead","transferred","emitEvent","size","entries","normalizedEntries","text","createWorker"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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EACtB;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,YAAY4B,GAAkE;AAChF,UAAMC,IAAoBD,EAAQ,IAAI,CAAC,CAAC9B,GAAMY,CAAI,MAAM,CAACb,EAAcC,CAAI,GAAGY,CAAI,CAAyC;AAE3H,WAAO,KAAKV,GAAQ,YAAY6B,CAAiB;AAAA,EACrD;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,SAAS/B,GAAgBO,IAAqB,SAA0B;AAC1E,UAAMC,IAAiBT,EAAcC,CAAI,GACnCS,IAAS,MAAM,KAAKP,GAAQ,SAASM,CAAc;AAEzD,WAAOG,EAAaF,GAAQF,CAAQ;AAAA,EACxC;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,UAAUP,GAAgBgC,GAAczB,IAAqB,SAAwB;AACvF,UAAMC,IAAiBT,EAAcC,CAAI,GACnCS,IAASI,EAAamB,GAAMzB,CAAQ;AAE1C,WAAO,KAAKL,GAAQ,UAAUM,GAAgBC,CAAM;AAAA,EACxD;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,WAAWT,GAAgBgC,GAAczB,IAAqB,SAAwB;AACxF,UAAMC,IAAiBT,EAAcC,CAAI,GACnCS,IAASI,EAAamB,GAAMzB,CAAQ;AAE1C,WAAO,KAAKL,GAAQ,WAAWM,GAAgBC,CAAM;AAAA,EACzD;AACJ;AC/VO,SAASwB,EACZ9B,GACc;AACd,SAAO,IAAIF,EAAeE,CAAO;AACrC;"}
package/dist/raw.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("comlink"),s=require("./helpers-TAynP0fb.cjs");class f{root;watchers=new Map;mountingPromise=null;broadcastChannel=null;options={root:"/",namespace:"",maxFileSize:50*1024*1024,hashAlgorithm:!1,broadcastChannel:"opfs-worker"};openFiles=new Map;nextFd=1;_getFileDescriptor(t){const e=this.openFiles.get(t);if(!e)throw new s.OPFSError(`Invalid file descriptor: ${t}`,"EBADF");return e}async notifyChange(t){if(!this.options.broadcastChannel)return;const e=t.path;if(![...this.watchers.values()].some(a=>s.matchMinimatch(e,a.pattern)&&a.include.some(n=>n&&s.matchMinimatch(e,n))&&!a.exclude.some(n=>n&&s.matchMinimatch(e,n))))return;let r;if(this.options.hashAlgorithm)try{r=(await this.stat(e)).hash}catch{}try{this.broadcastChannel||(this.broadcastChannel=new BroadcastChannel(this.options.broadcastChannel));const a={namespace:this.options.namespace,timestamp:new Date().toISOString(),...t,...r&&{hash:r}};this.broadcastChannel.postMessage(a)}catch(a){console.warn("Failed to send event via BroadcastChannel:",a)}}constructor(t){s.checkOPFSSupport(),t&&this.setOptions(t)}async mount(){const t=this.options.root;return this.mountingPromise&&await this.mountingPromise,this.mountingPromise=new Promise(async(e,i)=>{try{const r=await navigator.storage.getDirectory();this.root=t==="/"?r:await this.getDirectoryHandle(t,!0,r),e(!0)}catch(r){i(new s.OPFSError("Failed to initialize OPFS","INIT_FAILED",t,r))}finally{this.mountingPromise=null}}),this.mountingPromise}async setOptions(t){t.hashAlgorithm!==void 0&&(this.options.hashAlgorithm=t.hashAlgorithm),t.maxFileSize!==void 0&&(this.options.maxFileSize=t.maxFileSize),t.broadcastChannel!==void 0&&(this.broadcastChannel&&this.options.broadcastChannel!==t.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.options.broadcastChannel=t.broadcastChannel),t.namespace&&(this.options.namespace=t.namespace),t.root!==void 0&&(this.options.root=s.normalizePath(t.root),this.options.namespace||(this.options.namespace=`opfs-worker:${this.options.root}`),await this.mount())}async getDirectoryHandle(t,e=!1,i=this.root){const r=Array.isArray(t)?t:s.splitPath(t);let a=i;for(const n of r)a=await a.getDirectoryHandle(n,{create:e});return a}async getFileHandle(t,e=!1,i=this.root){const r=s.splitPath(t);if(r.length===0)throw new s.PathError("Path must not be empty",Array.isArray(t)?t.join("/"):t);const a=r.pop();return(await this.getDirectoryHandle(r,e,i)).getFileHandle(a,{create:e})}async index(){const t=new Map,e=async i=>{const r=await this.readDir(i);for(const a of r){const n=`${i==="/"?"":i}/${a.name}`;try{const o=await this.stat(n);t.set(n,o),o.isDirectory&&await e(n)}catch(o){console.warn(`Skipping broken entry: ${n}`,o)}}};return t.set("/",{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0}),await e("/"),t}async readFile(t){await this.mount();try{return await s.withLock(t,"shared",async()=>{const e=await this.open(t);try{const{size:i}=await this.fstat(e),r=new Uint8Array(i);return i>0&&await this.read(e,r,0,i,0),y.transfer(r,[r.buffer])}finally{await this.close(e)}})}catch(e){throw new s.FileNotFoundError(t,e)}}async writeFile(t,e){await this.mount();const i=e instanceof Uint8Array?e:new Uint8Array(e);await s.withLock(t,"exclusive",async()=>{const r=await this.exists(t),a=await this.open(t,{create:!0,truncate:!0});try{await this.write(a,i,0,i.length,null,!1),await this.fsync(a)}finally{await this.close(a)}await this.notifyChange({path:t,type:r?"changed":"added",isDirectory:!1})})}async appendFile(t,e){await this.mount();const i=e instanceof Uint8Array?e:new Uint8Array(e);await s.withLock(t,"exclusive",async()=>{const r=await this.open(t,{create:!0});try{const{size:a}=await this.fstat(r);await this.write(r,i,0,i.length,a,!1),await this.fsync(r)}finally{await this.close(r)}await this.notifyChange({path:t,type:"changed",isDirectory:!1})})}async mkdir(t,e){await this.mount();const i=e?.recursive??!1,r=s.splitPath(t);let a=this.root;for(let n=0;n<r.length;n++){const o=r[n];try{a=await a.getDirectoryHandle(o,{create:i||n===r.length-1})}catch(c){throw c.name==="NotFoundError"?new s.OPFSError(`Parent directory does not exist: ${s.joinPath(r.slice(0,n+1))}`,"ENOENT",void 0,c):c.name==="TypeMismatchError"?new s.OPFSError(`Path segment is not a directory: ${o}`,"ENOTDIR",void 0,c):new s.OPFSError("Failed to create directory","MKDIR_FAILED",void 0,c)}}await this.notifyChange({path:t,type:"added",isDirectory:!0})}async stat(t){if(await this.mount(),t==="/")return{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0};const e=s.basename(t),i=await this.getDirectoryHandle(s.dirname(t),!1),r=this.options.hashAlgorithm!==null;try{const n=await(await i.getFileHandle(e,{create:!1})).getFile(),o={kind:"file",size:n.size,mtime:new Date(n.lastModified).toISOString(),ctime:new Date(n.lastModified).toISOString(),isFile:!0,isDirectory:!1};if(r&&this.options.hashAlgorithm)try{const c=await s.calculateFileHash(n,this.options.hashAlgorithm,this.options.maxFileSize);o.hash=c}catch(c){console.warn(`Failed to calculate hash for ${t}:`,c)}return o}catch(a){if(a.name!=="TypeMismatchError"&&a.name!=="NotFoundError")throw new s.OPFSError("Failed to stat (file)","STAT_FAILED",void 0,a)}try{return await i.getDirectoryHandle(e,{create:!1}),{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0}}catch(a){throw a.name==="NotFoundError"?new s.OPFSError(`No such file or directory: ${t}`,"ENOENT",void 0,a):new s.OPFSError("Failed to stat (directory)","STAT_FAILED",void 0,a)}}async readDir(t){await this.mount();const e=await this.getDirectoryHandle(t,!1),i=[];for await(const[r,a]of e.entries()){const n=a.kind==="file";i.push({name:r,kind:a.kind,isFile:n,isDirectory:!n})}return i}async exists(t){if(await this.mount(),t==="/")return!0;const e=s.basename(t);let i=null;try{i=await this.getDirectoryHandle(s.dirname(t),!1)}catch(r){if(i=null,r.name!=="NotFoundError"&&r.name!=="TypeMismatchError")throw r}if(!i||!e)return!1;try{return await i.getFileHandle(e,{create:!1}),!0}catch(r){if(r.name!=="NotFoundError"&&r.name!=="TypeMismatchError")throw r;try{return await i.getDirectoryHandle(e,{create:!1}),!0}catch(a){if(a.name!=="NotFoundError"&&a.name!=="TypeMismatchError")throw a;return!1}}}async clear(t="/"){await this.mount();try{const e=await this.readDir(t);for(const i of e){const r=`${t==="/"?"":t}/${i.name}`;await this.remove(r,{recursive:!0})}await this.notifyChange({path:t,type:"changed",isDirectory:!0})}catch(e){throw e instanceof s.OPFSError?e:new s.OPFSError(`Failed to clear directory: ${t}`,"CLEAR_FAILED",void 0,e)}}async remove(t,e){if(await this.mount(),t==="/")throw new s.OPFSError("Cannot remove root directory","EROOT");const{recursive:i=!1,force:r=!1}=e||{},a=await this.getDirectoryHandle(s.dirname(t),!1),n=await this.stat(t);await s.removeEntry(a,t,{recursive:i,force:r}),await this.notifyChange({path:t,type:"removed",isDirectory:n.isDirectory})}async realpath(t){await this.mount();try{const e=s.resolvePath(t);if(!await this.exists(e))throw new s.FileNotFoundError(e);return e}catch(e){throw e instanceof s.OPFSError?e:new s.OPFSError(`Failed to resolve path: ${t}`,"REALPATH_FAILED",void 0,e)}}async rename(t,e,i){await this.mount();try{const r=i?.overwrite??!1,a=await this.stat(t);if(await this.exists(e)&&!r)throw new s.OPFSError(`Destination already exists: ${e}`,"EEXIST",void 0);await this.copy(t,e,{recursive:!0,overwrite:r}),await this.remove(t,{recursive:!0}),await this.notifyChange({path:t,type:"removed",isDirectory:a.isDirectory}),await this.notifyChange({path:e,type:"added",isDirectory:a.isDirectory})}catch(r){throw r instanceof s.OPFSError?r:new s.OPFSError(`Failed to rename from ${t} to ${e}`,"RENAME_FAILED",void 0,r)}}async copy(t,e,i){await this.mount();try{const r=i?.recursive??!1,a=i?.overwrite??!0;if(!await this.exists(t))throw new s.OPFSError(`Source does not exist: ${t}`,"ENOENT",void 0);if(await this.exists(e)&&!a)throw new s.OPFSError(`Destination already exists: ${e}`,"EEXIST",void 0);if((await this.stat(t)).isFile){const l=await this.readFile(t);await this.writeFile(e,l)}else{if(!r)throw new s.OPFSError(`Cannot copy directory without recursive option: ${t}`,"EISDIR",void 0);await this.mkdir(e,{recursive:!0});const l=await this.readDir(t);for(const h of l){const w=`${t}/${h.name}`,d=`${e}/${h.name}`;await this.copy(w,d,{recursive:!0,overwrite:a})}}}catch(r){throw r instanceof s.OPFSError?r:new s.OPFSError(`Failed to copy from ${t} to ${e}`,"CP_FAILED",void 0,r)}}async watch(t,e){if(!this.options.broadcastChannel)throw new s.OPFSError("This instance is not configured to send events. Please specify options.broadcastChannel to enable watching.","ENOENT");const i={pattern:s.normalizeMinimatch(t,e?.recursive??!0),include:Array.isArray(e?.include)?e.include:[e?.include??"**"],exclude:Array.isArray(e?.exclude)?e.exclude:[e?.exclude??""]};this.watchers.set(t,i)}unwatch(t){this.watchers.delete(t)}async open(t,e){await this.mount();const{create:i=!1,exclusive:r=!1,truncate:a=!1}=e||{},n=s.normalizePath(s.resolvePath(t));try{return i&&r?await s.withLock(n,"exclusive",async()=>{if(await this.exists(n))throw new s.OPFSError(`File already exists: ${n}`,"EEXIST",n);return this._openFile(n,i,a)}):await this._openFile(n,i,a)}catch(o){throw o instanceof s.OPFSError?o:new s.OPFSError(`Failed to open file: ${n}`,"OPEN_FAILED",n,o)}}async _openFile(t,e,i){const r=await this.getFileHandle(t,e);try{await r.getFile()}catch(o){throw o.name==="TypeMismatchError"?new s.OPFSError(`Is a directory: ${t}`,"EISDIR",t):o}const a=await s.createSyncHandleSafe(r,t);i&&(a.truncate(0),a.flush());const n=this.nextFd++;return this.openFiles.set(n,{path:t,fileHandle:r,syncHandle:a,position:0}),n}async close(t){const e=this._getFileDescriptor(t);s.safeCloseSyncHandle(t,e.syncHandle,e.path),this.openFiles.delete(t)}async read(t,e,i,r,a){const n=this._getFileDescriptor(t);s.validateReadWriteArgs(e.length,i,r,a);try{const o=a??n.position,c=n.syncHandle.getSize(),{isEOF:l,actualLength:h}=s.calculateReadLength(o,r,c);if(l)return y.transfer({bytesRead:0,buffer:e},[e.buffer]);const w=e.subarray(i,i+h),d=n.syncHandle.read(w,{at:o});return a==null&&(n.position=o+d),y.transfer({bytesRead:d,buffer:e},[e.buffer])}catch(o){throw s.createFDError("read",t,n.path,o)}}async write(t,e,i=0,r,a,n=!0){const o=this._getFileDescriptor(t),c=r??e.length-i;s.validateReadWriteArgs(e.length,i,c,a);try{const l=a??o.position,h=e.subarray(i,i+c),w=o.syncHandle.write(h,{at:l});return(a==null||a===o.position)&&(o.position=l+w),n&&await this.notifyChange({path:o.path,type:"changed",isDirectory:!1}),w}catch(l){throw s.createFDError("write",t,o.path,l)}}async fstat(t){const e=this._getFileDescriptor(t);return this.stat(e.path)}async ftruncate(t,e=0){const i=this._getFileDescriptor(t);if(e<0||!Number.isInteger(e))throw new s.OPFSError("Invalid size","EINVAL");try{i.syncHandle.truncate(e),i.syncHandle.flush(),i.position>e&&(i.position=e),await this.notifyChange({path:i.path,type:"changed",isDirectory:!1})}catch(r){throw s.createFDError("truncate",t,i.path,r)}}async fsync(t){const e=this._getFileDescriptor(t);try{e.syncHandle.flush()}catch(i){throw s.createFDError("sync",t,e.path,i)}}dispose(){this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.watchers.clear();for(const[t,e]of this.openFiles)s.safeCloseSyncHandle(t,e.syncHandle,e.path);this.openFiles.clear(),this.nextFd=1}async sync(t,e){await this.mount();try{(e?.cleanBefore??!1)&&await this.clear("/");for(const[r,a]of t){const n=s.normalizePath(r);let o;a instanceof Blob?o=await s.convertBlobToUint8Array(a):typeof a=="string"?o=new TextEncoder().encode(a):o=a,await this.writeFile(n,o)}}catch(i){throw i instanceof s.OPFSError?i:new s.OPFSError("Failed to sync file system","SYNC_FAILED",void 0,i)}}}typeof globalThis<"u"&&globalThis.constructor.name==="DedicatedWorkerGlobalScope"&&y.expose(new f);exports.OPFSWorker=f;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("comlink"),s=require("./helpers-TAynP0fb.cjs");class f{root;watchers=new Map;mountingPromise=null;broadcastChannel=null;options={root:"/",namespace:"",maxFileSize:50*1024*1024,hashAlgorithm:!1,broadcastChannel:"opfs-worker"};openFiles=new Map;nextFd=1;_getFileDescriptor(t){const e=this.openFiles.get(t);if(!e)throw new s.OPFSError(`Invalid file descriptor: ${t}`,"EBADF");return e}async notifyChange(t){if(!this.options.broadcastChannel)return;const e=t.path;if(![...this.watchers.values()].some(a=>s.matchMinimatch(e,a.pattern)&&a.include.some(n=>n&&s.matchMinimatch(e,n))&&!a.exclude.some(n=>n&&s.matchMinimatch(e,n))))return;let i;if(this.options.hashAlgorithm)try{i=(await this.stat(e)).hash}catch{}try{this.broadcastChannel||(this.broadcastChannel=new BroadcastChannel(this.options.broadcastChannel));const a={namespace:this.options.namespace,timestamp:new Date().toISOString(),...t,...i&&{hash:i}};this.broadcastChannel.postMessage(a)}catch(a){console.warn("Failed to send event via BroadcastChannel:",a)}}constructor(t){s.checkOPFSSupport(),t&&this.setOptions(t)}async mount(){const t=this.options.root;return this.mountingPromise&&await this.mountingPromise,this.mountingPromise=new Promise(async(e,r)=>{try{const i=await navigator.storage.getDirectory();this.root=t==="/"?i:await this.getDirectoryHandle(t,!0,i),e(!0)}catch(i){r(new s.OPFSError("Failed to initialize OPFS","INIT_FAILED",t,i))}finally{this.mountingPromise=null}}),this.mountingPromise}async setOptions(t){t.hashAlgorithm!==void 0&&(this.options.hashAlgorithm=t.hashAlgorithm),t.maxFileSize!==void 0&&(this.options.maxFileSize=t.maxFileSize),t.broadcastChannel!==void 0&&(this.broadcastChannel&&this.options.broadcastChannel!==t.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.options.broadcastChannel=t.broadcastChannel),t.namespace&&(this.options.namespace=t.namespace),t.root!==void 0&&(this.options.root=s.normalizePath(t.root),this.options.namespace||(this.options.namespace=`opfs-worker:${this.options.root}`),await this.mount())}async getDirectoryHandle(t,e=!1,r=this.root){const i=Array.isArray(t)?t:s.splitPath(t);let a=r;for(const n of i)a=await a.getDirectoryHandle(n,{create:e});return a}async getFileHandle(t,e=!1,r=this.root){const i=s.splitPath(t);if(i.length===0)throw new s.PathError("Path must not be empty",Array.isArray(t)?t.join("/"):t);const a=i.pop();return(await this.getDirectoryHandle(i,e,r)).getFileHandle(a,{create:e})}async index(){const t=new Map,e=async r=>{const i=await this.readDir(r);for(const a of i){const n=`${r==="/"?"":r}/${a.name}`;try{const o=await this.stat(n);t.set(n,o),o.isDirectory&&await e(n)}catch(o){console.warn(`Skipping broken entry: ${n}`,o)}}};return t.set("/",{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0}),await e("/"),t}async readFile(t){await this.mount();try{return await s.withLock(t,"shared",async()=>{const e=await this.open(t);try{const{size:r}=await this.fstat(e),i=new Uint8Array(r);return r>0&&await this.read(e,i,0,r,0),y.transfer(i,[i.buffer])}finally{await this.close(e)}})}catch(e){throw new s.FileNotFoundError(t,e)}}async writeFile(t,e){await this.mount();const r=e instanceof Uint8Array?e:new Uint8Array(e);await s.withLock(t,"exclusive",async()=>{const i=await this.exists(t),a=await this.open(t,{create:!0,truncate:!0});try{await this.write(a,r,0,r.length,null,!1),await this.fsync(a)}finally{await this.close(a)}await this.notifyChange({path:t,type:i?"changed":"added",isDirectory:!1})})}async appendFile(t,e){await this.mount();const r=e instanceof Uint8Array?e:new Uint8Array(e);await s.withLock(t,"exclusive",async()=>{const i=await this.open(t,{create:!0});try{const{size:a}=await this.fstat(i);await this.write(i,r,0,r.length,a,!1),await this.fsync(i)}finally{await this.close(i)}await this.notifyChange({path:t,type:"changed",isDirectory:!1})})}async mkdir(t,e){await this.mount();const r=e?.recursive??!1,i=s.splitPath(t);let a=this.root;for(let n=0;n<i.length;n++){const o=i[n];try{a=await a.getDirectoryHandle(o,{create:r||n===i.length-1})}catch(c){throw c.name==="NotFoundError"?new s.OPFSError(`Parent directory does not exist: ${s.joinPath(i.slice(0,n+1))}`,"ENOENT",void 0,c):c.name==="TypeMismatchError"?new s.OPFSError(`Path segment is not a directory: ${o}`,"ENOTDIR",void 0,c):new s.OPFSError("Failed to create directory","MKDIR_FAILED",void 0,c)}}await this.notifyChange({path:t,type:"added",isDirectory:!0})}async stat(t){if(await this.mount(),t==="/")return{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0};const e=s.basename(t),r=await this.getDirectoryHandle(s.dirname(t),!1),i=this.options.hashAlgorithm!==null;try{const n=await(await r.getFileHandle(e,{create:!1})).getFile(),o={kind:"file",size:n.size,mtime:new Date(n.lastModified).toISOString(),ctime:new Date(n.lastModified).toISOString(),isFile:!0,isDirectory:!1};if(i&&this.options.hashAlgorithm)try{const c=await s.calculateFileHash(n,this.options.hashAlgorithm,this.options.maxFileSize);o.hash=c}catch(c){console.warn(`Failed to calculate hash for ${t}:`,c)}return o}catch(a){if(a.name!=="TypeMismatchError"&&a.name!=="NotFoundError")throw new s.OPFSError("Failed to stat (file)","STAT_FAILED",void 0,a)}try{return await r.getDirectoryHandle(e,{create:!1}),{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0}}catch(a){throw a.name==="NotFoundError"?new s.OPFSError(`No such file or directory: ${t}`,"ENOENT",void 0,a):new s.OPFSError("Failed to stat (directory)","STAT_FAILED",void 0,a)}}async readDir(t){await this.mount();const e=await this.getDirectoryHandle(t,!1),r=[];for await(const[i,a]of e.entries()){const n=a.kind==="file";r.push({name:i,kind:a.kind,isFile:n,isDirectory:!n})}return r}async exists(t){if(await this.mount(),t==="/")return!0;const e=s.basename(t);let r=null;try{r=await this.getDirectoryHandle(s.dirname(t),!1)}catch(i){if(r=null,i.name!=="NotFoundError"&&i.name!=="TypeMismatchError")throw i}if(!r||!e)return!1;try{return await r.getFileHandle(e,{create:!1}),!0}catch(i){if(i.name!=="NotFoundError"&&i.name!=="TypeMismatchError")throw i;try{return await r.getDirectoryHandle(e,{create:!1}),!0}catch(a){if(a.name!=="NotFoundError"&&a.name!=="TypeMismatchError")throw a;return!1}}}async clear(t="/"){await this.mount();try{const e=await this.readDir(t);for(const r of e){const i=`${t==="/"?"":t}/${r.name}`;await this.remove(i,{recursive:!0})}await this.notifyChange({path:t,type:"changed",isDirectory:!0})}catch(e){throw e instanceof s.OPFSError?e:new s.OPFSError(`Failed to clear directory: ${t}`,"CLEAR_FAILED",void 0,e)}}async remove(t,e){if(await this.mount(),t==="/")throw new s.OPFSError("Cannot remove root directory","EROOT");const{recursive:r=!1,force:i=!1}=e||{},a=await this.getDirectoryHandle(s.dirname(t),!1),n=await this.stat(t);await s.removeEntry(a,t,{recursive:r,force:i}),await this.notifyChange({path:t,type:"removed",isDirectory:n.isDirectory})}async realpath(t){await this.mount();try{const e=s.resolvePath(t);if(!await this.exists(e))throw new s.FileNotFoundError(e);return e}catch(e){throw e instanceof s.OPFSError?e:new s.OPFSError(`Failed to resolve path: ${t}`,"REALPATH_FAILED",void 0,e)}}async rename(t,e,r){await this.mount();try{const i=r?.overwrite??!1,a=await this.stat(t);if(await this.exists(e)&&!i)throw new s.OPFSError(`Destination already exists: ${e}`,"EEXIST",void 0);await this.copy(t,e,{recursive:!0,overwrite:i}),await this.remove(t,{recursive:!0}),await this.notifyChange({path:t,type:"removed",isDirectory:a.isDirectory}),await this.notifyChange({path:e,type:"added",isDirectory:a.isDirectory})}catch(i){throw i instanceof s.OPFSError?i:new s.OPFSError(`Failed to rename from ${t} to ${e}`,"RENAME_FAILED",void 0,i)}}async copy(t,e,r){await this.mount();try{const i=r?.recursive??!1,a=r?.overwrite??!0;if(!await this.exists(t))throw new s.OPFSError(`Source does not exist: ${t}`,"ENOENT",void 0);if(await this.exists(e)&&!a)throw new s.OPFSError(`Destination already exists: ${e}`,"EEXIST",void 0);if((await this.stat(t)).isFile){const h=await this.readFile(t);await this.writeFile(e,h)}else{if(!i)throw new s.OPFSError(`Cannot copy directory without recursive option: ${t}`,"EISDIR",void 0);await this.mkdir(e,{recursive:!0});const h=await this.readDir(t);for(const l of h){const w=`${t}/${l.name}`,d=`${e}/${l.name}`;await this.copy(w,d,{recursive:!0,overwrite:a})}}}catch(i){throw i instanceof s.OPFSError?i:new s.OPFSError(`Failed to copy from ${t} to ${e}`,"CP_FAILED",void 0,i)}}async watch(t,e){if(!this.options.broadcastChannel)throw new s.OPFSError("This instance is not configured to send events. Please specify options.broadcastChannel to enable watching.","ENOENT");const r={pattern:s.normalizeMinimatch(t,e?.recursive??!0),include:Array.isArray(e?.include)?e.include:[e?.include??"**"],exclude:Array.isArray(e?.exclude)?e.exclude:[e?.exclude??""]};this.watchers.set(t,r)}unwatch(t){this.watchers.delete(t)}async open(t,e){await this.mount();const{create:r=!1,exclusive:i=!1,truncate:a=!1}=e||{},n=s.normalizePath(s.resolvePath(t));try{return r&&i?await s.withLock(n,"exclusive",async()=>{if(await this.exists(n))throw new s.OPFSError(`File already exists: ${n}`,"EEXIST",n);return this._openFile(n,r,a)}):await this._openFile(n,r,a)}catch(o){throw o instanceof s.OPFSError?o:new s.OPFSError(`Failed to open file: ${n}`,"OPEN_FAILED",n,o)}}async _openFile(t,e,r){const i=await this.getFileHandle(t,e);try{await i.getFile()}catch(o){throw o.name==="TypeMismatchError"?new s.OPFSError(`Is a directory: ${t}`,"EISDIR",t):o}const a=await s.createSyncHandleSafe(i,t);r&&(a.truncate(0),a.flush());const n=this.nextFd++;return this.openFiles.set(n,{path:t,fileHandle:i,syncHandle:a,position:0}),n}async close(t){const e=this._getFileDescriptor(t);s.safeCloseSyncHandle(t,e.syncHandle,e.path),this.openFiles.delete(t)}async read(t,e,r,i,a){const n=this._getFileDescriptor(t);s.validateReadWriteArgs(e.length,r,i,a);try{const o=a??n.position,c=n.syncHandle.getSize(),{isEOF:h,actualLength:l}=s.calculateReadLength(o,i,c);if(h)return y.transfer({bytesRead:0,buffer:e},[e.buffer]);const w=e.subarray(r,r+l),d=n.syncHandle.read(w,{at:o});return a==null&&(n.position=o+d),y.transfer({bytesRead:d,buffer:e},[e.buffer])}catch(o){throw s.createFDError("read",t,n.path,o)}}async write(t,e,r=0,i,a,n=!0){const o=this._getFileDescriptor(t),c=i??e.length-r;s.validateReadWriteArgs(e.length,r,c,a);try{const h=a??o.position,l=e.subarray(r,r+c),w=o.syncHandle.write(l,{at:h});return(a==null||a===o.position)&&(o.position=h+w),n&&await this.notifyChange({path:o.path,type:"changed",isDirectory:!1}),w}catch(h){throw s.createFDError("write",t,o.path,h)}}async fstat(t){const e=this._getFileDescriptor(t);return this.stat(e.path)}async ftruncate(t,e=0){const r=this._getFileDescriptor(t);if(e<0||!Number.isInteger(e))throw new s.OPFSError("Invalid size","EINVAL");try{r.syncHandle.truncate(e),r.syncHandle.flush(),r.position>e&&(r.position=e),await this.notifyChange({path:r.path,type:"changed",isDirectory:!1})}catch(i){throw s.createFDError("truncate",t,r.path,i)}}async fsync(t){const e=this._getFileDescriptor(t);try{e.syncHandle.flush()}catch(r){throw s.createFDError("sync",t,e.path,r)}}dispose(){this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.watchers.clear();for(const[t,e]of this.openFiles)s.safeCloseSyncHandle(t,e.syncHandle,e.path);this.openFiles.clear(),this.nextFd=1}async createIndex(t){await this.mount();try{for(const[e,r]of t){const i=s.normalizePath(e);let a;r instanceof Blob?a=await s.convertBlobToUint8Array(r):typeof r=="string"?a=new TextEncoder().encode(r):a=r,await this.writeFile(i,a)}}catch(e){throw e instanceof s.OPFSError?e:new s.OPFSError("Failed to sync file system","SYNC_FAILED",void 0,e)}}}typeof globalThis<"u"&&globalThis.constructor.name==="DedicatedWorkerGlobalScope"&&y.expose(new f);exports.OPFSWorker=f;
2
2
  //# sourceMappingURL=raw.cjs.map