opfs-worker 2.0.0 → 2.1.1

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