opfs-worker 1.3.2 → 2.1.0

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.
Files changed (149) hide show
  1. package/README.md +64 -458
  2. package/dist/BaseOPFS-BPw9AIQ-.cjs +4 -0
  3. package/dist/BaseOPFS-BPw9AIQ-.cjs.map +1 -0
  4. package/dist/BaseOPFS-Cylz6ijk.js +2036 -0
  5. package/dist/BaseOPFS-Cylz6ijk.js.map +1 -0
  6. package/dist/OPFSAsync-BKSAJJeh.js +124 -0
  7. package/dist/OPFSAsync-BKSAJJeh.js.map +1 -0
  8. package/dist/OPFSAsync-s2P7y3sw.cjs +2 -0
  9. package/dist/OPFSAsync-s2P7y3sw.cjs.map +1 -0
  10. package/dist/OPFSFacade-DePnNRgt.cjs +2 -0
  11. package/dist/OPFSFacade-DePnNRgt.cjs.map +1 -0
  12. package/dist/OPFSFacade-XohWlHuu.js +281 -0
  13. package/dist/OPFSFacade-XohWlHuu.js.map +1 -0
  14. package/dist/OPFSSync-C7KBepe_.cjs +2 -0
  15. package/dist/OPFSSync-C7KBepe_.cjs.map +1 -0
  16. package/dist/OPFSSync-CsSQkpk5.js +208 -0
  17. package/dist/OPFSSync-CsSQkpk5.js.map +1 -0
  18. package/dist/assets/dedicated.worker-nY3tK4zi.js.map +1 -0
  19. package/dist/{worker.d.ts → core/BaseOPFS.d.ts} +34 -300
  20. package/dist/core/BaseOPFS.d.ts.map +1 -0
  21. package/dist/core/OPFSAsync.d.ts +55 -0
  22. package/dist/core/OPFSAsync.d.ts.map +1 -0
  23. package/dist/core/OPFSSync.d.ts +54 -0
  24. package/dist/core/OPFSSync.d.ts.map +1 -0
  25. package/dist/createOPFSAsync-BwKDmHsy.cjs +2 -0
  26. package/dist/createOPFSAsync-BwKDmHsy.cjs.map +1 -0
  27. package/dist/createOPFSAsync-Y4Mg6qte.js +10 -0
  28. package/dist/createOPFSAsync-Y4Mg6qte.js.map +1 -0
  29. package/dist/createOPFSDedicated-CsnV6MLP.js +2333 -0
  30. package/dist/createOPFSDedicated-CsnV6MLP.js.map +1 -0
  31. package/dist/createOPFSDedicated-pKTRWLdz.cjs +2283 -0
  32. package/dist/createOPFSDedicated-pKTRWLdz.cjs.map +1 -0
  33. package/dist/createOPFSShared-CGdd__PH.js +23 -0
  34. package/dist/createOPFSShared-CGdd__PH.js.map +1 -0
  35. package/dist/createOPFSShared-CskROt7U.cjs +2 -0
  36. package/dist/createOPFSShared-CskROt7U.cjs.map +1 -0
  37. package/dist/dedicated.worker.js +2281 -0
  38. package/dist/dedicated.worker.js.map +1 -0
  39. package/dist/{facade.d.ts → facade/OPFSFacade.d.ts} +35 -10
  40. package/dist/facade/OPFSFacade.d.ts.map +1 -0
  41. package/dist/facade/createOPFSAsync.d.ts +16 -0
  42. package/dist/facade/createOPFSAsync.d.ts.map +1 -0
  43. package/dist/facade/createOPFSDedicated.d.ts +17 -0
  44. package/dist/facade/createOPFSDedicated.d.ts.map +1 -0
  45. package/dist/facade/createOPFSShared.d.ts +24 -0
  46. package/dist/facade/createOPFSShared.d.ts.map +1 -0
  47. package/dist/index.async.cjs +2 -0
  48. package/dist/index.async.cjs.map +1 -0
  49. package/dist/index.async.d.ts +10 -0
  50. package/dist/index.async.d.ts.map +1 -0
  51. package/dist/index.async.js +55 -0
  52. package/dist/index.async.js.map +1 -0
  53. package/dist/index.cjs +1 -2466
  54. package/dist/index.cjs.map +1 -1
  55. package/dist/index.d.ts +15 -7
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +61 -2799
  58. package/dist/index.js.map +1 -1
  59. package/dist/index.pure.cjs +2 -0
  60. package/dist/index.pure.cjs.map +1 -0
  61. package/dist/index.pure.d.ts +8 -0
  62. package/dist/index.pure.d.ts.map +1 -0
  63. package/dist/index.pure.js +53 -0
  64. package/dist/index.pure.js.map +1 -0
  65. package/dist/index.sharedworker.cjs +2 -0
  66. package/dist/index.sharedworker.cjs.map +1 -0
  67. package/dist/index.sharedworker.d.ts +11 -0
  68. package/dist/index.sharedworker.d.ts.map +1 -0
  69. package/dist/index.sharedworker.js +55 -0
  70. package/dist/index.sharedworker.js.map +1 -0
  71. package/dist/index.sync.cjs +2 -0
  72. package/dist/index.sync.cjs.map +1 -0
  73. package/dist/index.sync.d.ts +11 -0
  74. package/dist/index.sync.d.ts.map +1 -0
  75. package/dist/index.sync.js +55 -0
  76. package/dist/index.sync.js.map +1 -0
  77. package/dist/shared.worker.js +2166 -0
  78. package/dist/shared.worker.js.map +1 -0
  79. package/dist/types.d.ts +9 -4
  80. package/dist/types.d.ts.map +1 -1
  81. package/dist/utils/helpers.d.ts +11 -1
  82. package/dist/utils/helpers.d.ts.map +1 -1
  83. package/dist/worker/createDedicatedWorker.d.ts +30 -0
  84. package/dist/worker/createDedicatedWorker.d.ts.map +1 -0
  85. package/dist/worker/createSharedWorker.d.ts +37 -0
  86. package/dist/worker/createSharedWorker.d.ts.map +1 -0
  87. package/dist/worker/dedicated.worker.d.ts +2 -0
  88. package/dist/worker/dedicated.worker.d.ts.map +1 -0
  89. package/dist/worker/shared.worker.d.ts +2 -0
  90. package/dist/worker/shared.worker.d.ts.map +1 -0
  91. package/docs/README.md +30 -0
  92. package/docs/api/backend.md +36 -0
  93. package/docs/api/create.md +82 -0
  94. package/docs/api/facade.md +52 -0
  95. package/docs/choosing-a-mode.md +41 -0
  96. package/docs/file-descriptors.md +695 -0
  97. package/docs/guides/async.md +36 -0
  98. package/docs/guides/dedicated.md +76 -0
  99. package/docs/guides/hashing.md +34 -0
  100. package/docs/guides/pure.md +46 -0
  101. package/docs/guides/sharedworker.md +57 -0
  102. package/docs/guides/streaming.md +51 -0
  103. package/docs/guides/watching.md +35 -0
  104. package/docs/migration.md +41 -0
  105. package/docs/types.md +246 -0
  106. package/package.json +55 -10
  107. package/src/core/BaseOPFS.ts +951 -0
  108. package/src/core/OPFSAsync.ts +248 -0
  109. package/src/core/OPFSSync.ts +460 -0
  110. package/src/facade/OPFSFacade.ts +489 -0
  111. package/src/facade/createOPFSAsync.ts +22 -0
  112. package/src/facade/createOPFSDedicated.ts +23 -0
  113. package/src/facade/createOPFSShared.ts +30 -0
  114. package/src/index.async.ts +11 -0
  115. package/src/index.pure.ts +8 -0
  116. package/src/index.sharedworker.ts +12 -0
  117. package/src/index.sync.ts +12 -0
  118. package/src/index.ts +44 -0
  119. package/src/types.ts +103 -0
  120. package/src/utils/encoder.ts +205 -0
  121. package/src/utils/errors.ts +297 -0
  122. package/src/utils/helpers.ts +465 -0
  123. package/src/worker/createDedicatedWorker.ts +74 -0
  124. package/src/worker/createSharedWorker.ts +67 -0
  125. package/src/worker/dedicated.worker.ts +13 -0
  126. package/src/worker/shared.worker.ts +17 -0
  127. package/dist/assets/worker-1Wh1cr7P.js.map +0 -1
  128. package/dist/assets/worker-BeJaVyBV.js.map +0 -1
  129. package/dist/assets/worker-DYYLzR1Y.js.map +0 -1
  130. package/dist/facade.d.ts.map +0 -1
  131. package/dist/helpers-BuGfPAg0.js +0 -1439
  132. package/dist/helpers-BuGfPAg0.js.map +0 -1
  133. package/dist/helpers-CF7A2WQG.cjs +0 -4
  134. package/dist/helpers-CF7A2WQG.cjs.map +0 -1
  135. package/dist/helpers-CIiblZ8d.cjs +0 -4
  136. package/dist/helpers-CIiblZ8d.cjs.map +0 -1
  137. package/dist/helpers-CKOebsbw.js +0 -1423
  138. package/dist/helpers-CKOebsbw.js.map +0 -1
  139. package/dist/helpers-Ca2c767K.js +0 -1427
  140. package/dist/helpers-Ca2c767K.js.map +0 -1
  141. package/dist/helpers-Dwc92hv9.cjs +0 -4
  142. package/dist/helpers-Dwc92hv9.cjs.map +0 -1
  143. package/dist/raw.cjs +0 -2
  144. package/dist/raw.cjs.map +0 -1
  145. package/dist/raw.d.ts +0 -13
  146. package/dist/raw.d.ts.map +0 -1
  147. package/dist/raw.js +0 -1001
  148. package/dist/raw.js.map +0 -1
  149. package/dist/worker.d.ts.map +0 -1
@@ -0,0 +1,2281 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2019 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ const xt = Symbol("Comlink.proxy"), zt = Symbol("Comlink.endpoint"), Wt = Symbol("Comlink.releaseProxy"), X = Symbol("Comlink.finalizer"), j = Symbol("Comlink.thrown"), bt = (s) => typeof s == "object" && s !== null || typeof s == "function", jt = {
7
+ canHandle: (s) => bt(s) && s[xt],
8
+ serialize(s) {
9
+ const { port1: t, port2: e } = new MessageChannel();
10
+ return ot(s, t), [e, [e]];
11
+ },
12
+ deserialize(s) {
13
+ return s.start(), Gt(s);
14
+ }
15
+ }, _t = {
16
+ canHandle: (s) => bt(s) && j in s,
17
+ serialize({ value: s }) {
18
+ let t;
19
+ return s instanceof Error ? t = {
20
+ isError: !0,
21
+ value: {
22
+ message: s.message,
23
+ name: s.name,
24
+ stack: s.stack
25
+ }
26
+ } : t = { isError: !1, value: s }, [t, []];
27
+ },
28
+ deserialize(s) {
29
+ throw s.isError ? Object.assign(new Error(s.value.message), s.value) : s.value;
30
+ }
31
+ }, Ot = /* @__PURE__ */ new Map([
32
+ ["proxy", jt],
33
+ ["throw", _t]
34
+ ]);
35
+ function Bt(s, t) {
36
+ for (const e of s)
37
+ if (t === e || e === "*" || e instanceof RegExp && e.test(t))
38
+ return !0;
39
+ return !1;
40
+ }
41
+ function ot(s, t = globalThis, e = ["*"]) {
42
+ t.addEventListener("message", function n(r) {
43
+ if (!r || !r.data)
44
+ return;
45
+ if (!Bt(e, r.origin)) {
46
+ console.warn(`Invalid origin '${r.origin}' for comlink proxy`);
47
+ return;
48
+ }
49
+ const { id: i, type: o, path: a } = Object.assign({ path: [] }, r.data), c = (r.data.argumentList || []).map(N);
50
+ let h;
51
+ try {
52
+ const l = a.slice(0, -1).reduce((u, d) => u[d], s), f = a.reduce((u, d) => u[d], s);
53
+ switch (o) {
54
+ case "GET":
55
+ h = f;
56
+ break;
57
+ case "SET":
58
+ l[a.slice(-1)[0]] = N(r.data.value), h = !0;
59
+ break;
60
+ case "APPLY":
61
+ h = f.apply(l, c);
62
+ break;
63
+ case "CONSTRUCT":
64
+ {
65
+ const u = new f(...c);
66
+ h = Zt(u);
67
+ }
68
+ break;
69
+ case "ENDPOINT":
70
+ {
71
+ const { port1: u, port2: d } = new MessageChannel();
72
+ ot(s, d), h = _(u, [u]);
73
+ }
74
+ break;
75
+ case "RELEASE":
76
+ h = void 0;
77
+ break;
78
+ default:
79
+ return;
80
+ }
81
+ } catch (l) {
82
+ h = { value: l, [j]: 0 };
83
+ }
84
+ Promise.resolve(h).catch((l) => ({ value: l, [j]: 0 })).then((l) => {
85
+ const [f, u] = q(l);
86
+ t.postMessage(Object.assign(Object.assign({}, f), { id: i }), u), o === "RELEASE" && (t.removeEventListener("message", n), Dt(t), X in s && typeof s[X] == "function" && s[X]());
87
+ }).catch((l) => {
88
+ const [f, u] = q({
89
+ value: new TypeError("Unserializable return value"),
90
+ [j]: 0
91
+ });
92
+ t.postMessage(Object.assign(Object.assign({}, f), { id: i }), u);
93
+ });
94
+ }), t.start && t.start();
95
+ }
96
+ function Ut(s) {
97
+ return s.constructor.name === "MessagePort";
98
+ }
99
+ function Dt(s) {
100
+ Ut(s) && s.close();
101
+ }
102
+ function Gt(s, t) {
103
+ const e = /* @__PURE__ */ new Map();
104
+ return s.addEventListener("message", function(r) {
105
+ const { data: i } = r;
106
+ if (!i || !i.id)
107
+ return;
108
+ const o = e.get(i.id);
109
+ if (o)
110
+ try {
111
+ o(i);
112
+ } finally {
113
+ e.delete(i.id);
114
+ }
115
+ }), et(s, e, [], t);
116
+ }
117
+ function L(s) {
118
+ if (s)
119
+ throw new Error("Proxy has been released and is not useable");
120
+ }
121
+ function At(s) {
122
+ return F(s, /* @__PURE__ */ new Map(), {
123
+ type: "RELEASE"
124
+ }).then(() => {
125
+ Dt(s);
126
+ });
127
+ }
128
+ const U = /* @__PURE__ */ new WeakMap(), G = "FinalizationRegistry" in globalThis && new FinalizationRegistry((s) => {
129
+ const t = (U.get(s) || 0) - 1;
130
+ U.set(s, t), t === 0 && At(s);
131
+ });
132
+ function qt(s, t) {
133
+ const e = (U.get(t) || 0) + 1;
134
+ U.set(t, e), G && G.register(s, t, s);
135
+ }
136
+ function Vt(s) {
137
+ G && G.unregister(s);
138
+ }
139
+ function et(s, t, e = [], n = function() {
140
+ }) {
141
+ let r = !1;
142
+ const i = new Proxy(n, {
143
+ get(o, a) {
144
+ if (L(r), a === Wt)
145
+ return () => {
146
+ Vt(i), At(s), t.clear(), r = !0;
147
+ };
148
+ if (a === "then") {
149
+ if (e.length === 0)
150
+ return { then: () => i };
151
+ const c = F(s, t, {
152
+ type: "GET",
153
+ path: e.map((h) => h.toString())
154
+ }).then(N);
155
+ return c.then.bind(c);
156
+ }
157
+ return et(s, t, [...e, a]);
158
+ },
159
+ set(o, a, c) {
160
+ L(r);
161
+ const [h, l] = q(c);
162
+ return F(s, t, {
163
+ type: "SET",
164
+ path: [...e, a].map((f) => f.toString()),
165
+ value: h
166
+ }, l).then(N);
167
+ },
168
+ apply(o, a, c) {
169
+ L(r);
170
+ const h = e[e.length - 1];
171
+ if (h === zt)
172
+ return F(s, t, {
173
+ type: "ENDPOINT"
174
+ }).then(N);
175
+ if (h === "bind")
176
+ return et(s, t, e.slice(0, -1));
177
+ const [l, f] = ht(c);
178
+ return F(s, t, {
179
+ type: "APPLY",
180
+ path: e.map((u) => u.toString()),
181
+ argumentList: l
182
+ }, f).then(N);
183
+ },
184
+ construct(o, a) {
185
+ L(r);
186
+ const [c, h] = ht(a);
187
+ return F(s, t, {
188
+ type: "CONSTRUCT",
189
+ path: e.map((l) => l.toString()),
190
+ argumentList: c
191
+ }, h).then(N);
192
+ }
193
+ });
194
+ return qt(i, s), i;
195
+ }
196
+ function Yt(s) {
197
+ return Array.prototype.concat.apply([], s);
198
+ }
199
+ function ht(s) {
200
+ const t = s.map(q);
201
+ return [t.map((e) => e[0]), Yt(t.map((e) => e[1]))];
202
+ }
203
+ const vt = /* @__PURE__ */ new WeakMap();
204
+ function _(s, t) {
205
+ return vt.set(s, t), s;
206
+ }
207
+ function Zt(s) {
208
+ return Object.assign(s, { [xt]: !0 });
209
+ }
210
+ function q(s) {
211
+ for (const [t, e] of Ot)
212
+ if (e.canHandle(s)) {
213
+ const [n, r] = e.serialize(s);
214
+ return [
215
+ {
216
+ type: "HANDLER",
217
+ name: t,
218
+ value: n
219
+ },
220
+ r
221
+ ];
222
+ }
223
+ return [
224
+ {
225
+ type: "RAW",
226
+ value: s
227
+ },
228
+ vt.get(s) || []
229
+ ];
230
+ }
231
+ function N(s) {
232
+ switch (s.type) {
233
+ case "HANDLER":
234
+ return Ot.get(s.name).deserialize(s.value);
235
+ case "RAW":
236
+ return s.value;
237
+ }
238
+ }
239
+ function F(s, t, e, n) {
240
+ return new Promise((r) => {
241
+ const i = Xt();
242
+ t.set(i, r), s.start && s.start(), s.postMessage(Object.assign({ id: i }, e), n);
243
+ });
244
+ }
245
+ function Xt() {
246
+ return new Array(4).fill(0).map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)).join("-");
247
+ }
248
+ var b = /* @__PURE__ */ ((s) => (s.Added = "added", s.Changed = "changed", s.Removed = "removed", s))(b || {});
249
+ const Jt = {
250
+ ENOENT: -2,
251
+ // No such file or directory
252
+ EISDIR: -21,
253
+ // Is a directory
254
+ ENOTDIR: -20,
255
+ // Not a directory
256
+ EACCES: -13,
257
+ // Permission denied
258
+ EEXIST: -17,
259
+ // File exists
260
+ ENOTEMPTY: -39,
261
+ // Directory not empty
262
+ EINVAL: -22,
263
+ // Invalid argument
264
+ EIO: -5,
265
+ // I/O error
266
+ ENOSPC: -28,
267
+ // No space left on device
268
+ EBUSY: -16,
269
+ // Device or resource busy
270
+ EINTR: -4,
271
+ // Interrupted system call
272
+ ENOTSUP: -95,
273
+ // Operation not supported
274
+ ERANGE: -34,
275
+ // Result too large
276
+ EBADF: -9,
277
+ // Bad file descriptor
278
+ EROOT: -1
279
+ // Custom: Cannot remove root directory
280
+ };
281
+ class w extends Error {
282
+ errno;
283
+ syscall;
284
+ path;
285
+ constructor(t, e, n, r, i) {
286
+ super(t, { cause: i }), this.name = e, this.errno = Jt[e] || -1, this.path = n, this.syscall = r;
287
+ }
288
+ }
289
+ class Qt extends w {
290
+ constructor(t) {
291
+ super("OPFS is not supported in this browser", "ENOTSUP", void 0, void 0, t);
292
+ }
293
+ }
294
+ class Kt extends w {
295
+ constructor(t, e, n) {
296
+ super(t, "INVALID_PATH", e, "access", n);
297
+ }
298
+ }
299
+ class B extends w {
300
+ constructor(t, e, n) {
301
+ const r = {
302
+ file: `File not found: ${e}`,
303
+ directory: `Directory not found: ${e}`,
304
+ source: `Source does not exist: ${e}`
305
+ };
306
+ super(r[t], "ENOENT", e, "access", n);
307
+ }
308
+ }
309
+ class te extends w {
310
+ constructor(t, e, n) {
311
+ super(`Permission denied for ${e} on: ${t}`, "EACCES", t, e, n);
312
+ }
313
+ }
314
+ class ee extends w {
315
+ constructor(t, e, n) {
316
+ super(t, "ENOSPC", e, "write", n);
317
+ }
318
+ }
319
+ class se extends w {
320
+ constructor(t, e) {
321
+ super(`File is busy: ${t}`, "EBUSY", t, "open", e);
322
+ }
323
+ }
324
+ class st extends w {
325
+ constructor(t, e, n) {
326
+ const r = t === "directory" ? `Is a directory: ${e}` : `Not a directory: ${e}`, i = t === "directory" ? "EISDIR" : "ENOTDIR";
327
+ super(r, i, e, "access", n);
328
+ }
329
+ }
330
+ class C extends w {
331
+ constructor(t, e, n, r) {
332
+ const i = {
333
+ argument: "EINVAL",
334
+ format: "INVALID_FORMAT",
335
+ descriptor: "EBADF",
336
+ overflow: "ERANGE"
337
+ };
338
+ super(e, i[t], n, "validate", r);
339
+ }
340
+ }
341
+ class ne extends w {
342
+ constructor(t, e) {
343
+ super(`Operation aborted: ${t}`, "EINTR", t, "interrupt", e);
344
+ }
345
+ }
346
+ class ut extends w {
347
+ constructor(t, e, n) {
348
+ super(t, "EIO", e, "io", n);
349
+ }
350
+ }
351
+ class Ct extends w {
352
+ constructor(t, e) {
353
+ super(`Operation not supported: ${t}`, "ENOTSUP", t, "operation", e);
354
+ }
355
+ }
356
+ class nt extends w {
357
+ constructor(t, e, n) {
358
+ const r = {
359
+ RM_FAILED: `Failed to remove entry: ${e}`,
360
+ ENOTEMPTY: `Directory not empty: ${e}. Use recursive option to force removal.`,
361
+ EROOT: "Cannot remove root directory"
362
+ };
363
+ super(r[t] || `Directory operation failed: ${e}`, t, e, "unlink", n);
364
+ }
365
+ }
366
+ class re extends w {
367
+ constructor(t, e) {
368
+ super("Failed to initialize OPFS", "INIT_FAILED", t, "init", e);
369
+ }
370
+ }
371
+ class J extends w {
372
+ constructor(t, e, n) {
373
+ super(`Failed to ${t}: ${e}`, `${t.toUpperCase()}_FAILED`, e, t, n);
374
+ }
375
+ }
376
+ class rt extends w {
377
+ constructor(t, e) {
378
+ super(`Destination already exists: ${t}`, "EEXIST", t, "open", e);
379
+ }
380
+ }
381
+ function z(s, t, e, n) {
382
+ const r = `${s.toUpperCase()}_FAILED`;
383
+ return new w(`Failed to ${s} file descriptor: ${t}`, r, e, s, n);
384
+ }
385
+ function A(s, t) {
386
+ const e = t?.path, n = t?.isDirectory, r = t?.existenceType ?? "file", i = t?.operation;
387
+ switch (s.name) {
388
+ case "InvalidStateError":
389
+ return new se(e || "unknown", s);
390
+ case "QuotaExceededError":
391
+ return new ee(`No space left on device: ${e || "unknown"}`, e, s);
392
+ case "NotFoundError":
393
+ return new B(r, e, s);
394
+ case "TypeMismatchError":
395
+ return n !== void 0 ? n ? new st("directory", e || "unknown", s) : new st("file", e || "unknown", s) : new C("argument", `Type mismatch: ${e || "unknown"}`, e, s);
396
+ case "NotAllowedError":
397
+ case "SecurityError":
398
+ return new te(e, "unknown", s);
399
+ case "InvalidModificationError":
400
+ return i === "remove" ? new nt("ENOTEMPTY", e, s) : new C("argument", `Invalid modification: ${e || "unknown"}`, e, s);
401
+ case "AbortError":
402
+ return new ne(e || "unknown", s);
403
+ case "OperationError":
404
+ return new ut(`Operation failed: ${e || "unknown"}`, e, s);
405
+ case "TypeError":
406
+ return new Ct(e || "unknown", s);
407
+ default:
408
+ return i === "remove" ? new nt("RM_FAILED", e, s) : new ut(`I/O error: ${e || "unknown"}`, e, s);
409
+ }
410
+ }
411
+ const Nt = (s, t, e) => {
412
+ const n = s instanceof RegExp ? ft(s, e) : s, r = t instanceof RegExp ? ft(t, e) : t, i = n !== null && r != null && ie(n, r, e);
413
+ return i && {
414
+ start: i[0],
415
+ end: i[1],
416
+ pre: e.slice(0, i[0]),
417
+ body: e.slice(i[0] + n.length, i[1]),
418
+ post: e.slice(i[1] + r.length)
419
+ };
420
+ }, ft = (s, t) => {
421
+ const e = t.match(s);
422
+ return e ? e[0] : null;
423
+ }, ie = (s, t, e) => {
424
+ let n, r, i, o, a, c = e.indexOf(s), h = e.indexOf(t, c + 1), l = c;
425
+ if (c >= 0 && h > 0) {
426
+ if (s === t)
427
+ return [c, h];
428
+ for (n = [], i = e.length; l >= 0 && !a; ) {
429
+ if (l === c)
430
+ n.push(l), c = e.indexOf(s, l + 1);
431
+ else if (n.length === 1) {
432
+ const f = n.pop();
433
+ f !== void 0 && (a = [f, h]);
434
+ } else
435
+ r = n.pop(), r !== void 0 && r < i && (i = r, o = h), h = e.indexOf(t, l + 1);
436
+ l = c < h && c >= 0 ? c : h;
437
+ }
438
+ n.length && o !== void 0 && (a = [i, o]);
439
+ }
440
+ return a;
441
+ }, Ft = "\0SLASH" + Math.random() + "\0", $t = "\0OPEN" + Math.random() + "\0", at = "\0CLOSE" + Math.random() + "\0", Mt = "\0COMMA" + Math.random() + "\0", Tt = "\0PERIOD" + Math.random() + "\0", oe = new RegExp(Ft, "g"), ae = new RegExp($t, "g"), ce = new RegExp(at, "g"), le = new RegExp(Mt, "g"), he = new RegExp(Tt, "g"), ue = /\\\\/g, fe = /\\{/g, de = /\\}/g, pe = /\\,/g, ge = /\\./g;
442
+ function Q(s) {
443
+ return isNaN(s) ? s.charCodeAt(0) : parseInt(s, 10);
444
+ }
445
+ function we(s) {
446
+ return s.replace(ue, Ft).replace(fe, $t).replace(de, at).replace(pe, Mt).replace(ge, Tt);
447
+ }
448
+ function ye(s) {
449
+ return s.replace(oe, "\\").replace(ae, "{").replace(ce, "}").replace(le, ",").replace(he, ".");
450
+ }
451
+ function Pt(s) {
452
+ if (!s)
453
+ return [""];
454
+ const t = [], e = Nt("{", "}", s);
455
+ if (!e)
456
+ return s.split(",");
457
+ const { pre: n, body: r, post: i } = e, o = n.split(",");
458
+ o[o.length - 1] += "{" + r + "}";
459
+ const a = Pt(i);
460
+ return i.length && (o[o.length - 1] += a.shift(), o.push.apply(o, a)), t.push.apply(t, o), t;
461
+ }
462
+ function me(s) {
463
+ return s ? (s.slice(0, 2) === "{}" && (s = "\\{\\}" + s.slice(2)), k(we(s), !0).map(ye)) : [];
464
+ }
465
+ function Ee(s) {
466
+ return "{" + s + "}";
467
+ }
468
+ function Se(s) {
469
+ return /^-?0\d/.test(s);
470
+ }
471
+ function xe(s, t) {
472
+ return s <= t;
473
+ }
474
+ function be(s, t) {
475
+ return s >= t;
476
+ }
477
+ function k(s, t) {
478
+ const e = [], n = Nt("{", "}", s);
479
+ if (!n)
480
+ return [s];
481
+ const r = n.pre, i = n.post.length ? k(n.post, !1) : [""];
482
+ if (/\$$/.test(n.pre))
483
+ for (let o = 0; o < i.length; o++) {
484
+ const a = r + "{" + n.body + "}" + i[o];
485
+ e.push(a);
486
+ }
487
+ else {
488
+ const o = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(n.body), a = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(n.body), c = o || a, h = n.body.indexOf(",") >= 0;
489
+ if (!c && !h)
490
+ return n.post.match(/,(?!,).*\}/) ? (s = n.pre + "{" + n.body + at + n.post, k(s)) : [s];
491
+ let l;
492
+ if (c)
493
+ l = n.body.split(/\.\./);
494
+ else if (l = Pt(n.body), l.length === 1 && l[0] !== void 0 && (l = k(l[0], !1).map(Ee), l.length === 1))
495
+ return i.map((u) => n.pre + l[0] + u);
496
+ let f;
497
+ if (c && l[0] !== void 0 && l[1] !== void 0) {
498
+ const u = Q(l[0]), d = Q(l[1]), g = Math.max(l[0].length, l[1].length);
499
+ let p = l.length === 3 && l[2] !== void 0 ? Math.abs(Q(l[2])) : 1, S = xe;
500
+ d < u && (p *= -1, S = be);
501
+ const T = l.some(Se);
502
+ f = [];
503
+ for (let x = u; S(x, d); x += p) {
504
+ let y;
505
+ if (a)
506
+ y = String.fromCharCode(x), y === "\\" && (y = "");
507
+ else if (y = String(x), T) {
508
+ const P = g - y.length;
509
+ if (P > 0) {
510
+ const H = new Array(P + 1).join("0");
511
+ x < 0 ? y = "-" + H + y.slice(1) : y = H + y;
512
+ }
513
+ }
514
+ f.push(y);
515
+ }
516
+ } else {
517
+ f = [];
518
+ for (let u = 0; u < l.length; u++)
519
+ f.push.apply(f, k(l[u], !1));
520
+ }
521
+ for (let u = 0; u < f.length; u++)
522
+ for (let d = 0; d < i.length; d++) {
523
+ const g = r + f[u] + i[d];
524
+ (!t || c || g) && e.push(g);
525
+ }
526
+ }
527
+ return e;
528
+ }
529
+ const Oe = 1024 * 64, V = (s) => {
530
+ if (typeof s != "string")
531
+ throw new TypeError("invalid pattern");
532
+ if (s.length > Oe)
533
+ throw new TypeError("pattern is too long");
534
+ }, De = {
535
+ "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", !0],
536
+ "[:alpha:]": ["\\p{L}\\p{Nl}", !0],
537
+ "[:ascii:]": ["\\x00-\\x7f", !1],
538
+ "[:blank:]": ["\\p{Zs}\\t", !0],
539
+ "[:cntrl:]": ["\\p{Cc}", !0],
540
+ "[:digit:]": ["\\p{Nd}", !0],
541
+ "[:graph:]": ["\\p{Z}\\p{C}", !0, !0],
542
+ "[:lower:]": ["\\p{Ll}", !0],
543
+ "[:print:]": ["\\p{C}", !0],
544
+ "[:punct:]": ["\\p{P}", !0],
545
+ "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", !0],
546
+ "[:upper:]": ["\\p{Lu}", !0],
547
+ "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", !0],
548
+ "[:xdigit:]": ["A-Fa-f0-9", !1]
549
+ }, R = (s) => s.replace(/[[\]\\-]/g, "\\$&"), Ae = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), dt = (s) => s.join(""), ve = (s, t) => {
550
+ const e = t;
551
+ if (s.charAt(e) !== "[")
552
+ throw new Error("not in a brace expression");
553
+ const n = [], r = [];
554
+ let i = e + 1, o = !1, a = !1, c = !1, h = !1, l = e, f = "";
555
+ t: for (; i < s.length; ) {
556
+ const p = s.charAt(i);
557
+ if ((p === "!" || p === "^") && i === e + 1) {
558
+ h = !0, i++;
559
+ continue;
560
+ }
561
+ if (p === "]" && o && !c) {
562
+ l = i + 1;
563
+ break;
564
+ }
565
+ if (o = !0, p === "\\" && !c) {
566
+ c = !0, i++;
567
+ continue;
568
+ }
569
+ if (p === "[" && !c) {
570
+ for (const [S, [v, T, x]] of Object.entries(De))
571
+ if (s.startsWith(S, i)) {
572
+ if (f)
573
+ return ["$.", !1, s.length - e, !0];
574
+ i += S.length, x ? r.push(v) : n.push(v), a = a || T;
575
+ continue t;
576
+ }
577
+ }
578
+ if (c = !1, f) {
579
+ p > f ? n.push(R(f) + "-" + R(p)) : p === f && n.push(R(p)), f = "", i++;
580
+ continue;
581
+ }
582
+ if (s.startsWith("-]", i + 1)) {
583
+ n.push(R(p + "-")), i += 2;
584
+ continue;
585
+ }
586
+ if (s.startsWith("-", i + 1)) {
587
+ f = p, i += 2;
588
+ continue;
589
+ }
590
+ n.push(R(p)), i++;
591
+ }
592
+ if (l < i)
593
+ return ["", !1, 0, !1];
594
+ if (!n.length && !r.length)
595
+ return ["$.", !1, s.length - e, !0];
596
+ if (r.length === 0 && n.length === 1 && /^\\?.$/.test(n[0]) && !h) {
597
+ const p = n[0].length === 2 ? n[0].slice(-1) : n[0];
598
+ return [Ae(p), !1, l - e, !1];
599
+ }
600
+ const u = "[" + (h ? "^" : "") + dt(n) + "]", d = "[" + (h ? "" : "^") + dt(r) + "]";
601
+ return [n.length && r.length ? "(" + u + "|" + d + ")" : n.length ? u : d, a, l - e, !0];
602
+ }, I = (s, { windowsPathsNoEscape: t = !1 } = {}) => t ? s.replace(/\[([^\/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1"), Ce = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]), pt = (s) => Ce.has(s), Ne = "(?!(?:^|/)\\.\\.?(?:$|/))", W = "(?!\\.)", Fe = /* @__PURE__ */ new Set(["[", "."]), $e = /* @__PURE__ */ new Set(["..", "."]), Me = new Set("().*{}+?[]^$\\!"), Te = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), ct = "[^/]", gt = ct + "*?", wt = ct + "+?";
603
+ class E {
604
+ type;
605
+ #s;
606
+ #n;
607
+ #i = !1;
608
+ #t = [];
609
+ #e;
610
+ #o;
611
+ #c;
612
+ #a = !1;
613
+ #r;
614
+ #l;
615
+ // set to true if it's an extglob with no children
616
+ // (which really means one child of '')
617
+ #u = !1;
618
+ constructor(t, e, n = {}) {
619
+ this.type = t, t && (this.#n = !0), this.#e = e, this.#s = this.#e ? this.#e.#s : this, this.#r = this.#s === this ? n : this.#s.#r, this.#c = this.#s === this ? [] : this.#s.#c, t === "!" && !this.#s.#a && this.#c.push(this), this.#o = this.#e ? this.#e.#t.length : 0;
620
+ }
621
+ get hasMagic() {
622
+ if (this.#n !== void 0)
623
+ return this.#n;
624
+ for (const t of this.#t)
625
+ if (typeof t != "string" && (t.type || t.hasMagic))
626
+ return this.#n = !0;
627
+ return this.#n;
628
+ }
629
+ // reconstructs the pattern
630
+ toString() {
631
+ return this.#l !== void 0 ? this.#l : this.type ? this.#l = this.type + "(" + this.#t.map((t) => String(t)).join("|") + ")" : this.#l = this.#t.map((t) => String(t)).join("");
632
+ }
633
+ #d() {
634
+ if (this !== this.#s)
635
+ throw new Error("should only call on root");
636
+ if (this.#a)
637
+ return this;
638
+ this.toString(), this.#a = !0;
639
+ let t;
640
+ for (; t = this.#c.pop(); ) {
641
+ if (t.type !== "!")
642
+ continue;
643
+ let e = t, n = e.#e;
644
+ for (; n; ) {
645
+ for (let r = e.#o + 1; !n.type && r < n.#t.length; r++)
646
+ for (const i of t.#t) {
647
+ if (typeof i == "string")
648
+ throw new Error("string part in extglob AST??");
649
+ i.copyIn(n.#t[r]);
650
+ }
651
+ e = n, n = e.#e;
652
+ }
653
+ }
654
+ return this;
655
+ }
656
+ push(...t) {
657
+ for (const e of t)
658
+ if (e !== "") {
659
+ if (typeof e != "string" && !(e instanceof E && e.#e === this))
660
+ throw new Error("invalid part: " + e);
661
+ this.#t.push(e);
662
+ }
663
+ }
664
+ toJSON() {
665
+ const t = this.type === null ? this.#t.slice().map((e) => typeof e == "string" ? e : e.toJSON()) : [this.type, ...this.#t.map((e) => e.toJSON())];
666
+ return this.isStart() && !this.type && t.unshift([]), this.isEnd() && (this === this.#s || this.#s.#a && this.#e?.type === "!") && t.push({}), t;
667
+ }
668
+ isStart() {
669
+ if (this.#s === this)
670
+ return !0;
671
+ if (!this.#e?.isStart())
672
+ return !1;
673
+ if (this.#o === 0)
674
+ return !0;
675
+ const t = this.#e;
676
+ for (let e = 0; e < this.#o; e++) {
677
+ const n = t.#t[e];
678
+ if (!(n instanceof E && n.type === "!"))
679
+ return !1;
680
+ }
681
+ return !0;
682
+ }
683
+ isEnd() {
684
+ if (this.#s === this || this.#e?.type === "!")
685
+ return !0;
686
+ if (!this.#e?.isEnd())
687
+ return !1;
688
+ if (!this.type)
689
+ return this.#e?.isEnd();
690
+ const t = this.#e ? this.#e.#t.length : 0;
691
+ return this.#o === t - 1;
692
+ }
693
+ copyIn(t) {
694
+ typeof t == "string" ? this.push(t) : this.push(t.clone(this));
695
+ }
696
+ clone(t) {
697
+ const e = new E(this.type, t);
698
+ for (const n of this.#t)
699
+ e.copyIn(n);
700
+ return e;
701
+ }
702
+ static #h(t, e, n, r) {
703
+ let i = !1, o = !1, a = -1, c = !1;
704
+ if (e.type === null) {
705
+ let d = n, g = "";
706
+ for (; d < t.length; ) {
707
+ const p = t.charAt(d++);
708
+ if (i || p === "\\") {
709
+ i = !i, g += p;
710
+ continue;
711
+ }
712
+ if (o) {
713
+ d === a + 1 ? (p === "^" || p === "!") && (c = !0) : p === "]" && !(d === a + 2 && c) && (o = !1), g += p;
714
+ continue;
715
+ } else if (p === "[") {
716
+ o = !0, a = d, c = !1, g += p;
717
+ continue;
718
+ }
719
+ if (!r.noext && pt(p) && t.charAt(d) === "(") {
720
+ e.push(g), g = "";
721
+ const S = new E(p, e);
722
+ d = E.#h(t, S, d, r), e.push(S);
723
+ continue;
724
+ }
725
+ g += p;
726
+ }
727
+ return e.push(g), d;
728
+ }
729
+ let h = n + 1, l = new E(null, e);
730
+ const f = [];
731
+ let u = "";
732
+ for (; h < t.length; ) {
733
+ const d = t.charAt(h++);
734
+ if (i || d === "\\") {
735
+ i = !i, u += d;
736
+ continue;
737
+ }
738
+ if (o) {
739
+ h === a + 1 ? (d === "^" || d === "!") && (c = !0) : d === "]" && !(h === a + 2 && c) && (o = !1), u += d;
740
+ continue;
741
+ } else if (d === "[") {
742
+ o = !0, a = h, c = !1, u += d;
743
+ continue;
744
+ }
745
+ if (pt(d) && t.charAt(h) === "(") {
746
+ l.push(u), u = "";
747
+ const g = new E(d, l);
748
+ l.push(g), h = E.#h(t, g, h, r);
749
+ continue;
750
+ }
751
+ if (d === "|") {
752
+ l.push(u), u = "", f.push(l), l = new E(null, e);
753
+ continue;
754
+ }
755
+ if (d === ")")
756
+ return u === "" && e.#t.length === 0 && (e.#u = !0), l.push(u), u = "", e.push(...f, l), h;
757
+ u += d;
758
+ }
759
+ return e.type = null, e.#n = void 0, e.#t = [t.substring(n - 1)], h;
760
+ }
761
+ static fromGlob(t, e = {}) {
762
+ const n = new E(null, void 0, e);
763
+ return E.#h(t, n, 0, e), n;
764
+ }
765
+ // returns the regular expression if there's magic, or the unescaped
766
+ // string if not.
767
+ toMMPattern() {
768
+ if (this !== this.#s)
769
+ return this.#s.toMMPattern();
770
+ const t = this.toString(), [e, n, r, i] = this.toRegExpSource();
771
+ if (!(r || this.#n || this.#r.nocase && !this.#r.nocaseMagicOnly && t.toUpperCase() !== t.toLowerCase()))
772
+ return n;
773
+ const a = (this.#r.nocase ? "i" : "") + (i ? "u" : "");
774
+ return Object.assign(new RegExp(`^${e}$`, a), {
775
+ _src: e,
776
+ _glob: t
777
+ });
778
+ }
779
+ get options() {
780
+ return this.#r;
781
+ }
782
+ // returns the string match, the regexp source, whether there's magic
783
+ // in the regexp (so a regular expression is required) and whether or
784
+ // not the uflag is needed for the regular expression (for posix classes)
785
+ // TODO: instead of injecting the start/end at this point, just return
786
+ // the BODY of the regexp, along with the start/end portions suitable
787
+ // for binding the start/end in either a joined full-path makeRe context
788
+ // (where we bind to (^|/), or a standalone matchPart context (where
789
+ // we bind to ^, and not /). Otherwise slashes get duped!
790
+ //
791
+ // In part-matching mode, the start is:
792
+ // - if not isStart: nothing
793
+ // - if traversal possible, but not allowed: ^(?!\.\.?$)
794
+ // - if dots allowed or not possible: ^
795
+ // - if dots possible and not allowed: ^(?!\.)
796
+ // end is:
797
+ // - if not isEnd(): nothing
798
+ // - else: $
799
+ //
800
+ // In full-path matching mode, we put the slash at the START of the
801
+ // pattern, so start is:
802
+ // - if first pattern: same as part-matching mode
803
+ // - if not isStart(): nothing
804
+ // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
805
+ // - if dots allowed or not possible: /
806
+ // - if dots possible and not allowed: /(?!\.)
807
+ // end is:
808
+ // - if last pattern, same as part-matching mode
809
+ // - else nothing
810
+ //
811
+ // Always put the (?:$|/) on negated tails, though, because that has to be
812
+ // there to bind the end of the negated pattern portion, and it's easier to
813
+ // just stick it in now rather than try to inject it later in the middle of
814
+ // the pattern.
815
+ //
816
+ // We can just always return the same end, and leave it up to the caller
817
+ // to know whether it's going to be used joined or in parts.
818
+ // And, if the start is adjusted slightly, can do the same there:
819
+ // - if not isStart: nothing
820
+ // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
821
+ // - if dots allowed or not possible: (?:/|^)
822
+ // - if dots possible and not allowed: (?:/|^)(?!\.)
823
+ //
824
+ // But it's better to have a simpler binding without a conditional, for
825
+ // performance, so probably better to return both start options.
826
+ //
827
+ // Then the caller just ignores the end if it's not the first pattern,
828
+ // and the start always gets applied.
829
+ //
830
+ // But that's always going to be $ if it's the ending pattern, or nothing,
831
+ // so the caller can just attach $ at the end of the pattern when building.
832
+ //
833
+ // So the todo is:
834
+ // - better detect what kind of start is needed
835
+ // - return both flavors of starting pattern
836
+ // - attach $ at the end of the pattern when creating the actual RegExp
837
+ //
838
+ // Ah, but wait, no, that all only applies to the root when the first pattern
839
+ // is not an extglob. If the first pattern IS an extglob, then we need all
840
+ // that dot prevention biz to live in the extglob portions, because eg
841
+ // +(*|.x*) can match .xy but not .yx.
842
+ //
843
+ // So, return the two flavors if it's #root and the first child is not an
844
+ // AST, otherwise leave it to the child AST to handle it, and there,
845
+ // use the (?:^|/) style of start binding.
846
+ //
847
+ // Even simplified further:
848
+ // - Since the start for a join is eg /(?!\.) and the start for a part
849
+ // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
850
+ // or start or whatever) and prepend ^ or / at the Regexp construction.
851
+ toRegExpSource(t) {
852
+ const e = t ?? !!this.#r.dot;
853
+ if (this.#s === this && this.#d(), !this.type) {
854
+ const c = this.isStart() && this.isEnd(), h = this.#t.map((d) => {
855
+ const [g, p, S, v] = typeof d == "string" ? E.#p(d, this.#n, c) : d.toRegExpSource(t);
856
+ return this.#n = this.#n || S, this.#i = this.#i || v, g;
857
+ }).join("");
858
+ let l = "";
859
+ if (this.isStart() && typeof this.#t[0] == "string" && !(this.#t.length === 1 && $e.has(this.#t[0]))) {
860
+ const g = Fe, p = (
861
+ // dots are allowed, and the pattern starts with [ or .
862
+ e && g.has(h.charAt(0)) || // the pattern starts with \., and then [ or .
863
+ h.startsWith("\\.") && g.has(h.charAt(2)) || // the pattern starts with \.\., and then [ or .
864
+ h.startsWith("\\.\\.") && g.has(h.charAt(4))
865
+ ), S = !e && !t && g.has(h.charAt(0));
866
+ l = p ? Ne : S ? W : "";
867
+ }
868
+ let f = "";
869
+ return this.isEnd() && this.#s.#a && this.#e?.type === "!" && (f = "(?:$|\\/)"), [
870
+ l + h + f,
871
+ I(h),
872
+ this.#n = !!this.#n,
873
+ this.#i
874
+ ];
875
+ }
876
+ const n = this.type === "*" || this.type === "+", r = this.type === "!" ? "(?:(?!(?:" : "(?:";
877
+ let i = this.#f(e);
878
+ if (this.isStart() && this.isEnd() && !i && this.type !== "!") {
879
+ const c = this.toString();
880
+ return this.#t = [c], this.type = null, this.#n = void 0, [c, I(this.toString()), !1, !1];
881
+ }
882
+ let o = !n || t || e || !W ? "" : this.#f(!0);
883
+ o === i && (o = ""), o && (i = `(?:${i})(?:${o})*?`);
884
+ let a = "";
885
+ if (this.type === "!" && this.#u)
886
+ a = (this.isStart() && !e ? W : "") + wt;
887
+ else {
888
+ const c = this.type === "!" ? (
889
+ // !() must match something,but !(x) can match ''
890
+ "))" + (this.isStart() && !e && !t ? W : "") + gt + ")"
891
+ ) : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && o ? ")" : this.type === "*" && o ? ")?" : `)${this.type}`;
892
+ a = r + i + c;
893
+ }
894
+ return [
895
+ a,
896
+ I(i),
897
+ this.#n = !!this.#n,
898
+ this.#i
899
+ ];
900
+ }
901
+ #f(t) {
902
+ return this.#t.map((e) => {
903
+ if (typeof e == "string")
904
+ throw new Error("string type in extglob ast??");
905
+ const [n, r, i, o] = e.toRegExpSource(t);
906
+ return this.#i = this.#i || o, n;
907
+ }).filter((e) => !(this.isStart() && this.isEnd()) || !!e).join("|");
908
+ }
909
+ static #p(t, e, n = !1) {
910
+ let r = !1, i = "", o = !1;
911
+ for (let a = 0; a < t.length; a++) {
912
+ const c = t.charAt(a);
913
+ if (r) {
914
+ r = !1, i += (Me.has(c) ? "\\" : "") + c;
915
+ continue;
916
+ }
917
+ if (c === "\\") {
918
+ a === t.length - 1 ? i += "\\\\" : r = !0;
919
+ continue;
920
+ }
921
+ if (c === "[") {
922
+ const [h, l, f, u] = ve(t, a);
923
+ if (f) {
924
+ i += h, o = o || l, a += f - 1, e = e || u;
925
+ continue;
926
+ }
927
+ }
928
+ if (c === "*") {
929
+ n && t === "*" ? i += wt : i += gt, e = !0;
930
+ continue;
931
+ }
932
+ if (c === "?") {
933
+ i += ct, e = !0;
934
+ continue;
935
+ }
936
+ i += Te(c);
937
+ }
938
+ return [i, I(t), !!e, o];
939
+ }
940
+ }
941
+ const Pe = (s, { windowsPathsNoEscape: t = !1 } = {}) => t ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&"), m = (s, t, e = {}) => (V(t), !e.nocomment && t.charAt(0) === "#" ? !1 : new Z(t, e).match(s)), Re = /^\*+([^+@!?\*\[\(]*)$/, ke = (s) => (t) => !t.startsWith(".") && t.endsWith(s), Ie = (s) => (t) => t.endsWith(s), He = (s) => (s = s.toLowerCase(), (t) => !t.startsWith(".") && t.toLowerCase().endsWith(s)), Le = (s) => (s = s.toLowerCase(), (t) => t.toLowerCase().endsWith(s)), ze = /^\*+\.\*+$/, We = (s) => !s.startsWith(".") && s.includes("."), je = (s) => s !== "." && s !== ".." && s.includes("."), _e = /^\.\*+$/, Be = (s) => s !== "." && s !== ".." && s.startsWith("."), Ue = /^\*+$/, Ge = (s) => s.length !== 0 && !s.startsWith("."), qe = (s) => s.length !== 0 && s !== "." && s !== "..", Ve = /^\?+([^+@!?\*\[\(]*)?$/, Ye = ([s, t = ""]) => {
942
+ const e = Rt([s]);
943
+ return t ? (t = t.toLowerCase(), (n) => e(n) && n.toLowerCase().endsWith(t)) : e;
944
+ }, Ze = ([s, t = ""]) => {
945
+ const e = kt([s]);
946
+ return t ? (t = t.toLowerCase(), (n) => e(n) && n.toLowerCase().endsWith(t)) : e;
947
+ }, Xe = ([s, t = ""]) => {
948
+ const e = kt([s]);
949
+ return t ? (n) => e(n) && n.endsWith(t) : e;
950
+ }, Je = ([s, t = ""]) => {
951
+ const e = Rt([s]);
952
+ return t ? (n) => e(n) && n.endsWith(t) : e;
953
+ }, Rt = ([s]) => {
954
+ const t = s.length;
955
+ return (e) => e.length === t && !e.startsWith(".");
956
+ }, kt = ([s]) => {
957
+ const t = s.length;
958
+ return (e) => e.length === t && e !== "." && e !== "..";
959
+ }, It = typeof process == "object" && process ? typeof process.env == "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix", yt = {
960
+ win32: { sep: "\\" },
961
+ posix: { sep: "/" }
962
+ }, Qe = It === "win32" ? yt.win32.sep : yt.posix.sep;
963
+ m.sep = Qe;
964
+ const D = Symbol("globstar **");
965
+ m.GLOBSTAR = D;
966
+ const Ke = "[^/]", ts = Ke + "*?", es = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?", ss = "(?:(?!(?:\\/|^)\\.).)*?", ns = (s, t = {}) => (e) => m(e, s, t);
967
+ m.filter = ns;
968
+ const O = (s, t = {}) => Object.assign({}, s, t), rs = (s) => {
969
+ if (!s || typeof s != "object" || !Object.keys(s).length)
970
+ return m;
971
+ const t = m;
972
+ return Object.assign((n, r, i = {}) => t(n, r, O(s, i)), {
973
+ Minimatch: class extends t.Minimatch {
974
+ constructor(r, i = {}) {
975
+ super(r, O(s, i));
976
+ }
977
+ static defaults(r) {
978
+ return t.defaults(O(s, r)).Minimatch;
979
+ }
980
+ },
981
+ AST: class extends t.AST {
982
+ /* c8 ignore start */
983
+ constructor(r, i, o = {}) {
984
+ super(r, i, O(s, o));
985
+ }
986
+ /* c8 ignore stop */
987
+ static fromGlob(r, i = {}) {
988
+ return t.AST.fromGlob(r, O(s, i));
989
+ }
990
+ },
991
+ unescape: (n, r = {}) => t.unescape(n, O(s, r)),
992
+ escape: (n, r = {}) => t.escape(n, O(s, r)),
993
+ filter: (n, r = {}) => t.filter(n, O(s, r)),
994
+ defaults: (n) => t.defaults(O(s, n)),
995
+ makeRe: (n, r = {}) => t.makeRe(n, O(s, r)),
996
+ braceExpand: (n, r = {}) => t.braceExpand(n, O(s, r)),
997
+ match: (n, r, i = {}) => t.match(n, r, O(s, i)),
998
+ sep: t.sep,
999
+ GLOBSTAR: D
1000
+ });
1001
+ };
1002
+ m.defaults = rs;
1003
+ const Ht = (s, t = {}) => (V(s), t.nobrace || !/\{(?:(?!\{).)*\}/.test(s) ? [s] : me(s));
1004
+ m.braceExpand = Ht;
1005
+ const is = (s, t = {}) => new Z(s, t).makeRe();
1006
+ m.makeRe = is;
1007
+ const os = (s, t, e = {}) => {
1008
+ const n = new Z(t, e);
1009
+ return s = s.filter((r) => n.match(r)), n.options.nonull && !s.length && s.push(t), s;
1010
+ };
1011
+ m.match = os;
1012
+ const mt = /[?*]|[+@!]\(.*?\)|\[|\]/, as = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
1013
+ class Z {
1014
+ options;
1015
+ set;
1016
+ pattern;
1017
+ windowsPathsNoEscape;
1018
+ nonegate;
1019
+ negate;
1020
+ comment;
1021
+ empty;
1022
+ preserveMultipleSlashes;
1023
+ partial;
1024
+ globSet;
1025
+ globParts;
1026
+ nocase;
1027
+ isWindows;
1028
+ platform;
1029
+ windowsNoMagicRoot;
1030
+ regexp;
1031
+ constructor(t, e = {}) {
1032
+ V(t), e = e || {}, this.options = e, this.pattern = t, this.platform = e.platform || It, 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();
1033
+ }
1034
+ hasMagic() {
1035
+ if (this.options.magicalBraces && this.set.length > 1)
1036
+ return !0;
1037
+ for (const t of this.set)
1038
+ for (const e of t)
1039
+ if (typeof e != "string")
1040
+ return !0;
1041
+ return !1;
1042
+ }
1043
+ debug(...t) {
1044
+ }
1045
+ make() {
1046
+ const t = this.pattern, e = this.options;
1047
+ if (!e.nocomment && t.charAt(0) === "#") {
1048
+ this.comment = !0;
1049
+ return;
1050
+ }
1051
+ if (!t) {
1052
+ this.empty = !0;
1053
+ return;
1054
+ }
1055
+ this.parseNegate(), this.globSet = [...new Set(this.braceExpand())], e.debug && (this.debug = (...i) => console.error(...i)), this.debug(this.pattern, this.globSet);
1056
+ const n = this.globSet.map((i) => this.slashSplit(i));
1057
+ this.globParts = this.preprocess(n), this.debug(this.pattern, this.globParts);
1058
+ let r = this.globParts.map((i, o, a) => {
1059
+ if (this.isWindows && this.windowsNoMagicRoot) {
1060
+ const c = i[0] === "" && i[1] === "" && (i[2] === "?" || !mt.test(i[2])) && !mt.test(i[3]), h = /^[a-z]:/i.test(i[0]);
1061
+ if (c)
1062
+ return [...i.slice(0, 4), ...i.slice(4).map((l) => this.parse(l))];
1063
+ if (h)
1064
+ return [i[0], ...i.slice(1).map((l) => this.parse(l))];
1065
+ }
1066
+ return i.map((c) => this.parse(c));
1067
+ });
1068
+ if (this.debug(this.pattern, r), this.set = r.filter((i) => i.indexOf(!1) === -1), this.isWindows)
1069
+ for (let i = 0; i < this.set.length; i++) {
1070
+ const o = this.set[i];
1071
+ o[0] === "" && o[1] === "" && this.globParts[i][2] === "?" && typeof o[3] == "string" && /^[a-z]:$/i.test(o[3]) && (o[2] = "?");
1072
+ }
1073
+ this.debug(this.pattern, this.set);
1074
+ }
1075
+ // various transforms to equivalent pattern sets that are
1076
+ // faster to process in a filesystem walk. The goal is to
1077
+ // eliminate what we can, and push all ** patterns as far
1078
+ // to the right as possible, even if it increases the number
1079
+ // of patterns that we have to process.
1080
+ preprocess(t) {
1081
+ if (this.options.noglobstar)
1082
+ for (let n = 0; n < t.length; n++)
1083
+ for (let r = 0; r < t[n].length; r++)
1084
+ t[n][r] === "**" && (t[n][r] = "*");
1085
+ const { optimizationLevel: e = 1 } = this.options;
1086
+ return e >= 2 ? (t = this.firstPhasePreProcess(t), t = this.secondPhasePreProcess(t)) : e >= 1 ? t = this.levelOneOptimize(t) : t = this.adjascentGlobstarOptimize(t), t;
1087
+ }
1088
+ // just get rid of adjascent ** portions
1089
+ adjascentGlobstarOptimize(t) {
1090
+ return t.map((e) => {
1091
+ let n = -1;
1092
+ for (; (n = e.indexOf("**", n + 1)) !== -1; ) {
1093
+ let r = n;
1094
+ for (; e[r + 1] === "**"; )
1095
+ r++;
1096
+ r !== n && e.splice(n, r - n);
1097
+ }
1098
+ return e;
1099
+ });
1100
+ }
1101
+ // get rid of adjascent ** and resolve .. portions
1102
+ levelOneOptimize(t) {
1103
+ return t.map((e) => (e = e.reduce((n, r) => {
1104
+ const i = n[n.length - 1];
1105
+ return r === "**" && i === "**" ? n : r === ".." && i && i !== ".." && i !== "." && i !== "**" ? (n.pop(), n) : (n.push(r), n);
1106
+ }, []), e.length === 0 ? [""] : e));
1107
+ }
1108
+ levelTwoFileOptimize(t) {
1109
+ Array.isArray(t) || (t = this.slashSplit(t));
1110
+ let e = !1;
1111
+ do {
1112
+ if (e = !1, !this.preserveMultipleSlashes) {
1113
+ for (let r = 1; r < t.length - 1; r++) {
1114
+ const i = t[r];
1115
+ r === 1 && i === "" && t[0] === "" || (i === "." || i === "") && (e = !0, t.splice(r, 1), r--);
1116
+ }
1117
+ t[0] === "." && t.length === 2 && (t[1] === "." || t[1] === "") && (e = !0, t.pop());
1118
+ }
1119
+ let n = 0;
1120
+ for (; (n = t.indexOf("..", n + 1)) !== -1; ) {
1121
+ const r = t[n - 1];
1122
+ r && r !== "." && r !== ".." && r !== "**" && (e = !0, t.splice(n - 1, 2), n -= 2);
1123
+ }
1124
+ } while (e);
1125
+ return t.length === 0 ? [""] : t;
1126
+ }
1127
+ // First phase: single-pattern processing
1128
+ // <pre> is 1 or more portions
1129
+ // <rest> is 1 or more portions
1130
+ // <p> is any portion other than ., .., '', or **
1131
+ // <e> is . or ''
1132
+ //
1133
+ // **/.. is *brutal* for filesystem walking performance, because
1134
+ // it effectively resets the recursive walk each time it occurs,
1135
+ // and ** cannot be reduced out by a .. pattern part like a regexp
1136
+ // or most strings (other than .., ., and '') can be.
1137
+ //
1138
+ // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
1139
+ // <pre>/<e>/<rest> -> <pre>/<rest>
1140
+ // <pre>/<p>/../<rest> -> <pre>/<rest>
1141
+ // **/**/<rest> -> **/<rest>
1142
+ //
1143
+ // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
1144
+ // this WOULD be allowed if ** did follow symlinks, or * didn't
1145
+ firstPhasePreProcess(t) {
1146
+ let e = !1;
1147
+ do {
1148
+ e = !1;
1149
+ for (let n of t) {
1150
+ let r = -1;
1151
+ for (; (r = n.indexOf("**", r + 1)) !== -1; ) {
1152
+ let o = r;
1153
+ for (; n[o + 1] === "**"; )
1154
+ o++;
1155
+ o > r && n.splice(r + 1, o - r);
1156
+ let a = n[r + 1];
1157
+ const c = n[r + 2], h = n[r + 3];
1158
+ if (a !== ".." || !c || c === "." || c === ".." || !h || h === "." || h === "..")
1159
+ continue;
1160
+ e = !0, n.splice(r, 1);
1161
+ const l = n.slice(0);
1162
+ l[r] = "**", t.push(l), r--;
1163
+ }
1164
+ if (!this.preserveMultipleSlashes) {
1165
+ for (let o = 1; o < n.length - 1; o++) {
1166
+ const a = n[o];
1167
+ o === 1 && a === "" && n[0] === "" || (a === "." || a === "") && (e = !0, n.splice(o, 1), o--);
1168
+ }
1169
+ n[0] === "." && n.length === 2 && (n[1] === "." || n[1] === "") && (e = !0, n.pop());
1170
+ }
1171
+ let i = 0;
1172
+ for (; (i = n.indexOf("..", i + 1)) !== -1; ) {
1173
+ const o = n[i - 1];
1174
+ if (o && o !== "." && o !== ".." && o !== "**") {
1175
+ e = !0;
1176
+ const c = i === 1 && n[i + 1] === "**" ? ["."] : [];
1177
+ n.splice(i - 1, 2, ...c), n.length === 0 && n.push(""), i -= 2;
1178
+ }
1179
+ }
1180
+ }
1181
+ } while (e);
1182
+ return t;
1183
+ }
1184
+ // second phase: multi-pattern dedupes
1185
+ // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
1186
+ // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
1187
+ // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
1188
+ //
1189
+ // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
1190
+ // ^-- not valid because ** doens't follow symlinks
1191
+ secondPhasePreProcess(t) {
1192
+ for (let e = 0; e < t.length - 1; e++)
1193
+ for (let n = e + 1; n < t.length; n++) {
1194
+ const r = this.partsMatch(t[e], t[n], !this.preserveMultipleSlashes);
1195
+ if (r) {
1196
+ t[e] = [], t[n] = r;
1197
+ break;
1198
+ }
1199
+ }
1200
+ return t.filter((e) => e.length);
1201
+ }
1202
+ partsMatch(t, e, n = !1) {
1203
+ let r = 0, i = 0, o = [], a = "";
1204
+ for (; r < t.length && i < e.length; )
1205
+ if (t[r] === e[i])
1206
+ o.push(a === "b" ? e[i] : t[r]), r++, i++;
1207
+ else if (n && t[r] === "**" && e[i] === t[r + 1])
1208
+ o.push(t[r]), r++;
1209
+ else if (n && e[i] === "**" && t[r] === e[i + 1])
1210
+ o.push(e[i]), i++;
1211
+ else if (t[r] === "*" && e[i] && (this.options.dot || !e[i].startsWith(".")) && e[i] !== "**") {
1212
+ if (a === "b")
1213
+ return !1;
1214
+ a = "a", o.push(t[r]), r++, i++;
1215
+ } else if (e[i] === "*" && t[r] && (this.options.dot || !t[r].startsWith(".")) && t[r] !== "**") {
1216
+ if (a === "a")
1217
+ return !1;
1218
+ a = "b", o.push(e[i]), r++, i++;
1219
+ } else
1220
+ return !1;
1221
+ return t.length === e.length && o;
1222
+ }
1223
+ parseNegate() {
1224
+ if (this.nonegate)
1225
+ return;
1226
+ const t = this.pattern;
1227
+ let e = !1, n = 0;
1228
+ for (let r = 0; r < t.length && t.charAt(r) === "!"; r++)
1229
+ e = !e, n++;
1230
+ n && (this.pattern = t.slice(n)), this.negate = e;
1231
+ }
1232
+ // set partial to true to test if, for example,
1233
+ // "/a/b" matches the start of "/*/b/*/d"
1234
+ // Partial means, if you run out of file before you run
1235
+ // out of pattern, then that's fine, as long as all
1236
+ // the parts match.
1237
+ matchOne(t, e, n = !1) {
1238
+ const r = this.options;
1239
+ if (this.isWindows) {
1240
+ const p = typeof t[0] == "string" && /^[a-z]:$/i.test(t[0]), S = !p && t[0] === "" && t[1] === "" && t[2] === "?" && /^[a-z]:$/i.test(t[3]), v = typeof e[0] == "string" && /^[a-z]:$/i.test(e[0]), T = !v && e[0] === "" && e[1] === "" && e[2] === "?" && typeof e[3] == "string" && /^[a-z]:$/i.test(e[3]), x = S ? 3 : p ? 0 : void 0, y = T ? 3 : v ? 0 : void 0;
1241
+ if (typeof x == "number" && typeof y == "number") {
1242
+ const [P, H] = [t[x], e[y]];
1243
+ P.toLowerCase() === H.toLowerCase() && (e[y] = P, y > x ? e = e.slice(y) : x > y && (t = t.slice(x)));
1244
+ }
1245
+ }
1246
+ const { optimizationLevel: i = 1 } = this.options;
1247
+ i >= 2 && (t = this.levelTwoFileOptimize(t)), this.debug("matchOne", this, { file: t, pattern: e }), this.debug("matchOne", t.length, e.length);
1248
+ for (var o = 0, a = 0, c = t.length, h = e.length; o < c && a < h; o++, a++) {
1249
+ this.debug("matchOne loop");
1250
+ var l = e[a], f = t[o];
1251
+ if (this.debug(e, l, f), l === !1)
1252
+ return !1;
1253
+ if (l === D) {
1254
+ this.debug("GLOBSTAR", [e, l, f]);
1255
+ var u = o, d = a + 1;
1256
+ if (d === h) {
1257
+ for (this.debug("** at the end"); o < c; o++)
1258
+ if (t[o] === "." || t[o] === ".." || !r.dot && t[o].charAt(0) === ".")
1259
+ return !1;
1260
+ return !0;
1261
+ }
1262
+ for (; u < c; ) {
1263
+ var g = t[u];
1264
+ if (this.debug(`
1265
+ globstar while`, t, u, e, d, g), this.matchOne(t.slice(u), e.slice(d), n))
1266
+ return this.debug("globstar found match!", u, c, g), !0;
1267
+ if (g === "." || g === ".." || !r.dot && g.charAt(0) === ".") {
1268
+ this.debug("dot detected!", t, u, e, d);
1269
+ break;
1270
+ }
1271
+ this.debug("globstar swallow a segment, and continue"), u++;
1272
+ }
1273
+ return !!(n && (this.debug(`
1274
+ >>> no match, partial?`, t, u, e, d), u === c));
1275
+ }
1276
+ let p;
1277
+ if (typeof l == "string" ? (p = f === l, this.debug("string match", l, f, p)) : (p = l.test(f), this.debug("pattern match", l, f, p)), !p)
1278
+ return !1;
1279
+ }
1280
+ if (o === c && a === h)
1281
+ return !0;
1282
+ if (o === c)
1283
+ return n;
1284
+ if (a === h)
1285
+ return o === c - 1 && t[o] === "";
1286
+ throw new Error("wtf?");
1287
+ }
1288
+ braceExpand() {
1289
+ return Ht(this.pattern, this.options);
1290
+ }
1291
+ parse(t) {
1292
+ V(t);
1293
+ const e = this.options;
1294
+ if (t === "**")
1295
+ return D;
1296
+ if (t === "")
1297
+ return "";
1298
+ let n, r = null;
1299
+ (n = t.match(Ue)) ? r = e.dot ? qe : Ge : (n = t.match(Re)) ? r = (e.nocase ? e.dot ? Le : He : e.dot ? Ie : ke)(n[1]) : (n = t.match(Ve)) ? r = (e.nocase ? e.dot ? Ze : Ye : e.dot ? Xe : Je)(n) : (n = t.match(ze)) ? r = e.dot ? je : We : (n = t.match(_e)) && (r = Be);
1300
+ const i = E.fromGlob(t, this.options).toMMPattern();
1301
+ return r && typeof i == "object" && Reflect.defineProperty(i, "test", { value: r }), i;
1302
+ }
1303
+ makeRe() {
1304
+ if (this.regexp || this.regexp === !1)
1305
+ return this.regexp;
1306
+ const t = this.set;
1307
+ if (!t.length)
1308
+ return this.regexp = !1, this.regexp;
1309
+ const e = this.options, n = e.noglobstar ? ts : e.dot ? es : ss, r = new Set(e.nocase ? ["i"] : []);
1310
+ let i = t.map((c) => {
1311
+ const h = c.map((l) => {
1312
+ if (l instanceof RegExp)
1313
+ for (const f of l.flags.split(""))
1314
+ r.add(f);
1315
+ return typeof l == "string" ? as(l) : l === D ? D : l._src;
1316
+ });
1317
+ return h.forEach((l, f) => {
1318
+ const u = h[f + 1], d = h[f - 1];
1319
+ l !== D || d === D || (d === void 0 ? u !== void 0 && u !== D ? h[f + 1] = "(?:\\/|" + n + "\\/)?" + u : h[f] = n : u === void 0 ? h[f - 1] = d + "(?:\\/|" + n + ")?" : u !== D && (h[f - 1] = d + "(?:\\/|\\/" + n + "\\/)" + u, h[f + 1] = D));
1320
+ }), h.filter((l) => l !== D).join("/");
1321
+ }).join("|");
1322
+ const [o, a] = t.length > 1 ? ["(?:", ")"] : ["", ""];
1323
+ i = "^" + o + i + a + "$", this.negate && (i = "^(?!" + i + ").+$");
1324
+ try {
1325
+ this.regexp = new RegExp(i, [...r].join(""));
1326
+ } catch {
1327
+ this.regexp = !1;
1328
+ }
1329
+ return this.regexp;
1330
+ }
1331
+ slashSplit(t) {
1332
+ return this.preserveMultipleSlashes ? t.split("/") : this.isWindows && /^\/\/[^\/]+/.test(t) ? ["", ...t.split(/\/+/)] : t.split(/\/+/);
1333
+ }
1334
+ match(t, e = this.partial) {
1335
+ if (this.debug("match", t, this.pattern), this.comment)
1336
+ return !1;
1337
+ if (this.empty)
1338
+ return t === "";
1339
+ if (t === "/" && e)
1340
+ return !0;
1341
+ const n = this.options;
1342
+ this.isWindows && (t = t.split("\\").join("/"));
1343
+ const r = this.slashSplit(t);
1344
+ this.debug(this.pattern, "split", r);
1345
+ const i = this.set;
1346
+ this.debug(this.pattern, "set", i);
1347
+ let o = r[r.length - 1];
1348
+ if (!o)
1349
+ for (let a = r.length - 2; !o && a >= 0; a--)
1350
+ o = r[a];
1351
+ for (let a = 0; a < i.length; a++) {
1352
+ const c = i[a];
1353
+ let h = r;
1354
+ if (n.matchBase && c.length === 1 && (h = [o]), this.matchOne(h, c, e))
1355
+ return n.flipNegate ? !0 : !this.negate;
1356
+ }
1357
+ return n.flipNegate ? !1 : this.negate;
1358
+ }
1359
+ static defaults(t) {
1360
+ return m.defaults(t).Minimatch;
1361
+ }
1362
+ }
1363
+ m.AST = E;
1364
+ m.Minimatch = Z;
1365
+ m.escape = Pe;
1366
+ m.unescape = I;
1367
+ function cs() {
1368
+ if (!("storage" in navigator) || !("getDirectory" in navigator.storage))
1369
+ throw new Qt();
1370
+ }
1371
+ async function $(s, t) {
1372
+ return typeof navigator < "u" && navigator.locks?.request ? navigator.locks.request(`opfs:${s.replace(/\/+/g, "/")}`, { mode: "exclusive" }, t) : t();
1373
+ }
1374
+ function M(s) {
1375
+ return Array.isArray(s) ? s : (s.startsWith("~/") ? s.slice(2) : s).split("/").filter(Boolean);
1376
+ }
1377
+ function lt(s) {
1378
+ return typeof s == "string" ? s ?? "/" : `/${s.join("/")}`;
1379
+ }
1380
+ function it(s) {
1381
+ const t = M(s);
1382
+ return t[t.length - 1] || "";
1383
+ }
1384
+ function K(s) {
1385
+ const t = M(s);
1386
+ return t.pop(), lt(t);
1387
+ }
1388
+ function Y(s) {
1389
+ return !s || s === "/" ? "/" : s.startsWith("~/") ? `/${s.slice(2)}` : s.startsWith("/") ? s : `/${s}`;
1390
+ }
1391
+ function ls(s, t = !1) {
1392
+ return s = s.replace(/\/$/, ""), t && !s.includes("*") ? `${s}/**` : s;
1393
+ }
1394
+ function tt(s, t) {
1395
+ return m(s, t, {
1396
+ dot: !0,
1397
+ matchBase: !0
1398
+ });
1399
+ }
1400
+ function Lt(s) {
1401
+ const t = Y(s), e = M(t), n = [];
1402
+ for (const r of e)
1403
+ if (!(r === "." || r === ""))
1404
+ if (r === "..") {
1405
+ if (n.length === 0)
1406
+ continue;
1407
+ n.pop();
1408
+ } else
1409
+ n.push(r);
1410
+ return lt(n);
1411
+ }
1412
+ async function hs(s, t = "SHA-1", e = 50 * 1024 * 1024) {
1413
+ if (s instanceof File && (s = await s.arrayBuffer()), s.byteLength > e)
1414
+ throw new Error(`File size ${s.byteLength} bytes exceeds maximum allowed size ${e} bytes`);
1415
+ const n = new Uint8Array(s), r = await crypto.subtle.digest(t, n);
1416
+ return Array.from(new Uint8Array(r)).map((o) => o.toString(16).padStart(2, "0")).join("");
1417
+ }
1418
+ async function us(s) {
1419
+ const t = await s.arrayBuffer();
1420
+ return new Uint8Array(t);
1421
+ }
1422
+ async function fs(s, t, e = {}) {
1423
+ const n = it(t);
1424
+ return $(t, async () => {
1425
+ const r = e.recursive ?? !1, i = e.force ?? !1;
1426
+ try {
1427
+ await s.removeEntry(n, { recursive: r });
1428
+ } catch (o) {
1429
+ if (o.name === "NotFoundError" && i)
1430
+ return;
1431
+ const a = o.name === "TypeMismatchError" && !r;
1432
+ throw A(o, {
1433
+ path: t,
1434
+ operation: "remove",
1435
+ isDirectory: a
1436
+ });
1437
+ }
1438
+ });
1439
+ }
1440
+ function Et(s, t, e, n) {
1441
+ if (!Number.isInteger(t) || !Number.isInteger(e))
1442
+ throw new C("argument", "Invalid offset or length");
1443
+ if (t < 0 || e < 0)
1444
+ throw new C("argument", "Negative offset or length not allowed");
1445
+ if (t + e > s)
1446
+ throw new C("overflow", "Operation would overflow buffer");
1447
+ if (n != null && (!Number.isInteger(n) || n < 0))
1448
+ throw new C("argument", "Invalid position");
1449
+ }
1450
+ function St(s, t, e) {
1451
+ try {
1452
+ t.flush(), t.close();
1453
+ } catch (n) {
1454
+ console.warn(`Warning: Failed to properly close file descriptor ${s} (${e}):`, n);
1455
+ }
1456
+ }
1457
+ function ds(s, t, e) {
1458
+ if (s >= e)
1459
+ return { isEOF: !0, actualLength: 0 };
1460
+ const n = Math.min(t, e - s);
1461
+ return n <= 0 ? { isEOF: !0, actualLength: 0 } : { isEOF: !1, actualLength: n };
1462
+ }
1463
+ async function ps(s, t) {
1464
+ try {
1465
+ return await s.createSyncAccessHandle();
1466
+ } catch (e) {
1467
+ throw A(e, { path: t, isDirectory: !1 });
1468
+ }
1469
+ }
1470
+ class gs {
1471
+ /** Root directory handle for the file system */
1472
+ root;
1473
+ /** Map of watched paths and options */
1474
+ watchers = /* @__PURE__ */ new Map();
1475
+ /** Promise to prevent concurrent mount operations */
1476
+ mountingPromise = null;
1477
+ /** BroadcastChannel instance for sending events */
1478
+ broadcastChannel = null;
1479
+ /** Configuration options */
1480
+ options = {
1481
+ root: "/",
1482
+ namespace: "",
1483
+ maxFileSize: 50 * 1024 * 1024,
1484
+ hashAlgorithm: "etag",
1485
+ broadcastChannel: "opfs-worker"
1486
+ };
1487
+ /**
1488
+ * Notify about internal changes to the file system
1489
+ *
1490
+ * This method is called by internal operations to notify clients about
1491
+ * changes, even when no specific paths are being watched.
1492
+ *
1493
+ * @param event - The event describing the change
1494
+ */
1495
+ async notifyChange(t) {
1496
+ if (!this.options.broadcastChannel)
1497
+ return;
1498
+ const e = t.path;
1499
+ if (![...this.watchers.values()].some((i) => tt(e, i.pattern) && i.include.some((o) => o && tt(e, o)) && !i.exclude.some((o) => o && tt(e, o))))
1500
+ return;
1501
+ let r;
1502
+ if (this.options.hashAlgorithm)
1503
+ try {
1504
+ r = (await this.stat(e)).hash;
1505
+ } catch {
1506
+ }
1507
+ try {
1508
+ this.broadcastChannel || (this.broadcastChannel = new BroadcastChannel(this.options.broadcastChannel));
1509
+ const i = {
1510
+ namespace: this.options.namespace,
1511
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1512
+ ...t,
1513
+ ...r && { hash: r }
1514
+ };
1515
+ this.broadcastChannel.postMessage(i);
1516
+ } catch (i) {
1517
+ console.warn("Failed to send event via BroadcastChannel:", i);
1518
+ }
1519
+ }
1520
+ constructor(t) {
1521
+ cs(), t && this.setOptions(t);
1522
+ }
1523
+ /**
1524
+ * Initialize the file system within a given directory.
1525
+ * If no root is specified, uses the OPFS root directory.
1526
+ */
1527
+ async mount() {
1528
+ const t = this.options.root;
1529
+ return this.mountingPromise && await this.mountingPromise, this.mountingPromise = new Promise(async (e, n) => {
1530
+ try {
1531
+ const r = await navigator.storage.getDirectory();
1532
+ this.root = t === "/" ? r : await this.getDirectoryHandle(t, !0, r), e(!0);
1533
+ } catch (r) {
1534
+ n(new re(t, r));
1535
+ } finally {
1536
+ this.mountingPromise = null;
1537
+ }
1538
+ }), this.mountingPromise;
1539
+ }
1540
+ /**
1541
+ * Update configuration options
1542
+ *
1543
+ * @param options - Configuration options to update
1544
+ * @param options.root - Root path for the file system
1545
+ * @param options.watchInterval - Polling interval in milliseconds for file watching
1546
+ * @param options.hashAlgorithm - Hash algorithm for file hashing
1547
+ * @param options.maxFileSize - Maximum file size for hashing in bytes
1548
+ * @param options.broadcastChannel - Custom name for the broadcast channel
1549
+ */
1550
+ async setOptions(t) {
1551
+ 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 = Y(t.root), this.options.namespace || (this.options.namespace = `opfs-worker:${this.options.root}`), await this.mount());
1552
+ }
1553
+ /**
1554
+ * Get a directory handle from a path
1555
+ *
1556
+ * Navigates through the directory structure to find or create a directory
1557
+ * at the specified path.
1558
+ *
1559
+ * @param path - The path to the directory (string or array of segments)
1560
+ * @param create - Whether to create the directory if it doesn't exist (default: false)
1561
+ * @param from - The directory to start from (default: root directory)
1562
+ * @returns Promise that resolves to the directory handle
1563
+ * @throws {OPFSError} If the directory cannot be accessed or created
1564
+ *
1565
+ * @example
1566
+ * ```typescript
1567
+ * const docsDir = await fs.getDirectoryHandle('/users/john/documents', true);
1568
+ * const docsDir2 = await fs.getDirectoryHandle(['users', 'john', 'documents'], true);
1569
+ * ```
1570
+ */
1571
+ async getDirectoryHandle(t, e = !1, n = this.root) {
1572
+ const r = Array.isArray(t) ? t : M(t);
1573
+ let i = n;
1574
+ for (const o of r)
1575
+ i = await i.getDirectoryHandle(o, { create: e });
1576
+ return i;
1577
+ }
1578
+ /**
1579
+ * Get a file handle from a path
1580
+ *
1581
+ * Navigates to the parent directory and retrieves or creates a file handle
1582
+ * for the specified file path.
1583
+ *
1584
+ * @param path - The path to the file (string or array of segments)
1585
+ * @param create - Whether to create the file if it doesn't exist (default: false)
1586
+ * @param _from - The directory to start from (default: root directory)
1587
+ * @returns Promise that resolves to the file handle
1588
+ * @throws {PathError} If the path is empty
1589
+ * @throws {OPFSError} If the file cannot be accessed or created
1590
+ *
1591
+ * @example
1592
+ * ```typescript
1593
+ * const fileHandle = await fs.getFileHandle('/config/settings.json', true);
1594
+ * const fileHandle2 = await fs.getFileHandle(['config', 'settings.json'], true);
1595
+ * ```
1596
+ */
1597
+ async getFileHandle(t, e = !1, n = this.root) {
1598
+ const r = M(t);
1599
+ if (r.length === 0)
1600
+ throw new Kt("Path must not be empty", Array.isArray(t) ? t.join("/") : t);
1601
+ const i = r.pop();
1602
+ return (await this.getDirectoryHandle(r, e, n)).getFileHandle(i, { create: e });
1603
+ }
1604
+ /**
1605
+ * Get a complete index of all files and directories in the file system
1606
+ *
1607
+ * This method recursively traverses the entire file system and returns
1608
+ * a Map containing FileStat objects for every file and directory.
1609
+ *
1610
+ * @returns Promise that resolves to a Map of paths to FileStat objects
1611
+ * @throws {OPFSError} If the file system is not mounted
1612
+ *
1613
+ * @example
1614
+ * ```typescript
1615
+ * const index = await fs.index();
1616
+ * const fileStats = index.get('/data/config.json');
1617
+ * if (fileStats) {
1618
+ * console.log(`File size: ${fileStats.size} bytes`);
1619
+ * if (fileStats.hash) console.log(`Hash: ${fileStats.hash}`);
1620
+ * }
1621
+ * ```
1622
+ */
1623
+ async index() {
1624
+ const t = /* @__PURE__ */ new Map(), e = async (n) => {
1625
+ const r = await this.readDir(n);
1626
+ for (const i of r) {
1627
+ const o = `${n === "/" ? "" : n}/${i.name}`;
1628
+ try {
1629
+ const a = await this.stat(o);
1630
+ t.set(o, a), a.isDirectory && await e(o);
1631
+ } catch (a) {
1632
+ console.warn(`Skipping broken entry: ${o}`, a);
1633
+ }
1634
+ }
1635
+ };
1636
+ return t.set("/", {
1637
+ kind: "directory",
1638
+ size: 0,
1639
+ mtime: (/* @__PURE__ */ new Date(0)).toISOString(),
1640
+ ctime: (/* @__PURE__ */ new Date(0)).toISOString(),
1641
+ isFile: !1,
1642
+ isDirectory: !0
1643
+ }), await e("/"), t;
1644
+ }
1645
+ /**
1646
+ * Create a directory
1647
+ *
1648
+ * Creates a new directory at the specified path. If the recursive option
1649
+ * is enabled, parent directories will be created as needed.
1650
+ *
1651
+ * @param path - The path where the directory should be created
1652
+ * @param options - Options for directory creation
1653
+ * @param options.recursive - Whether to create parent directories if they don't exist (default: false)
1654
+ * @returns Promise that resolves when the directory is created
1655
+ * @throws {OPFSError} If the directory cannot be created
1656
+ *
1657
+ * @example
1658
+ * ```typescript
1659
+ * // Create a single directory
1660
+ * await fs.mkdir('/users/john');
1661
+ *
1662
+ * // Create nested directories
1663
+ * await fs.mkdir('/users/john/documents/projects', { recursive: true });
1664
+ * ```
1665
+ */
1666
+ async mkdir(t, e) {
1667
+ await this.mount();
1668
+ const n = e?.recursive ?? !1, r = M(t);
1669
+ let i = this.root;
1670
+ for (let o = 0; o < r.length; o++) {
1671
+ const a = r[o];
1672
+ try {
1673
+ i = await i.getDirectoryHandle(a, { create: n || o === r.length - 1 });
1674
+ } catch (c) {
1675
+ throw c.name === "NotFoundError" ? A(c, {
1676
+ path: lt(r.slice(0, o + 1)),
1677
+ existenceType: "directory"
1678
+ }) : c.name === "TypeMismatchError" ? A(c, { path: a, isDirectory: !1 }) : new J("create directory", a, c);
1679
+ }
1680
+ }
1681
+ await this.notifyChange({ path: t, type: b.Added, isDirectory: !0 });
1682
+ }
1683
+ /**
1684
+ * Get file or directory statistics
1685
+ *
1686
+ * Returns detailed information about a file or directory, including
1687
+ * size, modification time, and optionally a hash of the file content.
1688
+ *
1689
+ * @param path - The path to the file or directory
1690
+ * @returns Promise that resolves to FileStat object
1691
+ * @throws {OPFSError} If the path does not exist or cannot be accessed
1692
+ *
1693
+ * @example
1694
+ * ```typescript
1695
+ * const stats = await fs.stat('/data/config.json');
1696
+ * console.log(`File size: ${stats.size} bytes`);
1697
+ * console.log(`Last modified: ${stats.mtime}`);
1698
+ *
1699
+ * // If hashing is enabled, hash will be included
1700
+ * if (stats.hash) {
1701
+ * console.log(`Hash: ${stats.hash}`);
1702
+ * }
1703
+ * ```
1704
+ */
1705
+ async stat(t) {
1706
+ if (await this.mount(), t === "/")
1707
+ return {
1708
+ kind: "directory",
1709
+ size: 0,
1710
+ mtime: (/* @__PURE__ */ new Date(0)).toISOString(),
1711
+ ctime: (/* @__PURE__ */ new Date(0)).toISOString(),
1712
+ isFile: !1,
1713
+ isDirectory: !0
1714
+ };
1715
+ const e = it(t);
1716
+ let n;
1717
+ try {
1718
+ n = await this.getDirectoryHandle(K(t), !1);
1719
+ const r = this.options.hashAlgorithm, o = await (await n.getFileHandle(e, { create: !1 })).getFile(), a = {
1720
+ kind: "file",
1721
+ size: o.size,
1722
+ mtime: new Date(o.lastModified).toISOString(),
1723
+ ctime: new Date(o.lastModified).toISOString(),
1724
+ isFile: !0,
1725
+ isDirectory: !1
1726
+ };
1727
+ if (r === "etag")
1728
+ a.hash = `${o.lastModified.toString(36)}-${o.size.toString(36)}`;
1729
+ else if (typeof r == "string")
1730
+ try {
1731
+ const c = await hs(o, r, this.options.maxFileSize);
1732
+ a.hash = c;
1733
+ } catch (c) {
1734
+ console.warn(`Failed to calculate hash for ${t}:`, c);
1735
+ }
1736
+ return a;
1737
+ } catch (r) {
1738
+ if (r.name === "NotFoundError")
1739
+ throw new B("file", t, r);
1740
+ if (r.name !== "TypeMismatchError")
1741
+ throw new J("stat", t, r);
1742
+ }
1743
+ try {
1744
+ return await n.getDirectoryHandle(e, { create: !1 }), {
1745
+ kind: "directory",
1746
+ size: 0,
1747
+ mtime: (/* @__PURE__ */ new Date(0)).toISOString(),
1748
+ ctime: (/* @__PURE__ */ new Date(0)).toISOString(),
1749
+ isFile: !1,
1750
+ isDirectory: !0
1751
+ };
1752
+ } catch (r) {
1753
+ throw new J("stat", t, r);
1754
+ }
1755
+ }
1756
+ /**
1757
+ * Read a directory's contents
1758
+ *
1759
+ * Lists all files and subdirectories within the specified directory.
1760
+ *
1761
+ * @param path - The path to the directory to read
1762
+ * @returns Promise that resolves to an array of detailed file/directory information
1763
+ * @throws {OPFSError} If the directory does not exist or cannot be accessed
1764
+ *
1765
+ * @example
1766
+ * ```typescript
1767
+ * // Get detailed information about files and directories
1768
+ * const detailed = await fs.readDir('/users/john/documents');
1769
+ * detailed.forEach(item => {
1770
+ * console.log(`${item.name} - ${item.isFile ? 'file' : 'directory'}`);
1771
+ * });
1772
+ * ```
1773
+ */
1774
+ async readDir(t) {
1775
+ await this.mount();
1776
+ const e = await this.getDirectoryHandle(t, !1), n = [];
1777
+ for await (const [r, i] of e.entries()) {
1778
+ const o = i.kind === "file";
1779
+ n.push({
1780
+ name: r,
1781
+ kind: i.kind,
1782
+ isFile: o,
1783
+ isDirectory: !o
1784
+ });
1785
+ }
1786
+ return n;
1787
+ }
1788
+ /**
1789
+ * Check if a file or directory exists
1790
+ *
1791
+ * Verifies if a file or directory exists at the specified path.
1792
+ *
1793
+ * @param path - The path to check
1794
+ * @returns Promise that resolves to true if the file or directory exists, false otherwise
1795
+ *
1796
+ * @example
1797
+ * ```typescript
1798
+ * const exists = await fs.exists('/config/settings.json');
1799
+ * console.log(`File exists: ${exists}`);
1800
+ * ```
1801
+ */
1802
+ async exists(t) {
1803
+ if (await this.mount(), t === "/")
1804
+ return !0;
1805
+ const e = it(t);
1806
+ let n = null;
1807
+ try {
1808
+ n = await this.getDirectoryHandle(K(t), !1);
1809
+ } catch (r) {
1810
+ if (n = null, r.name !== "NotFoundError" && r.name !== "TypeMismatchError")
1811
+ throw r;
1812
+ }
1813
+ if (!n || !e)
1814
+ return !1;
1815
+ try {
1816
+ return await n.getFileHandle(e, { create: !1 }), !0;
1817
+ } catch (r) {
1818
+ if (r.name !== "NotFoundError" && r.name !== "TypeMismatchError")
1819
+ throw r;
1820
+ try {
1821
+ return await n.getDirectoryHandle(e, { create: !1 }), !0;
1822
+ } catch (i) {
1823
+ if (i.name !== "NotFoundError" && i.name !== "TypeMismatchError")
1824
+ throw i;
1825
+ return !1;
1826
+ }
1827
+ }
1828
+ }
1829
+ /**
1830
+ * Clear all contents of a directory without removing the directory itself
1831
+ *
1832
+ * Removes all files and subdirectories within the specified directory,
1833
+ * but keeps the directory itself.
1834
+ *
1835
+ * @param path - The path to the directory to clear (default: '/')
1836
+ * @returns Promise that resolves when all contents are removed
1837
+ * @throws {OPFSError} If the operation fails
1838
+ *
1839
+ * @example
1840
+ * ```typescript
1841
+ * // Clear root directory contents
1842
+ * await fs.clear('/');
1843
+ *
1844
+ * // Clear specific directory contents
1845
+ * await fs.clear('/data');
1846
+ * ```
1847
+ */
1848
+ async clear(t = "/") {
1849
+ await this.mount();
1850
+ try {
1851
+ const e = await this.readDir(t);
1852
+ for (const n of e) {
1853
+ const r = `${t === "/" ? "" : t}/${n.name}`;
1854
+ await this.remove(r, { recursive: !0 });
1855
+ }
1856
+ await this.notifyChange({ path: t, type: b.Changed, isDirectory: !0 });
1857
+ } catch (e) {
1858
+ throw e instanceof w ? e : A(e, { path: t, isDirectory: !0 });
1859
+ }
1860
+ }
1861
+ /**
1862
+ * Remove files and directories
1863
+ *
1864
+ * Removes files and directories. Similar to Node.js fs.rm().
1865
+ *
1866
+ * @param path - The path to remove
1867
+ * @param options - Options for removal
1868
+ * @param options.recursive - Whether to remove directories and their contents recursively (default: false)
1869
+ * @param options.force - Whether to ignore errors if the path doesn't exist (default: false)
1870
+ * @returns Promise that resolves when the removal is complete
1871
+ * @throws {OPFSError} If the removal fails
1872
+ *
1873
+ * @example
1874
+ * ```typescript
1875
+ * // Remove a file
1876
+ * await fs.rm('/path/to/file.txt');
1877
+ *
1878
+ * // Remove a directory and all its contents
1879
+ * await fs.rm('/path/to/directory', { recursive: true });
1880
+ *
1881
+ * // Remove with force (ignore if doesn't exist)
1882
+ * await fs.rm('/maybe/exists', { force: true });
1883
+ * ```
1884
+ */
1885
+ async remove(t, e) {
1886
+ if (await this.mount(), t === "/")
1887
+ throw new nt("EROOT", t);
1888
+ const { recursive: n = !1, force: r = !1 } = e || {}, i = await this.getDirectoryHandle(K(t), !1), o = await this.stat(t);
1889
+ await fs(i, t, { recursive: n, force: r }), await this.notifyChange({ path: t, type: b.Removed, isDirectory: o.isDirectory });
1890
+ }
1891
+ /**
1892
+ * Resolve a path to an absolute path
1893
+ *
1894
+ * Resolves relative paths and normalizes path segments (like '..' and '.').
1895
+ * Similar to Node.js fs.realpath() but without symlink resolution since OPFS doesn't support symlinks.
1896
+ *
1897
+ * @param path - The path to resolve
1898
+ * @returns Promise that resolves to the absolute normalized path
1899
+ * @throws {FileNotFoundError} If the path does not exist
1900
+ * @throws {OPFSError} If path resolution fails
1901
+ *
1902
+ * @example
1903
+ * ```typescript
1904
+ * // Resolve relative path
1905
+ * const absolute = await fs.realpath('./config/../data/file.txt');
1906
+ * console.log(absolute); // '/data/file.txt'
1907
+ * ```
1908
+ */
1909
+ async realpath(t) {
1910
+ await this.mount();
1911
+ try {
1912
+ const e = Lt(t);
1913
+ if (!await this.exists(e))
1914
+ throw new B("file", e);
1915
+ return e;
1916
+ } catch (e) {
1917
+ throw e instanceof w ? e : A(e, { path: t });
1918
+ }
1919
+ }
1920
+ /**
1921
+ * Rename a file or directory
1922
+ *
1923
+ * Changes the name of a file or directory. If the target path already exists,
1924
+ * it will be replaced only if overwrite option is enabled.
1925
+ *
1926
+ * @param oldPath - The current path of the file or directory
1927
+ * @param newPath - The new path for the file or directory
1928
+ * @param options - Options for renaming
1929
+ * @param options.overwrite - Whether to overwrite existing files (default: false)
1930
+ * @returns Promise that resolves when the rename operation is complete
1931
+ * @throws {OPFSError} If the rename operation fails
1932
+ *
1933
+ * @example
1934
+ * ```typescript
1935
+ * // Basic rename (fails if target exists)
1936
+ * await fs.rename('/old/path/file.txt', '/new/path/renamed.txt');
1937
+ *
1938
+ * // Rename with overwrite
1939
+ * await fs.rename('/old/path/file.txt', '/new/path/renamed.txt', { overwrite: true });
1940
+ * ```
1941
+ */
1942
+ async rename(t, e, n) {
1943
+ await this.mount();
1944
+ try {
1945
+ const r = n?.overwrite ?? !1, i = await this.stat(t);
1946
+ if (await this.exists(e) && !r)
1947
+ throw new rt(e);
1948
+ await this.copy(t, e, { recursive: !0, overwrite: r }), await this.remove(t, { recursive: !0 }), await this.notifyChange({ path: t, type: b.Removed, isDirectory: i.isDirectory }), await this.notifyChange({ path: e, type: b.Added, isDirectory: i.isDirectory });
1949
+ } catch (r) {
1950
+ throw r instanceof w ? r : A(r, { path: t });
1951
+ }
1952
+ }
1953
+ /**
1954
+ * Copy files and directories
1955
+ *
1956
+ * Copies files and directories. Similar to Node.js fs.cp().
1957
+ *
1958
+ * @param source - The source path to copy from
1959
+ * @param destination - The destination path to copy to
1960
+ * @param options - Options for copying
1961
+ * @param options.recursive - Whether to copy directories recursively (default: false)
1962
+ * @param options.overwrite - Whether to overwrite existing files (default: true)
1963
+ * @returns Promise that resolves when the copy operation is complete
1964
+ * @throws {OPFSError} If the copy operation fails
1965
+ *
1966
+ * @example
1967
+ * ```typescript
1968
+ * // Copy a file
1969
+ * await fs.copy('/source/file.txt', '/dest/file.txt');
1970
+ *
1971
+ * // Copy a directory and all its contents
1972
+ * await fs.copy('/source/dir', '/dest/dir', { recursive: true });
1973
+ *
1974
+ * // Copy without overwriting existing files
1975
+ * await fs.copy('/source', '/dest', { recursive: true, overwrite: false });
1976
+ * ```
1977
+ */
1978
+ async copy(t, e, n) {
1979
+ await this.mount();
1980
+ try {
1981
+ const r = n?.recursive ?? !1, i = n?.overwrite ?? !0;
1982
+ if (!await this.exists(t))
1983
+ throw new B("source", t);
1984
+ if (await this.exists(e) && !i)
1985
+ throw new rt(e);
1986
+ if ((await this.stat(t)).isFile) {
1987
+ const h = await this.readFile(t);
1988
+ await this.writeFile(e, h);
1989
+ } else {
1990
+ if (!r)
1991
+ throw new st("directory", t);
1992
+ await this.mkdir(e, { recursive: !0 });
1993
+ const h = await this.readDir(t);
1994
+ for (const l of h) {
1995
+ const f = `${t}/${l.name}`, u = `${e}/${l.name}`;
1996
+ await this.copy(f, u, { recursive: !0, overwrite: i });
1997
+ }
1998
+ }
1999
+ } catch (r) {
2000
+ throw r instanceof w ? r : A(r, { path: t });
2001
+ }
2002
+ }
2003
+ /**
2004
+ * Start watching a file or directory for changes
2005
+ *
2006
+ * @param path - The path to watch (minimatch syntax allowed)
2007
+ * @param options - Watch options
2008
+ * @param options.recursive - Whether to watch recursively (default: true)
2009
+ * @param options.exclude - Glob pattern(s) to exclude (minimatch).
2010
+ * @returns Promise that resolves when watching starts
2011
+ *
2012
+ * @example
2013
+ * ```typescript
2014
+ * // Watch entire directory tree recursively (default)
2015
+ * await fs.watch('/data');
2016
+ *
2017
+ * // Watch only immediate children (shallow)
2018
+ * await fs.watch('/data', { recursive: false });
2019
+ *
2020
+ * // Watch a single file
2021
+ * await fs.watch('/config.json', { recursive: false });
2022
+ *
2023
+ * // Watch all json files but not in dist directory
2024
+ * await fs.watch('/**\/*.json', { recursive: false, exclude: ['dist/**'] });
2025
+ *
2026
+ * ```
2027
+ */
2028
+ async watch(t, e) {
2029
+ if (!this.options.broadcastChannel)
2030
+ throw new Ct("This instance is not configured to send events. Please specify options.broadcastChannel to enable watching.");
2031
+ const n = {
2032
+ pattern: ls(t, e?.recursive ?? !0),
2033
+ include: Array.isArray(e?.include) ? e.include : [e?.include ?? "**"],
2034
+ exclude: Array.isArray(e?.exclude) ? e.exclude : [e?.exclude ?? ""]
2035
+ };
2036
+ this.watchers.set(t, n);
2037
+ }
2038
+ /**
2039
+ * Stop watching a previously watched path
2040
+ */
2041
+ unwatch(t) {
2042
+ this.watchers.delete(t);
2043
+ }
2044
+ /**
2045
+ * Bulk-create files from `[path, data]` entries (strings, bytes, or Blobs).
2046
+ *
2047
+ * @param entries - Array of `[path, data]` tuples
2048
+ * @throws {OPFSError} If a write fails
2049
+ *
2050
+ * @example
2051
+ * ```typescript
2052
+ * await fs.createIndex([
2053
+ * ['/config.json', JSON.stringify({ theme: 'dark' })],
2054
+ * ['/data/binary.dat', new Uint8Array([1, 2, 3, 4])],
2055
+ * ['/upload.txt', new Blob(['file content'], { type: 'text/plain' })],
2056
+ * ]);
2057
+ * ```
2058
+ */
2059
+ async createIndex(t) {
2060
+ await this.mount();
2061
+ try {
2062
+ for (const [e, n] of t) {
2063
+ const r = Y(e);
2064
+ let i;
2065
+ n instanceof Blob ? i = await us(n) : typeof n == "string" ? i = new TextEncoder().encode(n) : i = n, await this.writeFile(r, i);
2066
+ }
2067
+ } catch (e) {
2068
+ throw e instanceof w ? e : A(e);
2069
+ }
2070
+ }
2071
+ /**
2072
+ * Dispose of resources and clean up the file system instance
2073
+ */
2074
+ dispose() {
2075
+ this.broadcastChannel && (this.broadcastChannel.close(), this.broadcastChannel = null), this.watchers.clear();
2076
+ }
2077
+ }
2078
+ class ws extends gs {
2079
+ /** Shared sync handles per path (OPFS allows only one handle per file) */
2080
+ openHandles = /* @__PURE__ */ new Map();
2081
+ /** Map of open file descriptors to their metadata */
2082
+ openFiles = /* @__PURE__ */ new Map();
2083
+ /** Next available file descriptor number */
2084
+ nextFd = 1;
2085
+ constructor(t) {
2086
+ super(t);
2087
+ }
2088
+ /**
2089
+ * Get file info by descriptor with validation
2090
+ * @private
2091
+ */
2092
+ _getFileDescriptor(t) {
2093
+ const e = this.openFiles.get(t);
2094
+ if (!e)
2095
+ throw new C("descriptor", `Invalid file descriptor: ${t}`);
2096
+ return e;
2097
+ }
2098
+ async readFile(t) {
2099
+ await this.mount();
2100
+ try {
2101
+ return await $(t, async () => {
2102
+ const e = await this.open(t);
2103
+ try {
2104
+ const { size: n } = await this.fstat(e), r = new Uint8Array(n);
2105
+ return n > 0 && await this.read(e, r, 0, n, 0), _(r, [r.buffer]);
2106
+ } finally {
2107
+ await this.close(e);
2108
+ }
2109
+ });
2110
+ } catch (e) {
2111
+ throw e instanceof w ? e : A(e, { path: t, isDirectory: !1 });
2112
+ }
2113
+ }
2114
+ async writeFile(t, e) {
2115
+ await this.mount();
2116
+ const n = e instanceof Uint8Array ? e : new Uint8Array(e);
2117
+ await $(t, async () => {
2118
+ const r = await this.exists(t), i = await this.open(t, { create: !0, truncate: !0 });
2119
+ try {
2120
+ await this.write(i, n, 0, n.length, null, !1), await this.fsync(i);
2121
+ } finally {
2122
+ await this.close(i);
2123
+ }
2124
+ await this.notifyChange({ path: t, type: r ? b.Changed : b.Added, isDirectory: !1 });
2125
+ });
2126
+ }
2127
+ async appendFile(t, e) {
2128
+ await this.mount();
2129
+ const n = e instanceof Uint8Array ? e : new Uint8Array(e);
2130
+ await $(t, async () => {
2131
+ const r = await this.open(t, { create: !0 });
2132
+ try {
2133
+ const { size: i } = await this.fstat(r);
2134
+ await this.write(r, n, 0, n.length, i, !1), await this.fsync(r);
2135
+ } finally {
2136
+ await this.close(r);
2137
+ }
2138
+ await this.notifyChange({ path: t, type: b.Changed, isDirectory: !1 });
2139
+ });
2140
+ }
2141
+ async writeStream(t, e, n) {
2142
+ return await this.mount(), $(t, async () => {
2143
+ const r = await this.exists(t), i = await this.open(t, { create: !0, truncate: !0 }), o = e.getReader();
2144
+ let a = 0;
2145
+ try {
2146
+ for (; ; ) {
2147
+ const { done: c, value: h } = await o.read();
2148
+ if (c)
2149
+ break;
2150
+ let l = 0;
2151
+ for (; l < h.byteLength; )
2152
+ l += await this.write(
2153
+ i,
2154
+ h,
2155
+ l,
2156
+ h.byteLength - l,
2157
+ null,
2158
+ !1
2159
+ );
2160
+ a += h.byteLength, await n?.(a);
2161
+ }
2162
+ await this.fsync(i);
2163
+ } catch (c) {
2164
+ throw await o.cancel(c).catch(() => {
2165
+ }), c;
2166
+ } finally {
2167
+ o.releaseLock(), await this.close(i);
2168
+ }
2169
+ return await this.notifyChange({
2170
+ path: t,
2171
+ type: r ? b.Changed : b.Added,
2172
+ isDirectory: !1
2173
+ }), a;
2174
+ });
2175
+ }
2176
+ async open(t, e) {
2177
+ await this.mount();
2178
+ const { create: n = !1, exclusive: r = !1, truncate: i = !1 } = e || {}, o = Y(Lt(t));
2179
+ try {
2180
+ return n && r ? await $(o, async () => {
2181
+ if (await this.exists(o))
2182
+ throw new rt(o);
2183
+ return this._openFile(o, n, i);
2184
+ }) : await this._openFile(o, n, i);
2185
+ } catch (a) {
2186
+ if (a instanceof w)
2187
+ throw a;
2188
+ const c = a && a.name === "TypeMismatchError";
2189
+ throw A(a, {
2190
+ path: o,
2191
+ isDirectory: !!c
2192
+ });
2193
+ }
2194
+ }
2195
+ /**
2196
+ * Internal method to open a file (without locking)
2197
+ *
2198
+ * Multiple FDs for the same path share one sync access handle (OPFS limit),
2199
+ * with independent per-FD positions — similar to Node.js.
2200
+ * @private
2201
+ */
2202
+ async _openFile(t, e, n) {
2203
+ let r = this.openHandles.get(t);
2204
+ if (!r) {
2205
+ const o = await this.getFileHandle(t, e);
2206
+ try {
2207
+ await o.getFile();
2208
+ } catch (c) {
2209
+ throw A(c, { path: t, isDirectory: !0 });
2210
+ }
2211
+ const a = await ps(o, t);
2212
+ r = { fileHandle: o, syncHandle: a, refCount: 0 }, this.openHandles.set(t, r);
2213
+ }
2214
+ r.refCount++, n && (r.syncHandle.truncate(0), r.syncHandle.flush());
2215
+ const i = this.nextFd++;
2216
+ return this.openFiles.set(i, {
2217
+ path: t,
2218
+ fileHandle: r.fileHandle,
2219
+ syncHandle: r.syncHandle,
2220
+ position: 0
2221
+ }), i;
2222
+ }
2223
+ async close(t) {
2224
+ const e = this._getFileDescriptor(t);
2225
+ this.openFiles.delete(t);
2226
+ const n = this.openHandles.get(e.path);
2227
+ n && (n.refCount--, n.refCount <= 0 && (St(t, n.syncHandle, e.path), this.openHandles.delete(e.path)));
2228
+ }
2229
+ async read(t, e, n, r, i) {
2230
+ const o = this._getFileDescriptor(t);
2231
+ Et(e.length, n, r, i);
2232
+ try {
2233
+ const a = i ?? o.position, c = o.syncHandle.getSize(), { isEOF: h, actualLength: l } = ds(a, r, c);
2234
+ if (h)
2235
+ return _({ bytesRead: 0, buffer: e }, [e.buffer]);
2236
+ const f = e.subarray(n, n + l), u = o.syncHandle.read(f, { at: a });
2237
+ return i == null && (o.position = a + u), _({ bytesRead: u, buffer: e }, [e.buffer]);
2238
+ } catch (a) {
2239
+ throw z("read", t, o.path, a);
2240
+ }
2241
+ }
2242
+ async write(t, e, n = 0, r, i, o = !0) {
2243
+ const a = this._getFileDescriptor(t), c = r ?? e.length - n;
2244
+ Et(e.length, n, c, i);
2245
+ try {
2246
+ const h = i ?? a.position, l = e.subarray(n, n + c), f = a.syncHandle.write(l, { at: h });
2247
+ return (i == null || i === a.position) && (a.position = h + f), o && await this.notifyChange({ path: a.path, type: b.Changed, isDirectory: !1 }), f;
2248
+ } catch (h) {
2249
+ throw z("write", t, a.path, h);
2250
+ }
2251
+ }
2252
+ async fstat(t) {
2253
+ const e = this._getFileDescriptor(t);
2254
+ return this.stat(e.path);
2255
+ }
2256
+ async ftruncate(t, e = 0) {
2257
+ const n = this._getFileDescriptor(t);
2258
+ if (e < 0 || !Number.isInteger(e))
2259
+ throw new C("argument", "Invalid size");
2260
+ try {
2261
+ n.syncHandle.truncate(e), n.syncHandle.flush(), n.position > e && (n.position = e), await this.notifyChange({ path: n.path, type: b.Changed, isDirectory: !1 });
2262
+ } catch (r) {
2263
+ throw z("truncate", t, n.path, r);
2264
+ }
2265
+ }
2266
+ async fsync(t) {
2267
+ const e = this._getFileDescriptor(t);
2268
+ try {
2269
+ e.syncHandle.flush();
2270
+ } catch (n) {
2271
+ throw z("sync", t, e.path, n);
2272
+ }
2273
+ }
2274
+ dispose() {
2275
+ for (const [t, e] of this.openHandles)
2276
+ St(-1, e.syncHandle, t);
2277
+ this.openHandles.clear(), this.openFiles.clear(), this.nextFd = 1, super.dispose();
2278
+ }
2279
+ }
2280
+ ot(new ws());
2281
+ //# sourceMappingURL=dedicated.worker.js.map