opfs-mock 1.0.0 → 1.0.2

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
@@ -18,12 +18,27 @@ The easiest way to use it is to import `opfs-mock`, which will polyfill OPFS API
18
18
  import "opfs-mock";
19
19
  ```
20
20
 
21
- Alternatively, you can explicitly import `storage`:
21
+ Alternatively, you can explicitly import `storageFactory`:
22
22
 
23
23
  ```ts
24
- import { storage } from "opfs-mock";
24
+ import { storageFactory } from "opfs-mock";
25
25
 
26
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 predefined `quota` and `estimate` values set to `0`, which is fine if you're not using these properties.
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, estimate: 1_000 });
27
42
  const root = await storage.getDirectory();
28
43
  const directoryHandle = await root.getFileHandle('test-file.txt', { create: true });
29
44
  // rest of your test
@@ -37,14 +52,22 @@ To use `opfs-mock` in a single Vitest test suite, require `opfs-mock` at the beg
37
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:
38
53
 
39
54
  ```ts
40
- // vite.config.js
55
+ // vite.config.ts
41
56
 
42
- {
57
+ import { defineConfig as defineViteConfig, mergeConfig } from 'vite';
58
+ import { defineConfig as defineVitestConfig } from 'vitest/config';
59
+
60
+ const viteConfig = defineViteConfig({
43
61
  ...
62
+ });
63
+
64
+ const vitestConfig = defineVitestConfig({
44
65
  test: {
45
66
  setupFiles: ['opfs-mock'],
46
67
  },
47
- }
68
+ });
69
+
70
+ export default mergeConfig(viteConfig, vitestConfig);
48
71
  ```
49
72
 
50
73
  Alternatively you can create a new setup file which then imports this module.
@@ -60,13 +83,20 @@ Add that file to your `test.setupFiles` array:
60
83
  ```ts
61
84
  // vite.config.ts
62
85
 
63
- import { defineConfig } from 'vite'
86
+ import { defineConfig as defineViteConfig, mergeConfig } from 'vite';
87
+ import { defineConfig as defineVitestConfig } from 'vitest/config';
64
88
 
65
- export default defineConfig({
89
+ const viteConfig = defineViteConfig({
90
+ ...
91
+ });
92
+
93
+ const vitestConfig = defineVitestConfig({
66
94
  test: {
67
95
  setupFiles: ['vitest-setup.ts'],
68
- }
96
+ },
69
97
  });
98
+
99
+ export default mergeConfig(viteConfig, vitestConfig);
70
100
  ```
71
101
 
72
102
 
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- declare const storage: () => StorageManager;
1
+ declare const storageFactory: ({ usage, quota }?: StorageEstimate) => StorageManager;
2
2
  declare const mockOPFS: () => void;
3
3
  declare const resetMockOPFS: () => void;
4
- export { mockOPFS, resetMockOPFS, storage };
4
+
5
+ export { mockOPFS, resetMockOPFS, storageFactory };
package/dist/index.js CHANGED
@@ -1,128 +1,186 @@
1
- const g = (o, n) => ({
2
- kind: "file",
3
- name: o,
4
- isSameEntry: async (t) => t.name === o && t.kind === "file",
5
- getFile: async () => new File([n.content], o, {
6
- type: "application/json"
7
- }),
8
- // @ts-ignore TODO: Implement options, add missing properties
9
- createWritable: async (t) => new WritableStream({
10
- write: (e) => {
11
- const r = new TextDecoder().decode(e);
12
- n.content += r;
13
- },
14
- close: () => {
15
- },
16
- abort: (e) => {
17
- }
18
- }).getWriter(),
19
- createSyncAccessHandle: async () => ({
20
- getSize: () => n.content.length,
21
- read: (t, { at: s = 0 } = {}) => {
22
- const e = new TextEncoder().encode(n.content), r = Math.min(t.length, e.length - s);
23
- return t.set(e.subarray(s, s + r)), r;
24
- },
25
- write: (t, { at: s = 0 } = {}) => {
26
- const e = new TextDecoder().decode(t), r = n.content.length;
27
- return s < r ? n.content = n.content.slice(0, s) + e + n.content.slice(s + e.length) : n.content += e, t.byteLength;
28
- },
29
- // Flush is a no-op in memory
30
- flush: async () => {
1
+ // src/opfs.ts
2
+ var fileSystemFileHandleFactory = (name, fileData) => {
3
+ return {
4
+ kind: "file",
5
+ name,
6
+ isSameEntry: async (other) => {
7
+ return other.name === name && other.kind === "file";
31
8
  },
32
- // Close is a no-op in memory
33
- close: async () => {
9
+ getFile: async () => new File([fileData.content], name, {
10
+ type: "application/json"
11
+ }),
12
+ // @ts-ignore TODO: Implement options, add missing properties
13
+ createWritable: async (_options) => {
14
+ const writableStream = new WritableStream({
15
+ write: (chunk) => {
16
+ const newContent = new TextDecoder().decode(chunk);
17
+ fileData.content += newContent;
18
+ },
19
+ close: () => {
20
+ },
21
+ abort: (_reason) => {
22
+ }
23
+ });
24
+ return writableStream.getWriter();
34
25
  },
35
- truncate: async (t) => {
36
- n.content = n.content.slice(0, t);
37
- }
38
- })
39
- }), y = (o) => {
40
- const n = /* @__PURE__ */ new Map(), t = /* @__PURE__ */ new Map(), s = () => new Map([...n, ...t]);
26
+ createSyncAccessHandle: async () => ({
27
+ getSize: () => fileData.content.length,
28
+ read: (buffer, { at = 0 } = {}) => {
29
+ const text = new TextEncoder().encode(fileData.content);
30
+ const bytesRead = Math.min(buffer.length, text.length - at);
31
+ buffer.set(text.subarray(at, at + bytesRead));
32
+ return bytesRead;
33
+ },
34
+ write: (data, { at = 0 } = {}) => {
35
+ const newContent = new TextDecoder().decode(data);
36
+ const originalLength = fileData.content.length;
37
+ if (at < originalLength) {
38
+ fileData.content = fileData.content.slice(0, at) + newContent + fileData.content.slice(at + newContent.length);
39
+ } else {
40
+ fileData.content += newContent;
41
+ }
42
+ return data.byteLength;
43
+ },
44
+ // Flush is a no-op in memory
45
+ flush: async () => {
46
+ },
47
+ // Close is a no-op in memory
48
+ close: async () => {
49
+ },
50
+ truncate: async (size) => {
51
+ fileData.content = fileData.content.slice(0, size);
52
+ }
53
+ })
54
+ };
55
+ };
56
+ var fileSystemDirectoryHandleFactory = (name) => {
57
+ const files = /* @__PURE__ */ new Map();
58
+ const directories = /* @__PURE__ */ new Map();
59
+ const getJoinedMaps = () => {
60
+ return new Map([...files, ...directories]);
61
+ };
41
62
  return {
42
63
  kind: "directory",
43
- name: o,
44
- isSameEntry: async (e) => e.name === o && e.kind === "directory",
45
- getFileHandle: async (e, r) => {
46
- !n.has(e) && (r != null && r.create) && n.set(e, g(e, { content: "" }));
47
- const c = n.get(e);
48
- if (!c)
49
- throw new Error(`File not found: ${e}`);
50
- return c;
64
+ name,
65
+ isSameEntry: async (other) => {
66
+ return other.name === name && other.kind === "directory";
67
+ },
68
+ getFileHandle: async (fileName, options) => {
69
+ if (!files.has(fileName) && options?.create) {
70
+ files.set(fileName, fileSystemFileHandleFactory(fileName, { content: "" }));
71
+ }
72
+ const fileHandle = files.get(fileName);
73
+ if (!fileHandle) {
74
+ throw new Error(`File not found: ${fileName}`);
75
+ }
76
+ return fileHandle;
51
77
  },
52
- getDirectoryHandle: async (e, r) => {
53
- !t.has(e) && (r != null && r.create) && t.set(e, y(e));
54
- const c = t.get(e);
55
- if (!c)
56
- throw new Error(`Directory not found: ${e}`);
57
- return c;
78
+ getDirectoryHandle: async (dirName, options) => {
79
+ if (!directories.has(dirName) && options?.create) {
80
+ directories.set(dirName, fileSystemDirectoryHandleFactory(dirName));
81
+ }
82
+ const directoryHandle = directories.get(dirName);
83
+ if (!directoryHandle) {
84
+ throw new Error(`Directory not found: ${dirName}`);
85
+ }
86
+ return directoryHandle;
58
87
  },
59
- removeEntry: async (e) => {
60
- if (n.has(e))
61
- n.delete(e);
62
- else if (t.has(e))
63
- t.delete(e);
64
- else
65
- throw new Error(`Entry not found: ${e}`);
88
+ removeEntry: async (entryName) => {
89
+ if (files.has(entryName)) {
90
+ files.delete(entryName);
91
+ } else if (directories.has(entryName)) {
92
+ directories.delete(entryName);
93
+ } else {
94
+ throw new Error(`Entry not found: ${entryName}`);
95
+ }
66
96
  },
67
97
  entries: async function* () {
68
- yield* s().entries();
98
+ const joinedMaps = getJoinedMaps();
99
+ yield* joinedMaps.entries();
69
100
  },
70
101
  keys: async function* () {
71
- yield* s().keys();
102
+ const joinedMaps = getJoinedMaps();
103
+ yield* joinedMaps.keys();
72
104
  },
73
105
  values: async function* () {
74
- yield* s().values();
106
+ const joinedMaps = getJoinedMaps();
107
+ yield* joinedMaps.values();
75
108
  },
76
- resolve: async (e) => {
77
- const r = async (c, a, l = []) => {
78
- if (await c.isSameEntry(a))
79
- return l;
80
- for await (const [d, i] of c.entries())
81
- if (i.kind === "directory") {
82
- const u = await r(i, a, [...l, d]);
83
- if (u)
84
- return u;
85
- } else if (i.kind === "file" && await i.isSameEntry(a))
86
- return [...l, d];
109
+ resolve: async (possibleDescendant) => {
110
+ const traverseDirectory = async (directory, target, path = []) => {
111
+ if (await directory.isSameEntry(target)) {
112
+ return path;
113
+ }
114
+ for await (const [name2, handle] of directory.entries()) {
115
+ if (handle.kind === "directory") {
116
+ const subDirectory = handle;
117
+ const result = await traverseDirectory(subDirectory, target, [...path, name2]);
118
+ if (result) {
119
+ return result;
120
+ }
121
+ } else if (handle.kind === "file") {
122
+ if (await handle.isSameEntry(target)) {
123
+ return [...path, name2];
124
+ }
125
+ }
126
+ }
87
127
  return null;
88
128
  };
89
- return r(void 0, e);
129
+ return traverseDirectory(void 0, possibleDescendant);
90
130
  }
91
131
  };
92
- }, w = () => {
93
- const o = y("root");
132
+ };
133
+
134
+ // src/index.ts
135
+ var storageFactory = ({ usage = 0, quota = 0 } = {}) => {
136
+ const root = fileSystemDirectoryHandleFactory("root");
94
137
  return {
95
- estimate: async () => ({
96
- usage: 0,
97
- quota: 0
98
- }),
99
- getDirectory: async () => o,
100
- persist: async () => !0,
101
- persisted: async () => !0
138
+ estimate: async () => {
139
+ return {
140
+ usage,
141
+ quota
142
+ };
143
+ },
144
+ getDirectory: async () => {
145
+ return root;
146
+ },
147
+ persist: async () => {
148
+ return true;
149
+ },
150
+ persisted: async () => {
151
+ return true;
152
+ }
102
153
  };
103
- }, b = () => {
104
- if ("navigator" in globalThis || Object.defineProperty(globalThis, "navigator", {
105
- value: {},
106
- writable: !0
107
- }), !globalThis.navigator.storage) {
108
- const { getDirectory: o } = w();
154
+ };
155
+ var mockOPFS = () => {
156
+ if (!("navigator" in globalThis)) {
157
+ Object.defineProperty(globalThis, "navigator", {
158
+ value: {},
159
+ writable: true
160
+ });
161
+ }
162
+ if (!globalThis.navigator.storage) {
163
+ const { getDirectory } = storageFactory();
109
164
  Object.defineProperty(globalThis.navigator, "storage", {
110
165
  value: {
111
- getDirectory: o
166
+ getDirectory
112
167
  },
113
- writable: !0
168
+ writable: true
114
169
  });
115
170
  }
116
- }, h = () => {
117
- const o = y("root");
171
+ };
172
+ var resetMockOPFS = () => {
173
+ const root = fileSystemDirectoryHandleFactory("root");
118
174
  Object.defineProperty(globalThis.navigator.storage, "getDirectory", {
119
- value: () => o,
120
- writable: !0
175
+ value: () => root,
176
+ writable: true
121
177
  });
122
178
  };
123
- typeof globalThis < "u" && b();
179
+ if (typeof globalThis !== "undefined") {
180
+ mockOPFS();
181
+ }
124
182
  export {
125
- b as mockOPFS,
126
- h as resetMockOPFS,
127
- w as storage
183
+ mockOPFS,
184
+ resetMockOPFS,
185
+ storageFactory
128
186
  };
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "opfs-mock",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "type": "module",
5
5
  "description": "Mock all origin private file system APIs for your Jest or Vitest tests",
6
- "author": "jurerotar <hello@jurerotar.com>",
6
+ "author": "Jure Rotar <hello@jurerotar.com>",
7
7
  "license": "MIT",
8
8
  "homepage": "https://github.com/jurerotar/opfs-mock#README",
9
9
  "repository": {
@@ -23,25 +23,25 @@
23
23
  "import": "./dist/index.js"
24
24
  }
25
25
  },
26
+ "main": "dist/index.js",
26
27
  "module": "dist/index.js",
27
28
  "files": ["dist"],
28
29
  "scripts": {
29
- "dev": "vite",
30
- "build": "vite build",
30
+ "dev": "tsup --watch",
31
+ "build": "tsup",
31
32
  "lint:check": "npx @biomejs/biome lint",
32
33
  "lint": "npx @biomejs/biome lint --fix",
33
34
  "format:check": "npx @biomejs/biome format",
34
35
  "format": "npx @biomejs/biome format --write",
35
36
  "type-check": "tsc --noEmit",
36
37
  "test": "vitest",
37
- "build:types": "tsc --emitDeclarationOnly",
38
- "prepublishOnly": "npm run build && npm run build:types",
38
+ "prepublishOnly": "npm run build",
39
39
  "release": "npm publish --access public"
40
40
  },
41
41
  "devDependencies": {
42
- "@biomejs/biome": "1.9.3",
43
- "typescript": "5.6.2",
44
- "vite": "5.4.8",
45
- "vitest": "2.1.2"
42
+ "@biomejs/biome": "1.9.4",
43
+ "tsup": "8.3.5",
44
+ "typescript": "5.7.3",
45
+ "vitest": "2.1.8"
46
46
  }
47
47
  }
package/dist/opfs.d.ts DELETED
@@ -1 +0,0 @@
1
- export declare const fileSystemDirectoryHandleFactory: (name: string) => FileSystemDirectoryHandle;