opfs-mock 2.4.0 → 2.5.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,330 @@
1
+ //#region src/utils.ts
2
+ const isFileHandle = (handle) => {
3
+ return handle.kind === "file";
4
+ };
5
+ const isDirectoryHandle = (handle) => {
6
+ return handle.kind === "directory";
7
+ };
8
+ const getSizeOfDirectory = async (directory) => {
9
+ let totalSize = 0;
10
+ for await (const handle of directory.values()) if (isFileHandle(handle)) {
11
+ const file = await handle.getFile();
12
+ totalSize += file.size;
13
+ } else if (isDirectoryHandle(handle)) totalSize += await getSizeOfDirectory(handle);
14
+ return totalSize;
15
+ };
16
+
17
+ //#endregion
18
+ //#region src/opfs.ts
19
+ const isObject = (v) => typeof v === "object" && v !== null;
20
+ const isLegacyWriteParams = (v) => isObject(v) && !("type" in v) && "data" in v;
21
+ const fileSystemFileHandleFactory = (name, fileData, exists) => {
22
+ return {
23
+ kind: "file",
24
+ name,
25
+ queryPermission: async () => {
26
+ return "granted";
27
+ },
28
+ requestPermission: async () => {
29
+ return "granted";
30
+ },
31
+ isSameEntry: async function(other) {
32
+ return other === this;
33
+ },
34
+ getFile: async () => {
35
+ if (!exists()) throw new DOMException("A requested file or directory could not be found at the time an operation was processed.", "NotFoundError");
36
+ const f = new File([fileData.content], name, { lastModified: fileData.lastModified });
37
+ f._opfsId = fileData.id;
38
+ return f;
39
+ },
40
+ createWritable: async (options) => {
41
+ const keepExistingData = options?.keepExistingData;
42
+ let abortReason = "";
43
+ let isAborted = false;
44
+ let isClosed = false;
45
+ let content = keepExistingData ? new Uint8Array(fileData.content) : new Uint8Array();
46
+ let cursorPosition = keepExistingData ? fileData.content.length : 0;
47
+ const writeChunk = async (chunk) => {
48
+ if (isAborted) throw new Error(abortReason);
49
+ if (isClosed) throw new TypeError("Cannot write to a CLOSED writable stream");
50
+ if (chunk === void 0) throw new TypeError("Cannot write undefined data to the stream");
51
+ if (typeof chunk === "object" && "type" in chunk) {
52
+ if (chunk.type === "truncate") {
53
+ if (typeof chunk.size !== "number" || chunk.size < 0) throw new TypeError("Invalid size value in truncate parameters");
54
+ if (chunk.size < content.length) content = content.slice(0, chunk.size);
55
+ else {
56
+ const extended = new Uint8Array(chunk.size);
57
+ extended.set(content);
58
+ content = extended;
59
+ }
60
+ cursorPosition = Math.min(cursorPosition, chunk.size);
61
+ return;
62
+ }
63
+ if (chunk.type === "seek") {
64
+ const pos = chunk.position;
65
+ if (typeof pos !== "number" || pos < 0) throw new TypeError("Invalid position value in seek parameters");
66
+ cursorPosition = pos;
67
+ return;
68
+ }
69
+ if (chunk.type === "write") {
70
+ const wp = chunk;
71
+ if (wp.size !== void 0 && wp.size !== null) {
72
+ if (typeof wp.size !== "number" || wp.size < 0) throw new TypeError("Invalid size value in write parameters");
73
+ }
74
+ if (wp.position !== void 0 && wp.position !== null) {
75
+ if (typeof wp.position !== "number" || wp.position < 0) throw new TypeError("Invalid position value in write parameters");
76
+ cursorPosition = wp.position;
77
+ }
78
+ chunk = wp.data ?? new Uint8Array();
79
+ }
80
+ }
81
+ let encoded;
82
+ if (typeof chunk === "string") encoded = new TextEncoder().encode(chunk);
83
+ else if (chunk instanceof Blob) {
84
+ const ab = await chunk.arrayBuffer();
85
+ encoded = new Uint8Array(ab);
86
+ } else if (ArrayBuffer.isView(chunk)) encoded = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
87
+ else if (chunk instanceof ArrayBuffer) encoded = new Uint8Array(chunk);
88
+ else if (isLegacyWriteParams(chunk)) {
89
+ const wp = chunk;
90
+ if (wp.position !== void 0 && wp.position !== null) {
91
+ if (typeof wp.position !== "number" || wp.position < 0) throw new TypeError("Invalid position value in write parameters");
92
+ cursorPosition = wp.position;
93
+ }
94
+ const data = wp.data;
95
+ if (data === void 0 || data === null) encoded = new Uint8Array();
96
+ else if (typeof data === "string") encoded = new TextEncoder().encode(data);
97
+ else if (data instanceof Blob) {
98
+ const ab = await data.arrayBuffer();
99
+ encoded = new Uint8Array(ab);
100
+ } else if (ArrayBuffer.isView(data)) encoded = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
101
+ else if (data instanceof ArrayBuffer) encoded = new Uint8Array(data);
102
+ else throw new TypeError("Invalid data in WriteParams");
103
+ } else throw new TypeError("Invalid data type written to the file. Data must be of type FileSystemWriteChunkType.");
104
+ const requiredSize = cursorPosition + encoded.length;
105
+ if (content.length < requiredSize) {
106
+ const extended = new Uint8Array(requiredSize);
107
+ extended.set(content);
108
+ content = extended;
109
+ }
110
+ content.set(encoded, cursorPosition);
111
+ cursorPosition += encoded.length;
112
+ };
113
+ const doClose = async () => {
114
+ if (isClosed) throw new TypeError("Cannot close a CLOSED writable stream");
115
+ if (isAborted) throw new TypeError("Cannot close a ERRORED writable stream");
116
+ isClosed = true;
117
+ fileData.content = content;
118
+ fileData.lastModified = Date.now();
119
+ };
120
+ const doAbort = async (reason) => {
121
+ if (isAborted) return;
122
+ if (reason && !abortReason) abortReason = String(reason);
123
+ isAborted = true;
124
+ };
125
+ const doTruncate = async (size) => {
126
+ if (size < 0) throw new DOMException("Invalid truncate size", "IndexSizeError");
127
+ if (size < content.length) content = content.slice(0, size);
128
+ else if (size > content.length) {
129
+ const newBuffer = new Uint8Array(size);
130
+ newBuffer.set(content);
131
+ content = newBuffer;
132
+ }
133
+ cursorPosition = Math.min(cursorPosition, size);
134
+ };
135
+ const doSeek = async (position) => {
136
+ if (position < 0) throw new DOMException("Invalid seek position", "IndexSizeError");
137
+ cursorPosition = position;
138
+ };
139
+ const writableStream = new WritableStream({
140
+ write: writeChunk,
141
+ close: doClose,
142
+ abort: doAbort
143
+ });
144
+ const originalGetWriter = writableStream.getWriter.bind(writableStream);
145
+ return Object.assign(writableStream, {
146
+ getWriter: () => originalGetWriter(),
147
+ write: async (_chunk) => writeChunk(_chunk),
148
+ close: async () => doClose(),
149
+ abort: async (reason) => doAbort(reason),
150
+ truncate: async (size) => doTruncate(size),
151
+ seek: async (position) => doSeek(position)
152
+ });
153
+ },
154
+ createSyncAccessHandle: async () => {
155
+ if (fileData.locked) throw new DOMException("A sync access handle is already open for this file", "InvalidStateError");
156
+ fileData.locked = true;
157
+ let closed = false;
158
+ return {
159
+ getSize: () => {
160
+ if (closed) throw new DOMException("The access handle is closed", "InvalidStateError");
161
+ return fileData.content.byteLength;
162
+ },
163
+ read: (buffer, { at = 0 } = {}) => {
164
+ if (closed) throw new DOMException("The access handle is closed", "InvalidStateError");
165
+ const content = fileData.content;
166
+ if (at >= content.length) return 0;
167
+ const available = content.length - at;
168
+ const writable = buffer instanceof DataView ? buffer.byteLength : buffer.length;
169
+ const bytesToRead = Math.min(writable, available);
170
+ const slice = content.subarray(at, at + bytesToRead);
171
+ if (buffer instanceof DataView) for (let i = 0; i < slice.length; i++) buffer.setUint8(i, slice[i]);
172
+ else buffer.set(slice, 0);
173
+ return bytesToRead;
174
+ },
175
+ write: (data, { at = 0 } = {}) => {
176
+ if (closed) throw new DOMException("The access handle is closed", "InvalidStateError");
177
+ const writeLength = data instanceof DataView ? data.byteLength : data.length;
178
+ const requiredSize = at + writeLength;
179
+ if (fileData.content.length < requiredSize) {
180
+ const newBuffer = new Uint8Array(requiredSize);
181
+ newBuffer.set(fileData.content);
182
+ fileData.content = newBuffer;
183
+ }
184
+ if (data instanceof DataView) for (let i = 0; i < data.byteLength; i++) fileData.content[at + i] = data.getUint8(i);
185
+ else fileData.content.set(data, at);
186
+ fileData.lastModified = Date.now();
187
+ return writeLength;
188
+ },
189
+ truncate: (size) => {
190
+ if (closed) throw new DOMException("The access handle is closed", "InvalidStateError");
191
+ if (size < fileData.content.length) fileData.content = fileData.content.slice(0, size);
192
+ else if (size > fileData.content.length) {
193
+ const newBuffer = new Uint8Array(size);
194
+ newBuffer.set(fileData.content);
195
+ fileData.content = newBuffer;
196
+ }
197
+ fileData.lastModified = Date.now();
198
+ },
199
+ flush: async () => {
200
+ if (closed) throw new DOMException("The access handle is closed", "InvalidStateError");
201
+ },
202
+ close: async () => {
203
+ closed = true;
204
+ fileData.locked = false;
205
+ }
206
+ };
207
+ }
208
+ };
209
+ };
210
+ const fileSystemDirectoryHandleFactory = (name) => {
211
+ const files = /* @__PURE__ */ new Map();
212
+ const directories = /* @__PURE__ */ new Map();
213
+ const getJoinedMaps = () => {
214
+ return new Map([...files, ...directories]);
215
+ };
216
+ return {
217
+ kind: "directory",
218
+ name,
219
+ queryPermission: async () => "granted",
220
+ requestPermission: async () => "granted",
221
+ isSameEntry: async function(other) {
222
+ return other === this;
223
+ },
224
+ getFileHandle: async (fileName, options) => {
225
+ if (directories.has(fileName)) throw new DOMException(`A directory with the same name exists: ${fileName}`, "TypeMismatchError");
226
+ if (!files.has(fileName) && options?.create) files.set(fileName, fileSystemFileHandleFactory(fileName, {
227
+ content: new Uint8Array(),
228
+ lastModified: Date.now(),
229
+ id: Symbol("file")
230
+ }, () => files.has(fileName)));
231
+ const fileHandle = files.get(fileName);
232
+ if (!fileHandle) throw new DOMException(`File not found: ${fileName}`, "NotFoundError");
233
+ return fileHandle;
234
+ },
235
+ getDirectoryHandle: async (dirName, options) => {
236
+ if (files.has(dirName)) throw new DOMException(`A file with the same name exists: ${dirName}`, "TypeMismatchError");
237
+ if (!directories.has(dirName) && options?.create) {
238
+ const dir = fileSystemDirectoryHandleFactory(dirName);
239
+ directories.set(dirName, dir);
240
+ }
241
+ const directoryHandle = directories.get(dirName);
242
+ if (!directoryHandle) throw new DOMException(`Directory not found: ${dirName}`, "NotFoundError");
243
+ return directoryHandle;
244
+ },
245
+ removeEntry: async (entryName, options) => {
246
+ if (files.has(entryName)) {
247
+ files.delete(entryName);
248
+ return;
249
+ }
250
+ const dir = directories.get(entryName);
251
+ if (dir) {
252
+ if (!options?.recursive) for await (const _ of dir.values()) throw new DOMException("The directory is not empty", "InvalidModificationError");
253
+ directories.delete(entryName);
254
+ return;
255
+ }
256
+ throw new DOMException(`No such file or directory: ${entryName}`, "NotFoundError");
257
+ },
258
+ [Symbol.asyncIterator]: async function* () {
259
+ const entries = getJoinedMaps();
260
+ for (const [n, h] of entries) yield [n, h];
261
+ return void 0;
262
+ },
263
+ entries: async function* () {
264
+ yield* getJoinedMaps().entries();
265
+ },
266
+ keys: async function* () {
267
+ yield* getJoinedMaps().keys();
268
+ },
269
+ values: async function* () {
270
+ yield* getJoinedMaps().values();
271
+ },
272
+ resolve: async function(possibleDescendant) {
273
+ const traverseDirectory = async (directory, target, path = []) => {
274
+ if (await directory.isSameEntry(target)) return path;
275
+ for await (const [nm, h] of directory.entries()) if (isDirectoryHandle(h)) {
276
+ const result = await traverseDirectory(h, target, [...path, nm]);
277
+ if (result) return result;
278
+ } else if (isFileHandle(h)) {
279
+ if (await h.isSameEntry(target)) return [...path, nm];
280
+ }
281
+ return null;
282
+ };
283
+ return traverseDirectory(this, possibleDescendant);
284
+ }
285
+ };
286
+ };
287
+
288
+ //#endregion
289
+ //#region src/index.ts
290
+ const storageFactory = ({ usage = 0, quota = 1024 ** 3 } = {}) => {
291
+ const root = fileSystemDirectoryHandleFactory("root");
292
+ return {
293
+ estimate: async () => {
294
+ return {
295
+ usage: usage + await getSizeOfDirectory(root),
296
+ quota
297
+ };
298
+ },
299
+ getDirectory: async () => {
300
+ return root;
301
+ },
302
+ persist: async () => {
303
+ return true;
304
+ },
305
+ persisted: async () => {
306
+ return true;
307
+ }
308
+ };
309
+ };
310
+ const mockOPFS = () => {
311
+ if (!("navigator" in globalThis)) Object.defineProperty(globalThis, "navigator", {
312
+ value: {},
313
+ writable: true
314
+ });
315
+ if (!globalThis.navigator.storage) Object.defineProperty(globalThis.navigator, "storage", {
316
+ value: storageFactory(),
317
+ writable: true
318
+ });
319
+ };
320
+ const resetMockOPFS = () => {
321
+ const root = fileSystemDirectoryHandleFactory("root");
322
+ Object.defineProperty(globalThis.navigator.storage, "getDirectory", {
323
+ value: () => root,
324
+ writable: true
325
+ });
326
+ };
327
+ if (typeof globalThis !== "undefined") mockOPFS();
328
+
329
+ //#endregion
330
+ export { mockOPFS, resetMockOPFS, storageFactory };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opfs-mock",
3
- "version": "2.4.0",
3
+ "version": "2.5.1",
4
4
  "type": "module",
5
5
  "description": "Mock all origin private file system APIs for your Jest or Vitest tests",
6
6
  "author": "Jure Rotar <hello@jurerotar.com>",
@@ -26,14 +26,18 @@
26
26
  "publishConfig": {
27
27
  "access": "public"
28
28
  },
29
+ "module": "./dist/index.mjs",
30
+ "types": "./dist/index.d.mts",
29
31
  "exports": {
30
- ".": {
31
- "types": "./dist/index.d.ts",
32
- "import": "./dist/index.js"
32
+ "module-sync": {
33
+ "types": "./dist/index.d.mts",
34
+ "default": "./dist/index.mjs"
35
+ },
36
+ "import": {
37
+ "types": "./dist/index.d.mts",
38
+ "default": "./dist/index.mjs"
33
39
  }
34
40
  },
35
- "main": "dist/index.js",
36
- "module": "dist/index.js",
37
41
  "files": [
38
42
  "dist"
39
43
  ],
@@ -56,12 +60,13 @@
56
60
  "release": "npm publish --access public"
57
61
  },
58
62
  "devDependencies": {
59
- "@biomejs/biome": "2.2.6",
63
+ "@biomejs/biome": "2.3.4",
64
+ "@vitest/coverage-v8": "4.0.7",
60
65
  "@web-std/file": "3.0.3",
61
- "happy-dom": "20.0.5",
62
- "jsdom": "27.0.1",
63
- "tsdown": "0.15.7",
66
+ "happy-dom": "20.0.10",
67
+ "jsdom": "27.1.0",
68
+ "tsdown": "0.16.0",
64
69
  "typescript": "5.9.3",
65
- "vitest": "3.2.4"
70
+ "vitest": "4.0.7"
66
71
  }
67
72
  }
package/dist/index.js DELETED
@@ -1,270 +0,0 @@
1
- //#region src/utils.ts
2
- const isFileHandle = (handle) => {
3
- return handle.kind === "file";
4
- };
5
- const isDirectoryHandle = (handle) => {
6
- return handle.kind === "directory";
7
- };
8
- const getSizeOfDirectory = async (directory) => {
9
- let totalSize = 0;
10
- for await (const handle of directory.values()) if (isFileHandle(handle)) {
11
- const file = await handle.getFile();
12
- totalSize += file.size;
13
- } else if (isDirectoryHandle(handle)) totalSize += await getSizeOfDirectory(handle);
14
- return totalSize;
15
- };
16
-
17
- //#endregion
18
- //#region src/opfs.ts
19
- const fileSystemFileHandleFactory = (name, fileData, exists) => {
20
- return {
21
- kind: "file",
22
- name,
23
- isSameEntry: async (other) => {
24
- return other.name === name && other.kind === "file";
25
- },
26
- getFile: async () => {
27
- if (!exists()) throw new DOMException("A requested file or directory could not be found at the time an operation was processed.", "NotFoundError");
28
- return new File([fileData.content], name);
29
- },
30
- createWritable: async (options) => {
31
- const keepExistingData = options?.keepExistingData;
32
- let abortReason = "";
33
- let isAborted = false;
34
- let isClosed = false;
35
- let content = keepExistingData ? new Uint8Array(fileData.content) : new Uint8Array();
36
- let cursorPosition = keepExistingData ? fileData.content.length : 0;
37
- const writableStream = new WritableStream({
38
- write: () => {},
39
- close: () => {},
40
- abort: () => {}
41
- });
42
- return Object.assign(writableStream, {
43
- getWriter: () => writableStream.getWriter(),
44
- write: async function(chunk) {
45
- if (isAborted) throw new Error(abortReason);
46
- if (isClosed) throw new TypeError("Cannot write to a CLOSED writable stream");
47
- if (chunk === void 0) throw new TypeError("Cannot write undefined data to the stream");
48
- if (typeof chunk === "object" && "type" in chunk && chunk.type === "truncate") {
49
- if (typeof chunk.size !== "number" || chunk.size < 0) throw new TypeError("Invalid size value in truncate parameters");
50
- if (chunk.size < content.length) content = content.slice(0, chunk.size);
51
- else {
52
- const extended = new Uint8Array(chunk.size);
53
- extended.set(content);
54
- content = extended;
55
- }
56
- cursorPosition = Math.min(cursorPosition, chunk.size);
57
- return;
58
- }
59
- let encoded;
60
- if (typeof chunk === "string") encoded = new TextEncoder().encode(chunk);
61
- else if (chunk instanceof Blob) {
62
- const text = await chunk.text();
63
- encoded = new TextEncoder().encode(text);
64
- } else if (ArrayBuffer.isView(chunk)) encoded = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
65
- else if (chunk instanceof ArrayBuffer) encoded = new Uint8Array(chunk);
66
- else if (typeof chunk === "object" && "data" in chunk) {
67
- if (chunk.position !== void 0 && (typeof chunk.position !== "number" || chunk.position < 0)) throw new TypeError("Invalid position value in write parameters");
68
- if (chunk.size !== void 0 && (typeof chunk.size !== "number" || chunk.size < 0)) throw new TypeError("Invalid size value in write parameters");
69
- if (chunk.position !== void 0 && chunk.position !== null) cursorPosition = chunk.position;
70
- const data = chunk.data;
71
- if (data === void 0 || data === null) encoded = new Uint8Array();
72
- else if (typeof data === "string") encoded = new TextEncoder().encode(data);
73
- else if (data instanceof Blob) {
74
- const text = await data.text();
75
- encoded = new TextEncoder().encode(text);
76
- } else if (ArrayBuffer.isView(data)) encoded = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
77
- else if (data instanceof ArrayBuffer) encoded = new Uint8Array(data);
78
- else throw new TypeError("Invalid data in WriteParams");
79
- } else throw new TypeError("Invalid data type written to the file. Data must be of type FileSystemWriteChunkType.");
80
- const requiredSize = cursorPosition + encoded.length;
81
- if (content.length < requiredSize) {
82
- const extended = new Uint8Array(requiredSize);
83
- extended.set(content);
84
- content = extended;
85
- }
86
- content.set(encoded, cursorPosition);
87
- cursorPosition += encoded.length;
88
- },
89
- close: async function() {
90
- if (isClosed) throw new TypeError("Cannot close a CLOSED writable stream");
91
- if (isAborted) throw new TypeError("Cannot close a ERRORED writable stream");
92
- isClosed = true;
93
- fileData.content = content;
94
- },
95
- abort: async function(reason) {
96
- if (isAborted) return;
97
- if (reason && !abortReason) abortReason = reason;
98
- isAborted = true;
99
- return Promise.resolve(void 0);
100
- },
101
- truncate: async function(size) {
102
- if (size < 0) throw new DOMException("Invalid truncate size", "IndexSizeError");
103
- if (size < content.length) content = content.slice(0, size);
104
- else if (size > content.length) {
105
- const newBuffer = new Uint8Array(size);
106
- newBuffer.set(content);
107
- content = newBuffer;
108
- }
109
- cursorPosition = Math.min(cursorPosition, size);
110
- },
111
- seek: async function(position) {
112
- if (position < 0) throw new DOMException("Invalid seek position", "IndexSizeError");
113
- cursorPosition = position;
114
- }
115
- });
116
- },
117
- createSyncAccessHandle: async () => {
118
- let closed = false;
119
- return {
120
- getSize: () => {
121
- if (closed) throw new DOMException("InvalidStateError", "The access handle is closed");
122
- return fileData.content.byteLength;
123
- },
124
- read: (buffer, { at = 0 } = {}) => {
125
- if (closed) throw new DOMException("InvalidStateError", "The access handle is closed");
126
- const content = fileData.content;
127
- if (at >= content.length) return 0;
128
- const available = content.length - at;
129
- const writable = buffer instanceof DataView ? buffer.byteLength : buffer.length;
130
- const bytesToRead = Math.min(writable, available);
131
- const slice = content.subarray(at, at + bytesToRead);
132
- if (buffer instanceof DataView) for (let i = 0; i < slice.length; i++) buffer.setUint8(i, slice[i]);
133
- else buffer.set(slice, 0);
134
- return bytesToRead;
135
- },
136
- write: (data, { at = 0 } = {}) => {
137
- if (closed) throw new DOMException("InvalidStateError", "The access handle is closed");
138
- const writeLength = data instanceof DataView ? data.byteLength : data.length;
139
- const requiredSize = at + writeLength;
140
- if (fileData.content.length < requiredSize) {
141
- const newBuffer = new Uint8Array(requiredSize);
142
- newBuffer.set(fileData.content);
143
- fileData.content = newBuffer;
144
- }
145
- if (data instanceof DataView) for (let i = 0; i < data.byteLength; i++) fileData.content[at + i] = data.getUint8(i);
146
- else fileData.content.set(data, at);
147
- return writeLength;
148
- },
149
- truncate: (size) => {
150
- if (closed) throw new DOMException("InvalidStateError", "The access handle is closed");
151
- if (size < fileData.content.length) fileData.content = fileData.content.slice(0, size);
152
- else if (size > fileData.content.length) {
153
- const newBuffer = new Uint8Array(size);
154
- newBuffer.set(fileData.content);
155
- fileData.content = newBuffer;
156
- }
157
- },
158
- flush: async () => {
159
- if (closed) throw new DOMException("InvalidStateError", "The access handle is closed");
160
- },
161
- close: async () => {
162
- closed = true;
163
- }
164
- };
165
- }
166
- };
167
- };
168
- const fileSystemDirectoryHandleFactory = (name) => {
169
- const files = /* @__PURE__ */ new Map();
170
- const directories = /* @__PURE__ */ new Map();
171
- const getJoinedMaps = () => {
172
- return new Map([...files, ...directories]);
173
- };
174
- return {
175
- kind: "directory",
176
- name,
177
- isSameEntry: async (other) => {
178
- return other.name === name && other.kind === "directory";
179
- },
180
- getFileHandle: async (fileName, options) => {
181
- if (!files.has(fileName) && options?.create) files.set(fileName, fileSystemFileHandleFactory(fileName, { content: new Uint8Array() }, () => files.has(fileName)));
182
- const fileHandle = files.get(fileName);
183
- if (!fileHandle) throw new DOMException(`File not found: ${fileName}`, "NotFoundError");
184
- return fileHandle;
185
- },
186
- getDirectoryHandle: async (dirName, options) => {
187
- if (!directories.has(dirName) && options?.create) directories.set(dirName, fileSystemDirectoryHandleFactory(dirName));
188
- const directoryHandle = directories.get(dirName);
189
- if (!directoryHandle) throw new DOMException(`Directory not found: ${dirName}`, "NotFoundError");
190
- return directoryHandle;
191
- },
192
- removeEntry: async (entryName, options) => {
193
- if (files.has(entryName)) files.delete(entryName);
194
- else if (directories.has(entryName)) if (options?.recursive) directories.delete(entryName);
195
- else throw new DOMException(`Failed to remove directory: $1${entryName}`, "InvalidModificationError");
196
- else throw new DOMException(`No such file or directory: $1${entryName}`, "NotFoundError");
197
- },
198
- [Symbol.asyncIterator]: async function* () {
199
- const entries = getJoinedMaps();
200
- for (const [name$1, handle] of entries) yield [name$1, handle];
201
- return void 0;
202
- },
203
- entries: async function* () {
204
- yield* getJoinedMaps().entries();
205
- },
206
- keys: async function* () {
207
- yield* getJoinedMaps().keys();
208
- },
209
- values: async function* () {
210
- yield* getJoinedMaps().values();
211
- },
212
- resolve: async function(possibleDescendant) {
213
- const traverseDirectory = async (directory, target, path = []) => {
214
- if (await directory.isSameEntry(target)) return path;
215
- for await (const [name$1, handle] of directory.entries()) if (isDirectoryHandle(handle)) {
216
- const result = await traverseDirectory(handle, target, [...path, name$1]);
217
- if (result) return result;
218
- } else if (isFileHandle(handle)) {
219
- if (await handle.isSameEntry(target)) return [...path, name$1];
220
- }
221
- return null;
222
- };
223
- return traverseDirectory(this, possibleDescendant);
224
- }
225
- };
226
- };
227
-
228
- //#endregion
229
- //#region src/index.ts
230
- const storageFactory = ({ usage = 0, quota = 1024 ** 3 } = {}) => {
231
- const root = fileSystemDirectoryHandleFactory("root");
232
- return {
233
- estimate: async () => {
234
- return {
235
- usage: usage + await getSizeOfDirectory(root),
236
- quota
237
- };
238
- },
239
- getDirectory: async () => {
240
- return root;
241
- },
242
- persist: async () => {
243
- return true;
244
- },
245
- persisted: async () => {
246
- return true;
247
- }
248
- };
249
- };
250
- const mockOPFS = () => {
251
- if (!("navigator" in globalThis)) Object.defineProperty(globalThis, "navigator", {
252
- value: {},
253
- writable: true
254
- });
255
- if (!globalThis.navigator.storage) Object.defineProperty(globalThis.navigator, "storage", {
256
- value: storageFactory(),
257
- writable: true
258
- });
259
- };
260
- const resetMockOPFS = () => {
261
- const root = fileSystemDirectoryHandleFactory("root");
262
- Object.defineProperty(globalThis.navigator.storage, "getDirectory", {
263
- value: () => root,
264
- writable: true
265
- });
266
- };
267
- if (typeof globalThis !== "undefined") mockOPFS();
268
-
269
- //#endregion
270
- export { mockOPFS, resetMockOPFS, storageFactory };
File without changes