opfs-worker 0.2.1 → 0.2.3

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/worker.js DELETED
@@ -1,818 +0,0 @@
1
- import { expose } from 'comlink';
2
- import { decodeBuffer } from './utils/encoder';
3
- import { FileNotFoundError, OPFSError, OPFSNotMountedError, PathError } from './utils/errors';
4
- import { calculateFileHash, checkOPFSSupport, joinPath, readFileData, splitPath, writeFileData, basename, dirname, normalizePath, resolvePath, convertBlobToUint8Array } from './utils/helpers';
5
- /**
6
- * OPFS (Origin Private File System) File System implementation
7
- *
8
- * This class provides a high-level interface for working with the browser's
9
- * Origin Private File System API, offering file and directory operations
10
- * similar to Node.js fs module.
11
- *
12
- * @example
13
- * ```typescript
14
- * const fs = new OPFSFileSystem();
15
- * await fs.init('/my-app');
16
- * await fs.writeFile('/data/config.json', JSON.stringify({ theme: 'dark' }));
17
- * const config = await fs.readFile('/data/config.json');
18
- * ```
19
- */
20
- export class OPFSWorker {
21
- /** Root directory handle for the file system */
22
- root = null;
23
- /** Watch event callback */
24
- watchCallback = null;
25
- /** Map of watched paths to their last known state */
26
- watchers = new Map();
27
- /** Interval handle for polling watched paths */
28
- watchTimer = null;
29
- /** Polling interval in milliseconds */
30
- watchInterval = 1000;
31
- /** Flag to avoid concurrent scans */
32
- scanning = false;
33
- /**
34
- * Creates a new OPFSFileSystem instance
35
- *
36
- * @throws {OPFSError} If OPFS is not supported in the current browser
37
- */
38
- constructor() {
39
- checkOPFSSupport();
40
- }
41
- /**
42
- * Initialize the file system within a given directory
43
- *
44
- * This method sets up the root directory for all subsequent operations.
45
- * It must be called before any other file system operations.
46
- *
47
- * @param root - The root path for the file system (default: '/')
48
- * @returns Promise that resolves to true if initialization was successful
49
- * @throws {OPFSError} If initialization fails
50
- *
51
- * @example
52
- * ```typescript
53
- * const fs = new OPFSFileSystem();
54
- * const success = await fs.init('/my-app');
55
- * ```
56
- */
57
- async mount(root = '/', watchCallback, options) {
58
- try {
59
- const rootDir = await navigator.storage.getDirectory();
60
- this.root = await this.getDirectoryHandle(root, true, rootDir);
61
- if (watchCallback) {
62
- this.watchCallback = watchCallback;
63
- if (options?.watchInterval) {
64
- this.watchInterval = options.watchInterval;
65
- }
66
- }
67
- return true;
68
- }
69
- catch (error) {
70
- console.error(error);
71
- throw new OPFSError('Failed to initialize OPFS', 'INIT_FAILED');
72
- }
73
- }
74
- /**
75
- * Get a directory handle from a path
76
- *
77
- * Navigates through the directory structure to find or create a directory
78
- * at the specified path.
79
- *
80
- * @param path - The path to the directory (string or array of segments)
81
- * @param create - Whether to create the directory if it doesn't exist (default: false)
82
- * @param from - The directory to start from (default: root directory)
83
- * @returns Promise that resolves to the directory handle
84
- * @throws {OPFSError} If the directory cannot be accessed or created
85
- *
86
- * @example
87
- * ```typescript
88
- * const docsDir = await fs.getDirectoryHandle('/users/john/documents', true);
89
- * const docsDir2 = await fs.getDirectoryHandle(['users', 'john', 'documents'], true);
90
- * ```
91
- */
92
- async getDirectoryHandle(path, create = false, from = this.root) {
93
- if (!from) {
94
- throw new OPFSNotMountedError();
95
- }
96
- const segments = Array.isArray(path) ? path : splitPath(path);
97
- let current = from;
98
- for (const segment of segments) {
99
- current = await current.getDirectoryHandle(segment, { create });
100
- }
101
- return current;
102
- }
103
- /**
104
- * Get a file handle from a path
105
- *
106
- * Navigates to the parent directory and retrieves or creates a file handle
107
- * for the specified file path.
108
- *
109
- * @param path - The path to the file (string or array of segments)
110
- * @param create - Whether to create the file if it doesn't exist (default: false)
111
- * @param from - The directory to start from (default: root directory)
112
- * @returns Promise that resolves to the file handle
113
- * @throws {PathError} If the path is empty
114
- * @throws {OPFSError} If the file cannot be accessed or created
115
- *
116
- * @example
117
- * ```typescript
118
- * const fileHandle = await fs.getFileHandle('/config/settings.json', true);
119
- * const fileHandle2 = await fs.getFileHandle(['config', 'settings.json'], true);
120
- * ```
121
- */
122
- async getFileHandle(path, create = false, from = this.root) {
123
- if (!from) {
124
- throw new OPFSNotMountedError();
125
- }
126
- const segments = splitPath(path);
127
- if (segments.length === 0) {
128
- throw new PathError('Path must not be empty', Array.isArray(path) ? path.join('/') : path);
129
- }
130
- const fileName = segments.pop();
131
- const dir = await this.getDirectoryHandle(segments, create, from);
132
- return dir.getFileHandle(fileName, { create });
133
- }
134
- /**
135
- * Recursively list all files and directories with their stats
136
- *
137
- * Traverses the entire file system starting from the root and returns
138
- * a Map containing all paths and their corresponding file statistics.
139
- *
140
- * @param options - Options for indexing
141
- * @param options.includeHash - Whether to calculate file hash (default: false)
142
- * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)
143
- * @returns Promise that resolves to a Map of path => FileStat
144
- * @throws {OPFSError} If the indexing operation fails
145
- *
146
- * @example
147
- * ```typescript
148
- * // Basic index without hash
149
- * const index = await fs.index();
150
- *
151
- * // Index with file hash
152
- * const indexWithHash = await fs.index({
153
- * includeHash: true,
154
- * hashAlgorithm: 'SHA-1'
155
- * });
156
- *
157
- * // Iterate through all files and directories
158
- * for (const [path, stat] of index) {
159
- * console.log(`${path}: ${stat.isFile ? 'file' : 'directory'} (${stat.size} bytes)`);
160
- * if (stat.hash) console.log(` Hash: ${stat.hash}`);
161
- * }
162
- *
163
- * // Get specific file stats
164
- * const fileStats = index.get('/data/config.json');
165
- * if (fileStats) {
166
- * console.log(`File size: ${fileStats.size} bytes`);
167
- * if (fileStats.hash) console.log(`Hash: ${fileStats.hash}`);
168
- * }
169
- * ```
170
- */
171
- async index(options) {
172
- const result = new Map();
173
- const walk = async (dirPath) => {
174
- const items = await this.readdir(dirPath, { withFileTypes: true });
175
- for (const item of items) {
176
- const fullPath = `${dirPath === '/' ? '' : dirPath}/${item.name}`;
177
- try {
178
- const stat = await this.stat(fullPath, options);
179
- result.set(fullPath, stat);
180
- if (stat.isDirectory) {
181
- await walk(fullPath);
182
- }
183
- }
184
- catch (err) {
185
- console.warn(`Skipping broken entry: ${fullPath}`, err);
186
- }
187
- }
188
- };
189
- result.set('/', {
190
- kind: 'directory',
191
- size: 0,
192
- mtime: new Date(0).toISOString(),
193
- ctime: new Date(0).toISOString(),
194
- isFile: false,
195
- isDirectory: true,
196
- });
197
- await walk('/');
198
- return result;
199
- }
200
- async readFile(path, encoding = 'utf-8') {
201
- try {
202
- const fileHandle = await this.getFileHandle(path, false);
203
- const buffer = await readFileData(fileHandle);
204
- if (encoding === 'binary') {
205
- return buffer;
206
- }
207
- return decodeBuffer(buffer, encoding);
208
- }
209
- catch (err) {
210
- console.error(err);
211
- throw new FileNotFoundError(path);
212
- }
213
- }
214
- /**
215
- * Write data to a file
216
- *
217
- * Creates or overwrites a file with the specified data. If the file already
218
- * exists, it will be truncated before writing.
219
- *
220
- * @param path - The path to the file to write
221
- * @param data - The data to write to the file (string, Uint8Array, or ArrayBuffer)
222
- * @param encoding - The encoding to use when writing string data (default: 'utf-8')
223
- * @returns Promise that resolves when the write operation is complete
224
- * @throws {OPFSError} If writing the file fails
225
- *
226
- * @example
227
- * ```typescript
228
- * // Write text data
229
- * await fs.writeFile('/config/settings.json', JSON.stringify({ theme: 'dark' }));
230
- *
231
- * // Write binary data
232
- * const binaryData = new Uint8Array([1, 2, 3, 4, 5]);
233
- * await fs.writeFile('/data/binary.dat', binaryData);
234
- *
235
- * // Write with specific encoding
236
- * await fs.writeFile('/data/utf16.txt', 'Hello World', 'utf-16le');
237
- * ```
238
- */
239
- async writeFile(path, data, encoding) {
240
- const fileHandle = await this.getFileHandle(path, true);
241
- await writeFileData(fileHandle, data, encoding, { truncate: true });
242
- }
243
- /**
244
- * Append data to a file
245
- *
246
- * Adds data to the end of an existing file. If the file doesn't exist,
247
- * it will be created.
248
- *
249
- * @param path - The path to the file to append to
250
- * @param data - The data to append to the file (string, Uint8Array, or ArrayBuffer)
251
- * @param encoding - The encoding to use when appending string data (default: 'utf-8')
252
- * @returns Promise that resolves when the append operation is complete
253
- * @throws {OPFSError} If appending to the file fails
254
- *
255
- * @example
256
- * ```typescript
257
- * // Append text to a log file
258
- * await fs.appendFile('/logs/app.log', `[${new Date().toISOString()}] User logged in\n`);
259
- *
260
- * // Append binary data
261
- * const additionalData = new Uint8Array([6, 7, 8]);
262
- * await fs.appendFile('/data/binary.dat', additionalData);
263
- * ```
264
- */
265
- async appendFile(path, data, encoding) {
266
- const fileHandle = await this.getFileHandle(path, true);
267
- await writeFileData(fileHandle, data, encoding, { append: true });
268
- }
269
- /**
270
- * Create a directory
271
- *
272
- * Creates a new directory at the specified path. If the recursive option
273
- * is enabled, parent directories will be created as needed.
274
- *
275
- * @param path - The path where the directory should be created
276
- * @param options - Options for directory creation
277
- * @param options.recursive - Whether to create parent directories if they don't exist (default: false)
278
- * @returns Promise that resolves when the directory is created
279
- * @throws {OPFSError} If the directory cannot be created
280
- *
281
- * @example
282
- * ```typescript
283
- * // Create a single directory
284
- * await fs.mkdir('/users/john');
285
- *
286
- * // Create nested directories
287
- * await fs.mkdir('/users/john/documents/projects', { recursive: true });
288
- * ```
289
- */
290
- async mkdir(path, options) {
291
- if (!this.root) {
292
- throw new OPFSNotMountedError();
293
- }
294
- const recursive = options?.recursive ?? false;
295
- const segments = splitPath(path);
296
- let current = this.root;
297
- for (let i = 0; i < segments.length; i++) {
298
- const segment = segments[i];
299
- try {
300
- current = await current.getDirectoryHandle(segment, { create: recursive || i === segments.length - 1 });
301
- }
302
- catch (e) {
303
- if (e.name === 'NotFoundError') {
304
- throw new OPFSError(`Parent directory does not exist: ${joinPath(segments.slice(0, i + 1))}`, 'ENOENT');
305
- }
306
- if (e.name === 'TypeMismatchError') {
307
- throw new OPFSError(`Path segment is not a directory: ${segment}`, 'ENOTDIR');
308
- }
309
- throw new OPFSError('Failed to create directory', 'MKDIR_FAILED');
310
- }
311
- }
312
- }
313
- /**
314
- * Get file or directory stats
315
- *
316
- * Retrieves metadata about a file or directory, including size, modification time,
317
- * type information, and optionally file hashes.
318
- *
319
- * @param path - The path to the file or directory
320
- * @param options - Options for stat operation
321
- * @param options.includeHash - Whether to calculate file hash (default: false, only for files)
322
- * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)
323
- * @returns Promise that resolves to file/directory statistics
324
- * @throws {OPFSError} If the file or directory does not exist or cannot be accessed
325
- *
326
- * @example
327
- * ```typescript
328
- * // Basic stats
329
- * const stats = await fs.stat('/config/settings.json');
330
- * console.log(`File size: ${stats.size} bytes`);
331
- * console.log(`Is file: ${stats.isFile}`);
332
- * console.log(`Modified: ${stats.mtime}`);
333
- *
334
- * // Stats with hash (SHA-1 is fastest)
335
- * const statsWithHash = await fs.stat('/config/settings.json', {
336
- * includeHash: true,
337
- * hashAlgorithm: 'SHA-1'
338
- * });
339
- * console.log(`Hash: ${statsWithHash.hash}`);
340
- * ```
341
- */
342
- async stat(path, options) {
343
- const name = basename(path);
344
- const parentDir = await this.getDirectoryHandle(dirname(path), false);
345
- const includeHash = options?.includeHash ?? false;
346
- const hashAlgorithm = options?.hashAlgorithm ?? 'SHA-1';
347
- try {
348
- const fileHandle = await parentDir.getFileHandle(name, { create: false });
349
- const file = await fileHandle.getFile();
350
- const baseStat = {
351
- kind: 'file',
352
- size: file.size,
353
- mtime: new Date(file.lastModified).toISOString(),
354
- ctime: new Date(file.lastModified).toISOString(),
355
- isFile: true,
356
- isDirectory: false,
357
- };
358
- if (includeHash) {
359
- try {
360
- const buffer = new Uint8Array(await file.arrayBuffer());
361
- const hash = await calculateFileHash(buffer, hashAlgorithm);
362
- baseStat.hash = hash;
363
- }
364
- catch (error) {
365
- console.warn(`Failed to calculate hash for ${path}:`, error);
366
- }
367
- }
368
- return baseStat;
369
- }
370
- catch (e) {
371
- if (e.name !== 'TypeMismatchError' && e.name !== 'NotFoundError') {
372
- throw new OPFSError('Failed to stat (file)', 'STAT_FAILED');
373
- }
374
- }
375
- try {
376
- await parentDir.getDirectoryHandle(name, { create: false });
377
- return {
378
- kind: 'directory',
379
- size: 0,
380
- mtime: new Date(0).toISOString(),
381
- ctime: new Date(0).toISOString(),
382
- isFile: false,
383
- isDirectory: true,
384
- };
385
- }
386
- catch (e) {
387
- if (e.name === 'NotFoundError') {
388
- throw new OPFSError(`No such file or directory: ${path}`, 'ENOENT');
389
- }
390
- throw new OPFSError('Failed to stat (directory)', 'STAT_FAILED');
391
- }
392
- }
393
- async readdir(path, options) {
394
- const withTypes = options?.withFileTypes ?? false;
395
- const dir = await this.getDirectoryHandle(path, false);
396
- if (withTypes) {
397
- const results = [];
398
- for await (const [name, handle] of dir.entries()) {
399
- const isFile = handle.kind === 'file';
400
- results.push({
401
- name,
402
- kind: handle.kind,
403
- isFile,
404
- isDirectory: !isFile,
405
- });
406
- }
407
- return results;
408
- }
409
- else {
410
- const results = [];
411
- for await (const [name] of dir.entries()) {
412
- results.push(name);
413
- }
414
- return results;
415
- }
416
- }
417
- /**
418
- * Check if a file or directory exists
419
- *
420
- * Verifies if a file or directory exists at the specified path.
421
- *
422
- * @param path - The path to check
423
- * @returns Promise that resolves to true if the file or directory exists, false otherwise
424
- *
425
- * @example
426
- * ```typescript
427
- * const exists = await fs.exists('/config/settings.json');
428
- * console.log(`File exists: ${exists}`);
429
- * ```
430
- */
431
- async exists(path) {
432
- const name = basename(path);
433
- let dir = null;
434
- try {
435
- dir = await this.getDirectoryHandle(dirname(path), false);
436
- }
437
- catch (e) {
438
- if (e.name === 'NotFoundError' || e.name === 'TypeMismatchError') {
439
- dir = null;
440
- }
441
- throw e;
442
- }
443
- if (!dir || !name) {
444
- return false;
445
- }
446
- try {
447
- await dir.getFileHandle(name, { create: false });
448
- return true;
449
- }
450
- catch (e) {
451
- if (e.name !== 'NotFoundError' && e.name !== 'TypeMismatchError') {
452
- throw e;
453
- }
454
- }
455
- try {
456
- await dir.getDirectoryHandle(name, { create: false });
457
- return true;
458
- }
459
- catch (e) {
460
- if (e.name !== 'NotFoundError' && e.name !== 'TypeMismatchError') {
461
- throw e;
462
- }
463
- }
464
- return false;
465
- }
466
- /**
467
- * Clear all contents of a directory without removing the directory itself
468
- *
469
- * Removes all files and subdirectories within the specified directory,
470
- * but keeps the directory itself.
471
- *
472
- * @param path - The path to the directory to clear (default: '/')
473
- * @returns Promise that resolves when all contents are removed
474
- * @throws {OPFSError} If the operation fails
475
- *
476
- * @example
477
- * ```typescript
478
- * // Clear root directory contents
479
- * await fs.clear('/');
480
- *
481
- * // Clear specific directory contents
482
- * await fs.clear('/data');
483
- * ```
484
- */
485
- async clear(path = '/') {
486
- try {
487
- const items = await this.readdir(path, { withFileTypes: true });
488
- for (const item of items) {
489
- const itemPath = `${path === '/' ? '' : path}/${item.name}`;
490
- await this.remove(itemPath, { recursive: true });
491
- }
492
- }
493
- catch (error) {
494
- if (error instanceof OPFSError) {
495
- throw error;
496
- }
497
- throw new OPFSError(`Failed to clear directory: ${path}`, 'CLEAR_FAILED');
498
- }
499
- }
500
- /**
501
- * Remove files and directories
502
- *
503
- * Removes files and directories. Similar to Node.js fs.rm().
504
- *
505
- * @param path - The path to remove
506
- * @param options - Options for removal
507
- * @param options.recursive - Whether to remove directories and their contents recursively (default: false)
508
- * @param options.force - Whether to ignore errors if the path doesn't exist (default: false)
509
- * @returns Promise that resolves when the removal is complete
510
- * @throws {OPFSError} If the removal fails
511
- *
512
- * @example
513
- * ```typescript
514
- * // Remove a file
515
- * await fs.rm('/path/to/file.txt');
516
- *
517
- * // Remove a directory and all its contents
518
- * await fs.rm('/path/to/directory', { recursive: true });
519
- *
520
- * // Remove with force (ignore if doesn't exist)
521
- * await fs.rm('/maybe/exists', { force: true });
522
- * ```
523
- */
524
- async remove(path, options) {
525
- const recursive = options?.recursive ?? false;
526
- const force = options?.force ?? false;
527
- const name = basename(path);
528
- if (!name) {
529
- throw new PathError('Invalid path', path);
530
- }
531
- const parent = await this.getDirectoryHandle(dirname(path), false);
532
- try {
533
- await parent.removeEntry(name, { recursive });
534
- }
535
- catch (e) {
536
- if (e.name === 'NotFoundError') {
537
- if (!force) {
538
- throw new OPFSError(`No such file or directory: ${path}`, 'ENOENT');
539
- }
540
- }
541
- else if (e.name === 'InvalidModificationError') {
542
- throw new OPFSError(`Directory not empty: ${path}. Use recursive option to force removal.`, 'ENOTEMPTY');
543
- }
544
- else if (e.name === 'TypeMismatchError' && !recursive) {
545
- throw new OPFSError(`Cannot remove directory without recursive option: ${path}`, 'EISDIR');
546
- }
547
- else {
548
- throw new OPFSError(`Failed to remove path: ${path}`, 'RM_FAILED');
549
- }
550
- }
551
- }
552
- /**
553
- * Resolve a path to an absolute path
554
- *
555
- * Resolves relative paths and normalizes path segments (like '..' and '.').
556
- * Similar to Node.js fs.realpath() but without symlink resolution since OPFS doesn't support symlinks.
557
- *
558
- * @param path - The path to resolve
559
- * @returns Promise that resolves to the absolute normalized path
560
- * @throws {FileNotFoundError} If the path does not exist
561
- * @throws {OPFSError} If path resolution fails
562
- *
563
- * @example
564
- * ```typescript
565
- * // Resolve relative path
566
- * const absolute = await fs.realpath('./config/../data/file.txt');
567
- * console.log(absolute); // '/data/file.txt'
568
- * ```
569
- */
570
- async realpath(path) {
571
- try {
572
- const normalizedPath = resolvePath(path);
573
- const exists = await this.exists(normalizedPath);
574
- if (!exists) {
575
- throw new FileNotFoundError(normalizedPath);
576
- }
577
- return normalizedPath;
578
- }
579
- catch (error) {
580
- if (error instanceof OPFSError) {
581
- throw error;
582
- }
583
- throw new OPFSError(`Failed to resolve path: ${path}`, 'REALPATH_FAILED');
584
- }
585
- }
586
- /**
587
- * Rename a file or directory
588
- *
589
- * Changes the name of a file or directory. If the target path already exists,
590
- * it will be replaced.
591
- *
592
- * @param oldPath - The current path of the file or directory
593
- * @param newPath - The new path for the file or directory
594
- * @returns Promise that resolves when the rename operation is complete
595
- * @throws {OPFSError} If the rename operation fails
596
- *
597
- * @example
598
- * ```typescript
599
- * await fs.rename('/old/path/file.txt', '/new/path/renamed.txt');
600
- * ```
601
- */
602
- async rename(oldPath, newPath) {
603
- try {
604
- const sourceExists = await this.exists(oldPath);
605
- if (!sourceExists) {
606
- throw new FileNotFoundError(oldPath);
607
- }
608
- await this.copy(oldPath, newPath, { recursive: true });
609
- await this.remove(oldPath, { recursive: true });
610
- }
611
- catch (error) {
612
- if (error instanceof OPFSError) {
613
- throw error;
614
- }
615
- throw new OPFSError(`Failed to rename from ${oldPath} to ${newPath}`, 'RENAME_FAILED');
616
- }
617
- }
618
- /**
619
- * Copy files and directories
620
- *
621
- * Copies files and directories. Similar to Node.js fs.cp().
622
- *
623
- * @param source - The source path to copy from
624
- * @param destination - The destination path to copy to
625
- * @param options - Options for copying
626
- * @param options.recursive - Whether to copy directories recursively (default: false)
627
- * @param options.force - Whether to overwrite existing files (default: true)
628
- * @returns Promise that resolves when the copy operation is complete
629
- * @throws {OPFSError} If the copy operation fails
630
- *
631
- * @example
632
- * ```typescript
633
- * // Copy a file
634
- * await fs.cp('/source/file.txt', '/dest/file.txt');
635
- *
636
- * // Copy a directory and all its contents
637
- * await fs.cp('/source/dir', '/dest/dir', { recursive: true });
638
- *
639
- * // Copy without overwriting existing files
640
- * await fs.cp('/source', '/dest', { recursive: true, force: false });
641
- * ```
642
- */
643
- async copy(source, destination, options) {
644
- try {
645
- const recursive = options?.recursive ?? false;
646
- const force = options?.force ?? true;
647
- const sourceExists = await this.exists(source);
648
- if (!sourceExists) {
649
- throw new OPFSError(`Source does not exist: ${source}`, 'ENOENT');
650
- }
651
- const destExists = await this.exists(destination);
652
- if (destExists && !force) {
653
- throw new OPFSError(`Destination already exists: ${destination}`, 'EEXIST');
654
- }
655
- const sourceStats = await this.stat(source);
656
- if (sourceStats.isFile) {
657
- const content = await this.readFile(source, 'binary');
658
- await this.writeFile(destination, content);
659
- }
660
- else {
661
- if (!recursive) {
662
- throw new OPFSError(`Cannot copy directory without recursive option: ${source}`, 'EISDIR');
663
- }
664
- await this.mkdir(destination, { recursive: true });
665
- const items = await this.readdir(source, { withFileTypes: true });
666
- for (const item of items) {
667
- const sourceItemPath = `${source}/${item.name}`;
668
- const destItemPath = `${destination}/${item.name}`;
669
- await this.copy(sourceItemPath, destItemPath, { recursive: true, force });
670
- }
671
- }
672
- }
673
- catch (error) {
674
- if (error instanceof OPFSError) {
675
- throw error;
676
- }
677
- throw new OPFSError(`Failed to copy from ${source} to ${destination}`, 'CP_FAILED');
678
- }
679
- }
680
- /**
681
- * Start watching a file or directory for changes
682
- */
683
- async watch(path) {
684
- const normalizedPath = normalizePath(path);
685
- const snapshot = await this.buildSnapshot(normalizedPath);
686
- this.watchers.set(normalizedPath, snapshot);
687
- if (!this.watchTimer) {
688
- this.watchTimer = setInterval(() => {
689
- void this.scanWatches();
690
- }, this.watchInterval);
691
- }
692
- }
693
- /**
694
- * Stop watching a previously watched path
695
- */
696
- unwatch(path) {
697
- const normalizedPath = normalizePath(path);
698
- this.watchers.delete(normalizedPath);
699
- if (this.watchers.size === 0 && this.watchTimer) {
700
- clearInterval(this.watchTimer);
701
- this.watchTimer = null;
702
- }
703
- }
704
- async buildSnapshot(rootPath) {
705
- const result = new Map();
706
- const walk = async (current) => {
707
- const stat = await this.stat(current);
708
- result.set(current, stat);
709
- if (stat.isDirectory) {
710
- const entries = await this.readdir(current, { withFileTypes: true });
711
- for (const entry of entries) {
712
- const child = `${current === '/' ? '' : current}/${entry.name}`;
713
- await walk(child);
714
- }
715
- }
716
- };
717
- await walk(rootPath);
718
- return result;
719
- }
720
- async scanWatches() {
721
- if (this.scanning) {
722
- return;
723
- }
724
- this.scanning = true;
725
- try {
726
- await Promise.all([...this.watchers.entries()].map(async ([rootPath, prev]) => {
727
- let next;
728
- try {
729
- next = await this.buildSnapshot(rootPath);
730
- }
731
- catch {
732
- next = new Map();
733
- }
734
- const events = [];
735
- for (const [p, stat] of next) {
736
- const old = prev.get(p);
737
- if (!old) {
738
- events.push({ path: p, type: 'create' });
739
- }
740
- else if (old.mtime !== stat.mtime || old.size !== stat.size) {
741
- events.push({ path: p, type: 'change' });
742
- }
743
- }
744
- for (const p of prev.keys()) {
745
- if (!next.has(p)) {
746
- events.push({ path: p, type: 'delete' });
747
- }
748
- }
749
- if (events.length && this.watchCallback) {
750
- for (const event of events) {
751
- this.watchCallback(event);
752
- }
753
- }
754
- this.watchers.set(rootPath, next);
755
- }));
756
- }
757
- finally {
758
- this.scanning = false;
759
- }
760
- }
761
- /**
762
- * Synchronize the file system with external data
763
- *
764
- * Syncs the file system with an array of entries containing paths and data.
765
- * This is useful for importing data from external sources or syncing with remote data.
766
- *
767
- * @param entries - Array of [path, data] tuples to sync
768
- * @param options - Options for synchronization
769
- * @param options.cleanBefore - Whether to clear the file system before syncing (default: false)
770
- * @returns Promise that resolves when synchronization is complete
771
- * @throws {OPFSError} If the synchronization fails
772
- *
773
- * @example
774
- * ```typescript
775
- * // Sync with external data
776
- * const entries: [string, string | Uint8Array | Blob][] = [
777
- * ['/config.json', JSON.stringify({ theme: 'dark' })],
778
- * ['/data/binary.dat', new Uint8Array([1, 2, 3, 4])],
779
- * ['/upload.txt', new Blob(['file content'], { type: 'text/plain' })]
780
- * ];
781
- *
782
- * // Sync without clearing existing files
783
- * await fs.sync(entries);
784
- *
785
- * // Clean file system and then sync
786
- * await fs.sync(entries, { cleanBefore: true });
787
- * ```
788
- */
789
- async sync(entries, options) {
790
- try {
791
- const cleanBefore = options?.cleanBefore ?? false;
792
- if (cleanBefore) {
793
- await this.clear('/');
794
- }
795
- for (const [path, data] of entries) {
796
- const normalizedPath = normalizePath(path);
797
- let fileData;
798
- if (data instanceof Blob) {
799
- fileData = await convertBlobToUint8Array(data);
800
- }
801
- else {
802
- fileData = data;
803
- }
804
- await this.writeFile(normalizedPath, fileData);
805
- }
806
- }
807
- catch (error) {
808
- if (error instanceof OPFSError) {
809
- throw error;
810
- }
811
- throw new OPFSError('Failed to sync file system', 'SYNC_FAILED');
812
- }
813
- }
814
- }
815
- // Only expose the worker when running in a Web Worker environment
816
- if (typeof self !== 'undefined' && self.constructor.name === 'DedicatedWorkerGlobalScope') {
817
- expose(new OPFSWorker());
818
- }