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,2355 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2019 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ const bt = Symbol("Comlink.proxy"), Wt = Symbol("Comlink.endpoint"), jt = Symbol("Comlink.releaseProxy"), X = Symbol("Comlink.finalizer"), j = Symbol("Comlink.thrown"), Ot = (s) => typeof s == "object" && s !== null || typeof s == "function", _t = {
7
+ canHandle: (s) => Ot(s) && s[bt],
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(), qt(s);
14
+ }
15
+ }, Bt = {
16
+ canHandle: (s) => Ot(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
+ }, Dt = /* @__PURE__ */ new Map([
32
+ ["proxy", _t],
33
+ ["throw", Bt]
34
+ ]);
35
+ function Ut(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 (!Ut(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 = Xt(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), vt(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 Gt(s) {
97
+ return s.constructor.name === "MessagePort";
98
+ }
99
+ function vt(s) {
100
+ Gt(s) && s.close();
101
+ }
102
+ function qt(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
+ vt(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 Vt(s, t) {
133
+ const e = (U.get(t) || 0) + 1;
134
+ U.set(t, e), G && G.register(s, t, s);
135
+ }
136
+ function Yt(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 === jt)
145
+ return () => {
146
+ Yt(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 === Wt)
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 Vt(i, s), i;
195
+ }
196
+ function Zt(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]), Zt(t.map((e) => e[1]))];
202
+ }
203
+ const Ct = /* @__PURE__ */ new WeakMap();
204
+ function _(s, t) {
205
+ return Ct.set(s, t), s;
206
+ }
207
+ function Xt(s) {
208
+ return Object.assign(s, { [bt]: !0 });
209
+ }
210
+ function q(s) {
211
+ for (const [t, e] of Dt)
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
+ Ct.get(s) || []
229
+ ];
230
+ }
231
+ function N(s) {
232
+ switch (s.type) {
233
+ case "HANDLER":
234
+ return Dt.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 = Jt();
242
+ t.set(i, r), s.start && s.start(), s.postMessage(Object.assign({ id: i }, e), n);
243
+ });
244
+ }
245
+ function Jt() {
246
+ return new Array(4).fill(0).map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)).join("-");
247
+ }
248
+ var O = /* @__PURE__ */ ((s) => (s.Added = "added", s.Changed = "changed", s.Removed = "removed", s))(O || {});
249
+ const Qt = {
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 = Qt[e] || -1, this.path = n, this.syscall = r;
287
+ }
288
+ }
289
+ class Kt extends w {
290
+ constructor(t) {
291
+ super("OPFS is not supported in this browser", "ENOTSUP", void 0, void 0, t);
292
+ }
293
+ }
294
+ class te 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 ee extends w {
310
+ constructor(t, e, n) {
311
+ super(`Permission denied for ${e} on: ${t}`, "EACCES", t, e, n);
312
+ }
313
+ }
314
+ class se extends w {
315
+ constructor(t, e, n) {
316
+ super(t, "ENOSPC", e, "write", n);
317
+ }
318
+ }
319
+ class ne 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 re 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 Nt 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 ie 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 b(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 ne(e || "unknown", s);
390
+ case "QuotaExceededError":
391
+ return new se(`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 ee(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 re(e || "unknown", s);
403
+ case "OperationError":
404
+ return new ut(`Operation failed: ${e || "unknown"}`, e, s);
405
+ case "TypeError":
406
+ return new Nt(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 Ft = (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 && oe(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
+ }, oe = (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
+ }, Mt = "\0SLASH" + Math.random() + "\0", $t = "\0OPEN" + Math.random() + "\0", at = "\0CLOSE" + Math.random() + "\0", Tt = "\0COMMA" + Math.random() + "\0", Pt = "\0PERIOD" + Math.random() + "\0", ae = new RegExp(Mt, "g"), ce = new RegExp($t, "g"), le = new RegExp(at, "g"), he = new RegExp(Tt, "g"), ue = new RegExp(Pt, "g"), fe = /\\\\/g, de = /\\{/g, pe = /\\}/g, ge = /\\,/g, we = /\\./g;
442
+ function Q(s) {
443
+ return isNaN(s) ? s.charCodeAt(0) : parseInt(s, 10);
444
+ }
445
+ function ye(s) {
446
+ return s.replace(fe, Mt).replace(de, $t).replace(pe, at).replace(ge, Tt).replace(we, Pt);
447
+ }
448
+ function me(s) {
449
+ return s.replace(ae, "\\").replace(ce, "{").replace(le, "}").replace(he, ",").replace(ue, ".");
450
+ }
451
+ function Rt(s) {
452
+ if (!s)
453
+ return [""];
454
+ const t = [], e = Ft("{", "}", 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 = Rt(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 Ee(s) {
463
+ return s ? (s.slice(0, 2) === "{}" && (s = "\\{\\}" + s.slice(2)), I(ye(s), !0).map(me)) : [];
464
+ }
465
+ function Se(s) {
466
+ return "{" + s + "}";
467
+ }
468
+ function xe(s) {
469
+ return /^-?0\d/.test(s);
470
+ }
471
+ function be(s, t) {
472
+ return s <= t;
473
+ }
474
+ function Oe(s, t) {
475
+ return s >= t;
476
+ }
477
+ function I(s, t) {
478
+ const e = [], n = Ft("{", "}", s);
479
+ if (!n)
480
+ return [s];
481
+ const r = n.pre, i = n.post.length ? I(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, I(s)) : [s];
491
+ let l;
492
+ if (c)
493
+ l = n.body.split(/\.\./);
494
+ else if (l = Rt(n.body), l.length === 1 && l[0] !== void 0 && (l = I(l[0], !1).map(Se), 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 = be;
500
+ d < u && (p *= -1, S = Oe);
501
+ const T = l.some(xe);
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, I(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 De = 1024 * 64, V = (s) => {
530
+ if (typeof s != "string")
531
+ throw new TypeError("invalid pattern");
532
+ if (s.length > De)
533
+ throw new TypeError("pattern is too long");
534
+ }, ve = {
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(""), Ce = (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, [A, T, x]] of Object.entries(ve))
571
+ if (s.startsWith(S, i)) {
572
+ if (f)
573
+ return ["$.", !1, s.length - e, !0];
574
+ i += S.length, x ? r.push(A) : n.push(A), 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
+ }, k = (s, { windowsPathsNoEscape: t = !1 } = {}) => t ? s.replace(/\[([^\/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1"), Ne = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]), pt = (s) => Ne.has(s), Fe = "(?!(?:^|/)\\.\\.?(?:$|/))", W = "(?!\\.)", Me = /* @__PURE__ */ new Set(["[", "."]), $e = /* @__PURE__ */ new Set(["..", "."]), Te = new Set("().*{}+?[]^$\\!"), Pe = (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, A] = typeof d == "string" ? E.#p(d, this.#n, c) : d.toRegExpSource(t);
856
+ return this.#n = this.#n || S, this.#i = this.#i || A, 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 = Me, 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 ? Fe : S ? W : "";
867
+ }
868
+ let f = "";
869
+ return this.isEnd() && this.#s.#a && this.#e?.type === "!" && (f = "(?:$|\\/)"), [
870
+ l + h + f,
871
+ k(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, k(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
+ k(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 += (Te.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] = Ce(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 += Pe(c);
937
+ }
938
+ return [i, k(t), !!e, o];
939
+ }
940
+ }
941
+ const Re = (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)), Ie = /^\*+([^+@!?\*\[\(]*)$/, ke = (s) => (t) => !t.startsWith(".") && t.endsWith(s), He = (s) => (t) => t.endsWith(s), Le = (s) => (s = s.toLowerCase(), (t) => !t.startsWith(".") && t.toLowerCase().endsWith(s)), ze = (s) => (s = s.toLowerCase(), (t) => t.toLowerCase().endsWith(s)), We = /^\*+\.\*+$/, je = (s) => !s.startsWith(".") && s.includes("."), _e = (s) => s !== "." && s !== ".." && s.includes("."), Be = /^\.\*+$/, Ue = (s) => s !== "." && s !== ".." && s.startsWith("."), Ge = /^\*+$/, qe = (s) => s.length !== 0 && !s.startsWith("."), Ve = (s) => s.length !== 0 && s !== "." && s !== "..", Ye = /^\?+([^+@!?\*\[\(]*)?$/, Ze = ([s, t = ""]) => {
942
+ const e = It([s]);
943
+ return t ? (t = t.toLowerCase(), (n) => e(n) && n.toLowerCase().endsWith(t)) : e;
944
+ }, Xe = ([s, t = ""]) => {
945
+ const e = kt([s]);
946
+ return t ? (t = t.toLowerCase(), (n) => e(n) && n.toLowerCase().endsWith(t)) : e;
947
+ }, Je = ([s, t = ""]) => {
948
+ const e = kt([s]);
949
+ return t ? (n) => e(n) && n.endsWith(t) : e;
950
+ }, Qe = ([s, t = ""]) => {
951
+ const e = It([s]);
952
+ return t ? (n) => e(n) && n.endsWith(t) : e;
953
+ }, It = ([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
+ }, Ht = 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
+ }, Ke = Ht === "win32" ? yt.win32.sep : yt.posix.sep;
963
+ m.sep = Ke;
964
+ const v = Symbol("globstar **");
965
+ m.GLOBSTAR = v;
966
+ const ts = "[^/]", es = ts + "*?", ss = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?", ns = "(?:(?!(?:\\/|^)\\.).)*?", rs = (s, t = {}) => (e) => m(e, s, t);
967
+ m.filter = rs;
968
+ const D = (s, t = {}) => Object.assign({}, s, t), is = (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, D(s, i)), {
973
+ Minimatch: class extends t.Minimatch {
974
+ constructor(r, i = {}) {
975
+ super(r, D(s, i));
976
+ }
977
+ static defaults(r) {
978
+ return t.defaults(D(s, r)).Minimatch;
979
+ }
980
+ },
981
+ AST: class extends t.AST {
982
+ /* c8 ignore start */
983
+ constructor(r, i, o = {}) {
984
+ super(r, i, D(s, o));
985
+ }
986
+ /* c8 ignore stop */
987
+ static fromGlob(r, i = {}) {
988
+ return t.AST.fromGlob(r, D(s, i));
989
+ }
990
+ },
991
+ unescape: (n, r = {}) => t.unescape(n, D(s, r)),
992
+ escape: (n, r = {}) => t.escape(n, D(s, r)),
993
+ filter: (n, r = {}) => t.filter(n, D(s, r)),
994
+ defaults: (n) => t.defaults(D(s, n)),
995
+ makeRe: (n, r = {}) => t.makeRe(n, D(s, r)),
996
+ braceExpand: (n, r = {}) => t.braceExpand(n, D(s, r)),
997
+ match: (n, r, i = {}) => t.match(n, r, D(s, i)),
998
+ sep: t.sep,
999
+ GLOBSTAR: v
1000
+ });
1001
+ };
1002
+ m.defaults = is;
1003
+ const Lt = (s, t = {}) => (V(s), t.nobrace || !/\{(?:(?!\{).)*\}/.test(s) ? [s] : Ee(s));
1004
+ m.braceExpand = Lt;
1005
+ const os = (s, t = {}) => new Z(s, t).makeRe();
1006
+ m.makeRe = os;
1007
+ const as = (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 = as;
1012
+ const mt = /[?*]|[+@!]\(.*?\)|\[|\]/, cs = (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 || Ht, 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]), A = typeof e[0] == "string" && /^[a-z]:$/i.test(e[0]), T = !A && 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 : A ? 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 === v) {
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 Lt(this.pattern, this.options);
1290
+ }
1291
+ parse(t) {
1292
+ V(t);
1293
+ const e = this.options;
1294
+ if (t === "**")
1295
+ return v;
1296
+ if (t === "")
1297
+ return "";
1298
+ let n, r = null;
1299
+ (n = t.match(Ge)) ? r = e.dot ? Ve : qe : (n = t.match(Ie)) ? r = (e.nocase ? e.dot ? ze : Le : e.dot ? He : ke)(n[1]) : (n = t.match(Ye)) ? r = (e.nocase ? e.dot ? Xe : Ze : e.dot ? Je : Qe)(n) : (n = t.match(We)) ? r = e.dot ? _e : je : (n = t.match(Be)) && (r = Ue);
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 ? es : e.dot ? ss : ns, 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" ? cs(l) : l === v ? v : l._src;
1316
+ });
1317
+ return h.forEach((l, f) => {
1318
+ const u = h[f + 1], d = h[f - 1];
1319
+ l !== v || d === v || (d === void 0 ? u !== void 0 && u !== v ? h[f + 1] = "(?:\\/|" + n + "\\/)?" + u : h[f] = n : u === void 0 ? h[f - 1] = d + "(?:\\/|" + n + ")?" : u !== v && (h[f - 1] = d + "(?:\\/|\\/" + n + "\\/)" + u, h[f + 1] = v));
1320
+ }), h.filter((l) => l !== v).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 = Re;
1366
+ m.unescape = k;
1367
+ function ls() {
1368
+ if (!("storage" in navigator) || !("getDirectory" in navigator.storage))
1369
+ throw new Kt();
1370
+ }
1371
+ async function M(s, t) {
1372
+ return typeof navigator < "u" && navigator.locks?.request ? navigator.locks.request(`opfs:${s.replace(/\/+/g, "/")}`, { mode: "exclusive" }, t) : t();
1373
+ }
1374
+ function $(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 = $(s);
1382
+ return t[t.length - 1] || "";
1383
+ }
1384
+ function K(s) {
1385
+ const t = $(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 hs(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 zt(s) {
1401
+ const t = Y(s), e = $(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 us(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 fs(s, t, e = {}) {
1419
+ const n = it(t);
1420
+ return M(t, async () => {
1421
+ const r = e.recursive ?? !1, i = e.force ?? !1;
1422
+ try {
1423
+ await s.removeEntry(n, { recursive: r });
1424
+ } catch (o) {
1425
+ if (o.name === "NotFoundError" && i)
1426
+ return;
1427
+ const a = o.name === "TypeMismatchError" && !r;
1428
+ throw b(o, {
1429
+ path: t,
1430
+ operation: "remove",
1431
+ isDirectory: a
1432
+ });
1433
+ }
1434
+ });
1435
+ }
1436
+ function Et(s, t, e, n) {
1437
+ if (!Number.isInteger(t) || !Number.isInteger(e))
1438
+ throw new C("argument", "Invalid offset or length");
1439
+ if (t < 0 || e < 0)
1440
+ throw new C("argument", "Negative offset or length not allowed");
1441
+ if (t + e > s)
1442
+ throw new C("overflow", "Operation would overflow buffer");
1443
+ if (n != null && (!Number.isInteger(n) || n < 0))
1444
+ throw new C("argument", "Invalid position");
1445
+ }
1446
+ function St(s, t, e) {
1447
+ try {
1448
+ t.flush(), t.close();
1449
+ } catch (n) {
1450
+ console.warn(`Warning: Failed to properly close file descriptor ${s} (${e}):`, n);
1451
+ }
1452
+ }
1453
+ function ds(s, t, e) {
1454
+ if (s >= e)
1455
+ return { isEOF: !0, actualLength: 0 };
1456
+ const n = Math.min(t, e - s);
1457
+ return n <= 0 ? { isEOF: !0, actualLength: 0 } : { isEOF: !1, actualLength: n };
1458
+ }
1459
+ async function ps(s, t) {
1460
+ try {
1461
+ return await s.createSyncAccessHandle();
1462
+ } catch (e) {
1463
+ throw b(e, { path: t, isDirectory: !1 });
1464
+ }
1465
+ }
1466
+ class gs {
1467
+ /** Root directory handle for the file system */
1468
+ root;
1469
+ /** Map of watched paths and options */
1470
+ watchers = /* @__PURE__ */ new Map();
1471
+ /** Promise to prevent concurrent mount operations */
1472
+ mountingPromise = null;
1473
+ /** BroadcastChannel instance for sending events */
1474
+ broadcastChannel = null;
1475
+ /** Configuration options */
1476
+ options = {
1477
+ root: "/",
1478
+ namespace: "",
1479
+ maxFileSize: 50 * 1024 * 1024,
1480
+ hashAlgorithm: "etag",
1481
+ broadcastChannel: "opfs-worker"
1482
+ };
1483
+ /**
1484
+ * Notify about internal changes to the file system
1485
+ *
1486
+ * This method is called by internal operations to notify clients about
1487
+ * changes, even when no specific paths are being watched.
1488
+ *
1489
+ * @param event - The event describing the change
1490
+ */
1491
+ async notifyChange(t) {
1492
+ if (!this.options.broadcastChannel)
1493
+ return;
1494
+ const e = t.path;
1495
+ 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))))
1496
+ return;
1497
+ let r;
1498
+ if (this.options.hashAlgorithm)
1499
+ try {
1500
+ r = (await this.stat(e)).hash;
1501
+ } catch {
1502
+ }
1503
+ try {
1504
+ this.broadcastChannel || (this.broadcastChannel = new BroadcastChannel(this.options.broadcastChannel));
1505
+ const i = {
1506
+ namespace: this.options.namespace,
1507
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1508
+ ...t,
1509
+ ...r && { hash: r }
1510
+ };
1511
+ this.broadcastChannel.postMessage(i);
1512
+ } catch (i) {
1513
+ console.warn("Failed to send event via BroadcastChannel:", i);
1514
+ }
1515
+ }
1516
+ constructor(t) {
1517
+ ls(), t && this.setOptions(t);
1518
+ }
1519
+ /**
1520
+ * Initialize the file system within a given directory.
1521
+ * If no root is specified, uses the OPFS root directory.
1522
+ */
1523
+ async mount() {
1524
+ const t = this.options.root;
1525
+ return this.mountingPromise && await this.mountingPromise, this.mountingPromise = new Promise(async (e, n) => {
1526
+ try {
1527
+ const r = await navigator.storage.getDirectory();
1528
+ this.root = t === "/" ? r : await this.getDirectoryHandle(t, !0, r), e(!0);
1529
+ } catch (r) {
1530
+ n(new ie(t, r));
1531
+ } finally {
1532
+ this.mountingPromise = null;
1533
+ }
1534
+ }), this.mountingPromise;
1535
+ }
1536
+ /**
1537
+ * Update configuration options
1538
+ *
1539
+ * @param options - Configuration options to update
1540
+ * @param options.root - Root path for the file system
1541
+ * @param options.watchInterval - Polling interval in milliseconds for file watching
1542
+ * @param options.hashAlgorithm - Hash algorithm for file hashing
1543
+ * @param options.maxFileSize - Maximum file size for hashing in bytes
1544
+ * @param options.broadcastChannel - Custom name for the broadcast channel
1545
+ */
1546
+ async setOptions(t) {
1547
+ 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());
1548
+ }
1549
+ /**
1550
+ * Get a directory handle from a path
1551
+ *
1552
+ * Navigates through the directory structure to find or create a directory
1553
+ * at the specified path.
1554
+ *
1555
+ * @param path - The path to the directory (string or array of segments)
1556
+ * @param create - Whether to create the directory if it doesn't exist (default: false)
1557
+ * @param from - The directory to start from (default: root directory)
1558
+ * @returns Promise that resolves to the directory handle
1559
+ * @throws {OPFSError} If the directory cannot be accessed or created
1560
+ *
1561
+ * @example
1562
+ * ```typescript
1563
+ * const docsDir = await fs.getDirectoryHandle('/users/john/documents', true);
1564
+ * const docsDir2 = await fs.getDirectoryHandle(['users', 'john', 'documents'], true);
1565
+ * ```
1566
+ */
1567
+ async getDirectoryHandle(t, e = !1, n = this.root) {
1568
+ const r = Array.isArray(t) ? t : $(t);
1569
+ let i = n;
1570
+ for (const o of r)
1571
+ i = await i.getDirectoryHandle(o, { create: e });
1572
+ return i;
1573
+ }
1574
+ /**
1575
+ * Get a file handle from a path
1576
+ *
1577
+ * Navigates to the parent directory and retrieves or creates a file handle
1578
+ * for the specified file path.
1579
+ *
1580
+ * @param path - The path to the file (string or array of segments)
1581
+ * @param create - Whether to create the file if it doesn't exist (default: false)
1582
+ * @param _from - The directory to start from (default: root directory)
1583
+ * @returns Promise that resolves to the file handle
1584
+ * @throws {PathError} If the path is empty
1585
+ * @throws {OPFSError} If the file cannot be accessed or created
1586
+ *
1587
+ * @example
1588
+ * ```typescript
1589
+ * const fileHandle = await fs.getFileHandle('/config/settings.json', true);
1590
+ * const fileHandle2 = await fs.getFileHandle(['config', 'settings.json'], true);
1591
+ * ```
1592
+ */
1593
+ async getFileHandle(t, e = !1, n = this.root) {
1594
+ const r = $(t);
1595
+ if (r.length === 0)
1596
+ throw new te("Path must not be empty", Array.isArray(t) ? t.join("/") : t);
1597
+ const i = r.pop();
1598
+ return (await this.getDirectoryHandle(r, e, n)).getFileHandle(i, { create: e });
1599
+ }
1600
+ /**
1601
+ * Get a complete index of all files and directories in the file system
1602
+ *
1603
+ * This method recursively traverses the entire file system and returns
1604
+ * a Map containing FileStat objects for every file and directory.
1605
+ *
1606
+ * @returns Promise that resolves to a Map of paths to FileStat objects
1607
+ * @throws {OPFSError} If the file system is not mounted
1608
+ *
1609
+ * @example
1610
+ * ```typescript
1611
+ * const index = await fs.index();
1612
+ * const fileStats = index.get('/data/config.json');
1613
+ * if (fileStats) {
1614
+ * console.log(`File size: ${fileStats.size} bytes`);
1615
+ * if (fileStats.hash) console.log(`Hash: ${fileStats.hash}`);
1616
+ * }
1617
+ * ```
1618
+ */
1619
+ async index() {
1620
+ const t = /* @__PURE__ */ new Map(), e = async (n) => {
1621
+ const r = await this.readDir(n);
1622
+ for (const i of r) {
1623
+ const o = `${n === "/" ? "" : n}/${i.name}`;
1624
+ try {
1625
+ const a = await this.stat(o);
1626
+ t.set(o, a), a.isDirectory && await e(o);
1627
+ } catch (a) {
1628
+ console.warn(`Skipping broken entry: ${o}`, a);
1629
+ }
1630
+ }
1631
+ };
1632
+ return t.set("/", {
1633
+ kind: "directory",
1634
+ size: 0,
1635
+ mtime: (/* @__PURE__ */ new Date(0)).toISOString(),
1636
+ ctime: (/* @__PURE__ */ new Date(0)).toISOString(),
1637
+ isFile: !1,
1638
+ isDirectory: !0
1639
+ }), await e("/"), t;
1640
+ }
1641
+ /**
1642
+ * Create a directory
1643
+ *
1644
+ * Creates a new directory at the specified path. If the recursive option
1645
+ * is enabled, parent directories will be created as needed.
1646
+ *
1647
+ * @param path - The path where the directory should be created
1648
+ * @param options - Options for directory creation
1649
+ * @param options.recursive - Whether to create parent directories if they don't exist (default: false)
1650
+ * @returns Promise that resolves when the directory is created
1651
+ * @throws {OPFSError} If the directory cannot be created
1652
+ *
1653
+ * @example
1654
+ * ```typescript
1655
+ * // Create a single directory
1656
+ * await fs.mkdir('/users/john');
1657
+ *
1658
+ * // Create nested directories
1659
+ * await fs.mkdir('/users/john/documents/projects', { recursive: true });
1660
+ * ```
1661
+ */
1662
+ async mkdir(t, e) {
1663
+ await this.mount();
1664
+ const n = e?.recursive ?? !1, r = $(t);
1665
+ let i = this.root;
1666
+ for (let o = 0; o < r.length; o++) {
1667
+ const a = r[o];
1668
+ try {
1669
+ i = await i.getDirectoryHandle(a, { create: n || o === r.length - 1 });
1670
+ } catch (c) {
1671
+ throw c.name === "NotFoundError" ? b(c, {
1672
+ path: lt(r.slice(0, o + 1)),
1673
+ existenceType: "directory"
1674
+ }) : c.name === "TypeMismatchError" ? b(c, { path: a, isDirectory: !1 }) : new J("create directory", a, c);
1675
+ }
1676
+ }
1677
+ await this.notifyChange({ path: t, type: O.Added, isDirectory: !0 });
1678
+ }
1679
+ /**
1680
+ * Get file or directory statistics
1681
+ *
1682
+ * Returns detailed information about a file or directory, including
1683
+ * size, modification time, and optionally a hash of the file content.
1684
+ *
1685
+ * @param path - The path to the file or directory
1686
+ * @returns Promise that resolves to FileStat object
1687
+ * @throws {OPFSError} If the path does not exist or cannot be accessed
1688
+ *
1689
+ * @example
1690
+ * ```typescript
1691
+ * const stats = await fs.stat('/data/config.json');
1692
+ * console.log(`File size: ${stats.size} bytes`);
1693
+ * console.log(`Last modified: ${stats.mtime}`);
1694
+ *
1695
+ * // If hashing is enabled, hash will be included
1696
+ * if (stats.hash) {
1697
+ * console.log(`Hash: ${stats.hash}`);
1698
+ * }
1699
+ * ```
1700
+ */
1701
+ async stat(t) {
1702
+ if (await this.mount(), t === "/")
1703
+ return {
1704
+ kind: "directory",
1705
+ size: 0,
1706
+ mtime: (/* @__PURE__ */ new Date(0)).toISOString(),
1707
+ ctime: (/* @__PURE__ */ new Date(0)).toISOString(),
1708
+ isFile: !1,
1709
+ isDirectory: !0
1710
+ };
1711
+ const e = it(t);
1712
+ let n;
1713
+ try {
1714
+ n = await this.getDirectoryHandle(K(t), !1);
1715
+ const r = this.options.hashAlgorithm, o = await (await n.getFileHandle(e, { create: !1 })).getFile(), a = {
1716
+ kind: "file",
1717
+ size: o.size,
1718
+ mtime: new Date(o.lastModified).toISOString(),
1719
+ ctime: new Date(o.lastModified).toISOString(),
1720
+ isFile: !0,
1721
+ isDirectory: !1
1722
+ };
1723
+ if (r === "etag")
1724
+ a.hash = `${o.lastModified.toString(36)}-${o.size.toString(36)}`;
1725
+ else if (typeof r == "string")
1726
+ try {
1727
+ const c = await us(o, r, this.options.maxFileSize);
1728
+ a.hash = c;
1729
+ } catch (c) {
1730
+ console.warn(`Failed to calculate hash for ${t}:`, c);
1731
+ }
1732
+ return a;
1733
+ } catch (r) {
1734
+ if (r.name === "NotFoundError")
1735
+ throw new B("file", t, r);
1736
+ if (r.name !== "TypeMismatchError")
1737
+ throw new J("stat", t, r);
1738
+ }
1739
+ try {
1740
+ return await n.getDirectoryHandle(e, { create: !1 }), {
1741
+ kind: "directory",
1742
+ size: 0,
1743
+ mtime: (/* @__PURE__ */ new Date(0)).toISOString(),
1744
+ ctime: (/* @__PURE__ */ new Date(0)).toISOString(),
1745
+ isFile: !1,
1746
+ isDirectory: !0
1747
+ };
1748
+ } catch (r) {
1749
+ throw new J("stat", t, r);
1750
+ }
1751
+ }
1752
+ /**
1753
+ * Read a directory's contents
1754
+ *
1755
+ * Lists all files and subdirectories within the specified directory.
1756
+ *
1757
+ * @param path - The path to the directory to read
1758
+ * @returns Promise that resolves to an array of detailed file/directory information
1759
+ * @throws {OPFSError} If the directory does not exist or cannot be accessed
1760
+ *
1761
+ * @example
1762
+ * ```typescript
1763
+ * // Get detailed information about files and directories
1764
+ * const detailed = await fs.readDir('/users/john/documents');
1765
+ * detailed.forEach(item => {
1766
+ * console.log(`${item.name} - ${item.isFile ? 'file' : 'directory'}`);
1767
+ * });
1768
+ * ```
1769
+ */
1770
+ async readDir(t) {
1771
+ await this.mount();
1772
+ const e = await this.getDirectoryHandle(t, !1), n = [];
1773
+ for await (const [r, i] of e.entries()) {
1774
+ const o = i.kind === "file";
1775
+ n.push({
1776
+ name: r,
1777
+ kind: i.kind,
1778
+ isFile: o,
1779
+ isDirectory: !o
1780
+ });
1781
+ }
1782
+ return n;
1783
+ }
1784
+ /**
1785
+ * Check if a file or directory exists
1786
+ *
1787
+ * Verifies if a file or directory exists at the specified path.
1788
+ *
1789
+ * @param path - The path to check
1790
+ * @returns Promise that resolves to true if the file or directory exists, false otherwise
1791
+ *
1792
+ * @example
1793
+ * ```typescript
1794
+ * const exists = await fs.exists('/config/settings.json');
1795
+ * console.log(`File exists: ${exists}`);
1796
+ * ```
1797
+ */
1798
+ async exists(t) {
1799
+ if (await this.mount(), t === "/")
1800
+ return !0;
1801
+ const e = it(t);
1802
+ let n = null;
1803
+ try {
1804
+ n = await this.getDirectoryHandle(K(t), !1);
1805
+ } catch (r) {
1806
+ if (n = null, r.name !== "NotFoundError" && r.name !== "TypeMismatchError")
1807
+ throw r;
1808
+ }
1809
+ if (!n || !e)
1810
+ return !1;
1811
+ try {
1812
+ return await n.getFileHandle(e, { create: !1 }), !0;
1813
+ } catch (r) {
1814
+ if (r.name !== "NotFoundError" && r.name !== "TypeMismatchError")
1815
+ throw r;
1816
+ try {
1817
+ return await n.getDirectoryHandle(e, { create: !1 }), !0;
1818
+ } catch (i) {
1819
+ if (i.name !== "NotFoundError" && i.name !== "TypeMismatchError")
1820
+ throw i;
1821
+ return !1;
1822
+ }
1823
+ }
1824
+ }
1825
+ /**
1826
+ * Clear all contents of a directory without removing the directory itself
1827
+ *
1828
+ * Removes all files and subdirectories within the specified directory,
1829
+ * but keeps the directory itself.
1830
+ *
1831
+ * @param path - The path to the directory to clear (default: '/')
1832
+ * @returns Promise that resolves when all contents are removed
1833
+ * @throws {OPFSError} If the operation fails
1834
+ *
1835
+ * @example
1836
+ * ```typescript
1837
+ * // Clear root directory contents
1838
+ * await fs.clear('/');
1839
+ *
1840
+ * // Clear specific directory contents
1841
+ * await fs.clear('/data');
1842
+ * ```
1843
+ */
1844
+ async clear(t = "/") {
1845
+ await this.mount();
1846
+ try {
1847
+ const e = await this.readDir(t);
1848
+ for (const n of e) {
1849
+ const r = `${t === "/" ? "" : t}/${n.name}`;
1850
+ await this.remove(r, { recursive: !0 });
1851
+ }
1852
+ await this.notifyChange({ path: t, type: O.Changed, isDirectory: !0 });
1853
+ } catch (e) {
1854
+ throw e instanceof w ? e : b(e, { path: t, isDirectory: !0 });
1855
+ }
1856
+ }
1857
+ /**
1858
+ * Remove files and directories
1859
+ *
1860
+ * Removes files and directories. Similar to Node.js fs.rm().
1861
+ *
1862
+ * @param path - The path to remove
1863
+ * @param options - Options for removal
1864
+ * @param options.recursive - Whether to remove directories and their contents recursively (default: false)
1865
+ * @param options.force - Whether to ignore errors if the path doesn't exist (default: false)
1866
+ * @returns Promise that resolves when the removal is complete
1867
+ * @throws {OPFSError} If the removal fails
1868
+ *
1869
+ * @example
1870
+ * ```typescript
1871
+ * // Remove a file
1872
+ * await fs.rm('/path/to/file.txt');
1873
+ *
1874
+ * // Remove a directory and all its contents
1875
+ * await fs.rm('/path/to/directory', { recursive: true });
1876
+ *
1877
+ * // Remove with force (ignore if doesn't exist)
1878
+ * await fs.rm('/maybe/exists', { force: true });
1879
+ * ```
1880
+ */
1881
+ async remove(t, e) {
1882
+ if (await this.mount(), t === "/")
1883
+ throw new nt("EROOT", t);
1884
+ const { recursive: n = !1, force: r = !1 } = e || {}, i = await this.getDirectoryHandle(K(t), !1), o = await this.stat(t);
1885
+ await fs(i, t, { recursive: n, force: r }), await this.notifyChange({ path: t, type: O.Removed, isDirectory: o.isDirectory });
1886
+ }
1887
+ /**
1888
+ * Resolve a path to an absolute path
1889
+ *
1890
+ * Resolves relative paths and normalizes path segments (like '..' and '.').
1891
+ * Similar to Node.js fs.realpath() but without symlink resolution since OPFS doesn't support symlinks.
1892
+ *
1893
+ * @param path - The path to resolve
1894
+ * @returns Promise that resolves to the absolute normalized path
1895
+ * @throws {FileNotFoundError} If the path does not exist
1896
+ * @throws {OPFSError} If path resolution fails
1897
+ *
1898
+ * @example
1899
+ * ```typescript
1900
+ * // Resolve relative path
1901
+ * const absolute = await fs.realpath('./config/../data/file.txt');
1902
+ * console.log(absolute); // '/data/file.txt'
1903
+ * ```
1904
+ */
1905
+ async realpath(t) {
1906
+ await this.mount();
1907
+ try {
1908
+ const e = zt(t);
1909
+ if (!await this.exists(e))
1910
+ throw new B("file", e);
1911
+ return e;
1912
+ } catch (e) {
1913
+ throw e instanceof w ? e : b(e, { path: t });
1914
+ }
1915
+ }
1916
+ /**
1917
+ * Rename a file or directory
1918
+ *
1919
+ * Changes the name of a file or directory. If the target path already exists,
1920
+ * it will be replaced only if overwrite option is enabled.
1921
+ *
1922
+ * @param oldPath - The current path of the file or directory
1923
+ * @param newPath - The new path for the file or directory
1924
+ * @param options - Options for renaming
1925
+ * @param options.overwrite - Whether to overwrite existing files (default: false)
1926
+ * @returns Promise that resolves when the rename operation is complete
1927
+ * @throws {OPFSError} If the rename operation fails
1928
+ *
1929
+ * @example
1930
+ * ```typescript
1931
+ * // Basic rename (fails if target exists)
1932
+ * await fs.rename('/old/path/file.txt', '/new/path/renamed.txt');
1933
+ *
1934
+ * // Rename with overwrite
1935
+ * await fs.rename('/old/path/file.txt', '/new/path/renamed.txt', { overwrite: true });
1936
+ * ```
1937
+ */
1938
+ async rename(t, e, n) {
1939
+ await this.mount();
1940
+ try {
1941
+ const r = n?.overwrite ?? !1, i = await this.stat(t);
1942
+ if (await this.exists(e) && !r)
1943
+ throw new rt(e);
1944
+ await this.copy(t, e, { recursive: !0, overwrite: r }), await this.remove(t, { recursive: !0 }), await this.notifyChange({ path: t, type: O.Removed, isDirectory: i.isDirectory }), await this.notifyChange({ path: e, type: O.Added, isDirectory: i.isDirectory });
1945
+ } catch (r) {
1946
+ throw r instanceof w ? r : b(r, { path: t });
1947
+ }
1948
+ }
1949
+ /**
1950
+ * Copy files and directories
1951
+ *
1952
+ * Copies files and directories. Similar to Node.js fs.cp().
1953
+ *
1954
+ * @param source - The source path to copy from
1955
+ * @param destination - The destination path to copy to
1956
+ * @param options - Options for copying
1957
+ * @param options.recursive - Whether to copy directories recursively (default: false)
1958
+ * @param options.overwrite - Whether to overwrite existing files (default: true)
1959
+ * @returns Promise that resolves when the copy operation is complete
1960
+ * @throws {OPFSError} If the copy operation fails
1961
+ *
1962
+ * @example
1963
+ * ```typescript
1964
+ * // Copy a file
1965
+ * await fs.copy('/source/file.txt', '/dest/file.txt');
1966
+ *
1967
+ * // Copy a directory and all its contents
1968
+ * await fs.copy('/source/dir', '/dest/dir', { recursive: true });
1969
+ *
1970
+ * // Copy without overwriting existing files
1971
+ * await fs.copy('/source', '/dest', { recursive: true, overwrite: false });
1972
+ * ```
1973
+ */
1974
+ async copy(t, e, n) {
1975
+ await this.mount();
1976
+ try {
1977
+ const r = n?.recursive ?? !1, i = n?.overwrite ?? !0;
1978
+ if (!await this.exists(t))
1979
+ throw new B("source", t);
1980
+ if (await this.exists(e) && !i)
1981
+ throw new rt(e);
1982
+ if ((await this.stat(t)).isFile) {
1983
+ const h = await this.readFile(t);
1984
+ await this.writeFile(e, h);
1985
+ } else {
1986
+ if (!r)
1987
+ throw new st("directory", t);
1988
+ await this.mkdir(e, { recursive: !0 });
1989
+ const h = await this.readDir(t);
1990
+ for (const l of h) {
1991
+ const f = `${t}/${l.name}`, u = `${e}/${l.name}`;
1992
+ await this.copy(f, u, { recursive: !0, overwrite: i });
1993
+ }
1994
+ }
1995
+ } catch (r) {
1996
+ throw r instanceof w ? r : b(r, { path: t });
1997
+ }
1998
+ }
1999
+ /**
2000
+ * Start watching a file or directory for changes
2001
+ *
2002
+ * @param path - The path to watch (minimatch syntax allowed)
2003
+ * @param options - Watch options
2004
+ * @param options.recursive - Whether to watch recursively (default: true)
2005
+ * @param options.exclude - Glob pattern(s) to exclude (minimatch).
2006
+ * @returns Promise that resolves when watching starts
2007
+ *
2008
+ * @example
2009
+ * ```typescript
2010
+ * // Watch entire directory tree recursively (default)
2011
+ * await fs.watch('/data');
2012
+ *
2013
+ * // Watch only immediate children (shallow)
2014
+ * await fs.watch('/data', { recursive: false });
2015
+ *
2016
+ * // Watch a single file
2017
+ * await fs.watch('/config.json', { recursive: false });
2018
+ *
2019
+ * // Watch all json files but not in dist directory
2020
+ * await fs.watch('/**\/*.json', { recursive: false, exclude: ['dist/**'] });
2021
+ *
2022
+ * ```
2023
+ */
2024
+ async watch(t, e) {
2025
+ if (!this.options.broadcastChannel)
2026
+ throw new Nt("This instance is not configured to send events. Please specify options.broadcastChannel to enable watching.");
2027
+ const n = {
2028
+ pattern: hs(t, e?.recursive ?? !0),
2029
+ include: Array.isArray(e?.include) ? e.include : [e?.include ?? "**"],
2030
+ exclude: Array.isArray(e?.exclude) ? e.exclude : [e?.exclude ?? ""]
2031
+ };
2032
+ this.watchers.set(t, n);
2033
+ }
2034
+ /**
2035
+ * Stop watching a previously watched path
2036
+ */
2037
+ unwatch(t) {
2038
+ this.watchers.delete(t);
2039
+ }
2040
+ /**
2041
+ * Read a file as a `Blob` without copying its bytes into memory.
2042
+ *
2043
+ * OPFS hands back a disk-backed `File`, so the browser can stream it on
2044
+ * demand — pass it to `URL.createObjectURL()` for `<video>` / `<audio>` /
2045
+ * `<img>` and only the played range is actually read. Structured clone keeps
2046
+ * the reference intact when the file system runs in a worker.
2047
+ *
2048
+ * @param path - Path to the file
2049
+ * @returns Lazy `File` handle backed by OPFS storage
2050
+ * @throws {OPFSError} If the path is missing or is a directory
2051
+ *
2052
+ * @example
2053
+ * ```typescript
2054
+ * const blob = await fs.readBlob('/media/clip.mp4');
2055
+ * video.src = URL.createObjectURL(blob);
2056
+ * ```
2057
+ */
2058
+ async readBlob(t) {
2059
+ await this.mount();
2060
+ try {
2061
+ return await (await this.getFileHandle(t, !1)).getFile();
2062
+ } catch (e) {
2063
+ throw e instanceof w ? e : b(e, { path: t, isDirectory: e?.name === "TypeMismatchError" });
2064
+ }
2065
+ }
2066
+ /**
2067
+ * Bulk-import files from `[path, data]` entries (strings, bytes, Blobs, or Files).
2068
+ * Each entry is written via {@link writeStream} so large Blobs/Files are not
2069
+ * fully buffered in memory.
2070
+ *
2071
+ * Accepts an array of tuples, a `Map`, or any iterable of `[path, data]` pairs.
2072
+ *
2073
+ * @param entries - Files to write
2074
+ * @param onProgress - Per-chunk progress with path, index, and byte counts
2075
+ * @returns Written paths, count, and total bytes
2076
+ * @throws {OPFSError} If a write fails
2077
+ *
2078
+ * @example
2079
+ * ```typescript
2080
+ * const result = await fs.importFiles([
2081
+ * ['/config.json', JSON.stringify({ theme: 'dark' })],
2082
+ * ['/data/binary.dat', new Uint8Array([1, 2, 3, 4])],
2083
+ * ['/upload.txt', fileFromInput],
2084
+ * ], (p) => console.log(`${p.path}: ${p.bytesWritten}/${p.bytesTotal}`));
2085
+ *
2086
+ * console.log(result.count, result.bytesWritten, result.paths);
2087
+ * ```
2088
+ */
2089
+ async importFiles(t, e) {
2090
+ await this.mount();
2091
+ const n = [...t].map(([c, h]) => [Y(c), h]), r = n.length, i = n.map(([c]) => c), o = n.reduce((c, [, h]) => c + ws(h), 0);
2092
+ let a = 0;
2093
+ try {
2094
+ for (let c = 0; c < r; c++) {
2095
+ const [h, l] = n[c], { stream: f, size: u } = ys(l), d = a, g = await this.writeStream(
2096
+ h,
2097
+ f,
2098
+ e ? (p) => e({
2099
+ path: h,
2100
+ index: c,
2101
+ count: r,
2102
+ bytesWritten: p,
2103
+ bytesTotal: u,
2104
+ totalBytesWritten: d + p,
2105
+ totalBytes: o
2106
+ }) : void 0
2107
+ );
2108
+ a += g;
2109
+ }
2110
+ return {
2111
+ paths: i,
2112
+ count: r,
2113
+ bytesWritten: a
2114
+ };
2115
+ } catch (c) {
2116
+ throw c instanceof w ? c : b(c);
2117
+ }
2118
+ }
2119
+ /**
2120
+ * @deprecated Use {@link importFiles} instead.
2121
+ */
2122
+ async createIndex(t) {
2123
+ ms(), await this.importFiles(t);
2124
+ }
2125
+ /**
2126
+ * Dispose of resources and clean up the file system instance
2127
+ */
2128
+ dispose() {
2129
+ this.broadcastChannel && (this.broadcastChannel.close(), this.broadcastChannel = null), this.watchers.clear();
2130
+ }
2131
+ }
2132
+ function ws(s) {
2133
+ return typeof s == "string" ? new TextEncoder().encode(s).byteLength : s instanceof Blob ? s.size : s.byteLength;
2134
+ }
2135
+ function ys(s) {
2136
+ if (s instanceof Blob)
2137
+ return { stream: s.stream(), size: s.size };
2138
+ const t = typeof s == "string" ? new TextEncoder().encode(s) : s;
2139
+ return {
2140
+ size: t.byteLength,
2141
+ stream: new ReadableStream({
2142
+ start(e) {
2143
+ e.enqueue(t), e.close();
2144
+ }
2145
+ })
2146
+ };
2147
+ }
2148
+ let xt = !1;
2149
+ function ms() {
2150
+ xt || (xt = !0, console.warn("[opfs-worker] createIndex() is deprecated; use importFiles() instead"));
2151
+ }
2152
+ class Es extends gs {
2153
+ /** Shared sync handles per path (OPFS allows only one handle per file) */
2154
+ openHandles = /* @__PURE__ */ new Map();
2155
+ /** Map of open file descriptors to their metadata */
2156
+ openFiles = /* @__PURE__ */ new Map();
2157
+ /** Next available file descriptor number */
2158
+ nextFd = 1;
2159
+ constructor(t) {
2160
+ super(t);
2161
+ }
2162
+ /**
2163
+ * Get file info by descriptor with validation
2164
+ * @private
2165
+ */
2166
+ _getFileDescriptor(t) {
2167
+ const e = this.openFiles.get(t);
2168
+ if (!e)
2169
+ throw new C("descriptor", `Invalid file descriptor: ${t}`);
2170
+ return e;
2171
+ }
2172
+ async readFile(t) {
2173
+ await this.mount();
2174
+ try {
2175
+ return await M(t, async () => {
2176
+ const e = await this.open(t);
2177
+ try {
2178
+ const { size: n } = await this.fstat(e), r = new Uint8Array(n);
2179
+ return n > 0 && await this.read(e, r, 0, n, 0), _(r, [r.buffer]);
2180
+ } finally {
2181
+ await this.close(e);
2182
+ }
2183
+ });
2184
+ } catch (e) {
2185
+ throw e instanceof w ? e : b(e, { path: t, isDirectory: !1 });
2186
+ }
2187
+ }
2188
+ async writeFile(t, e) {
2189
+ await this.mount();
2190
+ const n = e instanceof Uint8Array ? e : new Uint8Array(e);
2191
+ await M(t, async () => {
2192
+ const r = await this.exists(t), i = await this.open(t, { create: !0, truncate: !0 });
2193
+ try {
2194
+ await this.write(i, n, 0, n.length, null, !1), await this.fsync(i);
2195
+ } finally {
2196
+ await this.close(i);
2197
+ }
2198
+ await this.notifyChange({ path: t, type: r ? O.Changed : O.Added, isDirectory: !1 });
2199
+ });
2200
+ }
2201
+ async appendFile(t, e) {
2202
+ await this.mount();
2203
+ const n = e instanceof Uint8Array ? e : new Uint8Array(e);
2204
+ await M(t, async () => {
2205
+ const r = await this.open(t, { create: !0 });
2206
+ try {
2207
+ const { size: i } = await this.fstat(r);
2208
+ await this.write(r, n, 0, n.length, i, !1), await this.fsync(r);
2209
+ } finally {
2210
+ await this.close(r);
2211
+ }
2212
+ await this.notifyChange({ path: t, type: O.Changed, isDirectory: !1 });
2213
+ });
2214
+ }
2215
+ async writeStream(t, e, n) {
2216
+ return await this.mount(), M(t, async () => {
2217
+ const r = await this.exists(t), i = await this.open(t, { create: !0, truncate: !0 }), o = e.getReader();
2218
+ let a = 0;
2219
+ try {
2220
+ for (; ; ) {
2221
+ const { done: c, value: h } = await o.read();
2222
+ if (c)
2223
+ break;
2224
+ let l = 0;
2225
+ for (; l < h.byteLength; )
2226
+ l += await this.write(
2227
+ i,
2228
+ h,
2229
+ l,
2230
+ h.byteLength - l,
2231
+ null,
2232
+ !1
2233
+ );
2234
+ a += h.byteLength, await n?.(a);
2235
+ }
2236
+ await this.fsync(i);
2237
+ } catch (c) {
2238
+ throw await o.cancel(c).catch(() => {
2239
+ }), c;
2240
+ } finally {
2241
+ o.releaseLock(), await this.close(i);
2242
+ }
2243
+ return await this.notifyChange({
2244
+ path: t,
2245
+ type: r ? O.Changed : O.Added,
2246
+ isDirectory: !1
2247
+ }), a;
2248
+ });
2249
+ }
2250
+ async open(t, e) {
2251
+ await this.mount();
2252
+ const { create: n = !1, exclusive: r = !1, truncate: i = !1 } = e || {}, o = Y(zt(t));
2253
+ try {
2254
+ return n && r ? await M(o, async () => {
2255
+ if (await this.exists(o))
2256
+ throw new rt(o);
2257
+ return this._openFile(o, n, i);
2258
+ }) : await this._openFile(o, n, i);
2259
+ } catch (a) {
2260
+ if (a instanceof w)
2261
+ throw a;
2262
+ const c = a && a.name === "TypeMismatchError";
2263
+ throw b(a, {
2264
+ path: o,
2265
+ isDirectory: !!c
2266
+ });
2267
+ }
2268
+ }
2269
+ /**
2270
+ * Internal method to open a file (without locking)
2271
+ *
2272
+ * Multiple FDs for the same path share one sync access handle (OPFS limit),
2273
+ * with independent per-FD positions — similar to Node.js.
2274
+ * @private
2275
+ */
2276
+ async _openFile(t, e, n) {
2277
+ let r = this.openHandles.get(t);
2278
+ if (!r) {
2279
+ const o = await this.getFileHandle(t, e);
2280
+ try {
2281
+ await o.getFile();
2282
+ } catch (c) {
2283
+ throw b(c, { path: t, isDirectory: !0 });
2284
+ }
2285
+ const a = await ps(o, t);
2286
+ r = { fileHandle: o, syncHandle: a, refCount: 0 }, this.openHandles.set(t, r);
2287
+ }
2288
+ r.refCount++, n && (r.syncHandle.truncate(0), r.syncHandle.flush());
2289
+ const i = this.nextFd++;
2290
+ return this.openFiles.set(i, {
2291
+ path: t,
2292
+ fileHandle: r.fileHandle,
2293
+ syncHandle: r.syncHandle,
2294
+ position: 0
2295
+ }), i;
2296
+ }
2297
+ async close(t) {
2298
+ const e = this._getFileDescriptor(t);
2299
+ this.openFiles.delete(t);
2300
+ const n = this.openHandles.get(e.path);
2301
+ n && (n.refCount--, n.refCount <= 0 && (St(t, n.syncHandle, e.path), this.openHandles.delete(e.path)));
2302
+ }
2303
+ async read(t, e, n, r, i) {
2304
+ const o = this._getFileDescriptor(t);
2305
+ Et(e.length, n, r, i);
2306
+ try {
2307
+ const a = i ?? o.position, c = o.syncHandle.getSize(), { isEOF: h, actualLength: l } = ds(a, r, c);
2308
+ if (h)
2309
+ return _({ bytesRead: 0, buffer: e }, [e.buffer]);
2310
+ const f = e.subarray(n, n + l), u = o.syncHandle.read(f, { at: a });
2311
+ return i == null && (o.position = a + u), _({ bytesRead: u, buffer: e }, [e.buffer]);
2312
+ } catch (a) {
2313
+ throw z("read", t, o.path, a);
2314
+ }
2315
+ }
2316
+ async write(t, e, n = 0, r, i, o = !0) {
2317
+ const a = this._getFileDescriptor(t), c = r ?? e.length - n;
2318
+ Et(e.length, n, c, i);
2319
+ try {
2320
+ const h = i ?? a.position, l = e.subarray(n, n + c), f = a.syncHandle.write(l, { at: h });
2321
+ return (i == null || i === a.position) && (a.position = h + f), o && await this.notifyChange({ path: a.path, type: O.Changed, isDirectory: !1 }), f;
2322
+ } catch (h) {
2323
+ throw z("write", t, a.path, h);
2324
+ }
2325
+ }
2326
+ async fstat(t) {
2327
+ const e = this._getFileDescriptor(t);
2328
+ return this.stat(e.path);
2329
+ }
2330
+ async ftruncate(t, e = 0) {
2331
+ const n = this._getFileDescriptor(t);
2332
+ if (e < 0 || !Number.isInteger(e))
2333
+ throw new C("argument", "Invalid size");
2334
+ try {
2335
+ n.syncHandle.truncate(e), n.syncHandle.flush(), n.position > e && (n.position = e), await this.notifyChange({ path: n.path, type: O.Changed, isDirectory: !1 });
2336
+ } catch (r) {
2337
+ throw z("truncate", t, n.path, r);
2338
+ }
2339
+ }
2340
+ async fsync(t) {
2341
+ const e = this._getFileDescriptor(t);
2342
+ try {
2343
+ e.syncHandle.flush();
2344
+ } catch (n) {
2345
+ throw z("sync", t, e.path, n);
2346
+ }
2347
+ }
2348
+ dispose() {
2349
+ for (const [t, e] of this.openHandles)
2350
+ St(-1, e.syncHandle, t);
2351
+ this.openHandles.clear(), this.openFiles.clear(), this.nextFd = 1, super.dispose();
2352
+ }
2353
+ }
2354
+ ot(new Es());
2355
+ //# sourceMappingURL=dedicated.worker.js.map