opfs-mock 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md CHANGED
@@ -1,21 +1,21 @@
1
- The MIT License (MIT)
2
-
3
- Copyright © 2024 Jure Rotar
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE
1
+ The MIT License (MIT)
2
+
3
+ Copyright © 2024 Jure Rotar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE
package/README.md CHANGED
@@ -1,159 +1,168 @@
1
- # opfs-mock
2
-
3
- This is a pure JS in-memory implementation of the [origin private file system](https://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Origin_private_file_system). Its main utility is for testing OPFS-dependent code in Node.js.
4
-
5
- ## Installation
6
-
7
- ```shell
8
- npm install -save-dev opfs-mock
9
- ```
10
-
11
- ## Usage
12
-
13
- It replicates the behavior of origin private file system, except data is not persisted to disk.
14
-
15
- The easiest way to use it is to import `opfs-mock`, which will polyfill OPFS API to global scope.
16
-
17
- ```ts
18
- import "opfs-mock";
19
- ```
20
-
21
- Alternatively, you can explicitly import `storageFactory`:
22
-
23
- ```ts
24
- import { storageFactory } from "opfs-mock";
25
-
26
- test('Your test', async () => {
27
- const storage = await storageFactory();
28
- const root = await storage.getDirectory();
29
- const directoryHandle = await root.getFileHandle('test-file.txt', { create: true });
30
- // rest of your test
31
- });
32
- ```
33
-
34
- `storageFactory` has `quota` and `usage` values set to `1024 ** 3 (1 GB)` and `0` respectively. When calling `storage.estimate()`, `usage` is dynamically calculated by summing the predefined usage value and any additional computed storage consumption.
35
- In case you need specific values, you can pass both as arguments to `storageFactory`.
36
-
37
- ```ts
38
- import { storageFactory } from "opfs-mock";
39
-
40
- test('Your test', async () => {
41
- const storage = await storageFactory({ quota: 1_000_000, usage: 1_000 });
42
- const root = await storage.getDirectory();
43
- const directoryHandle = await root.getFileHandle('test-file.txt', { create: true });
44
- // rest of your test
45
- });
46
- ```
47
-
48
- ### Vitest
49
-
50
- To use `opfs-mock` in a single Vitest test suite, require `opfs-mock` at the beginning of the test file, as described above.
51
-
52
- To use it on all Vitest tests without having to include it in each file, add the auto setup script to the `test.setupFiles` in your Vite config:
53
-
54
- ```ts
55
- // vite.config.ts
56
-
57
- import { defineConfig as defineViteConfig, mergeConfig } from 'vite';
58
- import { defineConfig as defineVitestConfig } from 'vitest/config';
59
-
60
- const viteConfig = defineViteConfig({
61
- ...
62
- });
63
-
64
- const vitestConfig = defineVitestConfig({
65
- test: {
66
- setupFiles: ['opfs-mock'],
67
- },
68
- });
69
-
70
- export default mergeConfig(viteConfig, vitestConfig);
71
- ```
72
-
73
- Alternatively you can create a new setup file which then imports this module.
74
-
75
- ```ts
76
- // vitest-setup.ts
77
-
78
- import "opfs-mock";
79
- ```
80
-
81
- Add that file to your `test.setupFiles` array:
82
-
83
- ```ts
84
- // vite.config.ts
85
-
86
- import { defineConfig as defineViteConfig, mergeConfig } from 'vite';
87
- import { defineConfig as defineVitestConfig } from 'vitest/config';
88
-
89
- const viteConfig = defineViteConfig({
90
- ...
91
- });
92
-
93
- const vitestConfig = defineVitestConfig({
94
- test: {
95
- setupFiles: ['vitest-setup.ts'],
96
- },
97
- });
98
-
99
- export default mergeConfig(viteConfig, vitestConfig);
100
- ```
101
-
102
-
103
- ### Jest
104
-
105
- To use `opfs-mock` in a single Jest test suite, require `opfs-mock` at the beginning of the test file, as described above.
106
-
107
- To use it on all Jest tests without having to include it in each file, add the auto setup script to the `setupFiles` in your Jest config:
108
-
109
- ```ts
110
- // jest.config.js
111
-
112
- {
113
- ...
114
- "setupFiles": [
115
- "opfs-mock"
116
- ]
117
- }
118
- ```
119
-
120
- Alternatively you can create a new setup file which then imports this module.
121
-
122
- ```ts
123
- // jest-setup.ts
124
-
125
- import "opfs-mock";
126
- ```
127
-
128
- Add that file to your `setupFiles` array:
129
-
130
- ```ts
131
- // jest.config.js
132
-
133
- {
134
- ...
135
- "setupFiles": [
136
- "jest-setup"
137
- ]
138
- }
139
- ```
140
-
141
- ## Wiping/resetting the OPFS mock for a fresh state
142
-
143
- If you are keeping your tests completely isolated you might want to "reset" the state of the mocked OPFS. You can do this by using `resetMockOPFS` function, which creates a completely new instance of the mock.
144
-
145
- ```ts
146
- import { resetMockOPFS } from 'opfs-mock';
147
-
148
- beforeEach(() => {
149
- resetMockOPFS();
150
- });
151
-
152
- test('First isolated test', async () => {
153
- // rest of your test
154
- });
155
-
156
- test('Second isolated test', async () => {
157
- // rest of your test
158
- });
159
- ```
1
+ # opfs-mock
2
+
3
+ In-memory implementation of the [origin private file system](https://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Origin_private_file_system). Its main utility is for testing OPFS-dependent code in Node.js. It's tested
4
+ on Node.js versions 20-24.
5
+
6
+ ## Installation
7
+
8
+ ```shell
9
+ npm install -save-dev opfs-mock
10
+ ```
11
+
12
+ ## Limitations
13
+
14
+ - `opfs-mock` requires **Node.js v20.0.0** or higher. It can work on Node v18.0.0 with either `--experimental-fetch` flag enabled or a global
15
+ `File` polyfill.
16
+
17
+ - `jsdom` testing environment is missing `File.prototype.text()` method, which is required for reading opfs files. Ensure your opfs-dependant tests are ran
18
+ in `node` or `happy-dom` environment.
19
+
20
+ ## Usage
21
+
22
+ It replicates the behavior of origin private file system, except data is not persisted to disk.
23
+
24
+ The easiest way to use it is to import `opfs-mock`, which will polyfill OPFS API to global scope.
25
+
26
+ ```ts
27
+ import "opfs-mock";
28
+ ```
29
+
30
+ Alternatively, you can explicitly import `storageFactory`:
31
+
32
+ ```ts
33
+ import { storageFactory } from "opfs-mock";
34
+
35
+ test('Your test', async () => {
36
+ const storage = await storageFactory();
37
+ const root = await storage.getDirectory();
38
+ const directoryHandle = await root.getFileHandle('test-file.txt', { create: true });
39
+ // rest of your test
40
+ });
41
+ ```
42
+
43
+ `storageFactory` has `quota` and `usage` values set to `1024 ** 3 (1 GB)` and `0` respectively. When calling `storage.estimate()`, `usage` is dynamically calculated by summing the predefined usage value and any additional computed storage consumption.
44
+ In case you need specific values, you can pass both as arguments to `storageFactory`.
45
+
46
+ ```ts
47
+ import { storageFactory } from "opfs-mock";
48
+
49
+ test('Your test', async () => {
50
+ const storage = await storageFactory({ quota: 1_000_000, usage: 1_000 });
51
+ const root = await storage.getDirectory();
52
+ const directoryHandle = await root.getFileHandle('test-file.txt', { create: true });
53
+ // rest of your test
54
+ });
55
+ ```
56
+
57
+ ### Vitest
58
+
59
+ To use `opfs-mock` in a single Vitest test suite, require `opfs-mock` at the beginning of the test file, as described above.
60
+
61
+ To use it on all Vitest tests without having to include it in each file, add the auto setup script to the `test.setupFiles` in your Vite config:
62
+
63
+ ```ts
64
+ // vite.config.ts
65
+
66
+ import { defineConfig as defineViteConfig, mergeConfig } from 'vite';
67
+ import { defineConfig as defineVitestConfig } from 'vitest/config';
68
+
69
+ const viteConfig = defineViteConfig({
70
+ ...
71
+ });
72
+
73
+ const vitestConfig = defineVitestConfig({
74
+ test: {
75
+ setupFiles: ['opfs-mock'],
76
+ },
77
+ });
78
+
79
+ export default mergeConfig(viteConfig, vitestConfig);
80
+ ```
81
+
82
+ Alternatively you can create a new setup file which then imports this module.
83
+
84
+ ```ts
85
+ // vitest-setup.ts
86
+
87
+ import "opfs-mock";
88
+ ```
89
+
90
+ Add that file to your `test.setupFiles` array:
91
+
92
+ ```ts
93
+ // vite.config.ts
94
+
95
+ import { defineConfig as defineViteConfig, mergeConfig } from 'vite';
96
+ import { defineConfig as defineVitestConfig } from 'vitest/config';
97
+
98
+ const viteConfig = defineViteConfig({
99
+ ...
100
+ });
101
+
102
+ const vitestConfig = defineVitestConfig({
103
+ test: {
104
+ setupFiles: ['vitest-setup.ts'],
105
+ },
106
+ });
107
+
108
+ export default mergeConfig(viteConfig, vitestConfig);
109
+ ```
110
+
111
+
112
+ ### Jest
113
+
114
+ To use `opfs-mock` in a single Jest test suite, require `opfs-mock` at the beginning of the test file, as described above.
115
+
116
+ To use it on all Jest tests without having to include it in each file, add the auto setup script to the `setupFiles` in your Jest config:
117
+
118
+ ```ts
119
+ // jest.config.js
120
+
121
+ {
122
+ ...
123
+ "setupFiles": [
124
+ "opfs-mock"
125
+ ]
126
+ }
127
+ ```
128
+
129
+ Alternatively you can create a new setup file which then imports this module.
130
+
131
+ ```ts
132
+ // jest-setup.ts
133
+
134
+ import "opfs-mock";
135
+ ```
136
+
137
+ Add that file to your `setupFiles` array:
138
+
139
+ ```ts
140
+ // jest.config.js
141
+
142
+ {
143
+ ...
144
+ "setupFiles": [
145
+ "jest-setup"
146
+ ]
147
+ }
148
+ ```
149
+
150
+ ## Wiping/resetting the OPFS mock for a fresh state
151
+
152
+ If you are keeping your tests completely isolated you might want to "reset" the state of the mocked OPFS. You can do this by using `resetMockOPFS` function, which creates a completely new instance of the mock.
153
+
154
+ ```ts
155
+ import { resetMockOPFS } from 'opfs-mock';
156
+
157
+ beforeEach(() => {
158
+ resetMockOPFS();
159
+ });
160
+
161
+ test('First isolated test', async () => {
162
+ // rest of your test
163
+ });
164
+
165
+ test('Second isolated test', async () => {
166
+ // rest of your test
167
+ });
168
+ ```
package/dist/index.d.ts CHANGED
@@ -1,5 +1,10 @@
1
- declare const storageFactory: ({ usage, quota }?: StorageEstimate) => StorageManager;
1
+ //#region src/index.d.ts
2
+ declare const storageFactory: ({
3
+ usage,
4
+ quota
5
+ }?: StorageEstimate) => StorageManager;
2
6
  declare const mockOPFS: () => void;
3
7
  declare const resetMockOPFS: () => void;
4
8
 
5
- export { mockOPFS, resetMockOPFS, storageFactory };
9
+ //#endregion
10
+ export { mockOPFS, resetMockOPFS, storageFactory };
package/dist/index.js CHANGED
@@ -1,321 +1,231 @@
1
- // src/utils.ts
2
- var isFileHandle = (handle) => {
3
- return handle.kind === "file";
1
+ //#region src/utils.ts
2
+ const isFileHandle = (handle) => {
3
+ return handle.kind === "file";
4
4
  };
5
- var isDirectoryHandle = (handle) => {
6
- return handle.kind === "directory";
5
+ const isDirectoryHandle = (handle) => {
6
+ return handle.kind === "directory";
7
7
  };
8
- var getSizeOfDirectory = async (directory) => {
9
- let totalSize = 0;
10
- for await (const handle of directory.values()) {
11
- if (isFileHandle(handle)) {
12
- const file = await handle.getFile();
13
- totalSize += file.size;
14
- } else if (isDirectoryHandle(handle)) {
15
- totalSize += await getSizeOfDirectory(handle);
16
- }
17
- }
18
- return totalSize;
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;
19
15
  };
20
16
 
21
- // src/opfs.ts
22
- var fileSystemFileHandleFactory = (name, fileData) => {
23
- return {
24
- kind: "file",
25
- name,
26
- isSameEntry: async (other) => {
27
- return other.name === name && other.kind === "file";
28
- },
29
- getFile: async () => new File([fileData.content], name),
30
- createWritable: async (options) => {
31
- const keepExistingData = options?.keepExistingData;
32
- let abortReason = "";
33
- let isAborted = false;
34
- let isClosed = false;
35
- let content = keepExistingData ? fileData.content : "";
36
- let cursorPosition = keepExistingData ? fileData.content.length : 0;
37
- const writableStream = new WritableStream({
38
- write: () => {
39
- },
40
- close: () => {
41
- },
42
- abort: () => {
43
- }
44
- });
45
- return Object.assign(writableStream, {
46
- getWriter: () => writableStream.getWriter(),
47
- write: async function(chunk) {
48
- if (isAborted) {
49
- throw new Error(abortReason);
50
- }
51
- if (isClosed) {
52
- throw new TypeError("Cannot write to a CLOSED writable stream");
53
- }
54
- if (chunk === void 0) {
55
- throw new TypeError("Cannot write undefined data to the stream");
56
- }
57
- let chunkText;
58
- if (typeof chunk === "string") {
59
- chunkText = chunk;
60
- } else if (chunk instanceof Blob) {
61
- chunkText = await chunk.text();
62
- } else if (ArrayBuffer.isView(chunk)) {
63
- chunkText = new TextDecoder().decode(new Uint8Array(chunk.buffer));
64
- } else if (typeof chunk === "object" && "data" in chunk) {
65
- if (chunk.position !== void 0 && (typeof chunk.position !== "number" || chunk.position < 0)) {
66
- throw new TypeError("Invalid position value in write parameters");
67
- }
68
- if (chunk.size !== void 0 && (typeof chunk.size !== "number" || chunk.size < 0)) {
69
- throw new TypeError("Invalid size value in write parameters");
70
- }
71
- if (chunk.position !== void 0 && chunk.position !== null) {
72
- cursorPosition = chunk.position;
73
- }
74
- if (chunk.data) {
75
- if (typeof chunk.data === "string") {
76
- chunkText = chunk.data;
77
- } else if (chunk.data instanceof Blob) {
78
- chunkText = await chunk.data.text();
79
- } else {
80
- chunkText = new TextDecoder().decode(new Uint8Array(chunk.data instanceof ArrayBuffer ? chunk.data : chunk.data.buffer));
81
- }
82
- } else {
83
- chunkText = "";
84
- }
85
- } else {
86
- throw new TypeError("Invalid data type written to the file. Data must be of type FileSystemWriteChunkType.");
87
- }
88
- content = content.slice(0, cursorPosition) + chunkText + content.slice(cursorPosition + chunkText.length);
89
- cursorPosition += chunkText.length;
90
- },
91
- close: async function() {
92
- if (isClosed) {
93
- throw new TypeError("Cannot close a CLOSED writable stream");
94
- }
95
- if (isAborted) {
96
- throw new TypeError("Cannot close a ERRORED writable stream");
97
- }
98
- isClosed = true;
99
- fileData.content = content;
100
- },
101
- abort: async function(reason) {
102
- if (isAborted) {
103
- return;
104
- }
105
- if (reason && !abortReason) {
106
- abortReason = reason;
107
- }
108
- isAborted = true;
109
- return Promise.resolve(void 0);
110
- },
111
- truncate: async function(size) {
112
- if (size < 0) {
113
- throw new DOMException("Invalid truncate size", "IndexSizeError");
114
- }
115
- if (size < content.length) {
116
- content = content.slice(0, size);
117
- } else {
118
- content = content.padEnd(size, "\0");
119
- }
120
- cursorPosition = Math.min(cursorPosition, size);
121
- },
122
- seek: async function(position) {
123
- if (position < 0 || position > content.length) {
124
- throw new DOMException("Invalid seek position", "IndexSizeError");
125
- }
126
- cursorPosition = position;
127
- }
128
- });
129
- },
130
- createSyncAccessHandle: async () => {
131
- let closed = false;
132
- return {
133
- getSize: () => {
134
- if (closed) {
135
- throw new DOMException("InvalidStateError", "The access handle is closed");
136
- }
137
- return fileData.content.length;
138
- },
139
- read: (buffer, { at = 0 } = {}) => {
140
- if (closed) {
141
- throw new DOMException("InvalidStateError", "The access handle is closed");
142
- }
143
- const text = new TextEncoder().encode(fileData.content);
144
- const bytesRead = Math.min(buffer.length, text.length - at);
145
- buffer.set(text.subarray(at, at + bytesRead));
146
- return bytesRead;
147
- },
148
- write: (data, options) => {
149
- const at = options?.at ?? 0;
150
- if (closed) {
151
- throw new DOMException("InvalidStateError", "The access handle is closed");
152
- }
153
- const newContent = new TextDecoder().decode(data);
154
- if (at < fileData.content.length) {
155
- fileData.content = fileData.content.slice(0, at) + newContent + fileData.content.slice(at + newContent.length);
156
- } else {
157
- fileData.content += newContent;
158
- }
159
- return data.byteLength;
160
- },
161
- truncate: (size) => {
162
- if (closed) {
163
- throw new DOMException("InvalidStateError", "The access handle is closed");
164
- }
165
- fileData.content = fileData.content.slice(0, size);
166
- },
167
- flush: async () => {
168
- if (closed) {
169
- throw new DOMException("InvalidStateError", "The access handle is closed");
170
- }
171
- },
172
- close: async () => {
173
- closed = true;
174
- }
175
- };
176
- }
177
- };
17
+ //#endregion
18
+ //#region src/opfs.ts
19
+ const fileSystemFileHandleFactory = (name, fileData) => {
20
+ return {
21
+ kind: "file",
22
+ name,
23
+ isSameEntry: async (other) => {
24
+ return other.name === name && other.kind === "file";
25
+ },
26
+ getFile: async () => new File([fileData.content], name),
27
+ createWritable: async (options) => {
28
+ const keepExistingData = options?.keepExistingData;
29
+ let abortReason = "";
30
+ let isAborted = false;
31
+ let isClosed = false;
32
+ let content = keepExistingData ? fileData.content : "";
33
+ let cursorPosition = keepExistingData ? fileData.content.length : 0;
34
+ const writableStream = new WritableStream({
35
+ write: () => {},
36
+ close: () => {},
37
+ abort: () => {}
38
+ });
39
+ return Object.assign(writableStream, {
40
+ getWriter: () => writableStream.getWriter(),
41
+ write: async function(chunk) {
42
+ if (isAborted) throw new Error(abortReason);
43
+ if (isClosed) throw new TypeError("Cannot write to a CLOSED writable stream");
44
+ if (chunk === void 0) throw new TypeError("Cannot write undefined data to the stream");
45
+ let chunkText;
46
+ if (typeof chunk === "string") chunkText = chunk;
47
+ else if (chunk instanceof Blob) chunkText = await chunk.text();
48
+ else if (ArrayBuffer.isView(chunk)) chunkText = new TextDecoder().decode(new Uint8Array(chunk.buffer));
49
+ else if (typeof chunk === "object" && "data" in chunk) {
50
+ if (chunk.position !== void 0 && (typeof chunk.position !== "number" || chunk.position < 0)) throw new TypeError("Invalid position value in write parameters");
51
+ if (chunk.size !== void 0 && (typeof chunk.size !== "number" || chunk.size < 0)) throw new TypeError("Invalid size value in write parameters");
52
+ if (chunk.position !== void 0 && chunk.position !== null) cursorPosition = chunk.position;
53
+ if (chunk.data) if (typeof chunk.data === "string") chunkText = chunk.data;
54
+ else if (chunk.data instanceof Blob) chunkText = await chunk.data.text();
55
+ else chunkText = new TextDecoder().decode(new Uint8Array(chunk.data instanceof ArrayBuffer ? chunk.data : chunk.data.buffer));
56
+ else chunkText = "";
57
+ } else throw new TypeError("Invalid data type written to the file. Data must be of type FileSystemWriteChunkType.");
58
+ content = content.slice(0, cursorPosition) + chunkText + content.slice(cursorPosition + chunkText.length);
59
+ cursorPosition += chunkText.length;
60
+ },
61
+ close: async function() {
62
+ if (isClosed) throw new TypeError("Cannot close a CLOSED writable stream");
63
+ if (isAborted) throw new TypeError("Cannot close a ERRORED writable stream");
64
+ isClosed = true;
65
+ fileData.content = content;
66
+ },
67
+ abort: async function(reason) {
68
+ if (isAborted) return;
69
+ if (reason && !abortReason) abortReason = reason;
70
+ isAborted = true;
71
+ return Promise.resolve(void 0);
72
+ },
73
+ truncate: async function(size) {
74
+ if (size < 0) throw new DOMException("Invalid truncate size", "IndexSizeError");
75
+ if (size < content.length) content = content.slice(0, size);
76
+ else content = content.padEnd(size, "\0");
77
+ cursorPosition = Math.min(cursorPosition, size);
78
+ },
79
+ seek: async function(position) {
80
+ if (position < 0 || position > content.length) throw new DOMException("Invalid seek position", "IndexSizeError");
81
+ cursorPosition = position;
82
+ }
83
+ });
84
+ },
85
+ createSyncAccessHandle: async () => {
86
+ let closed = false;
87
+ return {
88
+ getSize: () => {
89
+ if (closed) throw new DOMException("InvalidStateError", "The access handle is closed");
90
+ return fileData.content.length;
91
+ },
92
+ read: (buffer, { at = 0 } = {}) => {
93
+ if (closed) throw new DOMException("InvalidStateError", "The access handle is closed");
94
+ const text = new TextEncoder().encode(fileData.content);
95
+ const bytesRead = Math.min(buffer.length, text.length - at);
96
+ buffer.set(text.subarray(at, at + bytesRead));
97
+ return bytesRead;
98
+ },
99
+ write: (data, options) => {
100
+ const at = options?.at ?? 0;
101
+ if (closed) throw new DOMException("InvalidStateError", "The access handle is closed");
102
+ const newContent = new TextDecoder().decode(data);
103
+ if (at < fileData.content.length) fileData.content = fileData.content.slice(0, at) + newContent + fileData.content.slice(at + newContent.length);
104
+ else fileData.content += newContent;
105
+ return data.byteLength;
106
+ },
107
+ truncate: (size) => {
108
+ if (closed) throw new DOMException("InvalidStateError", "The access handle is closed");
109
+ fileData.content = fileData.content.slice(0, size);
110
+ },
111
+ flush: async () => {
112
+ if (closed) throw new DOMException("InvalidStateError", "The access handle is closed");
113
+ },
114
+ close: async () => {
115
+ closed = true;
116
+ }
117
+ };
118
+ }
119
+ };
178
120
  };
179
- var fileSystemDirectoryHandleFactory = (name) => {
180
- const files = /* @__PURE__ */ new Map();
181
- const directories = /* @__PURE__ */ new Map();
182
- const getJoinedMaps = () => {
183
- return new Map([...files, ...directories]);
184
- };
185
- return {
186
- kind: "directory",
187
- name,
188
- isSameEntry: async (other) => {
189
- return other.name === name && other.kind === "directory";
190
- },
191
- getFileHandle: async (fileName, options) => {
192
- if (!files.has(fileName) && options?.create) {
193
- files.set(fileName, fileSystemFileHandleFactory(fileName, { content: "" }));
194
- }
195
- const fileHandle = files.get(fileName);
196
- if (!fileHandle) {
197
- throw new Error(`File not found: ${fileName}`);
198
- }
199
- return fileHandle;
200
- },
201
- getDirectoryHandle: async (dirName, options) => {
202
- if (!directories.has(dirName) && options?.create) {
203
- directories.set(dirName, fileSystemDirectoryHandleFactory(dirName));
204
- }
205
- const directoryHandle = directories.get(dirName);
206
- if (!directoryHandle) {
207
- throw new Error(`Directory not found: ${dirName}`);
208
- }
209
- return directoryHandle;
210
- },
211
- removeEntry: async (entryName, options) => {
212
- if (files.has(entryName)) {
213
- files.delete(entryName);
214
- } else if (directories.has(entryName)) {
215
- if (options?.recursive) {
216
- directories.delete(entryName);
217
- } else {
218
- throw new DOMException(`Failed to remove directory: $1${entryName}`, "InvalidModificationError");
219
- }
220
- } else {
221
- throw new DOMException(`No such file or directory: $1${entryName}`, "NotFoundError");
222
- }
223
- },
224
- [Symbol.asyncIterator]: async function* () {
225
- const entries = getJoinedMaps();
226
- for (const [name2, handle] of entries) {
227
- yield [name2, handle];
228
- }
229
- return void 0;
230
- },
231
- entries: async function* () {
232
- const joinedMaps = getJoinedMaps();
233
- yield* joinedMaps.entries();
234
- },
235
- keys: async function* () {
236
- const joinedMaps = getJoinedMaps();
237
- yield* joinedMaps.keys();
238
- },
239
- values: async function* () {
240
- const joinedMaps = getJoinedMaps();
241
- yield* joinedMaps.values();
242
- },
243
- resolve: async function(possibleDescendant) {
244
- const traverseDirectory = async (directory, target, path = []) => {
245
- if (await directory.isSameEntry(target)) {
246
- return path;
247
- }
248
- for await (const [name2, handle] of directory.entries()) {
249
- if (isDirectoryHandle(handle)) {
250
- const result = await traverseDirectory(handle, target, [...path, name2]);
251
- if (result) {
252
- return result;
253
- }
254
- } else if (isFileHandle(handle)) {
255
- if (await handle.isSameEntry(target)) {
256
- return [...path, name2];
257
- }
258
- }
259
- }
260
- return null;
261
- };
262
- return traverseDirectory(this, possibleDescendant);
263
- }
264
- };
121
+ const fileSystemDirectoryHandleFactory = (name) => {
122
+ const files = new Map();
123
+ const directories = new Map();
124
+ const getJoinedMaps = () => {
125
+ return new Map([...files, ...directories]);
126
+ };
127
+ return {
128
+ kind: "directory",
129
+ name,
130
+ isSameEntry: async (other) => {
131
+ return other.name === name && other.kind === "directory";
132
+ },
133
+ getFileHandle: async (fileName, options) => {
134
+ if (!files.has(fileName) && options?.create) files.set(fileName, fileSystemFileHandleFactory(fileName, { content: "" }));
135
+ const fileHandle = files.get(fileName);
136
+ if (!fileHandle) throw new DOMException(`File not found: ${fileName}`, "NotFoundError");
137
+ return fileHandle;
138
+ },
139
+ getDirectoryHandle: async (dirName, options) => {
140
+ if (!directories.has(dirName) && options?.create) directories.set(dirName, fileSystemDirectoryHandleFactory(dirName));
141
+ const directoryHandle = directories.get(dirName);
142
+ if (!directoryHandle) throw new DOMException(`Directory not found: ${dirName}`, "NotFoundError");
143
+ return directoryHandle;
144
+ },
145
+ removeEntry: async (entryName, options) => {
146
+ if (files.has(entryName)) files.delete(entryName);
147
+ else if (directories.has(entryName)) if (options?.recursive) directories.delete(entryName);
148
+ else throw new DOMException(`Failed to remove directory: $1${entryName}`, "InvalidModificationError");
149
+ else throw new DOMException(`No such file or directory: $1${entryName}`, "NotFoundError");
150
+ },
151
+ [Symbol.asyncIterator]: async function* () {
152
+ const entries = getJoinedMaps();
153
+ for (const [name$1, handle] of entries) yield [name$1, handle];
154
+ return void 0;
155
+ },
156
+ entries: async function* () {
157
+ const joinedMaps = getJoinedMaps();
158
+ yield* joinedMaps.entries();
159
+ },
160
+ keys: async function* () {
161
+ const joinedMaps = getJoinedMaps();
162
+ yield* joinedMaps.keys();
163
+ },
164
+ values: async function* () {
165
+ const joinedMaps = getJoinedMaps();
166
+ yield* joinedMaps.values();
167
+ },
168
+ resolve: async function(possibleDescendant) {
169
+ const traverseDirectory = async (directory, target, path = []) => {
170
+ if (await directory.isSameEntry(target)) return path;
171
+ for await (const [name$1, handle] of directory.entries()) if (isDirectoryHandle(handle)) {
172
+ const result = await traverseDirectory(handle, target, [...path, name$1]);
173
+ if (result) return result;
174
+ } else if (isFileHandle(handle)) {
175
+ if (await handle.isSameEntry(target)) return [...path, name$1];
176
+ }
177
+ return null;
178
+ };
179
+ return traverseDirectory(this, possibleDescendant);
180
+ }
181
+ };
265
182
  };
266
183
 
267
- // src/index.ts
268
- var storageFactory = ({ usage = 0, quota = 1024 ** 3 } = {}) => {
269
- const root = fileSystemDirectoryHandleFactory("root");
270
- return {
271
- estimate: async () => {
272
- const defaultUsage = usage;
273
- const calculatedUsage = await getSizeOfDirectory(root);
274
- return {
275
- usage: defaultUsage + calculatedUsage,
276
- quota
277
- };
278
- },
279
- getDirectory: async () => {
280
- return root;
281
- },
282
- persist: async () => {
283
- return true;
284
- },
285
- persisted: async () => {
286
- return true;
287
- }
288
- };
184
+ //#endregion
185
+ //#region src/index.ts
186
+ const storageFactory = ({ usage = 0, quota = 1024 ** 3 } = {}) => {
187
+ const root = fileSystemDirectoryHandleFactory("root");
188
+ return {
189
+ estimate: async () => {
190
+ const defaultUsage = usage;
191
+ const calculatedUsage = await getSizeOfDirectory(root);
192
+ return {
193
+ usage: defaultUsage + calculatedUsage,
194
+ quota
195
+ };
196
+ },
197
+ getDirectory: async () => {
198
+ return root;
199
+ },
200
+ persist: async () => {
201
+ return true;
202
+ },
203
+ persisted: async () => {
204
+ return true;
205
+ }
206
+ };
289
207
  };
290
- var mockOPFS = () => {
291
- if (!("navigator" in globalThis)) {
292
- Object.defineProperty(globalThis, "navigator", {
293
- value: {},
294
- writable: true
295
- });
296
- }
297
- if (!globalThis.navigator.storage) {
298
- const { getDirectory } = storageFactory();
299
- Object.defineProperty(globalThis.navigator, "storage", {
300
- value: {
301
- getDirectory
302
- },
303
- writable: true
304
- });
305
- }
208
+ const mockOPFS = () => {
209
+ if (!("navigator" in globalThis)) Object.defineProperty(globalThis, "navigator", {
210
+ value: {},
211
+ writable: true
212
+ });
213
+ if (!globalThis.navigator.storage) {
214
+ const { getDirectory } = storageFactory();
215
+ Object.defineProperty(globalThis.navigator, "storage", {
216
+ value: { getDirectory },
217
+ writable: true
218
+ });
219
+ }
306
220
  };
307
- var resetMockOPFS = () => {
308
- const root = fileSystemDirectoryHandleFactory("root");
309
- Object.defineProperty(globalThis.navigator.storage, "getDirectory", {
310
- value: () => root,
311
- writable: true
312
- });
313
- };
314
- if (typeof globalThis !== "undefined") {
315
- mockOPFS();
316
- }
317
- export {
318
- mockOPFS,
319
- resetMockOPFS,
320
- storageFactory
221
+ const resetMockOPFS = () => {
222
+ const root = fileSystemDirectoryHandleFactory("root");
223
+ Object.defineProperty(globalThis.navigator.storage, "getDirectory", {
224
+ value: () => root,
225
+ writable: true
226
+ });
321
227
  };
228
+ if (typeof globalThis !== "undefined") mockOPFS();
229
+
230
+ //#endregion
231
+ export { mockOPFS, resetMockOPFS, storageFactory };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opfs-mock",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
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,22 +26,31 @@
26
26
  "main": "dist/index.js",
27
27
  "module": "dist/index.js",
28
28
  "files": ["dist"],
29
+ "engines": {
30
+ "node": ">=20.0.0"
31
+ },
29
32
  "scripts": {
30
- "dev": "tsup --watch",
31
- "build": "tsup",
33
+ "dev": "tsdown --watch",
34
+ "build": "tsdown",
32
35
  "lint:check": "npx @biomejs/biome lint",
33
36
  "lint": "npx @biomejs/biome lint --fix",
34
37
  "format:check": "npx @biomejs/biome format",
35
38
  "format": "npx @biomejs/biome format --write",
36
39
  "type-check": "tsc --noEmit",
37
- "test": "vitest",
40
+ "test": "npm run test:node && npm run test:happy-dom",
41
+ "test:node": "vitest --environment=node",
42
+ "test:jsdom": "vitest --environment=jsdom",
43
+ "test:happy-dom": "vitest --environment=happy-dom",
38
44
  "prepublishOnly": "npm run build",
39
45
  "release": "npm publish --access public"
40
46
  },
41
47
  "devDependencies": {
42
48
  "@biomejs/biome": "1.9.4",
43
- "tsup": "8.4.0",
44
- "typescript": "5.7.3",
45
- "vitest": "3.0.7"
49
+ "@web-std/file": "3.0.3",
50
+ "happy-dom": "17.4.7",
51
+ "jsdom": "26.1.0",
52
+ "tsdown": "0.12.3",
53
+ "typescript": "5.8.3",
54
+ "vitest": "3.1.4"
46
55
  }
47
56
  }