opfs-worker 1.3.1 → 2.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.
Files changed (62) hide show
  1. package/README.md +89 -106
  2. package/dist/{facade.d.ts → OPFSFacade.d.ts} +26 -9
  3. package/dist/OPFSFacade.d.ts.map +1 -0
  4. package/dist/{worker.d.ts → OPFSWorker.d.ts} +11 -11
  5. package/dist/OPFSWorker.d.ts.map +1 -0
  6. package/dist/assets/worker.entry-DUlEoroc.js.map +1 -0
  7. package/dist/createOPFSWorker.d.ts +17 -0
  8. package/dist/createOPFSWorker.d.ts.map +1 -0
  9. package/dist/helpers-DNj8ZoMu.cjs +4 -0
  10. package/dist/helpers-DNj8ZoMu.cjs.map +1 -0
  11. package/dist/{helpers-CKOebsbw.js → helpers-WY2jfbOT.js} +257 -253
  12. package/dist/helpers-WY2jfbOT.js.map +1 -0
  13. package/dist/index.cjs +349 -329
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.d.ts +3 -9
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +428 -382
  18. package/dist/index.js.map +1 -1
  19. package/dist/index.pure.cjs +2 -0
  20. package/dist/index.pure.cjs.map +1 -0
  21. package/dist/index.pure.d.ts +6 -0
  22. package/dist/index.pure.d.ts.map +1 -0
  23. package/dist/{raw.js → index.pure.js} +248 -188
  24. package/dist/index.pure.js.map +1 -0
  25. package/dist/types.d.ts +1 -1
  26. package/dist/types.d.ts.map +1 -1
  27. package/dist/utils/errors.d.ts +14 -6
  28. package/dist/utils/errors.d.ts.map +1 -1
  29. package/dist/utils/helpers.d.ts +15 -3
  30. package/dist/utils/helpers.d.ts.map +1 -1
  31. package/dist/worker.entry.d.ts +2 -0
  32. package/dist/worker.entry.d.ts.map +1 -0
  33. package/docs/api-reference.md +815 -0
  34. package/docs/file-descriptors.md +696 -0
  35. package/docs/types.md +232 -0
  36. package/package.json +15 -9
  37. package/src/OPFSFacade.ts +460 -0
  38. package/src/OPFSWorker.ts +1544 -0
  39. package/src/createOPFSWorker.ts +57 -0
  40. package/src/index.pure.ts +7 -0
  41. package/src/index.ts +15 -0
  42. package/src/types.ts +99 -0
  43. package/src/utils/encoder.ts +205 -0
  44. package/src/utils/errors.ts +297 -0
  45. package/src/utils/helpers.ts +465 -0
  46. package/src/worker.entry.ts +6 -0
  47. package/dist/assets/worker-1Wh1cr7P.js.map +0 -1
  48. package/dist/assets/worker-BeJaVyBV.js.map +0 -1
  49. package/dist/facade.d.ts.map +0 -1
  50. package/dist/helpers-BuGfPAg0.js +0 -1439
  51. package/dist/helpers-BuGfPAg0.js.map +0 -1
  52. package/dist/helpers-CF7A2WQG.cjs +0 -4
  53. package/dist/helpers-CF7A2WQG.cjs.map +0 -1
  54. package/dist/helpers-CIiblZ8d.cjs +0 -4
  55. package/dist/helpers-CIiblZ8d.cjs.map +0 -1
  56. package/dist/helpers-CKOebsbw.js.map +0 -1
  57. package/dist/raw.cjs +0 -2
  58. package/dist/raw.cjs.map +0 -1
  59. package/dist/raw.d.ts +0 -13
  60. package/dist/raw.d.ts.map +0 -1
  61. package/dist/raw.js.map +0 -1
  62. package/dist/worker.d.ts.map +0 -1
@@ -0,0 +1,1544 @@
1
+ import { transfer } from 'comlink';
2
+
3
+ import { WatchEventType } from './types';
4
+ import {
5
+ AlreadyExistsError,
6
+ DirectoryOperationError,
7
+ ExistenceError,
8
+ FileSystemOperationError,
9
+ FileTypeError,
10
+ InitializationFailedError,
11
+ OPFSError,
12
+ OperationNotSupportedError,
13
+ PathError,
14
+ ValidationError,
15
+ createFDError,
16
+ mapDomError
17
+ } from './utils/errors';
18
+
19
+ import {
20
+ basename,
21
+ calculateFileHash,
22
+ calculateReadLength,
23
+ checkOPFSSupport,
24
+ convertBlobToUint8Array,
25
+ createSyncHandleSafe,
26
+ dirname,
27
+ joinPath,
28
+ matchMinimatch,
29
+ normalizeMinimatch,
30
+ normalizePath,
31
+ removeEntry,
32
+ resolvePath,
33
+ safeCloseSyncHandle,
34
+ splitPath,
35
+ validateReadWriteArgs,
36
+ withLock
37
+ } from './utils/helpers';
38
+
39
+ import type { DirentData, FileOpenOptions, FileStat, OPFSOptions, RenameOptions, WatchEvent, WatchOptions, WatchSnapshot } from './types';
40
+
41
+
42
+ /**
43
+ * OPFS (Origin Private File System) File System implementation
44
+ *
45
+ * This class provides a high-level interface for working with the browser's
46
+ * Origin Private File System API, offering file and directory operations
47
+ * similar to Node.js fs module.
48
+ *
49
+ * @example
50
+ * ```typescript
51
+ * const fs = new OPFSWorker();
52
+ * await fs.writeFile('/data/config.json', new TextEncoder().encode(JSON.stringify({ theme: 'dark' })));
53
+ * const config = await fs.readFile('/data/config.json');
54
+ * ```
55
+ */
56
+ export class OPFSWorker {
57
+ /** Root directory handle for the file system */
58
+ private root!: FileSystemDirectoryHandle;
59
+
60
+ /** Map of watched paths and options */
61
+ private watchers = new Map<string, WatchSnapshot>();
62
+
63
+ /** Promise to prevent concurrent mount operations */
64
+ private mountingPromise: Promise<boolean> | null = null;
65
+
66
+ /** BroadcastChannel instance for sending events */
67
+ private broadcastChannel: BroadcastChannel | null = null;
68
+
69
+ /** Configuration options */
70
+ private options: Required<OPFSOptions> = {
71
+ root: '/',
72
+ namespace: '',
73
+ maxFileSize: 50 * 1024 * 1024,
74
+ hashAlgorithm: 'etag',
75
+ broadcastChannel: 'opfs-worker',
76
+ };
77
+
78
+ /** Shared sync handles per path (OPFS allows only one handle per file) */
79
+ private openHandles = new Map<string, {
80
+ fileHandle: FileSystemFileHandle;
81
+ syncHandle: FileSystemSyncAccessHandle;
82
+ refCount: number;
83
+ }>();
84
+
85
+ /** Map of open file descriptors to their metadata */
86
+ private openFiles = new Map<number, {
87
+ path: string;
88
+ fileHandle: FileSystemFileHandle;
89
+ syncHandle: FileSystemSyncAccessHandle;
90
+ position: number;
91
+ }>();
92
+
93
+ /** Next available file descriptor number */
94
+ private nextFd = 1;
95
+
96
+ /**
97
+ * Get file info by descriptor with validation
98
+ * @private
99
+ */
100
+ private _getFileDescriptor(fd: number): { path: string; fileHandle: FileSystemFileHandle; syncHandle: FileSystemSyncAccessHandle; position: number } {
101
+ const fileInfo = this.openFiles.get(fd);
102
+
103
+ if (!fileInfo) {
104
+ throw new ValidationError('descriptor', `Invalid file descriptor: ${ fd }`);
105
+ }
106
+
107
+ return fileInfo;
108
+ }
109
+
110
+
111
+ /**
112
+ * Notify about internal changes to the file system
113
+ *
114
+ * This method is called by internal operations to notify clients about
115
+ * changes, even when no specific paths are being watched.
116
+ *
117
+ * @param event - The event describing the change
118
+ */
119
+ private async notifyChange(event: Omit<WatchEvent, 'timestamp' | 'hash' | 'namespace'>): Promise<void> {
120
+ // This instance not configured to send events
121
+ if (!this.options.broadcastChannel) {
122
+ return;
123
+ }
124
+
125
+ const path = event.path;
126
+
127
+ const match = [...this.watchers.values()].some((snapshot) => {
128
+ return (
129
+ matchMinimatch(path, snapshot.pattern)
130
+ && snapshot.include.some(include => include && matchMinimatch(path, include))
131
+ && !snapshot.exclude.some(exclude => exclude && matchMinimatch(path, exclude))
132
+ );
133
+ });
134
+
135
+ if (!match) {
136
+ return;
137
+ }
138
+
139
+ let hash: string | undefined;
140
+
141
+ if (this.options.hashAlgorithm) {
142
+ try {
143
+ const stat = await this.stat(path);
144
+
145
+ hash = stat.hash;
146
+ }
147
+ catch {}
148
+ }
149
+
150
+ // Send event via BroadcastChannel
151
+ try {
152
+ if (!this.broadcastChannel) {
153
+ this.broadcastChannel = new BroadcastChannel(this.options.broadcastChannel as string);
154
+ }
155
+
156
+ const watchEvent: WatchEvent = {
157
+ namespace: this.options.namespace,
158
+ timestamp: new Date().toISOString(),
159
+ ...event,
160
+ ...(hash && { hash }),
161
+ };
162
+
163
+ this.broadcastChannel.postMessage(watchEvent);
164
+ }
165
+ catch (error) {
166
+ console.warn('Failed to send event via BroadcastChannel:', error);
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Creates a new OPFSWorker instance
172
+ *
173
+ * @param options - Optional configuration options
174
+ * @param options.root - Root path for the file system (default: '/')
175
+ * @param options.watchInterval - Polling interval in milliseconds for file watching
176
+ * @param options.hashAlgorithm - Hash algorithm for file hashing
177
+ * @param options.maxFileSize - Maximum file size for hashing in bytes (default: 50MB)
178
+ * @throws {OPFSError} If OPFS is not supported in the current browser
179
+ */
180
+ constructor(options?: OPFSOptions) {
181
+ checkOPFSSupport();
182
+
183
+ if (options) {
184
+ void this.setOptions(options);
185
+ }
186
+ }
187
+
188
+ /**
189
+ * Initialize the file system within a given directory
190
+ *
191
+ * This method sets up the root directory for all subsequent operations.
192
+ * If no root is specified, it will use the OPFS root directory.
193
+ *
194
+ * @returns Promise that resolves to true if initialization was successful
195
+ * @throws {OPFSError} If initialization fails
196
+ *
197
+ * @example
198
+ * ```typescript
199
+ * const fs = new OPFSWorker();
200
+ *
201
+ * // Use OPFS root (default)
202
+ * await fs.mount();
203
+ *
204
+ * // Use custom directory
205
+ * await fs.mount('/my-app');
206
+ * ```
207
+ */
208
+ private async mount(): Promise<boolean> {
209
+ const root = this.options.root;
210
+
211
+ // If already mounting, wait for previous operation to complete first
212
+ if (this.mountingPromise) {
213
+ await this.mountingPromise;
214
+ }
215
+
216
+ // eslint-disable-next-line no-async-promise-executor
217
+ this.mountingPromise = new Promise<boolean>(async(resolve, reject) => {
218
+ try {
219
+ const rootDir = await navigator.storage.getDirectory();
220
+
221
+ this.root = (root === '/') ? rootDir : await this.getDirectoryHandle(root, true, rootDir);
222
+
223
+ resolve(true);
224
+ }
225
+ catch (error) {
226
+ reject(new InitializationFailedError(root, error));
227
+ }
228
+ finally {
229
+ this.mountingPromise = null;
230
+ }
231
+ });
232
+
233
+ return this.mountingPromise;
234
+ }
235
+
236
+
237
+ /**
238
+ * Update configuration options
239
+ *
240
+ * @param options - Configuration options to update
241
+ * @param options.root - Root path for the file system
242
+ * @param options.watchInterval - Polling interval in milliseconds for file watching
243
+ * @param options.hashAlgorithm - Hash algorithm for file hashing
244
+ * @param options.maxFileSize - Maximum file size for hashing in bytes
245
+ * @param options.broadcastChannel - Custom name for the broadcast channel
246
+ */
247
+ async setOptions(options: OPFSOptions): Promise<void> {
248
+ if (options.hashAlgorithm !== undefined) {
249
+ this.options.hashAlgorithm = options.hashAlgorithm;
250
+ }
251
+
252
+ if (options.maxFileSize !== undefined) {
253
+ this.options.maxFileSize = options.maxFileSize;
254
+ }
255
+
256
+ if (options.broadcastChannel !== undefined) {
257
+ // Close existing channel if name changed
258
+ if (this.broadcastChannel && this.options.broadcastChannel !== options.broadcastChannel) {
259
+ this.broadcastChannel.close();
260
+ this.broadcastChannel = null;
261
+ }
262
+
263
+ this.options.broadcastChannel = options.broadcastChannel;
264
+ }
265
+
266
+ if (options.namespace) {
267
+ this.options.namespace = options.namespace;
268
+ }
269
+
270
+ if (options.root !== undefined) {
271
+ this.options.root = normalizePath(options.root);
272
+
273
+ if (!this.options.namespace) {
274
+ this.options.namespace = `opfs-worker:${ this.options.root }`;
275
+ }
276
+
277
+ await this.mount();
278
+ }
279
+ }
280
+
281
+ /**
282
+ * Get a directory handle from a path
283
+ *
284
+ * Navigates through the directory structure to find or create a directory
285
+ * at the specified path.
286
+ *
287
+ * @param path - The path to the directory (string or array of segments)
288
+ * @param create - Whether to create the directory if it doesn't exist (default: false)
289
+ * @param from - The directory to start from (default: root directory)
290
+ * @returns Promise that resolves to the directory handle
291
+ * @throws {OPFSError} If the directory cannot be accessed or created
292
+ *
293
+ * @example
294
+ * ```typescript
295
+ * const docsDir = await fs.getDirectoryHandle('/users/john/documents', true);
296
+ * const docsDir2 = await fs.getDirectoryHandle(['users', 'john', 'documents'], true);
297
+ * ```
298
+ */
299
+ private async getDirectoryHandle(path: string | string[], create: boolean = false, from: FileSystemDirectoryHandle | null = this.root): Promise<FileSystemDirectoryHandle> {
300
+ const segments = Array.isArray(path) ? path : splitPath(path);
301
+ let current = from;
302
+
303
+ for (const segment of segments) {
304
+ current = await current!.getDirectoryHandle(segment, { create });
305
+ }
306
+
307
+ return current!;
308
+ }
309
+
310
+ /**
311
+ * Get a file handle from a path
312
+ *
313
+ * Navigates to the parent directory and retrieves or creates a file handle
314
+ * for the specified file path.
315
+ *
316
+ * @param path - The path to the file (string or array of segments)
317
+ * @param create - Whether to create the file if it doesn't exist (default: false)
318
+ * @param _from - The directory to start from (default: root directory)
319
+ * @returns Promise that resolves to the file handle
320
+ * @throws {PathError} If the path is empty
321
+ * @throws {OPFSError} If the file cannot be accessed or created
322
+ *
323
+ * @example
324
+ * ```typescript
325
+ * const fileHandle = await fs.getFileHandle('/config/settings.json', true);
326
+ * const fileHandle2 = await fs.getFileHandle(['config', 'settings.json'], true);
327
+ * ```
328
+ */
329
+ private async getFileHandle(path: string | string[], create = false, _from: FileSystemDirectoryHandle | null = this.root): Promise<FileSystemFileHandle> {
330
+ const segments = splitPath(path);
331
+
332
+ if (segments.length === 0) {
333
+ throw new PathError('Path must not be empty', Array.isArray(path) ? path.join('/') : path);
334
+ }
335
+
336
+ const fileName = segments.pop()!;
337
+ const dir = await this.getDirectoryHandle(segments, create, _from);
338
+
339
+ return dir.getFileHandle(fileName, { create });
340
+ }
341
+
342
+ /**
343
+ * Get a complete index of all files and directories in the file system
344
+ *
345
+ * This method recursively traverses the entire file system and returns
346
+ * a Map containing FileStat objects for every file and directory.
347
+ *
348
+ * @returns Promise that resolves to a Map of paths to FileStat objects
349
+ * @throws {OPFSError} If the file system is not mounted
350
+ *
351
+ * @example
352
+ * ```typescript
353
+ * const index = await fs.index();
354
+ * const fileStats = index.get('/data/config.json');
355
+ * if (fileStats) {
356
+ * console.log(`File size: ${fileStats.size} bytes`);
357
+ * if (fileStats.hash) console.log(`Hash: ${fileStats.hash}`);
358
+ * }
359
+ * ```
360
+ */
361
+ async index(): Promise<Map<string, FileStat>> {
362
+ const result = new Map<string, FileStat>();
363
+
364
+ const walk = async(dirPath: string) => {
365
+ const items = await this.readDir(dirPath);
366
+
367
+ for (const item of items) {
368
+ const fullPath = `${ dirPath === '/' ? '' : dirPath }/${ item.name }`;
369
+
370
+ try {
371
+ const stat = await this.stat(fullPath);
372
+
373
+ result.set(fullPath, stat);
374
+
375
+ if (stat.isDirectory) {
376
+ await walk(fullPath);
377
+ }
378
+ }
379
+ catch (err) {
380
+ console.warn(`Skipping broken entry: ${ fullPath }`, err);
381
+ }
382
+ }
383
+ };
384
+
385
+ result.set('/', {
386
+ kind: 'directory',
387
+ size: 0,
388
+ mtime: new Date(0).toISOString(),
389
+ ctime: new Date(0).toISOString(),
390
+ isFile: false,
391
+ isDirectory: true,
392
+ });
393
+
394
+ await walk('/');
395
+
396
+ return result;
397
+ }
398
+
399
+ /**
400
+ * Read a file from the file system
401
+ *
402
+ * Reads the contents of a file and returns it as binary data.
403
+ *
404
+ * @param path - The path to the file to read
405
+ * @returns Promise that resolves to the file contents as Uint8Array
406
+ * @throws {FileNotFoundError} If the file does not exist
407
+ * @throws {OPFSError} If reading the file fails
408
+ *
409
+ * @example
410
+ * ```typescript
411
+ * // Read as binary data
412
+ * const content = await fs.readFile('/config/settings.json');
413
+ *
414
+ * // Read binary file
415
+ * const binaryData = await fs.readFile('/images/logo.png');
416
+ * ```
417
+ */
418
+ async readFile(path: string): Promise<Uint8Array> {
419
+ await this.mount();
420
+
421
+ try {
422
+ return await withLock(path, async() => {
423
+ const fd = await this.open(path);
424
+
425
+ try {
426
+ const { size } = await this.fstat(fd);
427
+ const buffer = new Uint8Array(size);
428
+
429
+ if (size > 0) {
430
+ await this.read(fd, buffer, 0, size, 0);
431
+ }
432
+
433
+ return transfer(buffer, [buffer.buffer]);
434
+ }
435
+ finally {
436
+ await this.close(fd);
437
+ }
438
+ });
439
+ }
440
+ catch (err) {
441
+ if (err instanceof OPFSError) {
442
+ throw err;
443
+ }
444
+
445
+ throw mapDomError(err, { path, isDirectory: false });
446
+ }
447
+ }
448
+
449
+ /**
450
+ * Write data to a file
451
+ *
452
+ * Creates or overwrites a file with the specified binary data. If the file already
453
+ * exists, it will be truncated before writing.
454
+ *
455
+ * @param path - The path to the file to write
456
+ * @param data - The binary data to write to the file (Uint8Array or ArrayBuffer)
457
+ * @returns Promise that resolves when the write operation is complete
458
+ * @throws {OPFSError} If writing the file fails
459
+ *
460
+ * @example
461
+ * ```typescript
462
+ * // Write binary data
463
+ * const binaryData = new Uint8Array([1, 2, 3, 4, 5]);
464
+ * await fs.writeFile('/data/binary.dat', binaryData);
465
+ *
466
+ * // Write from ArrayBuffer
467
+ * const arrayBuffer = new ArrayBuffer(10);
468
+ * await fs.writeFile('/data/buffer.dat', arrayBuffer);
469
+ * ```
470
+ */
471
+ async writeFile(
472
+ path: string,
473
+ data: Uint8Array | ArrayBuffer
474
+ ): Promise<void> {
475
+ await this.mount();
476
+
477
+ const buffer = data instanceof Uint8Array ? data : new Uint8Array(data);
478
+
479
+ await withLock(path, async() => {
480
+ const existed = await this.exists(path);
481
+ const fd = await this.open(path, { create: true, truncate: true });
482
+
483
+ try {
484
+ await this.write(fd, buffer, 0, buffer.length, null, false);
485
+ await this.fsync(fd);
486
+ }
487
+ finally {
488
+ await this.close(fd);
489
+ }
490
+
491
+ await this.notifyChange({ path, type: existed ? WatchEventType.Changed : WatchEventType.Added, isDirectory: false });
492
+ });
493
+ }
494
+
495
+ /**
496
+ * Append data to a file
497
+ *
498
+ * Adds binary data to the end of an existing file. If the file doesn't exist,
499
+ * it will be created.
500
+ *
501
+ * @param path - The path to the file to append to
502
+ * @param data - The binary data to append to the file (Uint8Array or ArrayBuffer)
503
+ * @returns Promise that resolves when the append operation is complete
504
+ * @throws {OPFSError} If appending to the file fails
505
+ *
506
+ * @example
507
+ * ```typescript
508
+ * // Append binary data
509
+ * const additionalData = new Uint8Array([6, 7, 8]);
510
+ * await fs.appendFile('/data/binary.dat', additionalData);
511
+ *
512
+ * // Append from ArrayBuffer
513
+ * const arrayBuffer = new ArrayBuffer(5);
514
+ * await fs.appendFile('/data/buffer.dat', arrayBuffer);
515
+ * ```
516
+ */
517
+ async appendFile(
518
+ path: string,
519
+ data: Uint8Array | ArrayBuffer
520
+ ): Promise<void> {
521
+ await this.mount();
522
+
523
+ const buffer = data instanceof Uint8Array ? data : new Uint8Array(data);
524
+
525
+ await withLock(path, async() => {
526
+ const fd = await this.open(path, { create: true });
527
+
528
+ try {
529
+ const { size } = await this.fstat(fd);
530
+
531
+ await this.write(fd, buffer, 0, buffer.length, size, false);
532
+ await this.fsync(fd);
533
+ }
534
+ finally {
535
+ await this.close(fd);
536
+ }
537
+
538
+ await this.notifyChange({ path, type: WatchEventType.Changed, isDirectory: false });
539
+ });
540
+ }
541
+
542
+ /**
543
+ * Create a directory
544
+ *
545
+ * Creates a new directory at the specified path. If the recursive option
546
+ * is enabled, parent directories will be created as needed.
547
+ *
548
+ * @param path - The path where the directory should be created
549
+ * @param options - Options for directory creation
550
+ * @param options.recursive - Whether to create parent directories if they don't exist (default: false)
551
+ * @returns Promise that resolves when the directory is created
552
+ * @throws {OPFSError} If the directory cannot be created
553
+ *
554
+ * @example
555
+ * ```typescript
556
+ * // Create a single directory
557
+ * await fs.mkdir('/users/john');
558
+ *
559
+ * // Create nested directories
560
+ * await fs.mkdir('/users/john/documents/projects', { recursive: true });
561
+ * ```
562
+ */
563
+ async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {
564
+ await this.mount();
565
+
566
+ const recursive = options?.recursive ?? false;
567
+ const segments = splitPath(path);
568
+
569
+ let current: FileSystemDirectoryHandle | null = this.root;
570
+
571
+ for (let i = 0; i < segments.length; i++) {
572
+ const segment = segments[i];
573
+
574
+ try {
575
+ current = await current.getDirectoryHandle(segment!, { create: recursive || i === segments.length - 1 });
576
+ }
577
+ catch (err: any) {
578
+ if (err.name === 'NotFoundError') {
579
+ throw mapDomError(err, {
580
+ path: joinPath(segments.slice(0, i + 1)),
581
+ existenceType: 'directory',
582
+ });
583
+ }
584
+
585
+ if (err.name === 'TypeMismatchError') {
586
+ throw mapDomError(err, { path: segment!, isDirectory: false });
587
+ }
588
+
589
+ throw new FileSystemOperationError('create directory', segment!, err);
590
+ }
591
+ }
592
+
593
+ await this.notifyChange({ path, type: WatchEventType.Added, isDirectory: true });
594
+ }
595
+
596
+ /**
597
+ * Get file or directory statistics
598
+ *
599
+ * Returns detailed information about a file or directory, including
600
+ * size, modification time, and optionally a hash of the file content.
601
+ *
602
+ * @param path - The path to the file or directory
603
+ * @returns Promise that resolves to FileStat object
604
+ * @throws {OPFSError} If the path does not exist or cannot be accessed
605
+ *
606
+ * @example
607
+ * ```typescript
608
+ * const stats = await fs.stat('/data/config.json');
609
+ * console.log(`File size: ${stats.size} bytes`);
610
+ * console.log(`Last modified: ${stats.mtime}`);
611
+ *
612
+ * // If hashing is enabled, hash will be included
613
+ * if (stats.hash) {
614
+ * console.log(`Hash: ${stats.hash}`);
615
+ * }
616
+ * ```
617
+ */
618
+ async stat(path: string): Promise<FileStat> {
619
+ await this.mount();
620
+
621
+ // Special handling for root directory
622
+ if (path === '/') {
623
+ return {
624
+ kind: 'directory',
625
+ size: 0,
626
+ mtime: new Date(0).toISOString(),
627
+ ctime: new Date(0).toISOString(),
628
+ isFile: false,
629
+ isDirectory: true,
630
+ };
631
+ }
632
+
633
+ const name = basename(path);
634
+ let parentDir: FileSystemDirectoryHandle;
635
+
636
+ try {
637
+ parentDir = await this.getDirectoryHandle(dirname(path), false);
638
+ const hashAlgorithm = this.options.hashAlgorithm;
639
+
640
+ const fileHandle = await parentDir.getFileHandle(name, { create: false });
641
+ const file = await fileHandle.getFile();
642
+
643
+ const baseStat: FileStat = {
644
+ kind: 'file',
645
+ size: file.size,
646
+ mtime: new Date(file.lastModified).toISOString(),
647
+ ctime: new Date(file.lastModified).toISOString(),
648
+ isFile: true,
649
+ isDirectory: false,
650
+ };
651
+
652
+ if (hashAlgorithm === 'etag') {
653
+ baseStat.hash = `${ file.lastModified.toString(36) }-${ file.size.toString(36) }`;
654
+ }
655
+ // Crypto hash
656
+ else if (typeof hashAlgorithm === 'string') {
657
+ try {
658
+ const hash = await calculateFileHash(file, hashAlgorithm, this.options.maxFileSize);
659
+
660
+ baseStat.hash = hash;
661
+ }
662
+ catch (error) {
663
+ console.warn(`Failed to calculate hash for ${ path }:`, error);
664
+ }
665
+ }
666
+
667
+ return baseStat;
668
+ }
669
+ catch (e: any) {
670
+ if (e.name === 'NotFoundError') {
671
+ throw new ExistenceError('file', path, e);
672
+ }
673
+
674
+ if (e.name !== 'TypeMismatchError') {
675
+ throw new FileSystemOperationError('stat', path, e);
676
+ }
677
+ }
678
+
679
+ try {
680
+ await parentDir!.getDirectoryHandle(name, { create: false });
681
+
682
+ return {
683
+ kind: 'directory',
684
+ size: 0,
685
+ mtime: new Date(0).toISOString(),
686
+ ctime: new Date(0).toISOString(),
687
+ isFile: false,
688
+ isDirectory: true,
689
+ };
690
+ }
691
+ catch (e: any) {
692
+ throw new FileSystemOperationError('stat', path, e);
693
+ }
694
+ }
695
+
696
+ /**
697
+ * Read a directory's contents
698
+ *
699
+ * Lists all files and subdirectories within the specified directory.
700
+ *
701
+ * @param path - The path to the directory to read
702
+ * @returns Promise that resolves to an array of detailed file/directory information
703
+ * @throws {OPFSError} If the directory does not exist or cannot be accessed
704
+ *
705
+ * @example
706
+ * ```typescript
707
+ * // Get detailed information about files and directories
708
+ * const detailed = await fs.readDir('/users/john/documents');
709
+ * detailed.forEach(item => {
710
+ * console.log(`${item.name} - ${item.isFile ? 'file' : 'directory'}`);
711
+ * });
712
+ * ```
713
+ */
714
+ async readDir(path: string): Promise<DirentData[]> {
715
+ await this.mount();
716
+
717
+ const dir = await this.getDirectoryHandle(path, false);
718
+
719
+ const results: DirentData[] = [];
720
+
721
+ for await (const [name, handle] of (dir as any).entries()) {
722
+ const isFile = handle.kind === 'file';
723
+
724
+ results.push({
725
+ name,
726
+ kind: handle.kind,
727
+ isFile,
728
+ isDirectory: !isFile,
729
+ });
730
+ }
731
+
732
+ return results;
733
+ }
734
+
735
+ /**
736
+ * Check if a file or directory exists
737
+ *
738
+ * Verifies if a file or directory exists at the specified path.
739
+ *
740
+ * @param path - The path to check
741
+ * @returns Promise that resolves to true if the file or directory exists, false otherwise
742
+ *
743
+ * @example
744
+ * ```typescript
745
+ * const exists = await fs.exists('/config/settings.json');
746
+ * console.log(`File exists: ${exists}`);
747
+ * ```
748
+ */
749
+ async exists(path: string): Promise<boolean> {
750
+ await this.mount();
751
+
752
+ if (path === '/') {
753
+ return true;
754
+ }
755
+
756
+ const name = basename(path);
757
+ let dir: FileSystemDirectoryHandle | null = null;
758
+
759
+ try {
760
+ dir = await this.getDirectoryHandle(dirname(path), false);
761
+ }
762
+ catch (e: any) {
763
+ dir = null;
764
+
765
+ if (e.name !== 'NotFoundError' && e.name !== 'TypeMismatchError') {
766
+ throw e;
767
+ }
768
+ }
769
+
770
+ if (!dir || !name) {
771
+ return false;
772
+ }
773
+
774
+ try {
775
+ await dir.getFileHandle(name, { create: false });
776
+
777
+ return true;
778
+ }
779
+ catch (err: any) {
780
+ if (err.name !== 'NotFoundError' && err.name !== 'TypeMismatchError') {
781
+ throw err;
782
+ }
783
+
784
+ try {
785
+ await dir.getDirectoryHandle(name, { create: false });
786
+
787
+ return true;
788
+ }
789
+ catch (err: any) {
790
+ if (err.name !== 'NotFoundError' && err.name !== 'TypeMismatchError') {
791
+ throw err;
792
+ }
793
+
794
+ return false;
795
+ }
796
+ }
797
+ }
798
+
799
+ /**
800
+ * Clear all contents of a directory without removing the directory itself
801
+ *
802
+ * Removes all files and subdirectories within the specified directory,
803
+ * but keeps the directory itself.
804
+ *
805
+ * @param path - The path to the directory to clear (default: '/')
806
+ * @returns Promise that resolves when all contents are removed
807
+ * @throws {OPFSError} If the operation fails
808
+ *
809
+ * @example
810
+ * ```typescript
811
+ * // Clear root directory contents
812
+ * await fs.clear('/');
813
+ *
814
+ * // Clear specific directory contents
815
+ * await fs.clear('/data');
816
+ * ```
817
+ */
818
+ async clear(path: string = '/'): Promise<void> {
819
+ await this.mount();
820
+
821
+ try {
822
+ const items = await this.readDir(path);
823
+
824
+ for (const item of items) {
825
+ const itemPath = `${ path === '/' ? '' : path }/${ item.name }`;
826
+
827
+ await this.remove(itemPath, { recursive: true });
828
+ }
829
+
830
+ await this.notifyChange({ path, type: WatchEventType.Changed, isDirectory: true });
831
+ }
832
+ catch (error: any) {
833
+ if (error instanceof OPFSError) {
834
+ throw error;
835
+ }
836
+
837
+ throw mapDomError(error, { path, isDirectory: true });
838
+ }
839
+ }
840
+
841
+ /**
842
+ * Remove files and directories
843
+ *
844
+ * Removes files and directories. Similar to Node.js fs.rm().
845
+ *
846
+ * @param path - The path to remove
847
+ * @param options - Options for removal
848
+ * @param options.recursive - Whether to remove directories and their contents recursively (default: false)
849
+ * @param options.force - Whether to ignore errors if the path doesn't exist (default: false)
850
+ * @returns Promise that resolves when the removal is complete
851
+ * @throws {OPFSError} If the removal fails
852
+ *
853
+ * @example
854
+ * ```typescript
855
+ * // Remove a file
856
+ * await fs.rm('/path/to/file.txt');
857
+ *
858
+ * // Remove a directory and all its contents
859
+ * await fs.rm('/path/to/directory', { recursive: true });
860
+ *
861
+ * // Remove with force (ignore if doesn't exist)
862
+ * await fs.rm('/maybe/exists', { force: true });
863
+ * ```
864
+ */
865
+ async remove(path: string, options?: { recursive?: boolean; force?: boolean }): Promise<void> {
866
+ await this.mount();
867
+
868
+ // Special handling for root directory
869
+ if (path === '/') {
870
+ throw new DirectoryOperationError('EROOT', path);
871
+ }
872
+
873
+ const { recursive = false, force = false } = options || {};
874
+
875
+ const parent = await this.getDirectoryHandle(dirname(path), false);
876
+ const stat = await this.stat(path);
877
+
878
+ await removeEntry(parent, path, { recursive, force });
879
+
880
+ await this.notifyChange({ path, type: WatchEventType.Removed, isDirectory: stat.isDirectory });
881
+ }
882
+
883
+ /**
884
+ * Resolve a path to an absolute path
885
+ *
886
+ * Resolves relative paths and normalizes path segments (like '..' and '.').
887
+ * Similar to Node.js fs.realpath() but without symlink resolution since OPFS doesn't support symlinks.
888
+ *
889
+ * @param path - The path to resolve
890
+ * @returns Promise that resolves to the absolute normalized path
891
+ * @throws {FileNotFoundError} If the path does not exist
892
+ * @throws {OPFSError} If path resolution fails
893
+ *
894
+ * @example
895
+ * ```typescript
896
+ * // Resolve relative path
897
+ * const absolute = await fs.realpath('./config/../data/file.txt');
898
+ * console.log(absolute); // '/data/file.txt'
899
+ * ```
900
+ */
901
+ async realpath(path: string): Promise<string> {
902
+ await this.mount();
903
+
904
+ try {
905
+ const normalizedPath = resolvePath(path);
906
+ const exists = await this.exists(normalizedPath);
907
+
908
+ if (!exists) {
909
+ throw new ExistenceError('file', normalizedPath);
910
+ }
911
+
912
+ return normalizedPath;
913
+ }
914
+ catch (error) {
915
+ if (error instanceof OPFSError) {
916
+ throw error;
917
+ }
918
+
919
+ throw mapDomError(error, { path });
920
+ }
921
+ }
922
+
923
+ /**
924
+ * Rename a file or directory
925
+ *
926
+ * Changes the name of a file or directory. If the target path already exists,
927
+ * it will be replaced only if overwrite option is enabled.
928
+ *
929
+ * @param oldPath - The current path of the file or directory
930
+ * @param newPath - The new path for the file or directory
931
+ * @param options - Options for renaming
932
+ * @param options.overwrite - Whether to overwrite existing files (default: false)
933
+ * @returns Promise that resolves when the rename operation is complete
934
+ * @throws {OPFSError} If the rename operation fails
935
+ *
936
+ * @example
937
+ * ```typescript
938
+ * // Basic rename (fails if target exists)
939
+ * await fs.rename('/old/path/file.txt', '/new/path/renamed.txt');
940
+ *
941
+ * // Rename with overwrite
942
+ * await fs.rename('/old/path/file.txt', '/new/path/renamed.txt', { overwrite: true });
943
+ * ```
944
+ */
945
+ async rename(oldPath: string, newPath: string, options?: RenameOptions): Promise<void> {
946
+ await this.mount();
947
+
948
+ try {
949
+ const overwrite = options?.overwrite ?? false;
950
+
951
+ const sourceStat = await this.stat(oldPath);
952
+ const destExists = await this.exists(newPath);
953
+
954
+ if (destExists && !overwrite) {
955
+ throw new AlreadyExistsError(newPath);
956
+ }
957
+
958
+ await this.copy(oldPath, newPath, { recursive: true, overwrite });
959
+ await this.remove(oldPath, { recursive: true });
960
+
961
+ // Notify about the rename operation
962
+ await this.notifyChange({ path: oldPath, type: WatchEventType.Removed, isDirectory: sourceStat.isDirectory });
963
+ await this.notifyChange({ path: newPath, type: WatchEventType.Added, isDirectory: sourceStat.isDirectory });
964
+ }
965
+ catch (error) {
966
+ if (error instanceof OPFSError) {
967
+ throw error;
968
+ }
969
+
970
+ throw mapDomError(error, { path: oldPath });
971
+ }
972
+ }
973
+
974
+ /**
975
+ * Copy files and directories
976
+ *
977
+ * Copies files and directories. Similar to Node.js fs.cp().
978
+ *
979
+ * @param source - The source path to copy from
980
+ * @param destination - The destination path to copy to
981
+ * @param options - Options for copying
982
+ * @param options.recursive - Whether to copy directories recursively (default: false)
983
+ * @param options.overwrite - Whether to overwrite existing files (default: true)
984
+ * @returns Promise that resolves when the copy operation is complete
985
+ * @throws {OPFSError} If the copy operation fails
986
+ *
987
+ * @example
988
+ * ```typescript
989
+ * // Copy a file
990
+ * await fs.copy('/source/file.txt', '/dest/file.txt');
991
+ *
992
+ * // Copy a directory and all its contents
993
+ * await fs.copy('/source/dir', '/dest/dir', { recursive: true });
994
+ *
995
+ * // Copy without overwriting existing files
996
+ * await fs.copy('/source', '/dest', { recursive: true, overwrite: false });
997
+ * ```
998
+ */
999
+ async copy(source: string, destination: string, options?: { recursive?: boolean; overwrite?: boolean }): Promise<void> {
1000
+ await this.mount();
1001
+
1002
+ try {
1003
+ const recursive = options?.recursive ?? false;
1004
+ const overwrite = options?.overwrite ?? true;
1005
+
1006
+ const sourceExists = await this.exists(source);
1007
+
1008
+ if (!sourceExists) {
1009
+ throw new ExistenceError('source', source);
1010
+ }
1011
+
1012
+ const destExists = await this.exists(destination);
1013
+
1014
+ if (destExists && !overwrite) {
1015
+ throw new AlreadyExistsError(destination);
1016
+ }
1017
+
1018
+ const sourceStats = await this.stat(source);
1019
+
1020
+ if (sourceStats.isFile) {
1021
+ const content = await this.readFile(source);
1022
+
1023
+ await this.writeFile(destination, content);
1024
+ }
1025
+ else {
1026
+ if (!recursive) {
1027
+ throw new FileTypeError('directory', source);
1028
+ }
1029
+
1030
+ await this.mkdir(destination, { recursive: true });
1031
+
1032
+ const items = await this.readDir(source);
1033
+
1034
+ for (const item of items) {
1035
+ const sourceItemPath = `${ source }/${ item.name }`;
1036
+ const destItemPath = `${ destination }/${ item.name }`;
1037
+
1038
+ await this.copy(sourceItemPath, destItemPath, { recursive: true, overwrite });
1039
+ }
1040
+ }
1041
+ }
1042
+ catch (error) {
1043
+ if (error instanceof OPFSError) {
1044
+ throw error;
1045
+ }
1046
+
1047
+ throw mapDomError(error, { path: source });
1048
+ }
1049
+ }
1050
+
1051
+ /**
1052
+ * Start watching a file or directory for changes
1053
+ *
1054
+ * @param path - The path to watch (minimatch syntax allowed)
1055
+ * @param options - Watch options
1056
+ * @param options.recursive - Whether to watch recursively (default: true)
1057
+ * @param options.exclude - Glob pattern(s) to exclude (minimatch).
1058
+ * @returns Promise that resolves when watching starts
1059
+ *
1060
+ * @example
1061
+ * ```typescript
1062
+ * // Watch entire directory tree recursively (default)
1063
+ * await fs.watch('/data');
1064
+ *
1065
+ * // Watch only immediate children (shallow)
1066
+ * await fs.watch('/data', { recursive: false });
1067
+ *
1068
+ * // Watch a single file
1069
+ * await fs.watch('/config.json', { recursive: false });
1070
+ *
1071
+ * // Watch all json files but not in dist directory
1072
+ * await fs.watch('/**\/*.json', { recursive: false, exclude: ['dist/**'] });
1073
+ *
1074
+ * ```
1075
+ */
1076
+ async watch(path: string, options?: WatchOptions): Promise<void> {
1077
+ if (!this.options.broadcastChannel) {
1078
+ throw new OperationNotSupportedError('This instance is not configured to send events. Please specify options.broadcastChannel to enable watching.');
1079
+ }
1080
+
1081
+ const snapshot: WatchSnapshot = {
1082
+ pattern: normalizeMinimatch(path, options?.recursive ?? true),
1083
+ include: Array.isArray(options?.include) ? options.include : [options?.include ?? '**'],
1084
+ exclude: Array.isArray(options?.exclude) ? options.exclude : [options?.exclude ?? ''],
1085
+ };
1086
+
1087
+ this.watchers.set(path, snapshot);
1088
+ }
1089
+
1090
+ /**
1091
+ * Stop watching a previously watched path
1092
+ */
1093
+ unwatch(path: string): void {
1094
+ this.watchers.delete(path);
1095
+ }
1096
+
1097
+ /**
1098
+ * Open a file and return a file descriptor
1099
+ *
1100
+ * @param path - The path to the file to open
1101
+ * @param options - Options for opening the file
1102
+ * @param options.create - Whether to create the file if it doesn't exist (default: false)
1103
+ * @param options.exclusive - If true and create is true, fails if file already exists (default: false)
1104
+ * Note: This is best-effort in OPFS, not fully atomic due to browser limitations
1105
+ * @param options.truncate - Whether to truncate the file to zero length (default: false)
1106
+ * @returns Promise that resolves to a file descriptor number
1107
+ * @throws {OPFSError} If opening the file fails
1108
+ *
1109
+ * @example
1110
+ * ```typescript
1111
+ * // Open existing file for reading
1112
+ * const fd = await fs.open('/data/config.json');
1113
+ *
1114
+ * // Create new file for writing
1115
+ * const fd = await fs.open('/data/new.txt', { create: true });
1116
+ *
1117
+ * // Create file exclusively (fails if exists)
1118
+ * const fd = await fs.open('/data/unique.txt', { create: true, exclusive: true });
1119
+ *
1120
+ * // Open and truncate file
1121
+ * const fd = await fs.open('/data/log.txt', { create: true, truncate: true });
1122
+ * ```
1123
+ */
1124
+ async open(path: string, options?: FileOpenOptions): Promise<number> {
1125
+ await this.mount();
1126
+
1127
+ const { create = false, exclusive = false, truncate = false } = options || {};
1128
+
1129
+ // Normalize path to prevent path-related issues
1130
+ const normalizedPath = normalizePath(resolvePath(path));
1131
+
1132
+ try {
1133
+ // Use lock for atomic operations when creating files
1134
+ if (create && exclusive) {
1135
+ return await withLock(normalizedPath, async() => {
1136
+ const exists = await this.exists(normalizedPath);
1137
+
1138
+ if (exists) {
1139
+ throw new AlreadyExistsError(normalizedPath);
1140
+ }
1141
+
1142
+ return this._openFile(normalizedPath, create, truncate);
1143
+ });
1144
+ }
1145
+
1146
+ return await this._openFile(normalizedPath, create, truncate);
1147
+ }
1148
+ catch (error: any) {
1149
+ if (error instanceof OPFSError) {
1150
+ throw error;
1151
+ }
1152
+
1153
+ // TypeMismatchError here means the path actually refers to a directory
1154
+ // so we map it as a directory-type error (EISDIR) for better Node.js parity.
1155
+ const isTypeMismatchDirectory = error && error.name === 'TypeMismatchError';
1156
+
1157
+ throw mapDomError(error, {
1158
+ path: normalizedPath,
1159
+ isDirectory: !!isTypeMismatchDirectory,
1160
+ });
1161
+ }
1162
+ }
1163
+
1164
+ /**
1165
+ * Internal method to open a file (without locking)
1166
+ *
1167
+ * Multiple FDs for the same path share one sync access handle (OPFS limit),
1168
+ * with independent per-FD positions — similar to Node.js.
1169
+ * @private
1170
+ */
1171
+ private async _openFile(path: string, create: boolean, truncate: boolean): Promise<number> {
1172
+ let shared = this.openHandles.get(path);
1173
+
1174
+ if (!shared) {
1175
+ const fileHandle = await this.getFileHandle(path, create);
1176
+
1177
+ // Verify that we got a file handle, not a directory
1178
+ try {
1179
+ await fileHandle.getFile();
1180
+ }
1181
+ catch (error: any) {
1182
+ throw mapDomError(error, { path, isDirectory: true });
1183
+ }
1184
+
1185
+ const syncHandle = await createSyncHandleSafe(fileHandle, path);
1186
+
1187
+ shared = { fileHandle, syncHandle, refCount: 0 };
1188
+ this.openHandles.set(path, shared);
1189
+ }
1190
+
1191
+ shared.refCount++;
1192
+
1193
+ if (truncate) {
1194
+ shared.syncHandle.truncate(0);
1195
+ shared.syncHandle.flush();
1196
+ }
1197
+
1198
+ const fd = this.nextFd++;
1199
+
1200
+ this.openFiles.set(fd, {
1201
+ path,
1202
+ fileHandle: shared.fileHandle,
1203
+ syncHandle: shared.syncHandle,
1204
+ position: 0,
1205
+ });
1206
+
1207
+ return fd;
1208
+ }
1209
+
1210
+ /**
1211
+ * Close a file descriptor
1212
+ *
1213
+ * @param fd - The file descriptor to close
1214
+ * @returns Promise that resolves when the file descriptor is closed
1215
+ * @throws {OPFSError} If the file descriptor is invalid or closing fails
1216
+ *
1217
+ * @example
1218
+ * ```typescript
1219
+ * const fd = await fs.open('/data/file.txt');
1220
+ * // ... use the file descriptor ...
1221
+ * await fs.close(fd);
1222
+ * ```
1223
+ */
1224
+ async close(fd: number): Promise<void> {
1225
+ const fileInfo = this._getFileDescriptor(fd);
1226
+
1227
+ this.openFiles.delete(fd);
1228
+
1229
+ const shared = this.openHandles.get(fileInfo.path);
1230
+
1231
+ if (!shared) {
1232
+ return;
1233
+ }
1234
+
1235
+ shared.refCount--;
1236
+
1237
+ // Only close the underlying sync handle when the last FD for this path is gone
1238
+ if (shared.refCount <= 0) {
1239
+ safeCloseSyncHandle(fd, shared.syncHandle, fileInfo.path);
1240
+ this.openHandles.delete(fileInfo.path);
1241
+ }
1242
+ }
1243
+
1244
+ /**
1245
+ * Read data from a file descriptor
1246
+ *
1247
+ * @param fd - The file descriptor to read from
1248
+ * @param buffer - The buffer to read data into
1249
+ * @param offset - The offset in the buffer to start writing at
1250
+ * @param length - The number of bytes to read
1251
+ * @param position - The position in the file to read from (null for current position)
1252
+ * @returns Promise that resolves to the number of bytes read and the modified buffer
1253
+ * @throws {OPFSError} If the file descriptor is invalid or reading fails
1254
+ *
1255
+ * @note This method uses Comlink.transfer() to efficiently pass the buffer as a Transferable Object,
1256
+ * ensuring zero-copy performance across Web Worker boundaries.
1257
+ *
1258
+ * @example
1259
+ * ```typescript
1260
+ * const fd = await fs.open('/data/file.txt');
1261
+ * const buffer = new Uint8Array(1024);
1262
+ * const { bytesRead, buffer: modifiedBuffer } = await fs.read(fd, buffer, 0, 1024, null);
1263
+ * console.log(`Read ${bytesRead} bytes`);
1264
+ * // Use modifiedBuffer which contains the actual data
1265
+ * await fs.close(fd);
1266
+ * ```
1267
+ */
1268
+ async read(
1269
+ fd: number,
1270
+ buffer: Uint8Array,
1271
+ offset: number,
1272
+ length: number,
1273
+ position: number | null | undefined
1274
+ ): Promise<{ bytesRead: number; buffer: Uint8Array }> {
1275
+ const fileInfo = this._getFileDescriptor(fd);
1276
+
1277
+ // Validate arguments
1278
+ validateReadWriteArgs(buffer.length, offset, length, position);
1279
+
1280
+ try {
1281
+ const readPosition = position ?? fileInfo.position;
1282
+
1283
+ // Get file size and calculate read length
1284
+ const fileSize = fileInfo.syncHandle.getSize();
1285
+ const { isEOF, actualLength } = calculateReadLength(readPosition, length, fileSize);
1286
+
1287
+ if (isEOF) {
1288
+ return transfer({ bytesRead: 0, buffer }, [buffer.buffer]); // End of file
1289
+ }
1290
+
1291
+ // Create a subarray view for the read operation
1292
+ const targetBuffer = buffer.subarray(offset, offset + actualLength);
1293
+
1294
+ // Perform efficient positioned read
1295
+ const bytesRead = fileInfo.syncHandle.read(targetBuffer, { at: readPosition });
1296
+
1297
+ // Update position if position was not explicitly specified (null means use current position)
1298
+ if (position == null) {
1299
+ fileInfo.position = readPosition + bytesRead;
1300
+ }
1301
+
1302
+ return transfer({ bytesRead, buffer }, [buffer.buffer]);
1303
+ }
1304
+ catch (error) {
1305
+ throw createFDError('read', fd, fileInfo.path, error);
1306
+ }
1307
+ }
1308
+
1309
+ /**
1310
+ * Write data to a file descriptor
1311
+ *
1312
+ * @param fd - The file descriptor to write to
1313
+ * @param buffer - The buffer containing data to write
1314
+ * @param offset - The offset in the buffer to start reading from (default: 0)
1315
+ * @param length - The number of bytes to write (default: entire buffer)
1316
+ * @param position - The position in the file to write to (null/undefined for current position)
1317
+ * @param emitEvent - Whether to emit a change event (default: true)
1318
+ * @returns Promise that resolves to the number of bytes written
1319
+ * @throws {OPFSError} If the file descriptor is invalid or writing fails
1320
+ *
1321
+ * @example
1322
+ * ```typescript
1323
+ * const fd = await fs.open('/data/file.txt', { create: true });
1324
+ * const data = new TextEncoder().encode('Hello, World!');
1325
+ * const bytesWritten = await fs.write(fd, data, 0, data.length, null);
1326
+ * console.log(`Wrote ${bytesWritten} bytes`);
1327
+ * await fs.close(fd);
1328
+ * ```
1329
+ */
1330
+ async write(
1331
+ fd: number,
1332
+ buffer: Uint8Array,
1333
+ offset: number = 0,
1334
+ length?: number,
1335
+ position?: number | null | undefined,
1336
+ emitEvent: boolean = true
1337
+ ): Promise<number> {
1338
+ const fileInfo = this._getFileDescriptor(fd);
1339
+
1340
+ // Calculate actual length to write
1341
+ const actualLength = length ?? (buffer.length - offset);
1342
+
1343
+ // Validate arguments using helper
1344
+ validateReadWriteArgs(buffer.length, offset, actualLength, position);
1345
+
1346
+ try {
1347
+ // Determine write position: use specified position, or current position if null/undefined
1348
+ const writePosition = position ?? fileInfo.position;
1349
+
1350
+ // Create a subarray view for the write operation
1351
+ const sourceBuffer = buffer.subarray(offset, offset + actualLength);
1352
+
1353
+ // Perform efficient positioned write
1354
+ const bytesWritten = fileInfo.syncHandle.write(sourceBuffer, { at: writePosition });
1355
+
1356
+ // Update position if position was null or undefined (i.e., use current position)
1357
+ // Also update position when writing at current position (position === fileInfo.position)
1358
+ if (position == null || position === fileInfo.position) {
1359
+ fileInfo.position = writePosition + bytesWritten;
1360
+ }
1361
+
1362
+ if (emitEvent) {
1363
+ await this.notifyChange({ path: fileInfo.path, type: WatchEventType.Changed, isDirectory: false });
1364
+ }
1365
+
1366
+ return bytesWritten;
1367
+ }
1368
+ catch (error) {
1369
+ throw createFDError('write', fd, fileInfo.path, error);
1370
+ }
1371
+ }
1372
+
1373
+ /**
1374
+ * Get file status information by file descriptor
1375
+ *
1376
+ * @param fd - The file descriptor
1377
+ * @returns Promise that resolves to FileStat object
1378
+ * @throws {OPFSError} If the file descriptor is invalid
1379
+ *
1380
+ * @example
1381
+ * ```typescript
1382
+ * const fd = await fs.open('/data/file.txt');
1383
+ * const stats = await fs.fstat(fd);
1384
+ * console.log(`File size: ${stats.size} bytes`);
1385
+ * console.log(`Last modified: ${stats.mtime}`);
1386
+ *
1387
+ * // If hashing is enabled, hash will be included
1388
+ * if (stats.hash) {
1389
+ * console.log(`Hash: ${stats.hash}`);
1390
+ * }
1391
+ * ```
1392
+ */
1393
+ async fstat(fd: number): Promise<FileStat> {
1394
+ const fileInfo = this._getFileDescriptor(fd);
1395
+
1396
+ // Simply reuse existing stat() method with the file path
1397
+ return this.stat(fileInfo.path);
1398
+ }
1399
+
1400
+ /**
1401
+ * Truncate file to specified size
1402
+ *
1403
+ * @param fd - The file descriptor
1404
+ * @param size - The new size of the file (default: 0)
1405
+ * @returns Promise that resolves when truncation is complete
1406
+ * @throws {OPFSError} If the file descriptor is invalid or truncation fails
1407
+ *
1408
+ * @example
1409
+ * ```typescript
1410
+ * const fd = await fs.open('/data/file.txt', { create: true });
1411
+ * await fs.truncate(fd, 100); // Truncate to 100 bytes
1412
+ * ```
1413
+ */
1414
+ async ftruncate(fd: number, size: number = 0): Promise<void> {
1415
+ const fileInfo = this._getFileDescriptor(fd);
1416
+
1417
+ // Validate size parameter
1418
+ if (size < 0 || !Number.isInteger(size)) {
1419
+ throw new ValidationError('argument', 'Invalid size');
1420
+ }
1421
+
1422
+ try {
1423
+ fileInfo.syncHandle.truncate(size);
1424
+ fileInfo.syncHandle.flush();
1425
+
1426
+ // Adjust position if it's beyond the new file size
1427
+ if (fileInfo.position > size) {
1428
+ fileInfo.position = size;
1429
+ }
1430
+
1431
+ await this.notifyChange({ path: fileInfo.path, type: WatchEventType.Changed, isDirectory: false });
1432
+ }
1433
+ catch (error) {
1434
+ throw createFDError('truncate', fd, fileInfo.path, error);
1435
+ }
1436
+ }
1437
+
1438
+ /**
1439
+ * Synchronize file data to storage (fsync equivalent)
1440
+ *
1441
+ * @param fd - The file descriptor
1442
+ * @returns Promise that resolves when synchronization is complete
1443
+ * @throws {OPFSError} If the file descriptor is invalid or sync fails
1444
+ *
1445
+ * @example
1446
+ * ```typescript
1447
+ * const fd = await fs.open('/data/file.txt', { create: true });
1448
+ * await fs.write(fd, data);
1449
+ * await fs.fsync(fd); // Ensure data is written to storage
1450
+ * ```
1451
+ */
1452
+ async fsync(fd: number): Promise<void> {
1453
+ const fileInfo = this._getFileDescriptor(fd);
1454
+
1455
+ try {
1456
+ fileInfo.syncHandle.flush();
1457
+ }
1458
+ catch (error) {
1459
+ throw createFDError('sync', fd, fileInfo.path, error);
1460
+ }
1461
+ }
1462
+
1463
+ /**
1464
+ * Dispose of resources and clean up the file system instance
1465
+ *
1466
+ * This method should be called when the file system instance is no longer needed
1467
+ * to properly clean up resources like the broadcast channel and watch timers.
1468
+ */
1469
+ dispose(): void {
1470
+ if (this.broadcastChannel) {
1471
+ this.broadcastChannel.close();
1472
+ this.broadcastChannel = null;
1473
+ }
1474
+
1475
+ this.watchers.clear();
1476
+
1477
+ // Close each shared sync handle once (not per FD)
1478
+ for (const [path, shared] of this.openHandles) {
1479
+ safeCloseSyncHandle(-1, shared.syncHandle, path);
1480
+ }
1481
+
1482
+ this.openHandles.clear();
1483
+ this.openFiles.clear();
1484
+ this.nextFd = 1;
1485
+ }
1486
+
1487
+ /**
1488
+ * Synchronize the file system with external data
1489
+ *
1490
+ * Syncs the file system with an array of entries containing paths and data.
1491
+ * This is useful for importing data from external sources or syncing with remote data.
1492
+ *
1493
+ * @param entries - Array of [path, data] tuples to sync
1494
+ * @returns Promise that resolves when synchronization is complete
1495
+ * @throws {OPFSError} If the synchronization fails
1496
+ *
1497
+ * @example
1498
+ * ```typescript
1499
+ * // Sync with external data
1500
+ * const entries: [string, string | Uint8Array | Blob][] = [
1501
+ * ['/config.json', JSON.stringify({ theme: 'dark' })],
1502
+ * ['/data/binary.dat', new Uint8Array([1, 2, 3, 4])],
1503
+ * ['/upload.txt', new Blob(['file content'], { type: 'text/plain' })]
1504
+ * ];
1505
+ *
1506
+ * // Sync without clearing existing files
1507
+ * await fs.sync(entries);
1508
+ *
1509
+ * // Clean file system and then sync
1510
+ * await fs.sync(entries, { cleanBefore: true });
1511
+ * ```
1512
+ */
1513
+ async createIndex(entries: [string, string | Uint8Array | Blob][]): Promise<void> {
1514
+ await this.mount();
1515
+
1516
+ try {
1517
+ for (const [path, data] of entries) {
1518
+ const normalizedPath = normalizePath(path);
1519
+
1520
+ let fileData: Uint8Array;
1521
+
1522
+ if (data instanceof Blob) {
1523
+ fileData = await convertBlobToUint8Array(data);
1524
+ }
1525
+ else if (typeof data === 'string') {
1526
+ // Convert string to Uint8Array using UTF-8 encoding
1527
+ fileData = new TextEncoder().encode(data);
1528
+ }
1529
+ else {
1530
+ fileData = data;
1531
+ }
1532
+
1533
+ await this.writeFile(normalizedPath, fileData);
1534
+ }
1535
+ }
1536
+ catch (error) {
1537
+ if (error instanceof OPFSError) {
1538
+ throw error;
1539
+ }
1540
+
1541
+ throw mapDomError(error);
1542
+ }
1543
+ }
1544
+ }