All files / lib/storage opfs.ts

92.3% Statements 60/65
85% Branches 17/20
100% Functions 18/18
91.52% Lines 54/59

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135              3x         3x                     88x 32x     56x     32x       9x 9x 9x     3x     5x   5x 5x   4x 4x           1x     1x 1x     3x 3x   3x   1x 5x       1x     4x     4x     7x       7x 1x 6x 2x 4x 3x   1x     7x   7x 7x 7x     2x 2x 2x 2x     4x 4x   4x   2x 2x 9x     2x     1x 1x   1x 1x 1x                  
import type { BinaryStorageBackend, BinaryStorageLocator } from './types.js';
 
import { pick } from '$lib/utils.js';
 
import { locatorToPath } from './utils.js';
 
export async function OPFSBackend(): Promise<BinaryStorageBackend<'opfs'>> {
	Iif (localStorage.getItem('playwright_mock_opfs') === 'true') {
		console.debug('Mocking OPFS...');
		await import('opfs-mock');
	}
 
	const root = await navigator.storage.getDirectory();
 
	// TODO:
	// If we're running in a web worker, we can use sync access handles, which are more performant
	// See https://developer.mozilla.org/en-US/docs/Web/API/FileSystemSyncAccessHandle
	// const isInWebWorker =
	// 	typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
 
	/** Get to the directory handle of the given path */
	async function walk(locator: BinaryStorageLocator) {
		async function recurse([top, ...rest]: string[], base: FileSystemDirectoryHandle) {
			if (rest.length === 0) {
				return [base, top] as const;
			}
 
			return recurse(rest, await base.getDirectoryHandle(top, { create: true }));
		}
 
		return recurse(locatorToPath(locator).split('/'), root);
	}
 
	async function getFile(locator: BinaryStorageLocator) {
		const [directory, name] = await walk(locator);
		const handle = await directory.getFileHandle(name);
		return await handle.getFile();
	}
 
	return {
		name: 'opfs',
		async exists(locator) {
			const [directory, name] = await walk(locator);
 
			try {
				await directory.getFileHandle(name);
			} catch (error) {
				Eif (error instanceof DOMException && error.name === 'NotFoundError') {
					return false;
				}
 
				throw error;
			}
 
			return true;
		},
		async delete(locator) {
			const [directory, name] = await walk(locator);
			await directory.removeEntry(name);
		},
		async *list(locator) {
			const [parent, name] = await walk(locator);
			const directory = await parent.getDirectoryHandle(name).catch(() => undefined);
 
			if (!directory) return;
 
			for await (const name of directory.keys()) {
				yield { ...locator, name };
			}
		},
		async read(locator) {
			return getFile(locator);
		},
		async bytes(locator) {
			return getFile(locator).then((file) => file.arrayBuffer());
		},
		async text(locator) {
			return getFile(locator).then((file) => file.text());
		},
		async write(locator, content) {
			const [directory, name] = await walk(locator);
 
			let blob: Blob;
 
			if (content instanceof Blob) {
				blob = content;
			} else if ('text' in content) {
				blob = new Blob([content.text], pick(content, 'type'));
			} else if ('bytes' in content) {
				blob = new Blob([content.bytes], pick(content, 'type'));
			} else {
				blob = new Blob([Uint8Array.fromBase64(content.base64)], pick(content, 'type'));
			}
 
			const handle = await directory.getFileHandle(name, { create: true });
 
			const writable = await handle.createWritable();
			await writable.write(blob);
			await writable.close();
		},
		async size(locator) {
			const [directory, name] = await walk(locator);
			const handle = await directory.getFileHandle(name);
			const file = await handle.getFile();
			return file.size;
		},
		async count(locator) {
			const [parent, name] = await walk(locator);
			const directory = await parent.getDirectoryHandle(name).catch(() => undefined);
 
			if (!directory) return 0;
 
			let total = 0;
			for await (const _ of directory) {
				total++;
			}
 
			return total;
		},
		async clear(locator) {
			const [parent, name] = await walk(locator);
			const directory = await parent.getDirectoryHandle(name);
 
			Eif (directory.remove) {
				await directory.remove({ recursive: true });
				return;
			}
 
			for await (const name of parent.keys()) {
				await parent.removeEntry(name, { recursive: true });
			}
		},
	};
}