opfs-worker 0.2.3 → 0.2.4

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/raw.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"raw.js","sources":["../src/worker.ts"],"sourcesContent":["import { expose } from 'comlink';\n\nimport { decodeBuffer } from './utils/encoder';\nimport {\n FileNotFoundError,\n OPFSError,\n OPFSNotMountedError,\n PathError\n} from './utils/errors';\n\nimport { \n calculateFileHash, \n checkOPFSSupport, \n joinPath, \n readFileData, \n splitPath, \n writeFileData,\n basename,\n dirname,\n normalizePath,\n resolvePath,\n convertBlobToUint8Array\n} from './utils/helpers';\n\nimport type { DirentData, FileStat, WatchEvent } from './types';\nimport type { BufferEncoding } from 'typescript';\n\n/**\n * OPFS (Origin Private File System) File System implementation\n * \n * This class provides a high-level interface for working with the browser's\n * Origin Private File System API, offering file and directory operations\n * similar to Node.js fs module.\n * \n * @example\n * ```typescript\n * const fs = new OPFSFileSystem();\n * await fs.init('/my-app');\n * await fs.writeFile('/data/config.json', JSON.stringify({ theme: 'dark' }));\n * const config = await fs.readFile('/data/config.json');\n * ```\n */\nexport class OPFSWorker {\n /** Root directory handle for the file system */\n private root: FileSystemDirectoryHandle | null = null;\n\n /** Watch event callback */\n private watchCallback: ((event: WatchEvent) => void) | null = null;\n\n /** Map of watched paths to their last known state */\n private watchers = new Map<string, Map<string, FileStat>>();\n\n /** Interval handle for polling watched paths */\n private watchTimer: ReturnType<typeof setInterval> | null = null;\n\n /** Polling interval in milliseconds */\n private watchInterval = 1000;\n\n /** Flag to avoid concurrent scans */\n private scanning = false;\n\n /** Promise to prevent concurrent mount operations */\n private mountingPromise: Promise<boolean> | null = null;\n\n /**\n * Creates a new OPFSFileSystem instance\n * \n * @param watchCallback - Optional callback for file change events\n * @param watchOptions - Optional configuration for watching\n * @throws {OPFSError} If OPFS is not supported in the current browser\n */\n constructor(\n watchCallback?: (event: WatchEvent) => void,\n watchOptions?: { watchInterval?: number }\n ) {\n checkOPFSSupport();\n \n if (watchCallback) {\n this.watchCallback = watchCallback;\n if (watchOptions?.watchInterval) {\n this.watchInterval = watchOptions.watchInterval;\n }\n }\n \n void this.mount('/');\n }\n\n /**\n * Initialize the file system within a given directory\n * \n * This method sets up the root directory for all subsequent operations.\n * If no root is specified, it will use the OPFS root directory.\n * \n * @param root - The root path for the file system (default: '/')\n * @returns Promise that resolves to true if initialization was successful\n * @throws {OPFSError} If initialization fails\n * \n * @example\n * ```typescript\n * const fs = new OPFSFileSystem();\n * \n * // Use OPFS root (default)\n * await fs.mount();\n * \n * // Use custom directory\n * await fs.mount('/my-app');\n * ```\n */\n async mount(root: string = '/'): Promise<boolean> {\n // If already mounting, wait for previous operation to complete first\n if (this.mountingPromise) {\n await this.mountingPromise;\n }\n\n this.mountingPromise = new Promise<boolean>(async(resolve, reject) => {\n this.root = null;\n \n try {\n const rootDir = await navigator.storage.getDirectory();\n \n if (root === '/') {\n this.root = rootDir;\n } \n else {\n this.root = await this.getDirectoryHandle(root, true, rootDir);\n }\n resolve(true);\n }\n catch (error) {\n console.error(error);\n reject(new OPFSError('Failed to initialize OPFS', 'INIT_FAILED'));\n }\n finally {\n this.mountingPromise = null;\n }\n });\n\n return this.mountingPromise;\n }\n\n /**\n * Set the watch callback for file change events\n * \n * @param callback - The callback function to invoke when files change\n * @param options - Optional configuration for watching\n */\n setWatchCallback(callback: (event: WatchEvent) => void, options?: { watchInterval?: number }): void {\n this.watchCallback = callback;\n\n if (options?.watchInterval) {\n this.watchInterval = options.watchInterval;\n }\n }\n\n /**\n * Automatically mount the OPFS root if not already mounted\n * \n * This method is called internally when file operations are performed\n * without explicitly mounting first.\n * \n * @returns Promise that resolves when auto-mount is complete\n * @throws {OPFSError} If auto-mount fails\n */\n private async ensureMounted(): Promise<void> {\n // If already mounted, return immediately\n if (this.root) {\n return;\n }\n\n // If already mounting, wait for that operation to complete\n if (this.mountingPromise) {\n await this.mountingPromise;\n return;\n }\n\n throw new OPFSError('OPFS not mounted', 'NOT_MOUNTED');\n }\n\n /**\n * Get a directory handle from a path\n * \n * Navigates through the directory structure to find or create a directory\n * at the specified path.\n * \n * @param path - The path to the directory (string or array of segments)\n * @param create - Whether to create the directory if it doesn't exist (default: false)\n * @param from - The directory to start from (default: root directory)\n * @returns Promise that resolves to the directory handle\n * @throws {OPFSError} If the directory cannot be accessed or created\n * \n * @example\n * ```typescript\n * const docsDir = await fs.getDirectoryHandle('/users/john/documents', true);\n * const docsDir2 = await fs.getDirectoryHandle(['users', 'john', 'documents'], true);\n * ```\n */\n private async getDirectoryHandle(path: string | string[], create: boolean = false, from: FileSystemDirectoryHandle | null = this.root): Promise<FileSystemDirectoryHandle> {\n if (!from) {\n throw new OPFSNotMountedError();\n }\n\n const segments = Array.isArray(path) ? path : splitPath(path);\n let current = from;\n\n for (const segment of segments) {\n current = await current.getDirectoryHandle(segment, { create });\n }\n\n return current;\n }\n\n /**\n * Get a file handle from a path\n * \n * Navigates to the parent directory and retrieves or creates a file handle\n * for the specified file path.\n * \n * @param path - The path to the file (string or array of segments)\n * @param create - Whether to create the file if it doesn't exist (default: false)\n * @param from - The directory to start from (default: root directory)\n * @returns Promise that resolves to the file handle\n * @throws {PathError} If the path is empty\n * @throws {OPFSError} If the file cannot be accessed or created\n * \n * @example\n * ```typescript\n * const fileHandle = await fs.getFileHandle('/config/settings.json', true);\n * const fileHandle2 = await fs.getFileHandle(['config', 'settings.json'], true);\n * ```\n */\n private async getFileHandle(path: string | string[], create = false, from: FileSystemDirectoryHandle | null = this.root): Promise<FileSystemFileHandle> {\n if (!from) {\n throw new OPFSNotMountedError();\n }\n\n const segments = splitPath(path);\n\n if (segments.length === 0) {\n throw new PathError('Path must not be empty', Array.isArray(path) ? path.join('/') : path);\n }\n\n const fileName = segments.pop()!;\n const dir = await this.getDirectoryHandle(segments, create, from);\n\n return dir.getFileHandle(fileName, { create });\n }\n\n\n /**\n * Recursively list all files and directories with their stats\n * \n * Traverses the entire file system starting from the root and returns\n * a Map containing all paths and their corresponding file statistics.\n * \n * @param options - Options for indexing\n * @param options.includeHash - Whether to calculate file hash (default: false)\n * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)\n * @returns Promise that resolves to a Map of path => FileStat\n * @throws {OPFSError} If the indexing operation fails\n * \n * @example\n * ```typescript\n * // Basic index without hash\n * const index = await fs.index();\n * \n * // Index with file hash\n * const indexWithHash = await fs.index({ \n * includeHash: true,\n * hashAlgorithm: 'SHA-1'\n * });\n * \n * // Iterate through all files and directories\n * for (const [path, stat] of index) {\n * console.log(`${path}: ${stat.isFile ? 'file' : 'directory'} (${stat.size} bytes)`);\n * if (stat.hash) console.log(` Hash: ${stat.hash}`);\n * }\n * \n * // Get specific file stats\n * const fileStats = index.get('/data/config.json');\n * if (fileStats) {\n * console.log(`File size: ${fileStats.size} bytes`);\n * if (fileStats.hash) console.log(`Hash: ${fileStats.hash}`);\n * }\n * ```\n */\n async index(options?: { includeHash?: boolean; hashAlgorithm?: 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512' }): Promise<Map<string, FileStat>> {\n const result = new Map<string, FileStat>();\n\n const walk = async(dirPath: string) => {\n const items = await this.readdir(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = `${ dirPath === '/' ? '' : dirPath }/${ item.name }`;\n\n try {\n const stat = await this.stat(fullPath, options);\n\n result.set(fullPath, stat);\n\n if (stat.isDirectory) {\n await walk(fullPath);\n }\n }\n catch (err) {\n console.warn(`Skipping broken entry: ${ fullPath }`, err);\n }\n }\n };\n\n result.set('/', {\n kind: 'directory',\n size: 0,\n mtime: new Date(0).toISOString(),\n ctime: new Date(0).toISOString(),\n isFile: false,\n isDirectory: true,\n });\n\n await walk('/');\n\n return result;\n }\n\n /**\n * Read a file from the file system\n * \n * Reads the contents of a file and returns it as a string or binary data\n * depending on the specified encoding.\n * \n * @param path - The path to the file to read\n * @param encoding - The encoding to use for reading the file\n * @returns Promise that resolves to the file contents\n * @throws {FileNotFoundError} If the file does not exist\n * @throws {OPFSError} If reading the file fails\n * \n * @example\n * ```typescript\n * // Read as text\n * const content = await fs.readFile('/config/settings.json');\n * \n * // Read as binary\n * const binaryData = await fs.readFile('/images/logo.png', 'binary');\n * \n * // Read with specific encoding\n * const utf8Content = await fs.readFile('/data/utf8.txt', 'utf-8');\n * ```\n */\n async readFile(path: string, encoding: 'binary'): Promise<Uint8Array>;\n async readFile(path: string, encoding?: BufferEncoding): Promise<string>;\n async readFile(\n path: string,\n encoding: BufferEncoding | 'binary' = 'utf-8'\n ): Promise<string | Uint8Array> {\n await this.ensureMounted();\n \n try {\n const fileHandle = await this.getFileHandle(path, false);\n const buffer = await readFileData(fileHandle);\n\n if (encoding === 'binary') {\n return buffer;\n }\n\n return decodeBuffer(buffer, encoding);\n }\n catch (err) {\n console.error(err);\n\n throw new FileNotFoundError(path);\n }\n }\n\n /**\n * Write data to a file\n * \n * Creates or overwrites a file with the specified data. If the file already\n * exists, it will be truncated before writing.\n * \n * @param path - The path to the file to write\n * @param data - The data to write to the file (string, Uint8Array, or ArrayBuffer)\n * @param encoding - The encoding to use when writing string data (default: 'utf-8')\n * @returns Promise that resolves when the write operation is complete\n * @throws {OPFSError} If writing the file fails\n * \n * @example\n * ```typescript\n * // Write text data\n * await fs.writeFile('/config/settings.json', JSON.stringify({ theme: 'dark' }));\n * \n * // Write binary data\n * const binaryData = new Uint8Array([1, 2, 3, 4, 5]);\n * await fs.writeFile('/data/binary.dat', binaryData);\n * \n * // Write with specific encoding\n * await fs.writeFile('/data/utf16.txt', 'Hello World', 'utf-16le');\n * ```\n */\n async writeFile(\n path: string,\n data: string | Uint8Array | ArrayBuffer,\n encoding?: BufferEncoding\n ): Promise<void> {\n await this.ensureMounted();\n \n const fileHandle = await this.getFileHandle(path, true);\n\n await writeFileData(fileHandle, data, encoding, { truncate: true });\n }\n\n /**\n * Append data to a file\n * \n * Adds data to the end of an existing file. If the file doesn't exist,\n * it will be created.\n * \n * @param path - The path to the file to append to\n * @param data - The data to append to the file (string, Uint8Array, or ArrayBuffer)\n * @param encoding - The encoding to use when appending string data (default: 'utf-8')\n * @returns Promise that resolves when the append operation is complete\n * @throws {OPFSError} If appending to the file fails\n * \n * @example\n * ```typescript\n * // Append text to a log file\n * await fs.appendFile('/logs/app.log', `[${new Date().toISOString()}] User logged in\\n`);\n * \n * // Append binary data\n * const additionalData = new Uint8Array([6, 7, 8]);\n * await fs.appendFile('/data/binary.dat', additionalData);\n * ```\n */\n async appendFile(\n path: string,\n data: string | Uint8Array | ArrayBuffer,\n encoding?: BufferEncoding\n ): Promise<void> {\n await this.ensureMounted();\n \n const fileHandle = await this.getFileHandle(path, true);\n\n await writeFileData(fileHandle, data, encoding, { append: true });\n }\n\n /**\n * Create a directory\n * \n * Creates a new directory at the specified path. If the recursive option\n * is enabled, parent directories will be created as needed.\n * \n * @param path - The path where the directory should be created\n * @param options - Options for directory creation\n * @param options.recursive - Whether to create parent directories if they don't exist (default: false)\n * @returns Promise that resolves when the directory is created\n * @throws {OPFSError} If the directory cannot be created\n * \n * @example\n * ```typescript\n * // Create a single directory\n * await fs.mkdir('/users/john');\n * \n * // Create nested directories\n * await fs.mkdir('/users/john/documents/projects', { recursive: true });\n * ```\n */\n async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n await this.ensureMounted();\n\n if (!this.root) {\n throw new OPFSNotMountedError();\n }\n\n const recursive = options?.recursive ?? false;\n const segments = splitPath(path);\n\n let current = this.root;\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n\n try {\n current = await current.getDirectoryHandle(segment!, { create: recursive || i === segments.length - 1 });\n }\n catch (e: any) {\n if (e.name === 'NotFoundError') {\n throw new OPFSError(\n `Parent directory does not exist: ${ joinPath(segments.slice(0, i + 1)) }`,\n 'ENOENT'\n );\n }\n\n if (e.name === 'TypeMismatchError') {\n throw new OPFSError(`Path segment is not a directory: ${ segment }`, 'ENOTDIR');\n }\n\n throw new OPFSError('Failed to create directory', 'MKDIR_FAILED');\n }\n }\n }\n\n /**\n * Get file or directory stats\n * \n * Retrieves metadata about a file or directory, including size, modification time,\n * type information, and optionally file hashes.\n * \n * @param path - The path to the file or directory\n * @param options - Options for stat operation\n * @param options.includeHash - Whether to calculate file hash (default: false, only for files)\n * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)\n * @returns Promise that resolves to file/directory statistics\n * @throws {OPFSError} If the file or directory does not exist or cannot be accessed\n * \n * @example\n * ```typescript\n * // Basic stats\n * const stats = await fs.stat('/config/settings.json');\n * console.log(`File size: ${stats.size} bytes`);\n * console.log(`Is file: ${stats.isFile}`);\n * console.log(`Modified: ${stats.mtime}`);\n * \n * // Stats with hash (SHA-1 is fastest)\n * const statsWithHash = await fs.stat('/config/settings.json', { \n * includeHash: true,\n * hashAlgorithm: 'SHA-1'\n * });\n * console.log(`Hash: ${statsWithHash.hash}`);\n * ```\n */\n async stat(path: string, options?: { includeHash?: boolean; hashAlgorithm?: 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512' }): Promise<FileStat> {\n await this.ensureMounted();\n \n // Special handling for root directory\n if (path === '/') {\n return {\n kind: 'directory',\n size: 0,\n mtime: new Date(0).toISOString(),\n ctime: new Date(0).toISOString(),\n isFile: false,\n isDirectory: true,\n };\n }\n \n const name = basename(path);\n const parentDir = await this.getDirectoryHandle(dirname(path), false);\n const includeHash = options?.includeHash ?? false;\n const hashAlgorithm = options?.hashAlgorithm ?? 'SHA-1';\n\n try {\n const fileHandle = await parentDir.getFileHandle(name!, { create: false });\n const file = await fileHandle.getFile();\n\n const baseStat: FileStat = {\n kind: 'file',\n size: file.size,\n mtime: new Date(file.lastModified).toISOString(),\n ctime: new Date(file.lastModified).toISOString(),\n isFile: true,\n isDirectory: false,\n };\n\n if (includeHash) {\n try {\n const buffer = new Uint8Array(await file.arrayBuffer());\n const hash = await calculateFileHash(buffer, hashAlgorithm);\n\n baseStat.hash = hash;\n }\n catch (error) {\n console.warn(`Failed to calculate hash for ${ path }:`, error);\n }\n }\n\n return baseStat;\n }\n catch (e: any) {\n if (e.name !== 'TypeMismatchError' && e.name !== 'NotFoundError') {\n throw new OPFSError('Failed to stat (file)', 'STAT_FAILED');\n }\n }\n\n try {\n await parentDir.getDirectoryHandle(name!, { create: false });\n\n return {\n kind: 'directory',\n size: 0,\n mtime: new Date(0).toISOString(),\n ctime: new Date(0).toISOString(),\n isFile: false,\n isDirectory: true,\n };\n }\n catch (e: any) {\n if (e.name === 'NotFoundError') {\n throw new OPFSError(`No such file or directory: ${ path }`, 'ENOENT');\n }\n\n throw new OPFSError('Failed to stat (directory)', 'STAT_FAILED');\n }\n }\n\n /**\n * Read a directory's contents\n * \n * Lists all files and subdirectories within the specified directory.\n * \n * @param path - The path to the directory to read\n * @param options - Options for the readdir operation\n * @param options.withFileTypes - Whether to return detailed file information (default: false)\n * @returns Promise that resolves to an array of file/directory names or detailed information\n * @throws {OPFSError} If the directory does not exist or cannot be accessed\n * \n * @example\n * ```typescript\n * // Get simple list of names\n * const files = await fs.readdir('/users/john/documents');\n * console.log('Files:', files); // ['readme.txt', 'config.json', 'images']\n * \n * // Get detailed information\n * const detailed = await fs.readdir('/users/john/documents', { withFileTypes: true });\n * detailed.forEach(item => {\n * console.log(`${item.name} - ${item.isFile ? 'file' : 'directory'}`);\n * });\n * ```\n */\n async readdir(path: string): Promise<string[]>;\n async readdir(path: string, options: { withFileTypes: true }): Promise<DirentData[]>;\n async readdir(path: string, options: { withFileTypes: false }): Promise<string[]>;\n async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirentData[]> {\n await this.ensureMounted();\n \n const withTypes = options?.withFileTypes ?? false;\n const dir = await this.getDirectoryHandle(path, false);\n\n if (withTypes) {\n const results: DirentData[] = [];\n\n for await (const [name, handle] of (dir as any).entries()) {\n const isFile = handle.kind === 'file';\n\n results.push({\n name,\n kind: handle.kind,\n isFile,\n isDirectory: !isFile,\n });\n }\n\n return results;\n }\n else {\n const results: string[] = [];\n\n for await (const [name] of (dir as any).entries()) {\n results.push(name);\n }\n\n return results;\n }\n }\n\n /**\n * Check if a file or directory exists\n * \n * Verifies if a file or directory exists at the specified path.\n * \n * @param path - The path to check\n * @returns Promise that resolves to true if the file or directory exists, false otherwise \n * \n * @example\n * ```typescript\n * const exists = await fs.exists('/config/settings.json');\n * console.log(`File exists: ${exists}`);\n * ```\n */\n async exists(path: string): Promise<boolean> {\n await this.ensureMounted();\n \n if (path === '/') {\n return true;\n }\n \n const name = basename(path);\n let dir: FileSystemDirectoryHandle | null = null;\n\n try {\n dir = await this.getDirectoryHandle(dirname(path), false);\n }\n catch (e: any) {\n if (e.name === 'NotFoundError' || e.name === 'TypeMismatchError') {\n dir = null;\n }\n\n throw e;\n }\n\n if (!dir || !name) {\n return false;\n }\n\n try {\n await dir.getFileHandle(name, { create: false });\n\n return true;\n }\n catch (e: any) {\n if (e.name !== 'NotFoundError' && e.name !== 'TypeMismatchError') {\n throw e;\n }\n }\n\n try {\n await dir.getDirectoryHandle(name, { create: false });\n\n return true;\n }\n catch (e: any) {\n if (e.name !== 'NotFoundError' && e.name !== 'TypeMismatchError') {\n throw e;\n }\n }\n\n return false;\n }\n\n /**\n * Clear all contents of a directory without removing the directory itself\n * \n * Removes all files and subdirectories within the specified directory,\n * but keeps the directory itself.\n * \n * @param path - The path to the directory to clear (default: '/')\n * @returns Promise that resolves when all contents are removed\n * @throws {OPFSError} If the operation fails\n * \n * @example\n * ```typescript\n * // Clear root directory contents\n * await fs.clear('/');\n * \n * // Clear specific directory contents\n * await fs.clear('/data');\n * ```\n */\n async clear(path: string = '/'): Promise<void> {\n await this.ensureMounted();\n \n try {\n const items = await this.readdir(path, { withFileTypes: true });\n\n for (const item of items) {\n const itemPath = `${ path === '/' ? '' : path }/${ item.name }`;\n\n await this.remove(itemPath, { recursive: true });\n }\n }\n catch (error: any) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to clear directory: ${ path }`, 'CLEAR_FAILED');\n }\n }\n\n /**\n * Remove files and directories\n * \n * Removes files and directories. Similar to Node.js fs.rm().\n * \n * @param path - The path to remove\n * @param options - Options for removal\n * @param options.recursive - Whether to remove directories and their contents recursively (default: false)\n * @param options.force - Whether to ignore errors if the path doesn't exist (default: false)\n * @returns Promise that resolves when the removal is complete\n * @throws {OPFSError} If the removal fails\n * \n * @example\n * ```typescript\n * // Remove a file\n * await fs.rm('/path/to/file.txt');\n * \n * // Remove a directory and all its contents\n * await fs.rm('/path/to/directory', { recursive: true });\n * \n * // Remove with force (ignore if doesn't exist)\n * await fs.rm('/maybe/exists', { force: true });\n * ```\n */\n async remove(path: string, options?: { recursive?: boolean; force?: boolean }): Promise<void> {\n await this.ensureMounted();\n \n const recursive = options?.recursive ?? false;\n const force = options?.force ?? false;\n\n // Special handling for root directory\n if (path === '/') {\n throw new OPFSError('Cannot remove root directory', 'EROOT');\n }\n\n const name = basename(path);\n\n if (!name) {\n throw new PathError('Invalid path', path);\n }\n\n const parent = await this.getDirectoryHandle(dirname(path), false);\n\n try {\n await parent.removeEntry(name, { recursive });\n }\n catch (e: any) {\n if (e.name === 'NotFoundError') {\n if (!force) {\n throw new OPFSError(`No such file or directory: ${ path }`, 'ENOENT');\n }\n }\n else if (e.name === 'InvalidModificationError') {\n throw new OPFSError(`Directory not empty: ${ path }. Use recursive option to force removal.`, 'ENOTEMPTY');\n }\n else if (e.name === 'TypeMismatchError' && !recursive) {\n throw new OPFSError(`Cannot remove directory without recursive option: ${ path }`, 'EISDIR');\n }\n else {\n throw new OPFSError(`Failed to remove path: ${ path }`, 'RM_FAILED');\n }\n }\n }\n\n /**\n * Resolve a path to an absolute path\n * \n * Resolves relative paths and normalizes path segments (like '..' and '.').\n * Similar to Node.js fs.realpath() but without symlink resolution since OPFS doesn't support symlinks.\n * \n * @param path - The path to resolve\n * @returns Promise that resolves to the absolute normalized path\n * @throws {FileNotFoundError} If the path does not exist\n * @throws {OPFSError} If path resolution fails\n * \n * @example\n * ```typescript\n * // Resolve relative path\n * const absolute = await fs.realpath('./config/../data/file.txt');\n * console.log(absolute); // '/data/file.txt'\n * ```\n */\n async realpath(path: string): Promise<string> {\n await this.ensureMounted();\n \n try {\n const normalizedPath = resolvePath(path);\n const exists = await this.exists(normalizedPath);\n\n if (!exists) {\n throw new FileNotFoundError(normalizedPath);\n }\n\n return normalizedPath;\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to resolve path: ${ path }`, 'REALPATH_FAILED');\n }\n }\n\n /**\n * Rename a file or directory\n * \n * Changes the name of a file or directory. If the target path already exists,\n * it will be replaced.\n * \n * @param oldPath - The current path of the file or directory\n * @param newPath - The new path for the file or directory\n * @returns Promise that resolves when the rename operation is complete\n * @throws {OPFSError} If the rename operation fails\n * \n * @example\n * ```typescript\n * await fs.rename('/old/path/file.txt', '/new/path/renamed.txt');\n * ```\n */\n async rename(oldPath: string, newPath: string): Promise<void> {\n await this.ensureMounted();\n \n try {\n const sourceExists = await this.exists(oldPath);\n\n if (!sourceExists) {\n throw new FileNotFoundError(oldPath);\n }\n\n await this.copy(oldPath, newPath, { recursive: true });\n await this.remove(oldPath, { recursive: true });\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to rename from ${ oldPath } to ${ newPath }`, 'RENAME_FAILED');\n }\n }\n\n /**\n * Copy files and directories\n * \n * Copies files and directories. Similar to Node.js fs.cp().\n * \n * @param source - The source path to copy from\n * @param destination - The destination path to copy to\n * @param options - Options for copying\n * @param options.recursive - Whether to copy directories recursively (default: false)\n * @param options.force - Whether to overwrite existing files (default: true)\n * @returns Promise that resolves when the copy operation is complete\n * @throws {OPFSError} If the copy operation fails\n * \n * @example\n * ```typescript\n * // Copy a file\n * await fs.copy('/source/file.txt', '/dest/file.txt');\n * \n * // Copy a directory and all its contents\n * await fs.copy('/source/dir', '/dest/dir', { recursive: true });\n * \n * // Copy without overwriting existing files\n * await fs.copy('/source', '/dest', { recursive: true, force: false });\n * ```\n */\n async copy(source: string, destination: string, options?: { recursive?: boolean; force?: boolean }): Promise<void> {\n await this.ensureMounted();\n \n try {\n const recursive = options?.recursive ?? false;\n const force = options?.force ?? true;\n\n const sourceExists = await this.exists(source);\n\n if (!sourceExists) {\n throw new OPFSError(`Source does not exist: ${ source }`, 'ENOENT');\n }\n\n const destExists = await this.exists(destination);\n\n if (destExists && !force) {\n throw new OPFSError(`Destination already exists: ${ destination }`, 'EEXIST');\n }\n\n const sourceStats = await this.stat(source);\n\n if (sourceStats.isFile) {\n const content = await this.readFile(source, 'binary');\n \n await this.writeFile(destination, content);\n }\n else {\n if (!recursive) {\n throw new OPFSError(`Cannot copy directory without recursive option: ${ source }`, 'EISDIR');\n }\n\n await this.mkdir(destination, { recursive: true });\n\n const items = await this.readdir(source, { withFileTypes: true });\n\n for (const item of items) {\n const sourceItemPath = `${ source }/${ item.name }`;\n const destItemPath = `${ destination }/${ item.name }`;\n\n await this.copy(sourceItemPath, destItemPath, { recursive: true, force });\n }\n }\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to copy from ${ source } to ${ destination }`, 'CP_FAILED');\n }\n }\n\n /**\n * Start watching a file or directory for changes\n */\n async watch(path: string): Promise<void> {\n await this.ensureMounted();\n \n const normalizedPath = normalizePath(path);\n const snapshot = await this.buildSnapshot(normalizedPath);\n this.watchers.set(normalizedPath, snapshot);\n\n if (!this.watchTimer) {\n this.watchTimer = setInterval(() => {\n void this.scanWatches();\n }, this.watchInterval);\n }\n }\n\n /**\n * Stop watching a previously watched path\n */\n unwatch(path: string): void {\n const normalizedPath = normalizePath(path);\n this.watchers.delete(normalizedPath);\n\n if (this.watchers.size === 0 && this.watchTimer) {\n clearInterval(this.watchTimer);\n this.watchTimer = null;\n }\n }\n\n private async buildSnapshot(rootPath: string): Promise<Map<string, FileStat>> {\n const result = new Map<string, FileStat>();\n\n const walk = async (current: string) => {\n const stat = await this.stat(current);\n result.set(current, stat);\n\n if (stat.isDirectory) {\n const entries = await this.readdir(current, { withFileTypes: true });\n for (const entry of entries) {\n const child = `${ current === '/' ? '' : current }/${ entry.name }`;\n await walk(child);\n }\n }\n };\n\n await walk(rootPath);\n return result;\n }\n\n private async scanWatches(): Promise<void> {\n if (this.scanning) {\n return;\n }\n\n this.scanning = true;\n\n try {\n await Promise.all(\n [...this.watchers.entries()].map(async ([rootPath, prev]) => {\n let next: Map<string, FileStat>;\n\n try {\n next = await this.buildSnapshot(rootPath);\n }\n catch {\n next = new Map();\n }\n\n const events: WatchEvent[] = [];\n\n for (const [p, stat] of next) {\n const old = prev.get(p);\n if (!old) {\n events.push({ path: p, type: 'create' });\n }\n else if (old.mtime !== stat.mtime || old.size !== stat.size) {\n events.push({ path: p, type: 'change' });\n }\n }\n\n for (const p of prev.keys()) {\n if (!next.has(p)) {\n events.push({ path: p, type: 'delete' });\n }\n }\n\n if (events.length && this.watchCallback) {\n for (const event of events) {\n this.watchCallback(event);\n }\n }\n\n this.watchers.set(rootPath, next);\n })\n );\n }\n finally {\n this.scanning = false;\n }\n }\n\n /**\n * Synchronize the file system with external data\n * \n * Syncs the file system with an array of entries containing paths and data.\n * This is useful for importing data from external sources or syncing with remote data.\n * \n * @param entries - Array of [path, data] tuples to sync\n * @param options - Options for synchronization\n * @param options.cleanBefore - Whether to clear the file system before syncing (default: false)\n * @returns Promise that resolves when synchronization is complete\n * @throws {OPFSError} If the synchronization fails\n * \n * @example\n * ```typescript\n * // Sync with external data\n * const entries: [string, string | Uint8Array | Blob][] = [\n * ['/config.json', JSON.stringify({ theme: 'dark' })],\n * ['/data/binary.dat', new Uint8Array([1, 2, 3, 4])],\n * ['/upload.txt', new Blob(['file content'], { type: 'text/plain' })]\n * ];\n * \n * // Sync without clearing existing files\n * await fs.sync(entries);\n * \n * // Clean file system and then sync\n * await fs.sync(entries, { cleanBefore: true });\n * ```\n */\n async sync(entries: [string, string | Uint8Array | Blob][], options?: { cleanBefore?: boolean }): Promise<void> {\n await this.ensureMounted();\n \n try {\n const cleanBefore = options?.cleanBefore ?? false;\n\n if (cleanBefore) {\n await this.clear('/');\n }\n\n for (const [path, data] of entries) {\n const normalizedPath = normalizePath(path);\n\n let fileData: string | Uint8Array;\n\n if (data instanceof Blob) {\n fileData = await convertBlobToUint8Array(data);\n }\n else {\n fileData = data;\n }\n\n await this.writeFile(normalizedPath, fileData);\n }\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError('Failed to sync file system', 'SYNC_FAILED');\n }\n }\n}\n\n// Only expose the worker when running in a Web Worker environment\nif (typeof self !== 'undefined' && self.constructor.name === 'DedicatedWorkerGlobalScope') {\n expose(new OPFSWorker());\n}\n"],"names":["OPFSWorker","watchCallback","watchOptions","checkOPFSSupport","root","resolve","reject","rootDir","error","OPFSError","callback","options","path","create","from","OPFSNotMountedError","segments","splitPath","current","segment","PathError","fileName","result","walk","dirPath","items","item","fullPath","stat","err","encoding","fileHandle","buffer","readFileData","decodeBuffer","FileNotFoundError","data","writeFileData","recursive","i","e","joinPath","name","basename","parentDir","dirname","includeHash","hashAlgorithm","file","baseStat","hash","calculateFileHash","withTypes","dir","results","handle","isFile","itemPath","force","parent","normalizedPath","resolvePath","oldPath","newPath","source","destination","content","sourceItemPath","destItemPath","normalizePath","snapshot","rootPath","entries","entry","child","prev","next","events","p","old","event","fileData","convertBlobToUint8Array","expose"],"mappings":";;AA0CO,MAAMA,EAAW;AAAA;AAAA,EAEZ,OAAyC;AAAA;AAAA,EAGzC,gBAAsD;AAAA;AAAA,EAGtD,+BAAe,IAAA;AAAA;AAAA,EAGf,aAAoD;AAAA;AAAA,EAGpD,gBAAgB;AAAA;AAAA,EAGhB,WAAW;AAAA;AAAA,EAGX,kBAA2C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASnD,YACIC,GACAC,GACF;AACE,IAAAC,EAAA,GAEIF,MACA,KAAK,gBAAgBA,GACjBC,GA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AA,MACpB;AAAA;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA8BA,MAAM,KAAKJ,GAAiD7D,GAAoD;AAC5G,UAAM,KAAK,cAAA;AAEX,QAAI;AAGA,OAFoBA,GAAS,eAAe,OAGxC,MAAM,KAAK,MAAM,GAAG;AAGxB,iBAAW,CAACC,GAAMwB,CAAI,KAAKoC,GAAS;AAChC,cAAMZ,IAAiBS,EAAczD,CAAI;AAEzC,YAAIqE;AAEJ,QAAI7C,aAAgB,OAChB6C,IAAW,MAAMC,EAAwB9C,CAAI,IAG7C6C,IAAW7C,GAGf,MAAM,KAAK,UAAUwB,GAAgBqB,CAAQ;AAAA,MACjD;AAAA,IACJ,SACOzE,GAAO;AACV,YAAIA,aAAiBC,IACXD,IAGJ,IAAIC,EAAU,8BAA8B,aAAa;AAAA,IACnE;AAAA,EACJ;AACJ;AAGI,OAAO,OAAS,OAAe,KAAK,YAAY,SAAS,gCAC3D0E,EAAO,IAAInF,GAAY;"}
1
+ {"version":3,"file":"raw.js","sources":["../src/worker.ts"],"sourcesContent":["import { expose } from 'comlink';\n\nimport { decodeBuffer } from './utils/encoder';\nimport {\n FileNotFoundError,\n OPFSError,\n OPFSNotMountedError,\n PathError\n} from './utils/errors';\n\nimport { \n calculateFileHash, \n checkOPFSSupport, \n joinPath, \n readFileData, \n splitPath, \n writeFileData,\n basename,\n dirname,\n normalizePath,\n resolvePath,\n convertBlobToUint8Array\n} from './utils/helpers';\n\nimport type { DirentData, FileStat, WatchEvent } from './types';\nimport type { BufferEncoding } from 'typescript';\n\n/**\n * OPFS (Origin Private File System) File System implementation\n * \n * This class provides a high-level interface for working with the browser's\n * Origin Private File System API, offering file and directory operations\n * similar to Node.js fs module.\n * \n * @example\n * ```typescript\n * const fs = new OPFSFileSystem();\n * await fs.init('/my-app');\n * await fs.writeFile('/data/config.json', JSON.stringify({ theme: 'dark' }));\n * const config = await fs.readFile('/data/config.json');\n * ```\n */\nexport class OPFSWorker {\n /** Root directory handle for the file system */\n private root: FileSystemDirectoryHandle | null = null;\n\n /** Watch event callback */\n private watchCallback: ((event: WatchEvent) => void) | null = null;\n\n /** Map of watched paths to their last known state */\n private watchers = new Map<string, Map<string, FileStat>>();\n\n /** Interval handle for polling watched paths */\n private watchTimer: ReturnType<typeof setInterval> | null = null;\n\n /** Polling interval in milliseconds */\n private watchInterval = 1000;\n\n /** Flag to avoid concurrent scans */\n private scanning = false;\n\n /** Promise to prevent concurrent mount operations */\n private mountingPromise: Promise<boolean> | null = null;\n\n /**\n * Notify about internal changes to the file system\n * \n * This method is called by internal operations to notify clients about\n * changes, even when no specific paths are being watched.\n * \n * @param path - The path that was changed\n * @param type - The type of change (create, change, delete)\n */\n private notifyInternalChange(path: string, type: 'create' | 'change' | 'delete'): void {\n if (!this.watchCallback) {\n return;\n }\n\n // Notify about the change immediately\n this.watchCallback({\n path,\n type\n });\n }\n\n /**\n * Creates a new OPFSFileSystem instance\n * \n * @param watchCallback - Optional callback for file change events\n * @param watchOptions - Optional configuration for watching\n * @throws {OPFSError} If OPFS is not supported in the current browser\n */\n constructor(\n watchCallback?: (event: WatchEvent) => void,\n watchOptions?: { watchInterval?: number }\n ) {\n checkOPFSSupport();\n \n if (watchCallback) {\n this.watchCallback = watchCallback;\n if (watchOptions?.watchInterval) {\n this.watchInterval = watchOptions.watchInterval;\n }\n }\n \n void this.mount('/');\n }\n\n /**\n * Initialize the file system within a given directory\n * \n * This method sets up the root directory for all subsequent operations.\n * If no root is specified, it will use the OPFS root directory.\n * \n * @param root - The root path for the file system (default: '/')\n * @returns Promise that resolves to true if initialization was successful\n * @throws {OPFSError} If initialization fails\n * \n * @example\n * ```typescript\n * const fs = new OPFSFileSystem();\n * \n * // Use OPFS root (default)\n * await fs.mount();\n * \n * // Use custom directory\n * await fs.mount('/my-app');\n * ```\n */\n async mount(root: string = '/'): Promise<boolean> {\n // If already mounting, wait for previous operation to complete first\n if (this.mountingPromise) {\n await this.mountingPromise;\n }\n\n this.mountingPromise = new Promise<boolean>(async(resolve, reject) => {\n this.root = null;\n \n try {\n const rootDir = await navigator.storage.getDirectory();\n \n if (root === '/') {\n this.root = rootDir;\n } \n else {\n this.root = await this.getDirectoryHandle(root, true, rootDir);\n }\n resolve(true);\n }\n catch (error) {\n console.error(error);\n reject(new OPFSError('Failed to initialize OPFS', 'INIT_FAILED'));\n }\n finally {\n this.mountingPromise = null;\n }\n });\n\n return this.mountingPromise;\n }\n\n /**\n * Set the watch callback for file change events\n * \n * @param callback - The callback function to invoke when files change\n * @param options - Optional configuration for watching\n */\n setWatchCallback(callback: (event: WatchEvent) => void, options?: { watchInterval?: number }): void {\n this.watchCallback = callback;\n\n if (options?.watchInterval) {\n this.watchInterval = options.watchInterval;\n }\n }\n\n /**\n * Automatically mount the OPFS root if not already mounted\n * \n * This method is called internally when file operations are performed\n * without explicitly mounting first.\n * \n * @returns Promise that resolves when auto-mount is complete\n * @throws {OPFSError} If auto-mount fails\n */\n private async ensureMounted(): Promise<void> {\n // If already mounted, return immediately\n if (this.root) {\n return;\n }\n\n // If already mounting, wait for that operation to complete\n if (this.mountingPromise) {\n await this.mountingPromise;\n return;\n }\n\n throw new OPFSError('OPFS not mounted', 'NOT_MOUNTED');\n }\n\n /**\n * Get a directory handle from a path\n * \n * Navigates through the directory structure to find or create a directory\n * at the specified path.\n * \n * @param path - The path to the directory (string or array of segments)\n * @param create - Whether to create the directory if it doesn't exist (default: false)\n * @param from - The directory to start from (default: root directory)\n * @returns Promise that resolves to the directory handle\n * @throws {OPFSError} If the directory cannot be accessed or created\n * \n * @example\n * ```typescript\n * const docsDir = await fs.getDirectoryHandle('/users/john/documents', true);\n * const docsDir2 = await fs.getDirectoryHandle(['users', 'john', 'documents'], true);\n * ```\n */\n private async getDirectoryHandle(path: string | string[], create: boolean = false, from: FileSystemDirectoryHandle | null = this.root): Promise<FileSystemDirectoryHandle> {\n if (!from) {\n throw new OPFSNotMountedError();\n }\n\n const segments = Array.isArray(path) ? path : splitPath(path);\n let current = from;\n\n for (const segment of segments) {\n current = await current.getDirectoryHandle(segment, { create });\n }\n\n return current;\n }\n\n /**\n * Get a file handle from a path\n * \n * Navigates to the parent directory and retrieves or creates a file handle\n * for the specified file path.\n * \n * @param path - The path to the file (string or array of segments)\n * @param create - Whether to create the file if it doesn't exist (default: false)\n * @param from - The directory to start from (default: root directory)\n * @returns Promise that resolves to the file handle\n * @throws {PathError} If the path is empty\n * @throws {OPFSError} If the file cannot be accessed or created\n * \n * @example\n * ```typescript\n * const fileHandle = await fs.getFileHandle('/config/settings.json', true);\n * const fileHandle2 = await fs.getFileHandle(['config', 'settings.json'], true);\n * ```\n */\n private async getFileHandle(path: string | string[], create = false, from: FileSystemDirectoryHandle | null = this.root): Promise<FileSystemFileHandle> {\n if (!from) {\n throw new OPFSNotMountedError();\n }\n\n const segments = splitPath(path);\n\n if (segments.length === 0) {\n throw new PathError('Path must not be empty', Array.isArray(path) ? path.join('/') : path);\n }\n\n const fileName = segments.pop()!;\n const dir = await this.getDirectoryHandle(segments, create, from);\n\n return dir.getFileHandle(fileName, { create });\n }\n\n\n /**\n * Recursively list all files and directories with their stats\n * \n * Traverses the entire file system starting from the root and returns\n * a Map containing all paths and their corresponding file statistics.\n * \n * @param options - Options for indexing\n * @param options.includeHash - Whether to calculate file hash (default: false)\n * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)\n * @returns Promise that resolves to a Map of path => FileStat\n * @throws {OPFSError} If the indexing operation fails\n * \n * @example\n * ```typescript\n * // Basic index without hash\n * const index = await fs.index();\n * \n * // Index with file hash\n * const indexWithHash = await fs.index({ \n * includeHash: true,\n * hashAlgorithm: 'SHA-1'\n * });\n * \n * // Iterate through all files and directories\n * for (const [path, stat] of index) {\n * console.log(`${path}: ${stat.isFile ? 'file' : 'directory'} (${stat.size} bytes)`);\n * if (stat.hash) console.log(` Hash: ${stat.hash}`);\n * }\n * \n * // Get specific file stats\n * const fileStats = index.get('/data/config.json');\n * if (fileStats) {\n * console.log(`File size: ${fileStats.size} bytes`);\n * if (fileStats.hash) console.log(`Hash: ${fileStats.hash}`);\n * }\n * ```\n */\n async index(options?: { includeHash?: boolean; hashAlgorithm?: 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512' }): Promise<Map<string, FileStat>> {\n const result = new Map<string, FileStat>();\n\n const walk = async(dirPath: string) => {\n const items = await this.readdir(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = `${ dirPath === '/' ? '' : dirPath }/${ item.name }`;\n\n try {\n const stat = await this.stat(fullPath, options);\n\n result.set(fullPath, stat);\n\n if (stat.isDirectory) {\n await walk(fullPath);\n }\n }\n catch (err) {\n console.warn(`Skipping broken entry: ${ fullPath }`, err);\n }\n }\n };\n\n result.set('/', {\n kind: 'directory',\n size: 0,\n mtime: new Date(0).toISOString(),\n ctime: new Date(0).toISOString(),\n isFile: false,\n isDirectory: true,\n });\n\n await walk('/');\n\n return result;\n }\n\n /**\n * Read a file from the file system\n * \n * Reads the contents of a file and returns it as a string or binary data\n * depending on the specified encoding.\n * \n * @param path - The path to the file to read\n * @param encoding - The encoding to use for reading the file\n * @returns Promise that resolves to the file contents\n * @throws {FileNotFoundError} If the file does not exist\n * @throws {OPFSError} If reading the file fails\n * \n * @example\n * ```typescript\n * // Read as text\n * const content = await fs.readFile('/config/settings.json');\n * \n * // Read as binary\n * const binaryData = await fs.readFile('/images/logo.png', 'binary');\n * \n * // Read with specific encoding\n * const utf8Content = await fs.readFile('/data/utf8.txt', 'utf-8');\n * ```\n */\n async readFile(path: string, encoding: 'binary'): Promise<Uint8Array>;\n async readFile(path: string, encoding?: BufferEncoding): Promise<string>;\n async readFile(\n path: string,\n encoding: BufferEncoding | 'binary' = 'utf-8'\n ): Promise<string | Uint8Array> {\n await this.ensureMounted();\n \n try {\n const fileHandle = await this.getFileHandle(path, false);\n const buffer = await readFileData(fileHandle);\n\n if (encoding === 'binary') {\n return buffer;\n }\n\n return decodeBuffer(buffer, encoding);\n }\n catch (err) {\n console.error(err);\n\n throw new FileNotFoundError(path);\n }\n }\n\n /**\n * Write data to a file\n * \n * Creates or overwrites a file with the specified data. If the file already\n * exists, it will be truncated before writing.\n * \n * @param path - The path to the file to write\n * @param data - The data to write to the file (string, Uint8Array, or ArrayBuffer)\n * @param encoding - The encoding to use when writing string data (default: 'utf-8')\n * @returns Promise that resolves when the write operation is complete\n * @throws {OPFSError} If writing the file fails\n * \n * @example\n * ```typescript\n * // Write text data\n * await fs.writeFile('/config/settings.json', JSON.stringify({ theme: 'dark' }));\n * \n * // Write binary data\n * const binaryData = new Uint8Array([1, 2, 3, 4, 5]);\n * await fs.writeFile('/data/binary.dat', binaryData);\n * \n * // Write with specific encoding\n * await fs.writeFile('/data/utf16.txt', 'Hello World', 'utf-16le');\n * ```\n */\n async writeFile(\n path: string,\n data: string | Uint8Array | ArrayBuffer,\n encoding?: BufferEncoding\n ): Promise<void> {\n await this.ensureMounted();\n \n const fileHandle = await this.getFileHandle(path, true);\n\n await writeFileData(fileHandle, data, encoding, { truncate: true });\n this.notifyInternalChange(path, 'change');\n }\n\n /**\n * Append data to a file\n * \n * Adds data to the end of an existing file. If the file doesn't exist,\n * it will be created.\n * \n * @param path - The path to the file to append to\n * @param data - The data to append to the file (string, Uint8Array, or ArrayBuffer)\n * @param encoding - The encoding to use when appending string data (default: 'utf-8')\n * @returns Promise that resolves when the append operation is complete\n * @throws {OPFSError} If appending to the file fails\n * \n * @example\n * ```typescript\n * // Append text to a log file\n * await fs.appendFile('/logs/app.log', `[${new Date().toISOString()}] User logged in\\n`);\n * \n * // Append binary data\n * const additionalData = new Uint8Array([6, 7, 8]);\n * await fs.appendFile('/data/binary.dat', additionalData);\n * ```\n */\n async appendFile(\n path: string,\n data: string | Uint8Array | ArrayBuffer,\n encoding?: BufferEncoding\n ): Promise<void> {\n await this.ensureMounted();\n \n const fileHandle = await this.getFileHandle(path, true);\n\n await writeFileData(fileHandle, data, encoding, { append: true });\n this.notifyInternalChange(path, 'change');\n }\n\n /**\n * Create a directory\n * \n * Creates a new directory at the specified path. If the recursive option\n * is enabled, parent directories will be created as needed.\n * \n * @param path - The path where the directory should be created\n * @param options - Options for directory creation\n * @param options.recursive - Whether to create parent directories if they don't exist (default: false)\n * @returns Promise that resolves when the directory is created\n * @throws {OPFSError} If the directory cannot be created\n * \n * @example\n * ```typescript\n * // Create a single directory\n * await fs.mkdir('/users/john');\n * \n * // Create nested directories\n * await fs.mkdir('/users/john/documents/projects', { recursive: true });\n * ```\n */\n async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n await this.ensureMounted();\n\n if (!this.root) {\n throw new OPFSNotMountedError();\n }\n\n const recursive = options?.recursive ?? false;\n const segments = splitPath(path);\n\n let current = this.root;\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n\n try {\n current = await current.getDirectoryHandle(segment!, { create: recursive || i === segments.length - 1 });\n }\n catch (e: any) {\n if (e.name === 'NotFoundError') {\n throw new OPFSError(\n `Parent directory does not exist: ${ joinPath(segments.slice(0, i + 1)) }`,\n 'ENOENT'\n );\n }\n\n if (e.name === 'TypeMismatchError') {\n throw new OPFSError(`Path segment is not a directory: ${ segment }`, 'ENOTDIR');\n }\n\n throw new OPFSError('Failed to create directory', 'MKDIR_FAILED');\n }\n }\n this.notifyInternalChange(path, 'create');\n }\n\n /**\n * Get file or directory stats\n * \n * Retrieves metadata about a file or directory, including size, modification time,\n * type information, and optionally file hashes.\n * \n * @param path - The path to the file or directory\n * @param options - Options for stat operation\n * @param options.includeHash - Whether to calculate file hash (default: false, only for files)\n * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)\n * @returns Promise that resolves to file/directory statistics\n * @throws {OPFSError} If the file or directory does not exist or cannot be accessed\n * \n * @example\n * ```typescript\n * // Basic stats\n * const stats = await fs.stat('/config/settings.json');\n * console.log(`File size: ${stats.size} bytes`);\n * console.log(`Is file: ${stats.isFile}`);\n * console.log(`Modified: ${stats.mtime}`);\n * \n * // Stats with hash (SHA-1 is fastest)\n * const statsWithHash = await fs.stat('/config/settings.json', { \n * includeHash: true,\n * hashAlgorithm: 'SHA-1'\n * });\n * console.log(`Hash: ${statsWithHash.hash}`);\n * ```\n */\n async stat(path: string, options?: { includeHash?: boolean; hashAlgorithm?: 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512' }): Promise<FileStat> {\n await this.ensureMounted();\n \n // Special handling for root directory\n if (path === '/') {\n return {\n kind: 'directory',\n size: 0,\n mtime: new Date(0).toISOString(),\n ctime: new Date(0).toISOString(),\n isFile: false,\n isDirectory: true,\n };\n }\n \n const name = basename(path);\n const parentDir = await this.getDirectoryHandle(dirname(path), false);\n const includeHash = options?.includeHash ?? false;\n const hashAlgorithm = options?.hashAlgorithm ?? 'SHA-1';\n\n try {\n const fileHandle = await parentDir.getFileHandle(name!, { create: false });\n const file = await fileHandle.getFile();\n\n const baseStat: FileStat = {\n kind: 'file',\n size: file.size,\n mtime: new Date(file.lastModified).toISOString(),\n ctime: new Date(file.lastModified).toISOString(),\n isFile: true,\n isDirectory: false,\n };\n\n if (includeHash) {\n try {\n const buffer = new Uint8Array(await file.arrayBuffer());\n const hash = await calculateFileHash(buffer, hashAlgorithm);\n\n baseStat.hash = hash;\n }\n catch (error) {\n console.warn(`Failed to calculate hash for ${ path }:`, error);\n }\n }\n\n return baseStat;\n }\n catch (e: any) {\n if (e.name !== 'TypeMismatchError' && e.name !== 'NotFoundError') {\n throw new OPFSError('Failed to stat (file)', 'STAT_FAILED');\n }\n }\n\n try {\n await parentDir.getDirectoryHandle(name!, { create: false });\n\n return {\n kind: 'directory',\n size: 0,\n mtime: new Date(0).toISOString(),\n ctime: new Date(0).toISOString(),\n isFile: false,\n isDirectory: true,\n };\n }\n catch (e: any) {\n if (e.name === 'NotFoundError') {\n throw new OPFSError(`No such file or directory: ${ path }`, 'ENOENT');\n }\n\n throw new OPFSError('Failed to stat (directory)', 'STAT_FAILED');\n }\n }\n\n /**\n * Read a directory's contents\n * \n * Lists all files and subdirectories within the specified directory.\n * \n * @param path - The path to the directory to read\n * @param options - Options for the readdir operation\n * @param options.withFileTypes - Whether to return detailed file information (default: false)\n * @returns Promise that resolves to an array of file/directory names or detailed information\n * @throws {OPFSError} If the directory does not exist or cannot be accessed\n * \n * @example\n * ```typescript\n * // Get simple list of names\n * const files = await fs.readdir('/users/john/documents');\n * console.log('Files:', files); // ['readme.txt', 'config.json', 'images']\n * \n * // Get detailed information\n * const detailed = await fs.readdir('/users/john/documents', { withFileTypes: true });\n * detailed.forEach(item => {\n * console.log(`${item.name} - ${item.isFile ? 'file' : 'directory'}`);\n * });\n * ```\n */\n async readdir(path: string): Promise<string[]>;\n async readdir(path: string, options: { withFileTypes: true }): Promise<DirentData[]>;\n async readdir(path: string, options: { withFileTypes: false }): Promise<string[]>;\n async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirentData[]> {\n await this.ensureMounted();\n \n const withTypes = options?.withFileTypes ?? false;\n const dir = await this.getDirectoryHandle(path, false);\n\n if (withTypes) {\n const results: DirentData[] = [];\n\n for await (const [name, handle] of (dir as any).entries()) {\n const isFile = handle.kind === 'file';\n\n results.push({\n name,\n kind: handle.kind,\n isFile,\n isDirectory: !isFile,\n });\n }\n\n return results;\n }\n else {\n const results: string[] = [];\n\n for await (const [name] of (dir as any).entries()) {\n results.push(name);\n }\n\n return results;\n }\n }\n\n /**\n * Check if a file or directory exists\n * \n * Verifies if a file or directory exists at the specified path.\n * \n * @param path - The path to check\n * @returns Promise that resolves to true if the file or directory exists, false otherwise \n * \n * @example\n * ```typescript\n * const exists = await fs.exists('/config/settings.json');\n * console.log(`File exists: ${exists}`);\n * ```\n */\n async exists(path: string): Promise<boolean> {\n await this.ensureMounted();\n \n if (path === '/') {\n return true;\n }\n \n const name = basename(path);\n let dir: FileSystemDirectoryHandle | null = null;\n\n try {\n dir = await this.getDirectoryHandle(dirname(path), false);\n }\n catch (e: any) {\n if (e.name === 'NotFoundError' || e.name === 'TypeMismatchError') {\n dir = null;\n }\n\n throw e;\n }\n\n if (!dir || !name) {\n return false;\n }\n\n try {\n await dir.getFileHandle(name, { create: false });\n\n return true;\n }\n catch (e: any) {\n if (e.name !== 'NotFoundError' && e.name !== 'TypeMismatchError') {\n throw e;\n }\n }\n\n try {\n await dir.getDirectoryHandle(name, { create: false });\n\n return true;\n }\n catch (e: any) {\n if (e.name !== 'NotFoundError' && e.name !== 'TypeMismatchError') {\n throw e;\n }\n }\n\n return false;\n }\n\n /**\n * Clear all contents of a directory without removing the directory itself\n * \n * Removes all files and subdirectories within the specified directory,\n * but keeps the directory itself.\n * \n * @param path - The path to the directory to clear (default: '/')\n * @returns Promise that resolves when all contents are removed\n * @throws {OPFSError} If the operation fails\n * \n * @example\n * ```typescript\n * // Clear root directory contents\n * await fs.clear('/');\n * \n * // Clear specific directory contents\n * await fs.clear('/data');\n * ```\n */\n async clear(path: string = '/'): Promise<void> {\n await this.ensureMounted();\n \n try {\n const items = await this.readdir(path, { withFileTypes: true });\n\n for (const item of items) {\n const itemPath = `${ path === '/' ? '' : path }/${ item.name }`;\n\n await this.remove(itemPath, { recursive: true });\n }\n \n // Notify about the clear operation\n this.notifyInternalChange(path, 'change');\n }\n catch (error: any) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to clear directory: ${ path }`, 'CLEAR_FAILED');\n }\n }\n\n /**\n * Remove files and directories\n * \n * Removes files and directories. Similar to Node.js fs.rm().\n * \n * @param path - The path to remove\n * @param options - Options for removal\n * @param options.recursive - Whether to remove directories and their contents recursively (default: false)\n * @param options.force - Whether to ignore errors if the path doesn't exist (default: false)\n * @returns Promise that resolves when the removal is complete\n * @throws {OPFSError} If the removal fails\n * \n * @example\n * ```typescript\n * // Remove a file\n * await fs.rm('/path/to/file.txt');\n * \n * // Remove a directory and all its contents\n * await fs.rm('/path/to/directory', { recursive: true });\n * \n * // Remove with force (ignore if doesn't exist)\n * await fs.rm('/maybe/exists', { force: true });\n * ```\n */\n async remove(path: string, options?: { recursive?: boolean; force?: boolean }): Promise<void> {\n await this.ensureMounted();\n \n const recursive = options?.recursive ?? false;\n const force = options?.force ?? false;\n\n // Special handling for root directory\n if (path === '/') {\n throw new OPFSError('Cannot remove root directory', 'EROOT');\n }\n\n const name = basename(path);\n\n if (!name) {\n throw new PathError('Invalid path', path);\n }\n\n const parent = await this.getDirectoryHandle(dirname(path), false);\n\n try {\n await parent.removeEntry(name, { recursive });\n }\n catch (e: any) {\n if (e.name === 'NotFoundError') {\n if (!force) {\n throw new OPFSError(`No such file or directory: ${ path }`, 'ENOENT');\n }\n }\n else if (e.name === 'InvalidModificationError') {\n throw new OPFSError(`Directory not empty: ${ path }. Use recursive option to force removal.`, 'ENOTEMPTY');\n }\n else if (e.name === 'TypeMismatchError' && !recursive) {\n throw new OPFSError(`Cannot remove directory without recursive option: ${ path }`, 'EISDIR');\n }\n else {\n throw new OPFSError(`Failed to remove path: ${ path }`, 'RM_FAILED');\n }\n }\n this.notifyInternalChange(path, 'delete');\n }\n\n /**\n * Resolve a path to an absolute path\n * \n * Resolves relative paths and normalizes path segments (like '..' and '.').\n * Similar to Node.js fs.realpath() but without symlink resolution since OPFS doesn't support symlinks.\n * \n * @param path - The path to resolve\n * @returns Promise that resolves to the absolute normalized path\n * @throws {FileNotFoundError} If the path does not exist\n * @throws {OPFSError} If path resolution fails\n * \n * @example\n * ```typescript\n * // Resolve relative path\n * const absolute = await fs.realpath('./config/../data/file.txt');\n * console.log(absolute); // '/data/file.txt'\n * ```\n */\n async realpath(path: string): Promise<string> {\n await this.ensureMounted();\n \n try {\n const normalizedPath = resolvePath(path);\n const exists = await this.exists(normalizedPath);\n\n if (!exists) {\n throw new FileNotFoundError(normalizedPath);\n }\n\n return normalizedPath;\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to resolve path: ${ path }`, 'REALPATH_FAILED');\n }\n }\n\n /**\n * Rename a file or directory\n * \n * Changes the name of a file or directory. If the target path already exists,\n * it will be replaced.\n * \n * @param oldPath - The current path of the file or directory\n * @param newPath - The new path for the file or directory\n * @returns Promise that resolves when the rename operation is complete\n * @throws {OPFSError} If the rename operation fails\n * \n * @example\n * ```typescript\n * await fs.rename('/old/path/file.txt', '/new/path/renamed.txt');\n * ```\n */\n async rename(oldPath: string, newPath: string): Promise<void> {\n await this.ensureMounted();\n \n try {\n const sourceExists = await this.exists(oldPath);\n\n if (!sourceExists) {\n throw new FileNotFoundError(oldPath);\n }\n\n await this.copy(oldPath, newPath, { recursive: true });\n await this.remove(oldPath, { recursive: true });\n \n // Notify about the rename operation\n this.notifyInternalChange(oldPath, 'delete');\n this.notifyInternalChange(newPath, 'create');\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to rename from ${ oldPath } to ${ newPath }`, 'RENAME_FAILED');\n }\n }\n\n /**\n * Copy files and directories\n * \n * Copies files and directories. Similar to Node.js fs.cp().\n * \n * @param source - The source path to copy from\n * @param destination - The destination path to copy to\n * @param options - Options for copying\n * @param options.recursive - Whether to copy directories recursively (default: false)\n * @param options.force - Whether to overwrite existing files (default: true)\n * @returns Promise that resolves when the copy operation is complete\n * @throws {OPFSError} If the copy operation fails\n * \n * @example\n * ```typescript\n * // Copy a file\n * await fs.copy('/source/file.txt', '/dest/file.txt');\n * \n * // Copy a directory and all its contents\n * await fs.copy('/source/dir', '/dest/dir', { recursive: true });\n * \n * // Copy without overwriting existing files\n * await fs.copy('/source', '/dest', { recursive: true, force: false });\n * ```\n */\n async copy(source: string, destination: string, options?: { recursive?: boolean; force?: boolean }): Promise<void> {\n await this.ensureMounted();\n \n try {\n const recursive = options?.recursive ?? false;\n const force = options?.force ?? true;\n\n const sourceExists = await this.exists(source);\n\n if (!sourceExists) {\n throw new OPFSError(`Source does not exist: ${ source }`, 'ENOENT');\n }\n\n const destExists = await this.exists(destination);\n\n if (destExists && !force) {\n throw new OPFSError(`Destination already exists: ${ destination }`, 'EEXIST');\n }\n\n const sourceStats = await this.stat(source);\n\n if (sourceStats.isFile) {\n const content = await this.readFile(source, 'binary');\n \n await this.writeFile(destination, content);\n }\n else {\n if (!recursive) {\n throw new OPFSError(`Cannot copy directory without recursive option: ${ source }`, 'EISDIR');\n }\n\n await this.mkdir(destination, { recursive: true });\n\n const items = await this.readdir(source, { withFileTypes: true });\n\n for (const item of items) {\n const sourceItemPath = `${ source }/${ item.name }`;\n const destItemPath = `${ destination }/${ item.name }`;\n\n await this.copy(sourceItemPath, destItemPath, { recursive: true, force });\n }\n }\n \n // Notify about the copy operation\n this.notifyInternalChange(destination, 'create');\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to copy from ${ source } to ${ destination }`, 'CP_FAILED');\n }\n }\n\n /**\n * Start watching a file or directory for changes\n */\n async watch(path: string): Promise<void> {\n await this.ensureMounted();\n \n const normalizedPath = normalizePath(path);\n const snapshot = await this.buildSnapshot(normalizedPath);\n this.watchers.set(normalizedPath, snapshot);\n\n if (!this.watchTimer) {\n this.watchTimer = setInterval(() => {\n void this.scanWatches();\n }, this.watchInterval);\n }\n }\n\n /**\n * Stop watching a previously watched path\n */\n unwatch(path: string): void {\n const normalizedPath = normalizePath(path);\n this.watchers.delete(normalizedPath);\n\n if (this.watchers.size === 0 && this.watchTimer) {\n clearInterval(this.watchTimer);\n this.watchTimer = null;\n }\n }\n\n private async buildSnapshot(rootPath: string): Promise<Map<string, FileStat>> {\n const result = new Map<string, FileStat>();\n\n const walk = async (current: string) => {\n const stat = await this.stat(current);\n result.set(current, stat);\n\n if (stat.isDirectory) {\n const entries = await this.readdir(current, { withFileTypes: true });\n for (const entry of entries) {\n const child = `${ current === '/' ? '' : current }/${ entry.name }`;\n await walk(child);\n }\n }\n };\n\n await walk(rootPath);\n return result;\n }\n\n private async scanWatches(): Promise<void> {\n if (this.scanning) {\n return;\n }\n\n this.scanning = true;\n\n try {\n await Promise.all(\n [...this.watchers.entries()].map(async([rootPath, prev]) => {\n let next: Map<string, FileStat>;\n\n try {\n next = await this.buildSnapshot(rootPath);\n }\n catch {\n next = new Map();\n }\n\n const events: WatchEvent[] = [];\n\n for (const [p, stat] of next) {\n const old = prev.get(p);\n if (!old) {\n events.push({ path: p, type: 'create' });\n }\n else if (old.mtime !== stat.mtime || old.size !== stat.size) {\n events.push({ path: p, type: 'change' });\n }\n }\n\n for (const p of prev.keys()) {\n if (!next.has(p)) {\n events.push({ path: p, type: 'delete' });\n }\n }\n\n if (events.length && this.watchCallback) {\n for (const event of events) {\n this.watchCallback(event);\n }\n }\n\n this.watchers.set(rootPath, next);\n })\n );\n }\n finally {\n this.scanning = false;\n }\n }\n\n /**\n * Synchronize the file system with external data\n * \n * Syncs the file system with an array of entries containing paths and data.\n * This is useful for importing data from external sources or syncing with remote data.\n * \n * @param entries - Array of [path, data] tuples to sync\n * @param options - Options for synchronization\n * @param options.cleanBefore - Whether to clear the file system before syncing (default: false)\n * @returns Promise that resolves when synchronization is complete\n * @throws {OPFSError} If the synchronization fails\n * \n * @example\n * ```typescript\n * // Sync with external data\n * const entries: [string, string | Uint8Array | Blob][] = [\n * ['/config.json', JSON.stringify({ theme: 'dark' })],\n * ['/data/binary.dat', new Uint8Array([1, 2, 3, 4])],\n * ['/upload.txt', new Blob(['file content'], { type: 'text/plain' })]\n * ];\n * \n * // Sync without clearing existing files\n * await fs.sync(entries);\n * \n * // Clean file system and then sync\n * await fs.sync(entries, { cleanBefore: true });\n * ```\n */\n async sync(entries: [string, string | Uint8Array | Blob][], options?: { cleanBefore?: boolean }): Promise<void> {\n await this.ensureMounted();\n \n try {\n const cleanBefore = options?.cleanBefore ?? false;\n\n if (cleanBefore) {\n await this.clear('/');\n }\n\n for (const [path, data] of entries) {\n const normalizedPath = normalizePath(path);\n\n let fileData: string | Uint8Array;\n\n if (data instanceof Blob) {\n fileData = await convertBlobToUint8Array(data);\n }\n else {\n fileData = data;\n }\n\n await this.writeFile(normalizedPath, fileData);\n }\n \n // Notify about the sync operation\n this.notifyInternalChange('/', 'change');\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError('Failed to sync file system', 'SYNC_FAILED');\n }\n }\n}\n\n// Only expose the worker when running in a Web Worker environment\nif (typeof self !== 'undefined' && self.constructor.name === 'DedicatedWorkerGlobalScope') {\n expose(new OPFSWorker());\n}\n"],"names":["OPFSWorker","path","type","watchCallback","watchOptions","checkOPFSSupport","root","resolve","reject","rootDir","error","OPFSError","callback","options","create","from","OPFSNotMountedError","segments","splitPath","current","segment","PathError","fileName","result","walk","dirPath","items","item","fullPath","stat","err","encoding","fileHandle","buffer","readFileData","decodeBuffer","FileNotFoundError","data","writeFileData","recursive","i","e","joinPath","name","basename","parentDir","dirname","includeHash","hashAlgorithm","file","baseStat","hash","calculateFileHash","withTypes","dir","results","handle","isFile","itemPath","force","parent","normalizedPath","resolvePath","oldPath","newPath","source","destination","content","sourceItemPath","destItemPath","normalizePath","snapshot","rootPath","entries","entry","child","prev","next","events","p","old","event","fileData","convertBlobToUint8Array","expose"],"mappings":";;AA0CO,MAAMA,EAAW;AAAA;AAAA,EAEZ,OAAyC;AAAA;AAAA,EAGzC,gBAAsD;AAAA;AAAA,EAGtD,+BAAe,IAAA;AAAA;AAAA,EAGf,aAAoD;AAAA;AAAA,EAGpD,gBAAgB;AAAA;AAAA,EAGhB,WAAW;AAAA;AAAA,EAGX,kBAA2C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAW3C,qBAAqBC,GAAcC,GAA4C;AACnF,IAAK,KAAK,iBAKV,KAAK,cAAc;AAAA,MACf,MAAAD;AAAA,MACA,MAAAC;AAAA,IAAA,CACH;AAAA,EACL;AAAA;AAAA;AAAA;AAAA;AAAA;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30,6 +30,16 @@ export declare class OPFSWorker {
30
30
  private scanning;
31
31
  /** Promise to prevent concurrent mount operations */
32
32
  private mountingPromise;
33
+ /**
34
+ * Notify about internal changes to the file system
35
+ *
36
+ * This method is called by internal operations to notify clients about
37
+ * changes, even when no specific paths are being watched.
38
+ *
39
+ * @param path - The path that was changed
40
+ * @param type - The type of change (create, change, delete)
41
+ */
42
+ private notifyInternalChange;
33
43
  /**
34
44
  * Creates a new OPFSFileSystem instance
35
45
  *
@@ -1 +1 @@
1
- {"version":3,"file":"worker.d.ts","sourceRoot":"","sources":["../src/worker.ts"],"names":[],"mappings":"AAwBA,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAChE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD;;;;;;;;;;;;;;GAcG;AACH,qBAAa,UAAU;IACnB,gDAAgD;IAChD,OAAO,CAAC,IAAI,CAA0C;IAEtD,2BAA2B;IAC3B,OAAO,CAAC,aAAa,CAA8C;IAEnE,qDAAqD;IACrD,OAAO,CAAC,QAAQ,CAA4C;IAE5D,gDAAgD;IAChD,OAAO,CAAC,UAAU,CAA+C;IAEjE,uCAAuC;IACvC,OAAO,CAAC,aAAa,CAAQ;IAE7B,qCAAqC;IACrC,OAAO,CAAC,QAAQ,CAAS;IAEzB,qDAAqD;IACrD,OAAO,CAAC,eAAe,CAAiC;IAExD;;;;;;OAMG;gBAEC,aAAa,CAAC,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,EAC3C,YAAY,CAAC,EAAE;QAAE,aAAa,CAAC,EAAE,MAAM,CAAA;KAAE;IAc7C;;;;;;;;;;;;;;;;;;;;OAoBG;IACG,KAAK,CAAC,IAAI,GAAE,MAAY,GAAG,OAAO,CAAC,OAAO,CAAC;IAgCjD;;;;;OAKG;IACH,gBAAgB,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,EA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;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACG,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAyC7F;;;;;;;;;;;;;;;;;OAiBG;IACG,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAsB7C;;;;;;;;;;;;;;;OAeG;IACG,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA0B7D;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACG,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAuDlH;;OAEG;IACG,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAcxC;;OAEG;IACH,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;YAUb,aAAa;YAoBb,WAAW;IAoDzB;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;IACG,IAAI,CAAC,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,GAAG,UAAU,GAAG,IAAI,CAAC,EAAE,EAAE,OAAO,CAAC,EAAE;QAAE,WAAW,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAoClH"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opfs-worker",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "A robust TypeScript library for working with Origin Private File System (OPFS) through Web Workers",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -1 +0,0 @@
1
- {"version":3,"file":"worker-CRHhlrlS.js","sources":["../node_modules/comlink/dist/esm/comlink.mjs","../src/utils/errors.ts","../src/utils/encoder.ts","../src/utils/helpers.ts","../src/worker.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nconst proxyMarker = Symbol(\"Comlink.proxy\");\nconst createEndpoint = Symbol(\"Comlink.endpoint\");\nconst releaseProxy = Symbol(\"Comlink.releaseProxy\");\nconst finalizer = Symbol(\"Comlink.finalizer\");\nconst throwMarker = Symbol(\"Comlink.thrown\");\nconst isObject = (val) => (typeof val === \"object\" && val !== null) || typeof val === \"function\";\n/**\n * Internal transfer handle to handle objects marked to proxy.\n */\nconst proxyTransferHandler = {\n canHandle: (val) => isObject(val) && val[proxyMarker],\n serialize(obj) {\n const { port1, port2 } = new MessageChannel();\n expose(obj, port1);\n return [port2, [port2]];\n },\n deserialize(port) {\n port.start();\n return wrap(port);\n },\n};\n/**\n * Internal transfer handler to handle thrown exceptions.\n */\nconst throwTransferHandler = {\n canHandle: (value) => isObject(value) && throwMarker in value,\n serialize({ value }) {\n let serialized;\n if (value instanceof Error) {\n serialized = {\n isError: true,\n value: {\n message: value.message,\n name: value.name,\n stack: value.stack,\n },\n };\n }\n else {\n serialized = { isError: false, value };\n }\n return [serialized, []];\n },\n deserialize(serialized) {\n if (serialized.isError) {\n throw Object.assign(new Error(serialized.value.message), serialized.value);\n }\n throw serialized.value;\n },\n};\n/**\n * Allows customizing the serialization of certain values.\n */\nconst transferHandlers = new Map([\n [\"proxy\", proxyTransferHandler],\n [\"throw\", throwTransferHandler],\n]);\nfunction isAllowedOrigin(allowedOrigins, origin) {\n for (const allowedOrigin of allowedOrigins) {\n if (origin === allowedOrigin || allowedOrigin === \"*\") {\n return true;\n }\n if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin)) {\n return true;\n }\n }\n return false;\n}\nfunction expose(obj, ep = globalThis, allowedOrigins = [\"*\"]) {\n ep.addEventListener(\"message\", function callback(ev) {\n if (!ev || !ev.data) {\n return;\n }\n if (!isAllowedOrigin(allowedOrigins, ev.origin)) {\n console.warn(`Invalid origin '${ev.origin}' for comlink proxy`);\n return;\n }\n const { id, type, path } = Object.assign({ path: [] }, ev.data);\n const argumentList = (ev.data.argumentList || []).map(fromWireValue);\n let returnValue;\n try {\n const parent = path.slice(0, -1).reduce((obj, prop) => obj[prop], obj);\n const rawValue = path.reduce((obj, prop) => obj[prop], obj);\n switch (type) {\n case \"GET\" /* MessageType.GET */:\n {\n returnValue = rawValue;\n }\n break;\n case \"SET\" /* MessageType.SET */:\n {\n parent[path.slice(-1)[0]] = fromWireValue(ev.data.value);\n returnValue = true;\n }\n break;\n case \"APPLY\" /* MessageType.APPLY */:\n {\n returnValue = rawValue.apply(parent, argumentList);\n }\n break;\n case \"CONSTRUCT\" /* MessageType.CONSTRUCT */:\n {\n const value = new rawValue(...argumentList);\n returnValue = proxy(value);\n }\n break;\n case \"ENDPOINT\" /* MessageType.ENDPOINT */:\n {\n const { port1, port2 } = new MessageChannel();\n expose(obj, port2);\n returnValue = transfer(port1, [port1]);\n }\n break;\n case \"RELEASE\" /* MessageType.RELEASE */:\n {\n returnValue = undefined;\n }\n break;\n default:\n return;\n }\n }\n catch (value) {\n returnValue = { value, [throwMarker]: 0 };\n }\n Promise.resolve(returnValue)\n .catch((value) => {\n return { value, [throwMarker]: 0 };\n })\n .then((returnValue) => {\n const [wireValue, transferables] = toWireValue(returnValue);\n ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);\n if (type === \"RELEASE\" /* MessageType.RELEASE */) {\n // detach and deactive after sending release response above.\n ep.removeEventListener(\"message\", callback);\n closeEndPoint(ep);\n if (finalizer in obj && typeof obj[finalizer] === \"function\") {\n obj[finalizer]();\n }\n }\n })\n .catch((error) => {\n // Send Serialization Error To Caller\n const [wireValue, transferables] = toWireValue({\n value: new TypeError(\"Unserializable return value\"),\n [throwMarker]: 0,\n });\n ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);\n });\n });\n if (ep.start) {\n ep.start();\n }\n}\nfunction isMessagePort(endpoint) {\n return endpoint.constructor.name === \"MessagePort\";\n}\nfunction closeEndPoint(endpoint) {\n if (isMessagePort(endpoint))\n endpoint.close();\n}\nfunction wrap(ep, target) {\n const pendingListeners = new Map();\n ep.addEventListener(\"message\", function handleMessage(ev) {\n const { data } = ev;\n if (!data || !data.id) {\n return;\n }\n const resolver = pendingListeners.get(data.id);\n if (!resolver) {\n return;\n }\n try {\n resolver(data);\n }\n finally {\n pendingListeners.delete(data.id);\n }\n });\n return createProxy(ep, pendingListeners, [], target);\n}\nfunction throwIfProxyReleased(isReleased) {\n if (isReleased) {\n throw new Error(\"Proxy has been released and is not useable\");\n }\n}\nfunction releaseEndpoint(ep) {\n return requestResponseMessage(ep, new Map(), {\n type: \"RELEASE\" /* MessageType.RELEASE */,\n }).then(() => {\n closeEndPoint(ep);\n });\n}\nconst proxyCounter = new WeakMap();\nconst proxyFinalizers = \"FinalizationRegistry\" in globalThis &&\n new FinalizationRegistry((ep) => {\n const newCount = (proxyCounter.get(ep) || 0) - 1;\n proxyCounter.set(ep, newCount);\n if (newCount === 0) {\n releaseEndpoint(ep);\n }\n });\nfunction registerProxy(proxy, ep) {\n const newCount = (proxyCounter.get(ep) || 0) + 1;\n proxyCounter.set(ep, newCount);\n if (proxyFinalizers) {\n proxyFinalizers.register(proxy, ep, proxy);\n }\n}\nfunction unregisterProxy(proxy) {\n if (proxyFinalizers) {\n proxyFinalizers.unregister(proxy);\n }\n}\nfunction createProxy(ep, pendingListeners, path = [], target = function () { }) {\n let isProxyReleased = false;\n const proxy = new Proxy(target, {\n get(_target, prop) {\n throwIfProxyReleased(isProxyReleased);\n if (prop === releaseProxy) {\n return () => {\n unregisterProxy(proxy);\n releaseEndpoint(ep);\n pendingListeners.clear();\n isProxyReleased = true;\n };\n }\n if (prop === \"then\") {\n if (path.length === 0) {\n return { then: () => proxy };\n }\n const r = requestResponseMessage(ep, pendingListeners, {\n type: \"GET\" /* MessageType.GET */,\n path: path.map((p) => p.toString()),\n }).then(fromWireValue);\n return r.then.bind(r);\n }\n return createProxy(ep, pendingListeners, [...path, prop]);\n },\n set(_target, prop, rawValue) {\n throwIfProxyReleased(isProxyReleased);\n // FIXME: ES6 Proxy Handler `set` methods are supposed to return a\n // boolean. To show good will, we return true asynchronously ¯\\_(ツ)_/¯\n const [value, transferables] = toWireValue(rawValue);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"SET\" /* MessageType.SET */,\n path: [...path, prop].map((p) => p.toString()),\n value,\n }, transferables).then(fromWireValue);\n },\n apply(_target, _thisArg, rawArgumentList) {\n throwIfProxyReleased(isProxyReleased);\n const last = path[path.length - 1];\n if (last === createEndpoint) {\n return requestResponseMessage(ep, pendingListeners, {\n type: \"ENDPOINT\" /* MessageType.ENDPOINT */,\n }).then(fromWireValue);\n }\n // We just pretend that `bind()` didn’t happen.\n if (last === \"bind\") {\n return createProxy(ep, pendingListeners, path.slice(0, -1));\n }\n const [argumentList, transferables] = processArguments(rawArgumentList);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"APPLY\" /* MessageType.APPLY */,\n path: path.map((p) => p.toString()),\n argumentList,\n }, transferables).then(fromWireValue);\n },\n construct(_target, rawArgumentList) {\n throwIfProxyReleased(isProxyReleased);\n const [argumentList, transferables] = processArguments(rawArgumentList);\n return requestResponseMessage(ep, pendingListeners, {\n type: \"CONSTRUCT\" /* MessageType.CONSTRUCT */,\n path: path.map((p) => p.toString()),\n argumentList,\n }, transferables).then(fromWireValue);\n },\n });\n registerProxy(proxy, ep);\n return proxy;\n}\nfunction myFlat(arr) {\n return Array.prototype.concat.apply([], arr);\n}\nfunction processArguments(argumentList) {\n const processed = argumentList.map(toWireValue);\n return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))];\n}\nconst transferCache = new WeakMap();\nfunction transfer(obj, transfers) {\n transferCache.set(obj, transfers);\n return obj;\n}\nfunction proxy(obj) {\n return Object.assign(obj, { [proxyMarker]: true });\n}\nfunction windowEndpoint(w, context = globalThis, targetOrigin = \"*\") {\n return {\n postMessage: (msg, transferables) => w.postMessage(msg, targetOrigin, transferables),\n addEventListener: context.addEventListener.bind(context),\n removeEventListener: context.removeEventListener.bind(context),\n };\n}\nfunction toWireValue(value) {\n for (const [name, handler] of transferHandlers) {\n if (handler.canHandle(value)) {\n const [serializedValue, transferables] = handler.serialize(value);\n return [\n {\n type: \"HANDLER\" /* WireValueType.HANDLER */,\n name,\n value: serializedValue,\n },\n transferables,\n ];\n }\n }\n return [\n {\n type: \"RAW\" /* WireValueType.RAW */,\n value,\n },\n transferCache.get(value) || [],\n ];\n}\nfunction fromWireValue(value) {\n switch (value.type) {\n case \"HANDLER\" /* WireValueType.HANDLER */:\n return transferHandlers.get(value.name).deserialize(value.value);\n case \"RAW\" /* WireValueType.RAW */:\n return value.value;\n }\n}\nfunction requestResponseMessage(ep, pendingListeners, msg, transfers) {\n return new Promise((resolve) => {\n const id = generateUUID();\n pendingListeners.set(id, resolve);\n if (ep.start) {\n ep.start();\n }\n ep.postMessage(Object.assign({ id }, msg), transfers);\n });\n}\nfunction generateUUID() {\n return new Array(4)\n .fill(0)\n .map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16))\n .join(\"-\");\n}\n\nexport { createEndpoint, expose, finalizer, proxy, proxyMarker, releaseProxy, transfer, transferHandlers, windowEndpoint, wrap };\n//# sourceMappingURL=comlink.mjs.map\n","/**\n * Base error class for all OPFS-related errors\n */\nexport class OPFSError extends Error {\n constructor(message: string, public readonly code: string, public readonly path?: string) {\n super(message);\n this.name = 'OPFSError';\n }\n}\n\n/**\n * Error thrown when OPFS is not supported in the current browser\n */\nexport class OPFSNotSupportedError extends OPFSError {\n constructor() {\n super('OPFS is not supported in this browser', 'OPFS_NOT_SUPPORTED');\n }\n}\n\n\n/**\n * Error thrown when OPFS is not mounted\n */\nexport class OPFSNotMountedError extends OPFSError {\n constructor() {\n super('OPFS is not mounted', 'OPFS_NOT_MOUNTED');\n }\n}\n\n/**\n * Error thrown for invalid paths or path traversal attempts\n */\nexport class PathError extends OPFSError {\n constructor(message: string, path: string) {\n super(message, 'INVALID_PATH', path);\n }\n}\n\n/**\n * Error thrown when a requested file doesn't exist\n */\nexport class FileNotFoundError extends OPFSError {\n constructor(path: string) {\n super(`File not found: ${ path }`, 'FILE_NOT_FOUND', path);\n }\n}\n\n/**\n * Error thrown when a requested directory doesn't exist\n */\nexport class DirectoryNotFoundError extends OPFSError {\n constructor(path: string) {\n super(`Directory not found: ${ path }`, 'DIRECTORY_NOT_FOUND', path);\n }\n}\n\n/**\n * Error thrown when permission is denied for an operation\n */\nexport class PermissionError extends OPFSError {\n constructor(path: string, operation: string) {\n super(`Permission denied for ${ operation } on: ${ path }`, 'PERMISSION_DENIED', path);\n }\n}\n\n/**\n * Error thrown when an operation fails due to insufficient storage\n */\nexport class StorageError extends OPFSError {\n constructor(message: string, path?: string) {\n super(message, 'STORAGE_ERROR', path);\n }\n}\n\n/**\n * Error thrown when an operation times out\n */\nexport class TimeoutError extends OPFSError {\n constructor(operation: string, path?: string) {\n super(`Operation timed out: ${ operation }`, 'TIMEOUT_ERROR', path);\n }\n}\n","import { OPFSError } from './errors';\n\nimport type { BufferEncoding } from 'typescript';\n\nexport function encodeString(data: string, encoding: BufferEncoding = 'utf-8'): Uint8Array {\n switch (encoding) {\n case 'utf8':\n case 'utf-8':\n return new TextEncoder().encode(data);\n\n case 'utf16le':\n case 'ucs2':\n case 'ucs-2':\n return encodeUtf16LE(data);\n\n case 'ascii':\n return encodeAscii(data);\n\n case 'latin1':\n return encodeLatin1(data);\n\n case 'binary':\n return Uint8Array.from(data, char => char.charCodeAt(0));\n\n case 'base64':\n return Uint8Array.from(atob(data), c => c.charCodeAt(0));\n\n case 'hex':\n if (!/^[\\da-f]+$/i.test(data) || data.length % 2 !== 0) {\n throw new OPFSError('Invalid hex string', 'INVALID_HEX_FORMAT');\n }\n\n return Uint8Array.from(data.match(/.{1,2}/g)!.map(b => parseInt(b, 16)));\n\n default:\n console.warn('Encoding not supported, falling back to UTF-8');\n\n return new TextEncoder().encode(data);\n }\n}\n\nexport function decodeBuffer(buffer: Uint8Array, encoding: BufferEncoding = 'utf-8'): string {\n switch (encoding) {\n case 'utf8':\n case 'utf-8':\n return new TextDecoder().decode(buffer);\n\n case 'utf16le':\n case 'ucs2':\n case 'ucs-2':\n return decodeUtf16LE(buffer);\n\n case 'latin1':\n return String.fromCharCode(...buffer);\n\n case 'binary':\n return String.fromCharCode(...buffer);\n\n case 'ascii':\n return String.fromCharCode(...buffer.map(b => b & 0x7F));\n\n case 'base64':\n return btoa(String.fromCharCode(...buffer));\n\n case 'hex':\n return Array.from(buffer).map(b => b.toString(16).padStart(2, '0')).join('');\n\n default:\n console.warn('Unsupported encoding, falling back to UTF-8');\n\n return new TextDecoder().decode(buffer);\n }\n}\n\nfunction encodeUtf16LE(str: string): Uint8Array {\n const buf = new Uint8Array(str.length * 2);\n\n for (let i = 0; i < str.length; i++) {\n const code = str.charCodeAt(i);\n\n buf[(i * 2)] = code & 0xFF;\n buf[(i * 2) + 1] = code >> 8;\n }\n\n return buf;\n}\n\nfunction decodeUtf16LE(buf: Uint8Array): string {\n if (buf.length % 2 !== 0) {\n console.warn('Invalid UTF-16LE buffer length, truncating last byte');\n buf = buf.slice(0, buf.length - 1);\n }\n\n const codeUnits = new Uint16Array(buf.buffer, buf.byteOffset, buf.byteLength / 2);\n\n return String.fromCharCode(...codeUnits);\n}\n\nfunction encodeLatin1(str: string): Uint8Array {\n const buf = new Uint8Array(str.length);\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i) & 0xFF;\n }\n\n return buf;\n}\n\nfunction encodeAscii(str: string): Uint8Array {\n const buf = new Uint8Array(str.length);\n\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i) & 0x7F;\n }\n\n return buf;\n}\n","import { encodeString } from './encoder';\nimport { OPFSError, OPFSNotSupportedError } from './errors';\n\nimport type { BufferEncoding } from 'typescript';\n\n/**\n * Check if the browser supports the OPFS API\n * \n * @throws {OPFSNotSupportedError} If the browser does not support the OPFS API\n */\nexport function checkOPFSSupport(): void {\n if (!('storage' in navigator) || !('getDirectory' in (navigator.storage as any))) {\n throw new OPFSNotSupportedError();\n }\n}\n\n/** \n * Split a path into an array of segments\n * \n * @param path - The path to split\n * @returns The array of segments\n */\nexport function splitPath(path: string | string[]): string[] {\n if (Array.isArray(path)) {\n return path;\n }\n\n return path.split('/').filter(Boolean);\n}\n\n\n/**\n * Join an array of path segments into a single path\n * \n * @param segments - The array of path segments\n * @returns The joined path\n */\nexport function joinPath(segments: string[] | string): string {\n return typeof segments === 'string'\n ? (segments ?? '/')\n : `/${ segments.join('/') }`;\n}\n\n/**\n * Extract the filename from a path\n * \n * @param path - The file path\n * @returns The filename without the directory path\n * \n * @example\n * ```typescript\n * basename('/path/to/file.txt'); // 'file.txt'\n * basename('/path/to/directory/'); // ''\n * basename('file.txt'); // 'file.txt'\n * ```\n */\nexport function basename(path: string): string {\n const segments = splitPath(path);\n return segments[segments.length - 1] || '';\n}\n\n/**\n * Extract the directory path from a file path\n * \n * @param path - The file path\n * @returns The directory path without the filename\n * \n * @example\n * ```typescript\n * dirname('/path/to/file.txt'); // '/path/to'\n * dirname('/path/to/directory/'); // '/path/to/directory'\n * dirname('file.txt'); // '/'\n * ```\n */\nexport function dirname(path: string): string {\n const segments = splitPath(path);\n segments.pop();\n return joinPath(segments);\n}\n\n/**\n * Normalize a path to ensure it starts with '/'\n * \n * @param path - The path to normalize\n * @returns The normalized path\n * \n * @example\n * ```typescript\n * normalizePath('path/to/file'); // '/path/to/file'\n * normalizePath('/path/to/file'); // '/path/to/file'\n * normalizePath(''); // '/'\n * ```\n */\nexport function normalizePath(path: string): string {\n if (!path || path === '/') {\n return '/';\n }\n return path.startsWith('/') ? path : `/${path}`;\n}\n\n/**\n * Resolve a path to an absolute path, handling relative segments\n * \n * @param path - The path to resolve\n * @returns The resolved absolute path\n * \n * @example\n * ```typescript\n * resolvePath('./config/../data/file.txt'); // '/data/file.txt'\n * resolvePath('/path/to/../file.txt'); // '/path/file.txt'\n * resolvePath('../../file.txt'); // '/file.txt' (truncated to root)\n * ```\n */\nexport function resolvePath(path: string): string {\n const segments = splitPath(path);\n const normalizedSegments: string[] = [];\n\n for (const segment of segments) {\n if (segment === '.' || segment === '') {\n // Skip current directory references and empty segments\n continue;\n }\n else if (segment === '..') {\n if (normalizedSegments.length === 0) {\n // Path escapes root, keep at root level\n continue;\n }\n // Go up one directory\n normalizedSegments.pop();\n }\n else {\n normalizedSegments.push(segment);\n }\n }\n\n return joinPath(normalizedSegments);\n}\n\n/**\n * Get the file extension from a path\n * \n * @param path - The file path\n * @returns The file extension including the dot, or empty string if no extension\n * \n * @example\n * ```typescript\n * extname('/path/to/file.txt'); // '.txt'\n * extname('/path/to/file'); // ''\n * extname('/path/to/file.name.ext'); // '.ext'\n * extname('/path/to/.hidden'); // ''\n * ```\n */\nexport function extname(path: string): string {\n const filename = basename(path);\n const lastDotIndex = filename.lastIndexOf('.');\n \n if (lastDotIndex <= 0 || lastDotIndex === filename.length - 1) {\n return '';\n }\n \n return filename.slice(lastDotIndex);\n}\n\nexport function createBuffer(data: string | Uint8Array | ArrayBuffer, encoding: BufferEncoding = 'utf-8'): Uint8Array {\n if (typeof data === 'string') {\n return encodeString(data, encoding);\n }\n\n return data instanceof Uint8Array ? data : new Uint8Array(data);\n}\n\n\n/**\n * Read raw binary data from a file using a file handle\n *\n * @param fileHandle - The file handle to read from\n * @returns The raw binary data as Uint8Array\n */\nexport async function readFileData(fileHandle: FileSystemFileHandle): Promise<Uint8Array> {\n const handle = await fileHandle.createSyncAccessHandle();\n\n try {\n const size = handle.getSize();\n const buffer = new Uint8Array(size);\n\n handle.read(buffer, { at: 0 });\n\n return buffer;\n }\n finally {\n handle.close();\n }\n}\n\n/**\n * Write data to a file using a file handle\n *\n * @param fileHandle - The file handle to write to\n * @param data - The data to write to the file\n * @param encoding - The encoding to use\n * @param options - Write options (truncate or append)\n */\nexport async function writeFileData(\n fileHandle: FileSystemFileHandle,\n data: string | Uint8Array | ArrayBuffer,\n encoding?: BufferEncoding,\n options: { truncate?: boolean; append?: boolean } = {}\n): Promise<void> {\n let handle: FileSystemSyncAccessHandle | null = null;\n\n try {\n handle = await fileHandle.createSyncAccessHandle();\n\n const buffer = createBuffer(data, encoding);\n const writeOffset = options.append ? handle.getSize() : 0;\n\n handle.write(buffer, { at: writeOffset });\n\n if (options.truncate && !options.append) {\n handle.truncate(buffer.byteLength);\n }\n\n handle.flush();\n }\n catch (error) {\n console.error(error);\n const operation = options.append ? 'append' : 'write';\n\n throw new OPFSError(`Failed to ${ operation } file`, `${ operation.toUpperCase() }_FAILED`);\n }\n finally {\n if (handle) {\n try {\n handle.close();\n }\n catch { /* ~ */ }\n }\n }\n}\n\n/**\n * Calculate file hash using Web Crypto API\n * \n * @param buffer - The file content as Uint8Array\n * @param algorithm - Hash algorithm to use (default: 'SHA-1')\n * @returns Promise that resolves to the hash string\n */\nexport async function calculateFileHash(buffer: Uint8Array, algorithm: string = 'SHA-1'): Promise<string> {\n try {\n const bufferSource = new Uint8Array(buffer);\n const hashBuffer = await crypto.subtle.digest(algorithm, bufferSource);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n\n return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n }\n catch (error) {\n console.warn(`Failed to calculate ${ algorithm } hash:`, error);\n\n throw error;\n }\n}\n\n/**\n * Convert a Blob to Uint8Array\n * \n * This function converts a Blob object to a Uint8Array for use with file operations.\n * It's useful when working with file uploads or other Blob data sources.\n * \n * @param blob - The Blob to convert\n * @returns Promise that resolves to the Uint8Array representation of the Blob\n * \n * @example\n * ```typescript\n * const fileInput = document.getElementById('file') as HTMLInputElement;\n * const file = fileInput.files?.[0];\n * if (file) {\n * const data = await convertBlobToUint8Array(file);\n * await fs.writeFile('/uploaded-file', data);\n * }\n * ```\n */\nexport async function convertBlobToUint8Array(blob: Blob): Promise<Uint8Array> {\n const arrayBuffer = await blob.arrayBuffer();\n return new Uint8Array(arrayBuffer);\n}\n","import { expose } from 'comlink';\n\nimport { decodeBuffer } from './utils/encoder';\nimport {\n FileNotFoundError,\n OPFSError,\n OPFSNotMountedError,\n PathError\n} from './utils/errors';\n\nimport { \n calculateFileHash, \n checkOPFSSupport, \n joinPath, \n readFileData, \n splitPath, \n writeFileData,\n basename,\n dirname,\n normalizePath,\n resolvePath,\n convertBlobToUint8Array\n} from './utils/helpers';\n\nimport type { DirentData, FileStat, WatchEvent } from './types';\nimport type { BufferEncoding } from 'typescript';\n\n/**\n * OPFS (Origin Private File System) File System implementation\n * \n * This class provides a high-level interface for working with the browser's\n * Origin Private File System API, offering file and directory operations\n * similar to Node.js fs module.\n * \n * @example\n * ```typescript\n * const fs = new OPFSFileSystem();\n * await fs.init('/my-app');\n * await fs.writeFile('/data/config.json', JSON.stringify({ theme: 'dark' }));\n * const config = await fs.readFile('/data/config.json');\n * ```\n */\nexport class OPFSWorker {\n /** Root directory handle for the file system */\n private root: FileSystemDirectoryHandle | null = null;\n\n /** Watch event callback */\n private watchCallback: ((event: WatchEvent) => void) | null = null;\n\n /** Map of watched paths to their last known state */\n private watchers = new Map<string, Map<string, FileStat>>();\n\n /** Interval handle for polling watched paths */\n private watchTimer: ReturnType<typeof setInterval> | null = null;\n\n /** Polling interval in milliseconds */\n private watchInterval = 1000;\n\n /** Flag to avoid concurrent scans */\n private scanning = false;\n\n /** Promise to prevent concurrent mount operations */\n private mountingPromise: Promise<boolean> | null = null;\n\n /**\n * Creates a new OPFSFileSystem instance\n * \n * @param watchCallback - Optional callback for file change events\n * @param watchOptions - Optional configuration for watching\n * @throws {OPFSError} If OPFS is not supported in the current browser\n */\n constructor(\n watchCallback?: (event: WatchEvent) => void,\n watchOptions?: { watchInterval?: number }\n ) {\n checkOPFSSupport();\n \n if (watchCallback) {\n this.watchCallback = watchCallback;\n if (watchOptions?.watchInterval) {\n this.watchInterval = watchOptions.watchInterval;\n }\n }\n \n void this.mount('/');\n }\n\n /**\n * Initialize the file system within a given directory\n * \n * This method sets up the root directory for all subsequent operations.\n * If no root is specified, it will use the OPFS root directory.\n * \n * @param root - The root path for the file system (default: '/')\n * @returns Promise that resolves to true if initialization was successful\n * @throws {OPFSError} If initialization fails\n * \n * @example\n * ```typescript\n * const fs = new OPFSFileSystem();\n * \n * // Use OPFS root (default)\n * await fs.mount();\n * \n * // Use custom directory\n * await fs.mount('/my-app');\n * ```\n */\n async mount(root: string = '/'): Promise<boolean> {\n // If already mounting, wait for previous operation to complete first\n if (this.mountingPromise) {\n await this.mountingPromise;\n }\n\n this.mountingPromise = new Promise<boolean>(async(resolve, reject) => {\n this.root = null;\n \n try {\n const rootDir = await navigator.storage.getDirectory();\n \n if (root === '/') {\n this.root = rootDir;\n } \n else {\n this.root = await this.getDirectoryHandle(root, true, rootDir);\n }\n resolve(true);\n }\n catch (error) {\n console.error(error);\n reject(new OPFSError('Failed to initialize OPFS', 'INIT_FAILED'));\n }\n finally {\n this.mountingPromise = null;\n }\n });\n\n return this.mountingPromise;\n }\n\n /**\n * Set the watch callback for file change events\n * \n * @param callback - The callback function to invoke when files change\n * @param options - Optional configuration for watching\n */\n setWatchCallback(callback: (event: WatchEvent) => void, options?: { watchInterval?: number }): void {\n this.watchCallback = callback;\n\n if (options?.watchInterval) {\n this.watchInterval = options.watchInterval;\n }\n }\n\n /**\n * Automatically mount the OPFS root if not already mounted\n * \n * This method is called internally when file operations are performed\n * without explicitly mounting first.\n * \n * @returns Promise that resolves when auto-mount is complete\n * @throws {OPFSError} If auto-mount fails\n */\n private async ensureMounted(): Promise<void> {\n // If already mounted, return immediately\n if (this.root) {\n return;\n }\n\n // If already mounting, wait for that operation to complete\n if (this.mountingPromise) {\n await this.mountingPromise;\n return;\n }\n\n throw new OPFSError('OPFS not mounted', 'NOT_MOUNTED');\n }\n\n /**\n * Get a directory handle from a path\n * \n * Navigates through the directory structure to find or create a directory\n * at the specified path.\n * \n * @param path - The path to the directory (string or array of segments)\n * @param create - Whether to create the directory if it doesn't exist (default: false)\n * @param from - The directory to start from (default: root directory)\n * @returns Promise that resolves to the directory handle\n * @throws {OPFSError} If the directory cannot be accessed or created\n * \n * @example\n * ```typescript\n * const docsDir = await fs.getDirectoryHandle('/users/john/documents', true);\n * const docsDir2 = await fs.getDirectoryHandle(['users', 'john', 'documents'], true);\n * ```\n */\n private async getDirectoryHandle(path: string | string[], create: boolean = false, from: FileSystemDirectoryHandle | null = this.root): Promise<FileSystemDirectoryHandle> {\n if (!from) {\n throw new OPFSNotMountedError();\n }\n\n const segments = Array.isArray(path) ? path : splitPath(path);\n let current = from;\n\n for (const segment of segments) {\n current = await current.getDirectoryHandle(segment, { create });\n }\n\n return current;\n }\n\n /**\n * Get a file handle from a path\n * \n * Navigates to the parent directory and retrieves or creates a file handle\n * for the specified file path.\n * \n * @param path - The path to the file (string or array of segments)\n * @param create - Whether to create the file if it doesn't exist (default: false)\n * @param from - The directory to start from (default: root directory)\n * @returns Promise that resolves to the file handle\n * @throws {PathError} If the path is empty\n * @throws {OPFSError} If the file cannot be accessed or created\n * \n * @example\n * ```typescript\n * const fileHandle = await fs.getFileHandle('/config/settings.json', true);\n * const fileHandle2 = await fs.getFileHandle(['config', 'settings.json'], true);\n * ```\n */\n private async getFileHandle(path: string | string[], create = false, from: FileSystemDirectoryHandle | null = this.root): Promise<FileSystemFileHandle> {\n if (!from) {\n throw new OPFSNotMountedError();\n }\n\n const segments = splitPath(path);\n\n if (segments.length === 0) {\n throw new PathError('Path must not be empty', Array.isArray(path) ? path.join('/') : path);\n }\n\n const fileName = segments.pop()!;\n const dir = await this.getDirectoryHandle(segments, create, from);\n\n return dir.getFileHandle(fileName, { create });\n }\n\n\n /**\n * Recursively list all files and directories with their stats\n * \n * Traverses the entire file system starting from the root and returns\n * a Map containing all paths and their corresponding file statistics.\n * \n * @param options - Options for indexing\n * @param options.includeHash - Whether to calculate file hash (default: false)\n * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)\n * @returns Promise that resolves to a Map of path => FileStat\n * @throws {OPFSError} If the indexing operation fails\n * \n * @example\n * ```typescript\n * // Basic index without hash\n * const index = await fs.index();\n * \n * // Index with file hash\n * const indexWithHash = await fs.index({ \n * includeHash: true,\n * hashAlgorithm: 'SHA-1'\n * });\n * \n * // Iterate through all files and directories\n * for (const [path, stat] of index) {\n * console.log(`${path}: ${stat.isFile ? 'file' : 'directory'} (${stat.size} bytes)`);\n * if (stat.hash) console.log(` Hash: ${stat.hash}`);\n * }\n * \n * // Get specific file stats\n * const fileStats = index.get('/data/config.json');\n * if (fileStats) {\n * console.log(`File size: ${fileStats.size} bytes`);\n * if (fileStats.hash) console.log(`Hash: ${fileStats.hash}`);\n * }\n * ```\n */\n async index(options?: { includeHash?: boolean; hashAlgorithm?: 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512' }): Promise<Map<string, FileStat>> {\n const result = new Map<string, FileStat>();\n\n const walk = async(dirPath: string) => {\n const items = await this.readdir(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = `${ dirPath === '/' ? '' : dirPath }/${ item.name }`;\n\n try {\n const stat = await this.stat(fullPath, options);\n\n result.set(fullPath, stat);\n\n if (stat.isDirectory) {\n await walk(fullPath);\n }\n }\n catch (err) {\n console.warn(`Skipping broken entry: ${ fullPath }`, err);\n }\n }\n };\n\n result.set('/', {\n kind: 'directory',\n size: 0,\n mtime: new Date(0).toISOString(),\n ctime: new Date(0).toISOString(),\n isFile: false,\n isDirectory: true,\n });\n\n await walk('/');\n\n return result;\n }\n\n /**\n * Read a file from the file system\n * \n * Reads the contents of a file and returns it as a string or binary data\n * depending on the specified encoding.\n * \n * @param path - The path to the file to read\n * @param encoding - The encoding to use for reading the file\n * @returns Promise that resolves to the file contents\n * @throws {FileNotFoundError} If the file does not exist\n * @throws {OPFSError} If reading the file fails\n * \n * @example\n * ```typescript\n * // Read as text\n * const content = await fs.readFile('/config/settings.json');\n * \n * // Read as binary\n * const binaryData = await fs.readFile('/images/logo.png', 'binary');\n * \n * // Read with specific encoding\n * const utf8Content = await fs.readFile('/data/utf8.txt', 'utf-8');\n * ```\n */\n async readFile(path: string, encoding: 'binary'): Promise<Uint8Array>;\n async readFile(path: string, encoding?: BufferEncoding): Promise<string>;\n async readFile(\n path: string,\n encoding: BufferEncoding | 'binary' = 'utf-8'\n ): Promise<string | Uint8Array> {\n await this.ensureMounted();\n \n try {\n const fileHandle = await this.getFileHandle(path, false);\n const buffer = await readFileData(fileHandle);\n\n if (encoding === 'binary') {\n return buffer;\n }\n\n return decodeBuffer(buffer, encoding);\n }\n catch (err) {\n console.error(err);\n\n throw new FileNotFoundError(path);\n }\n }\n\n /**\n * Write data to a file\n * \n * Creates or overwrites a file with the specified data. If the file already\n * exists, it will be truncated before writing.\n * \n * @param path - The path to the file to write\n * @param data - The data to write to the file (string, Uint8Array, or ArrayBuffer)\n * @param encoding - The encoding to use when writing string data (default: 'utf-8')\n * @returns Promise that resolves when the write operation is complete\n * @throws {OPFSError} If writing the file fails\n * \n * @example\n * ```typescript\n * // Write text data\n * await fs.writeFile('/config/settings.json', JSON.stringify({ theme: 'dark' }));\n * \n * // Write binary data\n * const binaryData = new Uint8Array([1, 2, 3, 4, 5]);\n * await fs.writeFile('/data/binary.dat', binaryData);\n * \n * // Write with specific encoding\n * await fs.writeFile('/data/utf16.txt', 'Hello World', 'utf-16le');\n * ```\n */\n async writeFile(\n path: string,\n data: string | Uint8Array | ArrayBuffer,\n encoding?: BufferEncoding\n ): Promise<void> {\n await this.ensureMounted();\n \n const fileHandle = await this.getFileHandle(path, true);\n\n await writeFileData(fileHandle, data, encoding, { truncate: true });\n }\n\n /**\n * Append data to a file\n * \n * Adds data to the end of an existing file. If the file doesn't exist,\n * it will be created.\n * \n * @param path - The path to the file to append to\n * @param data - The data to append to the file (string, Uint8Array, or ArrayBuffer)\n * @param encoding - The encoding to use when appending string data (default: 'utf-8')\n * @returns Promise that resolves when the append operation is complete\n * @throws {OPFSError} If appending to the file fails\n * \n * @example\n * ```typescript\n * // Append text to a log file\n * await fs.appendFile('/logs/app.log', `[${new Date().toISOString()}] User logged in\\n`);\n * \n * // Append binary data\n * const additionalData = new Uint8Array([6, 7, 8]);\n * await fs.appendFile('/data/binary.dat', additionalData);\n * ```\n */\n async appendFile(\n path: string,\n data: string | Uint8Array | ArrayBuffer,\n encoding?: BufferEncoding\n ): Promise<void> {\n await this.ensureMounted();\n \n const fileHandle = await this.getFileHandle(path, true);\n\n await writeFileData(fileHandle, data, encoding, { append: true });\n }\n\n /**\n * Create a directory\n * \n * Creates a new directory at the specified path. If the recursive option\n * is enabled, parent directories will be created as needed.\n * \n * @param path - The path where the directory should be created\n * @param options - Options for directory creation\n * @param options.recursive - Whether to create parent directories if they don't exist (default: false)\n * @returns Promise that resolves when the directory is created\n * @throws {OPFSError} If the directory cannot be created\n * \n * @example\n * ```typescript\n * // Create a single directory\n * await fs.mkdir('/users/john');\n * \n * // Create nested directories\n * await fs.mkdir('/users/john/documents/projects', { recursive: true });\n * ```\n */\n async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n await this.ensureMounted();\n\n if (!this.root) {\n throw new OPFSNotMountedError();\n }\n\n const recursive = options?.recursive ?? false;\n const segments = splitPath(path);\n\n let current = this.root;\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n\n try {\n current = await current.getDirectoryHandle(segment!, { create: recursive || i === segments.length - 1 });\n }\n catch (e: any) {\n if (e.name === 'NotFoundError') {\n throw new OPFSError(\n `Parent directory does not exist: ${ joinPath(segments.slice(0, i + 1)) }`,\n 'ENOENT'\n );\n }\n\n if (e.name === 'TypeMismatchError') {\n throw new OPFSError(`Path segment is not a directory: ${ segment }`, 'ENOTDIR');\n }\n\n throw new OPFSError('Failed to create directory', 'MKDIR_FAILED');\n }\n }\n }\n\n /**\n * Get file or directory stats\n * \n * Retrieves metadata about a file or directory, including size, modification time,\n * type information, and optionally file hashes.\n * \n * @param path - The path to the file or directory\n * @param options - Options for stat operation\n * @param options.includeHash - Whether to calculate file hash (default: false, only for files)\n * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)\n * @returns Promise that resolves to file/directory statistics\n * @throws {OPFSError} If the file or directory does not exist or cannot be accessed\n * \n * @example\n * ```typescript\n * // Basic stats\n * const stats = await fs.stat('/config/settings.json');\n * console.log(`File size: ${stats.size} bytes`);\n * console.log(`Is file: ${stats.isFile}`);\n * console.log(`Modified: ${stats.mtime}`);\n * \n * // Stats with hash (SHA-1 is fastest)\n * const statsWithHash = await fs.stat('/config/settings.json', { \n * includeHash: true,\n * hashAlgorithm: 'SHA-1'\n * });\n * console.log(`Hash: ${statsWithHash.hash}`);\n * ```\n */\n async stat(path: string, options?: { includeHash?: boolean; hashAlgorithm?: 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512' }): Promise<FileStat> {\n await this.ensureMounted();\n \n // Special handling for root directory\n if (path === '/') {\n return {\n kind: 'directory',\n size: 0,\n mtime: new Date(0).toISOString(),\n ctime: new Date(0).toISOString(),\n isFile: false,\n isDirectory: true,\n };\n }\n \n const name = basename(path);\n const parentDir = await this.getDirectoryHandle(dirname(path), false);\n const includeHash = options?.includeHash ?? false;\n const hashAlgorithm = options?.hashAlgorithm ?? 'SHA-1';\n\n try {\n const fileHandle = await parentDir.getFileHandle(name!, { create: false });\n const file = await fileHandle.getFile();\n\n const baseStat: FileStat = {\n kind: 'file',\n size: file.size,\n mtime: new Date(file.lastModified).toISOString(),\n ctime: new Date(file.lastModified).toISOString(),\n isFile: true,\n isDirectory: false,\n };\n\n if (includeHash) {\n try {\n const buffer = new Uint8Array(await file.arrayBuffer());\n const hash = await calculateFileHash(buffer, hashAlgorithm);\n\n baseStat.hash = hash;\n }\n catch (error) {\n console.warn(`Failed to calculate hash for ${ path }:`, error);\n }\n }\n\n return baseStat;\n }\n catch (e: any) {\n if (e.name !== 'TypeMismatchError' && e.name !== 'NotFoundError') {\n throw new OPFSError('Failed to stat (file)', 'STAT_FAILED');\n }\n }\n\n try {\n await parentDir.getDirectoryHandle(name!, { create: false });\n\n return {\n kind: 'directory',\n size: 0,\n mtime: new Date(0).toISOString(),\n ctime: new Date(0).toISOString(),\n isFile: false,\n isDirectory: true,\n };\n }\n catch (e: any) {\n if (e.name === 'NotFoundError') {\n throw new OPFSError(`No such file or directory: ${ path }`, 'ENOENT');\n }\n\n throw new OPFSError('Failed to stat (directory)', 'STAT_FAILED');\n }\n }\n\n /**\n * Read a directory's contents\n * \n * Lists all files and subdirectories within the specified directory.\n * \n * @param path - The path to the directory to read\n * @param options - Options for the readdir operation\n * @param options.withFileTypes - Whether to return detailed file information (default: false)\n * @returns Promise that resolves to an array of file/directory names or detailed information\n * @throws {OPFSError} If the directory does not exist or cannot be accessed\n * \n * @example\n * ```typescript\n * // Get simple list of names\n * const files = await fs.readdir('/users/john/documents');\n * console.log('Files:', files); // ['readme.txt', 'config.json', 'images']\n * \n * // Get detailed information\n * const detailed = await fs.readdir('/users/john/documents', { withFileTypes: true });\n * detailed.forEach(item => {\n * console.log(`${item.name} - ${item.isFile ? 'file' : 'directory'}`);\n * });\n * ```\n */\n async readdir(path: string): Promise<string[]>;\n async readdir(path: string, options: { withFileTypes: true }): Promise<DirentData[]>;\n async readdir(path: string, options: { withFileTypes: false }): Promise<string[]>;\n async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirentData[]> {\n await this.ensureMounted();\n \n const withTypes = options?.withFileTypes ?? false;\n const dir = await this.getDirectoryHandle(path, false);\n\n if (withTypes) {\n const results: DirentData[] = [];\n\n for await (const [name, handle] of (dir as any).entries()) {\n const isFile = handle.kind === 'file';\n\n results.push({\n name,\n kind: handle.kind,\n isFile,\n isDirectory: !isFile,\n });\n }\n\n return results;\n }\n else {\n const results: string[] = [];\n\n for await (const [name] of (dir as any).entries()) {\n results.push(name);\n }\n\n return results;\n }\n }\n\n /**\n * Check if a file or directory exists\n * \n * Verifies if a file or directory exists at the specified path.\n * \n * @param path - The path to check\n * @returns Promise that resolves to true if the file or directory exists, false otherwise \n * \n * @example\n * ```typescript\n * const exists = await fs.exists('/config/settings.json');\n * console.log(`File exists: ${exists}`);\n * ```\n */\n async exists(path: string): Promise<boolean> {\n await this.ensureMounted();\n \n if (path === '/') {\n return true;\n }\n \n const name = basename(path);\n let dir: FileSystemDirectoryHandle | null = null;\n\n try {\n dir = await this.getDirectoryHandle(dirname(path), false);\n }\n catch (e: any) {\n if (e.name === 'NotFoundError' || e.name === 'TypeMismatchError') {\n dir = null;\n }\n\n throw e;\n }\n\n if (!dir || !name) {\n return false;\n }\n\n try {\n await dir.getFileHandle(name, { create: false });\n\n return true;\n }\n catch (e: any) {\n if (e.name !== 'NotFoundError' && e.name !== 'TypeMismatchError') {\n throw e;\n }\n }\n\n try {\n await dir.getDirectoryHandle(name, { create: false });\n\n return true;\n }\n catch (e: any) {\n if (e.name !== 'NotFoundError' && e.name !== 'TypeMismatchError') {\n throw e;\n }\n }\n\n return false;\n }\n\n /**\n * Clear all contents of a directory without removing the directory itself\n * \n * Removes all files and subdirectories within the specified directory,\n * but keeps the directory itself.\n * \n * @param path - The path to the directory to clear (default: '/')\n * @returns Promise that resolves when all contents are removed\n * @throws {OPFSError} If the operation fails\n * \n * @example\n * ```typescript\n * // Clear root directory contents\n * await fs.clear('/');\n * \n * // Clear specific directory contents\n * await fs.clear('/data');\n * ```\n */\n async clear(path: string = '/'): Promise<void> {\n await this.ensureMounted();\n \n try {\n const items = await this.readdir(path, { withFileTypes: true });\n\n for (const item of items) {\n const itemPath = `${ path === '/' ? '' : path }/${ item.name }`;\n\n await this.remove(itemPath, { recursive: true });\n }\n }\n catch (error: any) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to clear directory: ${ path }`, 'CLEAR_FAILED');\n }\n }\n\n /**\n * Remove files and directories\n * \n * Removes files and directories. Similar to Node.js fs.rm().\n * \n * @param path - The path to remove\n * @param options - Options for removal\n * @param options.recursive - Whether to remove directories and their contents recursively (default: false)\n * @param options.force - Whether to ignore errors if the path doesn't exist (default: false)\n * @returns Promise that resolves when the removal is complete\n * @throws {OPFSError} If the removal fails\n * \n * @example\n * ```typescript\n * // Remove a file\n * await fs.rm('/path/to/file.txt');\n * \n * // Remove a directory and all its contents\n * await fs.rm('/path/to/directory', { recursive: true });\n * \n * // Remove with force (ignore if doesn't exist)\n * await fs.rm('/maybe/exists', { force: true });\n * ```\n */\n async remove(path: string, options?: { recursive?: boolean; force?: boolean }): Promise<void> {\n await this.ensureMounted();\n \n const recursive = options?.recursive ?? false;\n const force = options?.force ?? false;\n\n // Special handling for root directory\n if (path === '/') {\n throw new OPFSError('Cannot remove root directory', 'EROOT');\n }\n\n const name = basename(path);\n\n if (!name) {\n throw new PathError('Invalid path', path);\n }\n\n const parent = await this.getDirectoryHandle(dirname(path), false);\n\n try {\n await parent.removeEntry(name, { recursive });\n }\n catch (e: any) {\n if (e.name === 'NotFoundError') {\n if (!force) {\n throw new OPFSError(`No such file or directory: ${ path }`, 'ENOENT');\n }\n }\n else if (e.name === 'InvalidModificationError') {\n throw new OPFSError(`Directory not empty: ${ path }. Use recursive option to force removal.`, 'ENOTEMPTY');\n }\n else if (e.name === 'TypeMismatchError' && !recursive) {\n throw new OPFSError(`Cannot remove directory without recursive option: ${ path }`, 'EISDIR');\n }\n else {\n throw new OPFSError(`Failed to remove path: ${ path }`, 'RM_FAILED');\n }\n }\n }\n\n /**\n * Resolve a path to an absolute path\n * \n * Resolves relative paths and normalizes path segments (like '..' and '.').\n * Similar to Node.js fs.realpath() but without symlink resolution since OPFS doesn't support symlinks.\n * \n * @param path - The path to resolve\n * @returns Promise that resolves to the absolute normalized path\n * @throws {FileNotFoundError} If the path does not exist\n * @throws {OPFSError} If path resolution fails\n * \n * @example\n * ```typescript\n * // Resolve relative path\n * const absolute = await fs.realpath('./config/../data/file.txt');\n * console.log(absolute); // '/data/file.txt'\n * ```\n */\n async realpath(path: string): Promise<string> {\n await this.ensureMounted();\n \n try {\n const normalizedPath = resolvePath(path);\n const exists = await this.exists(normalizedPath);\n\n if (!exists) {\n throw new FileNotFoundError(normalizedPath);\n }\n\n return normalizedPath;\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to resolve path: ${ path }`, 'REALPATH_FAILED');\n }\n }\n\n /**\n * Rename a file or directory\n * \n * Changes the name of a file or directory. If the target path already exists,\n * it will be replaced.\n * \n * @param oldPath - The current path of the file or directory\n * @param newPath - The new path for the file or directory\n * @returns Promise that resolves when the rename operation is complete\n * @throws {OPFSError} If the rename operation fails\n * \n * @example\n * ```typescript\n * await fs.rename('/old/path/file.txt', '/new/path/renamed.txt');\n * ```\n */\n async rename(oldPath: string, newPath: string): Promise<void> {\n await this.ensureMounted();\n \n try {\n const sourceExists = await this.exists(oldPath);\n\n if (!sourceExists) {\n throw new FileNotFoundError(oldPath);\n }\n\n await this.copy(oldPath, newPath, { recursive: true });\n await this.remove(oldPath, { recursive: true });\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to rename from ${ oldPath } to ${ newPath }`, 'RENAME_FAILED');\n }\n }\n\n /**\n * Copy files and directories\n * \n * Copies files and directories. Similar to Node.js fs.cp().\n * \n * @param source - The source path to copy from\n * @param destination - The destination path to copy to\n * @param options - Options for copying\n * @param options.recursive - Whether to copy directories recursively (default: false)\n * @param options.force - Whether to overwrite existing files (default: true)\n * @returns Promise that resolves when the copy operation is complete\n * @throws {OPFSError} If the copy operation fails\n * \n * @example\n * ```typescript\n * // Copy a file\n * await fs.copy('/source/file.txt', '/dest/file.txt');\n * \n * // Copy a directory and all its contents\n * await fs.copy('/source/dir', '/dest/dir', { recursive: true });\n * \n * // Copy without overwriting existing files\n * await fs.copy('/source', '/dest', { recursive: true, force: false });\n * ```\n */\n async copy(source: string, destination: string, options?: { recursive?: boolean; force?: boolean }): Promise<void> {\n await this.ensureMounted();\n \n try {\n const recursive = options?.recursive ?? false;\n const force = options?.force ?? true;\n\n const sourceExists = await this.exists(source);\n\n if (!sourceExists) {\n throw new OPFSError(`Source does not exist: ${ source }`, 'ENOENT');\n }\n\n const destExists = await this.exists(destination);\n\n if (destExists && !force) {\n throw new OPFSError(`Destination already exists: ${ destination }`, 'EEXIST');\n }\n\n const sourceStats = await this.stat(source);\n\n if (sourceStats.isFile) {\n const content = await this.readFile(source, 'binary');\n \n await this.writeFile(destination, content);\n }\n else {\n if (!recursive) {\n throw new OPFSError(`Cannot copy directory without recursive option: ${ source }`, 'EISDIR');\n }\n\n await this.mkdir(destination, { recursive: true });\n\n const items = await this.readdir(source, { withFileTypes: true });\n\n for (const item of items) {\n const sourceItemPath = `${ source }/${ item.name }`;\n const destItemPath = `${ destination }/${ item.name }`;\n\n await this.copy(sourceItemPath, destItemPath, { recursive: true, force });\n }\n }\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to copy from ${ source } to ${ destination }`, 'CP_FAILED');\n }\n }\n\n /**\n * Start watching a file or directory for changes\n */\n async watch(path: string): Promise<void> {\n await this.ensureMounted();\n \n const normalizedPath = normalizePath(path);\n const snapshot = await this.buildSnapshot(normalizedPath);\n this.watchers.set(normalizedPath, snapshot);\n\n if (!this.watchTimer) {\n this.watchTimer = setInterval(() => {\n void this.scanWatches();\n }, this.watchInterval);\n }\n }\n\n /**\n * Stop watching a previously watched path\n */\n unwatch(path: string): void {\n const normalizedPath = normalizePath(path);\n this.watchers.delete(normalizedPath);\n\n if (this.watchers.size === 0 && this.watchTimer) {\n clearInterval(this.watchTimer);\n this.watchTimer = null;\n }\n }\n\n private async buildSnapshot(rootPath: string): Promise<Map<string, FileStat>> {\n const result = new Map<string, FileStat>();\n\n const walk = async (current: string) => {\n const stat = await this.stat(current);\n result.set(current, stat);\n\n if (stat.isDirectory) {\n const entries = await this.readdir(current, { withFileTypes: true });\n for (const entry of entries) {\n const child = `${ current === '/' ? '' : current }/${ entry.name }`;\n await walk(child);\n }\n }\n };\n\n await walk(rootPath);\n return result;\n }\n\n private async scanWatches(): Promise<void> {\n if (this.scanning) {\n return;\n }\n\n this.scanning = true;\n\n try {\n await Promise.all(\n [...this.watchers.entries()].map(async ([rootPath, prev]) => {\n let next: Map<string, FileStat>;\n\n try {\n next = await this.buildSnapshot(rootPath);\n }\n catch {\n next = new Map();\n }\n\n const events: WatchEvent[] = [];\n\n for (const [p, stat] of next) {\n const old = prev.get(p);\n if (!old) {\n events.push({ path: p, type: 'create' });\n }\n else if (old.mtime !== stat.mtime || old.size !== stat.size) {\n events.push({ path: p, type: 'change' });\n }\n }\n\n for (const p of prev.keys()) {\n if (!next.has(p)) {\n events.push({ path: p, type: 'delete' });\n }\n }\n\n if (events.length && this.watchCallback) {\n for (const event of events) {\n this.watchCallback(event);\n }\n }\n\n this.watchers.set(rootPath, next);\n })\n );\n }\n finally {\n this.scanning = false;\n }\n }\n\n /**\n * Synchronize the file system with external data\n * \n * Syncs the file system with an array of entries containing paths and data.\n * This is useful for importing data from external sources or syncing with remote data.\n * \n * @param entries - Array of [path, data] tuples to sync\n * @param options - Options for synchronization\n * @param options.cleanBefore - Whether to clear the file system before syncing (default: false)\n * @returns Promise that resolves when synchronization is complete\n * @throws {OPFSError} If the synchronization fails\n * \n * @example\n * ```typescript\n * // Sync with external data\n * const entries: [string, string | Uint8Array | Blob][] = [\n * ['/config.json', JSON.stringify({ theme: 'dark' })],\n * ['/data/binary.dat', new Uint8Array([1, 2, 3, 4])],\n * ['/upload.txt', new Blob(['file content'], { type: 'text/plain' })]\n * ];\n * \n * // Sync without clearing existing files\n * await fs.sync(entries);\n * \n * // Clean file system and then sync\n * await fs.sync(entries, { cleanBefore: true });\n * ```\n */\n async sync(entries: [string, string | Uint8Array | Blob][], options?: { cleanBefore?: boolean }): Promise<void> {\n await this.ensureMounted();\n \n try {\n const cleanBefore = options?.cleanBefore ?? false;\n\n if (cleanBefore) {\n await this.clear('/');\n }\n\n for (const [path, data] of entries) {\n const normalizedPath = normalizePath(path);\n\n let fileData: string | Uint8Array;\n\n if (data instanceof Blob) {\n fileData = await convertBlobToUint8Array(data);\n }\n else {\n fileData = data;\n }\n\n await this.writeFile(normalizedPath, fileData);\n }\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError('Failed to sync file system', 'SYNC_FAILED');\n }\n }\n}\n\n// Only expose the worker when running in a Web Worker environment\nif (typeof self !== 'undefined' && self.constructor.name === 'DedicatedWorkerGlobalScope') {\n expose(new OPFSWorker());\n}\n"],"names":["proxyMarker","createEndpoint","releaseProxy","finalizer","throwMarker","isObject","val","proxyTransferHandler","obj","port1","port2","expose","port","wrap","throwTransferHandler","value","serialized","transferHandlers","isAllowedOrigin","allowedOrigins","origin","allowedOrigin","ep","callback","ev","id","type","path","argumentList","fromWireValue","returnValue","parent","prop","rawValue","proxy","transfer","wireValue","transferables","toWireValue","closeEndPoint","error","isMessagePort","endpoint","target","pendingListeners","data","resolver","createProxy","throwIfProxyReleased","isReleased","releaseEndpoint","requestResponseMessage","proxyCounter","proxyFinalizers","newCount","registerProxy","unregisterProxy","isProxyReleased","_target","r","p","_thisArg","rawArgumentList","last","processArguments","myFlat","arr","processed","v","transferCache","transfers","name","handler","serializedValue","msg","resolve","generateUUID","OPFSError","message","code","OPFSNotSupportedError","OPFSNotMountedError","PathError","FileNotFoundError","encodeString","encoding","encodeUtf16LE","encodeAscii","encodeLatin1","char","c","b","decodeBuffer","buffer","decodeUtf16LE","str","buf","i","codeUnits","checkOPFSSupport","splitPath","joinPath","segments","basename","dirname","normalizePath","resolvePath","normalizedSegments","segment","createBuffer","readFileData","fileHandle","handle","size","writeFileData","options","writeOffset","operation","calculateFileHash","algorithm","bufferSource","hashBuffer","convertBlobToUint8Array","blob","arrayBuffer","OPFSWorker","watchCallback","watchOptions","root","reject","rootDir","create","from","current","fileName","result","walk","dirPath","items","item","fullPath","stat","err","recursive","e","parentDir","includeHash","hashAlgorithm","file","baseStat","hash","withTypes","dir","results","isFile","itemPath","force","normalizedPath","oldPath","newPath","source","destination","content","sourceItemPath","destItemPath","snapshot","rootPath","entries","entry","child","prev","next","events","old","event","fileData"],"mappings":"AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,MAAMA,IAAc,OAAO,eAAe,GACpCC,IAAiB,OAAO,kBAAkB,GAC1CC,IAAe,OAAO,sBAAsB,GAC5CC,IAAY,OAAO,mBAAmB,GACtCC,IAAc,OAAO,gBAAgB,GACrCC,IAAW,CAACC,MAAS,OAAOA,KAAQ,YAAYA,MAAQ,QAAS,OAAOA,KAAQ,YAIhFC,IAAuB;AAAA,EACzB,WAAW,CAACD,MAAQD,EAASC,CAAG,KAAKA,EAAIN,CAAW;AAAA,EACpD,UAAUQ,GAAK;AACX,UAAM,EAAE,OAAAC,GAAO,OAAAC,EAAK,IAAK,IAAI,eAAc;AAC3C,WAAAC,EAAOH,GAAKC,CAAK,GACV,CAACC,GAAO,CAACA,CAAK,CAAC;AAAA,EAC1B;AAAA,EACA,YAAYE,GAAM;AACd,WAAAA,EAAK,MAAK,GACHC,EAAKD,CAAI;AAAA,EACpB;AACJ,GAIME,IAAuB;AAAA,EACzB,WAAW,CAACC,MAAUV,EAASU,CAAK,KAAKX,KAAeW;AAAA,EACxD,UAAU,EAAE,OAAAA,KAAS;AACjB,QAAIC;AACJ,WAAID,aAAiB,QACjBC,IAAa;AAAA,MACT,SAAS;AAAA,MACT,OAAO;AAAA,QACH,SAASD,EAAM;AAAA,QACf,MAAMA,EAAM;AAAA,QACZ,OAAOA,EAAM;AAAA,MACjC;AAAA,IACA,IAGYC,IAAa,EAAE,SAAS,IAAO,OAAAD,EAAK,GAEjC,CAACC,GAAY,EAAE;AAAA,EAC1B;AAAA,EACA,YAAYA,GAAY;AACpB,UAAIA,EAAW,UACL,OAAO,OAAO,IAAI,MAAMA,EAAW,MAAM,OAA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