opfs-mock 1.0.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 ADDED
@@ -0,0 +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
package/README.md ADDED
@@ -0,0 +1,129 @@
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 `storage`:
22
+
23
+ ```ts
24
+ import { storage } from "opfs-mock";
25
+
26
+ test('Your test', async () => {
27
+ const root = await storage.getDirectory();
28
+ const directoryHandle = await root.getFileHandle('test-file.txt', { create: true });
29
+ // rest of your test
30
+ });
31
+ ```
32
+
33
+ ### Vitest
34
+
35
+ To use `opfs-mock` in a single Vitest test suite, require `opfs-mock` at the beginning of the test file, as described above.
36
+
37
+ 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
+
39
+ ```ts
40
+ // vite.config.js
41
+
42
+ {
43
+ ...
44
+ test: {
45
+ setupFiles: ['opfs-mock'],
46
+ },
47
+ }
48
+ ```
49
+
50
+ Alternatively you can create a new setup file which then imports this module.
51
+
52
+ ```ts
53
+ // vitest-setup.ts
54
+
55
+ import "opfs-mock";
56
+ ```
57
+
58
+ Add that file to your `test.setupFiles` array:
59
+
60
+ ```ts
61
+ // vite.config.ts
62
+
63
+ import { defineConfig } from 'vite'
64
+
65
+ export default defineConfig({
66
+ test: {
67
+ setupFiles: ['vitest-setup.ts'],
68
+ }
69
+ });
70
+ ```
71
+
72
+
73
+ ### Jest
74
+
75
+ To use `opfs-mock` in a single Jest test suite, require `opfs-mock` at the beginning of the test file, as described above.
76
+
77
+ 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:
78
+
79
+ ```ts
80
+ // jest.config.js
81
+
82
+ {
83
+ ...
84
+ "setupFiles": [
85
+ "opfs-mock"
86
+ ]
87
+ }
88
+ ```
89
+
90
+ Alternatively you can create a new setup file which then imports this module.
91
+
92
+ ```ts
93
+ // jest-setup.ts
94
+
95
+ import "opfs-mock";
96
+ ```
97
+
98
+ Add that file to your `setupFiles` array:
99
+
100
+ ```ts
101
+ // jest.config.js
102
+
103
+ {
104
+ ...
105
+ "setupFiles": [
106
+ "jest-setup"
107
+ ]
108
+ }
109
+ ```
110
+
111
+ ## Wiping/resetting the OPFS mock for a fresh state
112
+
113
+ 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.
114
+
115
+ ```ts
116
+ import { resetMockOPFS } from 'opfs-mock';
117
+
118
+ beforeEach(() => {
119
+ resetMockOPFS();
120
+ });
121
+
122
+ test('First isolated test', async () => {
123
+ // rest of your test
124
+ });
125
+
126
+ test('Second isolated test', async () => {
127
+ // rest of your test
128
+ });
129
+ ```
@@ -0,0 +1,4 @@
1
+ declare const storage: () => StorageManager;
2
+ declare const mockOPFS: () => void;
3
+ declare const resetMockOPFS: () => void;
4
+ export { mockOPFS, resetMockOPFS, storage };
package/dist/index.js ADDED
@@ -0,0 +1,128 @@
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 () => {
31
+ },
32
+ // Close is a no-op in memory
33
+ close: async () => {
34
+ },
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]);
41
+ return {
42
+ 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;
51
+ },
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;
58
+ },
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}`);
66
+ },
67
+ entries: async function* () {
68
+ yield* s().entries();
69
+ },
70
+ keys: async function* () {
71
+ yield* s().keys();
72
+ },
73
+ values: async function* () {
74
+ yield* s().values();
75
+ },
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];
87
+ return null;
88
+ };
89
+ return r(void 0, e);
90
+ }
91
+ };
92
+ }, w = () => {
93
+ const o = y("root");
94
+ return {
95
+ estimate: async () => ({
96
+ usage: 0,
97
+ quota: 0
98
+ }),
99
+ getDirectory: async () => o,
100
+ persist: async () => !0,
101
+ persisted: async () => !0
102
+ };
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();
109
+ Object.defineProperty(globalThis.navigator, "storage", {
110
+ value: {
111
+ getDirectory: o
112
+ },
113
+ writable: !0
114
+ });
115
+ }
116
+ }, h = () => {
117
+ const o = y("root");
118
+ Object.defineProperty(globalThis.navigator.storage, "getDirectory", {
119
+ value: () => o,
120
+ writable: !0
121
+ });
122
+ };
123
+ typeof globalThis < "u" && b();
124
+ export {
125
+ b as mockOPFS,
126
+ h as resetMockOPFS,
127
+ w as storage
128
+ };
package/dist/opfs.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare const fileSystemDirectoryHandleFactory: (name: string) => FileSystemDirectoryHandle;
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "opfs-mock",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "description": "Mock all origin private file system APIs for your Jest or Vitest tests",
6
+ "author": "jurerotar <hello@jurerotar.com>",
7
+ "license": "MIT",
8
+ "homepage": "https://github.com/jurerotar/opfs-mock#README",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/jurerotar/opfs-mock.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/jurerotar/opfs-mock/issues"
15
+ },
16
+ "keywords": ["vitest", "jest", "test", "mock", "opfs", "storage", "node", "browser"],
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "import": "./dist/index.js"
24
+ }
25
+ },
26
+ "module": "dist/index.js",
27
+ "files": ["dist"],
28
+ "scripts": {
29
+ "dev": "vite",
30
+ "build": "vite build",
31
+ "lint:check": "npx @biomejs/biome lint",
32
+ "lint": "npx @biomejs/biome lint --fix",
33
+ "format:check": "npx @biomejs/biome format",
34
+ "format": "npx @biomejs/biome format --write",
35
+ "type-check": "tsc --noEmit",
36
+ "test": "vitest",
37
+ "build:types": "tsc --emitDeclarationOnly",
38
+ "prepublishOnly": "npm run build && npm run build:types",
39
+ "release": "npm publish --access public"
40
+ },
41
+ "devDependencies": {
42
+ "@biomejs/biome": "1.9.3",
43
+ "typescript": "5.6.2",
44
+ "vite": "5.4.8",
45
+ "vitest": "2.1.2"
46
+ }
47
+ }