opfs-worker 0.3.1 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/worker-CLK22qZk.js.map +1 -0
- package/dist/index.cjs +2 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +5 -4
- package/dist/index.js.map +1 -1
- package/dist/raw.cjs +1 -1
- package/dist/raw.cjs.map +1 -1
- package/dist/raw.js +1 -0
- package/dist/raw.js.map +1 -1
- package/dist/types.d.ts +1 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/worker.d.ts.map +1 -1
- package/package.json +10 -10
- package/dist/assets/worker-DilNsKoO.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worker-CLK22qZk.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 * \n * @example\n * ```typescript\n * splitPath('/path/to/file'); // ['path', 'to', 'file']\n * splitPath('~/path/to/file'); // ['path', 'to', 'file'] (home dir handled)\n * splitPath('relative/path'); // ['relative', 'path']\n * ```\n */\nexport function splitPath(path: string | string[]): string[] {\n if (Array.isArray(path)) {\n return path;\n }\n\n const normalizedPath = path.startsWith('~/') ? path.slice(2) : path;\n\n return normalizedPath.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('~/path/to/file'); // '/path/to/file' (home dir normalized to root)\n * normalizePath(''); // '/'\n * ```\n */\nexport function normalizePath(path: string): string {\n if (!path || path === '/') {\n return '/';\n }\n \n if (path.startsWith('~/')) {\n return `/${path.slice(2)}`;\n }\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 * resolvePath('~/config/../data/file.txt'); // '/data/file.txt' (home dir normalized to root)\n * ```\n */\nexport function resolvePath(path: string): string {\n // First normalize the path to handle home directory references\n const normalizedPath = normalizePath(path);\n const segments = splitPath(normalizedPath);\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 File, ArrayBuffer, or Uint8Array\n * @param algorithm - Hash algorithm to use (default: 'SHA-1')\n * @param maxSize - Maximum file size in bytes. If file is larger, throws error (default: 50MB)\n * @returns Promise that resolves to the hash string\n * @throws Error if file size exceeds maxSize\n */\nexport async function calculateFileHash(\n buffer: File | ArrayBuffer | Uint8Array, \n algorithm: string = 'SHA-1',\n maxSize: number = 50 * 1024 * 1024 // 50MB default\n): Promise<string> {\n if (buffer instanceof File) {\n buffer = await buffer.arrayBuffer();\n }\n \n // Check file size before processing\n if (buffer.byteLength > maxSize) {\n throw new Error(`File size ${buffer.byteLength} bytes exceeds maximum allowed size ${maxSize} bytes`);\n }\n\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\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, OPFSOptions } 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 /** 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 /** 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 /** BroadcastChannel instance for sending events */\n private broadcastChannel: BroadcastChannel | null = null;\n\n /** Configuration options */\n private options: Required<OPFSOptions> = {\n watchInterval: 1000,\n maxFileSize: 50 * 1024 * 1024,\n hashAlgorithm: null,\n broadcastChannel: 'opfs-worker',\n };\n \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 async notifyChange(event: Omit<WatchEvent, 'timestamp' | 'hash' | 'root'>): Promise<void> {\n if (!this.options.broadcastChannel) {\n return;\n }\n\n // Calculate hash if hashing is enabled and this is a file operation\n let hash: string | undefined;\n \n if (this.options.hashAlgorithm && !event.isDirectory && event.type !== 'removed') {\n try {\n const stats = await this.stat(event.path);\n\n if (stats.isFile && stats.hash) {\n hash = stats.hash;\n }\n } \n catch (error) {\n console.warn(`Failed to calculate hash for ${event.path}:`, error);\n }\n }\n\n // Send event via BroadcastChannel\n try {\n if (!this.broadcastChannel) {\n this.broadcastChannel = new BroadcastChannel(this.options.broadcastChannel);\n }\n \n const watchEvent: WatchEvent = {\n root: this.root!.name,\n timestamp: new Date().toISOString(),\n ...event,\n ...(hash && { hash })\n };\n \n this.broadcastChannel.postMessage(watchEvent);\n } \n catch (error) {\n console.warn(`Failed to send event via BroadcastChannel:`, error);\n }\n }\n\n /**\n * Creates a new OPFSFileSystem instance\n * \n * @param options - Optional configuration options\n * @param options.watchInterval - Polling interval in milliseconds for file watching\n * @param options.hashAlgorithm - Hash algorithm for file hashing\n * @param options.maxFileSize - Maximum file size for hashing in bytes (default: 50MB)\n * @throws {OPFSError} If OPFS is not supported in the current browser\n */\n constructor(options?: OPFSOptions) {\n checkOPFSSupport();\n \n if (options) {\n this.setOptions(options);\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 \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 /**\n * Update configuration options\n * \n * @param options - Configuration options to update\n * @param options.watchInterval - Polling interval in milliseconds for file watching\n * @param options.hashAlgorithm - Hash algorithm for file hashing\n * @param options.maxFileSize - Maximum file size for hashing in bytes\n * @param options.broadcastChannel - Custom name for the broadcast channel\n */\n setOptions(options: OPFSOptions): void {\n if (options.watchInterval !== undefined) {\n this.options.watchInterval = options.watchInterval;\n }\n\n if (options.hashAlgorithm !== undefined) {\n this.options.hashAlgorithm = options.hashAlgorithm;\n }\n\n if (options.maxFileSize !== undefined) {\n this.options.maxFileSize = options.maxFileSize;\n }\n\n if (options.broadcastChannel !== undefined) {\n // Close existing channel if name changed\n if (this.broadcastChannel && this.options.broadcastChannel !== options.broadcastChannel) {\n this.broadcastChannel.close();\n this.broadcastChannel = null;\n }\n \n this.options.broadcastChannel = options.broadcastChannel;\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 * Get a complete index of all files and directories in the file system\n * \n * This method recursively traverses the entire file system and returns\n * a Map containing FileStat objects for every file and directory.\n * \n * @returns Promise that resolves to a Map of paths to FileStat objects\n * @throws {OPFSError} If the file system is not mounted\n * \n * @example\n * ```typescript\n * const index = await fs.index();\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(): 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);\n\n for (const item of items) {\n const fullPath = `${ dirPath === '/' ? '' : dirPath }/${ item.name }`;\n\n try {\n const stat = await this.stat(fullPath);\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 await this.notifyChange({ path, type: 'changed', isDirectory: false });\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 await this.notifyChange({ path, type: 'changed', isDirectory: false });\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 await this.notifyChange({ path, type: 'added', isDirectory: true });\n }\n\n /**\n * Get file or directory statistics\n * \n * Returns detailed information about a file or directory, including\n * size, modification time, and optionally a hash of the file content.\n * \n * @param path - The path to the file or directory\n * @returns Promise that resolves to FileStat object\n * @throws {OPFSError} If the path does not exist or cannot be accessed\n * \n * @example\n * ```typescript\n * const stats = await fs.stat('/data/config.json');\n * console.log(`File size: ${stats.size} bytes`);\n * console.log(`Last modified: ${stats.mtime}`);\n * \n * // If hashing is enabled, hash will be included\n * if (stats.hash) {\n * console.log(`Hash: ${stats.hash}`);\n * }\n * ```\n */\n async stat(path: string): 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 = this.options.hashAlgorithm !== null;\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 && this.options.hashAlgorithm) {\n try {\n const hash = await calculateFileHash(file, this.options.hashAlgorithm, this.options.maxFileSize);\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 * @returns Promise that resolves to an array of detailed file/directory information\n * @throws {OPFSError} If the directory does not exist or cannot be accessed\n * \n * @example\n * ```typescript\n * // Get detailed information about files and directories\n * const detailed = await fs.readDir('/users/john/documents');\n * detailed.forEach(item => {\n * console.log(`${item.name} - ${item.isFile ? 'file' : 'directory'}`);\n * });\n * ```\n */\n async readDir(path: string): Promise<DirentData[]> {\n await this.ensureMounted();\n \n const dir = await this.getDirectoryHandle(path, false);\n\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\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);\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 await this.notifyChange({ path, type: 'changed', isDirectory: true });\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 await this.notifyChange({ path, type: 'removed', isDirectory: false });\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 await this.notifyChange({ path: oldPath, type: 'removed', isDirectory: false });\n await this.notifyChange({ path: newPath, type: 'added', isDirectory: false });\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);\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 await this.notifyChange({ path: destination, type: 'added', isDirectory: false });\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\n this.watchers.set(normalizedPath, snapshot);\n\n if (!this.watchTimer) {\n this.watchTimer = setInterval(() => {\n void this.scanWatches();\n }, this.options.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 /**\n * Dispose of resources and clean up the file system instance\n * \n * This method should be called when the file system instance is no longer needed\n * to properly clean up resources like the broadcast channel and watch timers.\n */\n dispose(): void {\n if (this.broadcastChannel) {\n this.broadcastChannel.close();\n this.broadcastChannel = null;\n }\n \n if (this.watchTimer) {\n clearInterval(this.watchTimer);\n this.watchTimer = null;\n }\n \n this.watchers.clear();\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);\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 (error) {\n next = new Map();\n }\n\n for (const [p, stat] of next) {\n const old = prev.get(p);\n \n if (!old) {\n await this.notifyChange({ path: p, type: 'added', isDirectory: stat.isDirectory });\n }\n else if (old.mtime !== stat.mtime || old.size !== stat.size) {\n await this.notifyChange({ path: p, type: 'changed', isDirectory: stat.isDirectory });\n }\n }\n\n for (const p of prev.keys()) {\n if (!next.has(p)) {\n const oldStat = prev.get(p);\n await this.notifyChange({ path: p, type: 'removed', isDirectory: oldStat?.isDirectory ?? false });\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 await this.notifyChange({ path: '/', type: 'changed', isDirectory: true });\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}"],"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","normalizedPath","normalizedSegments","segment","createBuffer","readFileData","fileHandle","handle","size","writeFileData","options","writeOffset","operation","calculateFileHash","algorithm","maxSize","bufferSource","hashBuffer","convertBlobToUint8Array","blob","arrayBuffer","OPFSWorker","event","hash","stats","watchEvent","root","reject","rootDir","create","from","current","fileName","result","walk","dirPath","items","item","fullPath","stat","err","recursive","e","parentDir","includeHash","file","baseStat","dir","results","isFile","itemPath","force","oldPath","newPath","source","destination","content","sourceItemPath","destItemPath","snapshot","rootPath","entries","entry","child","prev","next","old","oldStat","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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A;AAAA;AAAA;AAAA;AAAA;AAAA,EA8BA,MAAM,KAAKJ,GAAiDnD,GAAoD;AAC5G,UAAM,KAAK,cAAA;AAEX,QAAI;AAGA,OAFoBA,GAAS,eAAe,OAGxC,MAAM,KAAK,MAAM,GAAG;AAGxB,iBAAW,CAACzF,GAAMkB,CAAI,KAAK0H,GAAS;AAChC,cAAM5D,IAAiBF,EAAc9E,CAAI;AAEzC,YAAImJ;AAEJ,QAAIjI,aAAgB,OAChBiI,IAAW,MAAMlD,GAAwB/E,CAAI,IAG7CiI,IAAWjI,GAGf,MAAM,KAAK,UAAU8D,GAAgBmE,CAAQ;AAAA,MACjD;AAGA,YAAM,KAAK,aAAa,EAAE,MAAM,KAAK,MAAM,WAAW,aAAa,IAAM;AAAA,IAC7E,SACOtI,GAAO;AACV,YAAIA,aAAiBqC,IACXrC,IAGJ,IAAIqC,EAAU,8BAA8B,aAAa;AAAA,IACnE;AAAA,EACJ;AACJ;AAGI,OAAO,OAAS,OAAe,KAAK,YAAY,SAAS,gCAC3DlE,EAAO,IAAIoH,IAAY;","x_google_ignoreList":[0]}
|
package/dist/index.cjs
CHANGED
|
@@ -459,6 +459,7 @@ class wt {
|
|
|
459
459
|
try {
|
|
460
460
|
this.broadcastChannel || (this.broadcastChannel = new BroadcastChannel(this.options.broadcastChannel));
|
|
461
461
|
const i = {
|
|
462
|
+
root: this.root.name,
|
|
462
463
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
463
464
|
...t,
|
|
464
465
|
...r && { hash: r }
|
|
@@ -1177,6 +1178,6 @@ class wt {
|
|
|
1177
1178
|
}
|
|
1178
1179
|
}
|
|
1179
1180
|
typeof self < "u" && self.constructor.name === "DedicatedWorkerGlobalScope" && x(new wt());
|
|
1180
|
-
//# sourceMappingURL=worker-
|
|
1181
|
+
//# sourceMappingURL=worker-CLK22qZk.js.map
|
|
1181
1182
|
`,a=typeof self<"u"&&self.Blob&&new Blob(["URL.revokeObjectURL(import.meta.url);",i],{type:"text/javascript;charset=utf-8"});function s(e){let t;try{if(t=a&&(self.URL||self.webkitURL).createObjectURL(a),!t)throw"";const r=new Worker(t,{type:"module",name:e?.name});return r.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),r}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(i),{type:"module",name:e?.name})}}function c(e){const t=o.wrap(new s);return e&&t.setOptions(e),t}exports.DirectoryNotFoundError=n.DirectoryNotFoundError;exports.FileNotFoundError=n.FileNotFoundError;exports.OPFSError=n.OPFSError;exports.OPFSNotMountedError=n.OPFSNotMountedError;exports.OPFSNotSupportedError=n.OPFSNotSupportedError;exports.PathError=n.PathError;exports.PermissionError=n.PermissionError;exports.StorageError=n.StorageError;exports.TimeoutError=n.TimeoutError;exports.basename=n.basename;exports.calculateFileHash=n.calculateFileHash;exports.checkOPFSSupport=n.checkOPFSSupport;exports.convertBlobToUint8Array=n.convertBlobToUint8Array;exports.createBuffer=n.createBuffer;exports.decodeBuffer=n.decodeBuffer;exports.dirname=n.dirname;exports.encodeString=n.encodeString;exports.extname=n.extname;exports.joinPath=n.joinPath;exports.normalizePath=n.normalizePath;exports.readFileData=n.readFileData;exports.resolvePath=n.resolvePath;exports.splitPath=n.splitPath;exports.writeFileData=n.writeFileData;exports.createWorker=c;
|
|
1182
1183
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../src/index.ts"],"sourcesContent":["import { wrap, proxy } from 'comlink';\n\nimport WorkerCtor from './worker?worker&inline';\n\nimport type { OPFSWorker, RemoteOPFSWorker, WatchEvent, OPFSOptions } from './types';\n\nexport * from './types';\nexport * from './utils/errors';\nexport * from './utils/helpers';\nexport * from './utils/encoder';\n\n/**\n * Creates a new file system instance with inline worker\n * @param options - Optional configuration options\n * @returns Promise resolving to the file system interface\n */\nexport function createWorker(\n options?: OPFSOptions\n): RemoteOPFSWorker {\n const wrapped = wrap<OPFSWorker>(new WorkerCtor());\n \n // Set up options if provided\n if (options) {\n wrapped.setOptions(options);\n }\n \n return wrapped;\n}\n"],"names":["createWorker","options","wrapped","wrap","WorkerCtor"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../src/index.ts"],"sourcesContent":["import { wrap, proxy } from 'comlink';\n\nimport WorkerCtor from './worker?worker&inline';\n\nimport type { OPFSWorker, RemoteOPFSWorker, WatchEvent, OPFSOptions } from './types';\n\nexport * from './types';\nexport * from './utils/errors';\nexport * from './utils/helpers';\nexport * from './utils/encoder';\n\n/**\n * Creates a new file system instance with inline worker\n * @param options - Optional configuration options\n * @returns Promise resolving to the file system interface\n */\nexport function createWorker(\n options?: OPFSOptions\n): RemoteOPFSWorker {\n const wrapped = wrap<OPFSWorker>(new WorkerCtor());\n \n // Set up options if provided\n if (options) {\n wrapped.setOptions(options);\n }\n \n return wrapped;\n}\n"],"names":["createWorker","options","wrapped","wrap","WorkerCtor"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qdAgBO,SAASA,EACZC,EACgB,CAChB,MAAMC,EAAUC,EAAAA,KAAiB,IAAIC,CAAY,EAGjD,OAAIH,GACAC,EAAQ,WAAWD,CAAO,EAGvBC,CACX"}
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { wrap as i } from "comlink";
|
|
2
|
-
import { D as d, F as f, O as p, b as u, a as y, P as m, c as w, S as g, T as v, e as b, k as E, d as S, l as F, h as P, o as x, f as D, m as
|
|
2
|
+
import { D as d, F as f, O as p, b as u, a as y, P as m, c as w, S as g, T as v, e as b, k as E, d as S, l as F, h as P, o as x, f as D, m as C, g as T, j as A, n as O, i as _, r as I, s as U, w as R } from "./helpers-DxFcNkZe.js";
|
|
3
3
|
const a = `/**
|
|
4
4
|
* @license
|
|
5
5
|
* Copyright 2019 Google LLC
|
|
@@ -461,6 +461,7 @@ class wt {
|
|
|
461
461
|
try {
|
|
462
462
|
this.broadcastChannel || (this.broadcastChannel = new BroadcastChannel(this.options.broadcastChannel));
|
|
463
463
|
const i = {
|
|
464
|
+
root: this.root.name,
|
|
464
465
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
465
466
|
...t,
|
|
466
467
|
...r && { hash: r }
|
|
@@ -1179,7 +1180,7 @@ class wt {
|
|
|
1179
1180
|
}
|
|
1180
1181
|
}
|
|
1181
1182
|
typeof self < "u" && self.constructor.name === "DedicatedWorkerGlobalScope" && x(new wt());
|
|
1182
|
-
//# sourceMappingURL=worker-
|
|
1183
|
+
//# sourceMappingURL=worker-CLK22qZk.js.map
|
|
1183
1184
|
`, r = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", a], { type: "text/javascript;charset=utf-8" });
|
|
1184
1185
|
function o(t) {
|
|
1185
1186
|
let n;
|
|
@@ -1224,8 +1225,8 @@ export {
|
|
|
1224
1225
|
c as createWorker,
|
|
1225
1226
|
x as decodeBuffer,
|
|
1226
1227
|
D as dirname,
|
|
1227
|
-
|
|
1228
|
-
|
|
1228
|
+
C as encodeString,
|
|
1229
|
+
T as extname,
|
|
1229
1230
|
A as joinPath,
|
|
1230
1231
|
O as normalizePath,
|
|
1231
1232
|
_ as readFileData,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import { wrap, proxy } from 'comlink';\n\nimport WorkerCtor from './worker?worker&inline';\n\nimport type { OPFSWorker, RemoteOPFSWorker, WatchEvent, OPFSOptions } from './types';\n\nexport * from './types';\nexport * from './utils/errors';\nexport * from './utils/helpers';\nexport * from './utils/encoder';\n\n/**\n * Creates a new file system instance with inline worker\n * @param options - Optional configuration options\n * @returns Promise resolving to the file system interface\n */\nexport function createWorker(\n options?: OPFSOptions\n): RemoteOPFSWorker {\n const wrapped = wrap<OPFSWorker>(new WorkerCtor());\n \n // Set up options if provided\n if (options) {\n wrapped.setOptions(options);\n }\n \n return wrapped;\n}\n"],"names":["createWorker","options","wrapped","wrap","WorkerCtor"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import { wrap, proxy } from 'comlink';\n\nimport WorkerCtor from './worker?worker&inline';\n\nimport type { OPFSWorker, RemoteOPFSWorker, WatchEvent, OPFSOptions } from './types';\n\nexport * from './types';\nexport * from './utils/errors';\nexport * from './utils/helpers';\nexport * from './utils/encoder';\n\n/**\n * Creates a new file system instance with inline worker\n * @param options - Optional configuration options\n * @returns Promise resolving to the file system interface\n */\nexport function createWorker(\n options?: OPFSOptions\n): RemoteOPFSWorker {\n const wrapped = wrap<OPFSWorker>(new WorkerCtor());\n \n // Set up options if provided\n if (options) {\n wrapped.setOptions(options);\n }\n \n return wrapped;\n}\n"],"names":["createWorker","options","wrapped","wrap","WorkerCtor"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBO,SAASA,EACZC,GACgB;AAChB,QAAMC,IAAUC,EAAiB,IAAIC,GAAY;AAGjD,SAAIH,KACAC,EAAQ,WAAWD,CAAO,GAGvBC;AACX;"}
|
package/dist/raw.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("comlink"),a=require("./helpers-B87wz5kv.cjs");class w{root=null;watchers=new Map;watchTimer=null;scanning=!1;mountingPromise=null;broadcastChannel=null;options={watchInterval:1e3,maxFileSize:50*1024*1024,hashAlgorithm:null,broadcastChannel:"opfs-worker"};async notifyChange(t){if(!this.options.broadcastChannel)return;let e;if(this.options.hashAlgorithm&&!t.isDirectory&&t.type!=="removed")try{const r=await this.stat(t.path);r.isFile&&r.hash&&(e=r.hash)}catch(r){console.warn(`Failed to calculate hash for ${t.path}:`,r)}try{this.broadcastChannel||(this.broadcastChannel=new BroadcastChannel(this.options.broadcastChannel));const r={timestamp:new Date().toISOString(),...t,...e&&{hash:e}};this.broadcastChannel.postMessage(r)}catch(r){console.warn("Failed to send event via BroadcastChannel:",r)}}constructor(t){a.checkOPFSSupport(),t&&this.setOptions(t),this.mount("/")}async mount(t="/"){return this.mountingPromise&&await this.mountingPromise,this.mountingPromise=new Promise(async(e,r)=>{this.root=null;try{const i=await navigator.storage.getDirectory();t==="/"?this.root=i:this.root=await this.getDirectoryHandle(t,!0,i),e(!0)}catch(i){console.error(i),r(new a.OPFSError("Failed to initialize OPFS","INIT_FAILED"))}finally{this.mountingPromise=null}}),this.mountingPromise}setOptions(t){t.watchInterval!==void 0&&(this.options.watchInterval=t.watchInterval),t.hashAlgorithm!==void 0&&(this.options.hashAlgorithm=t.hashAlgorithm),t.maxFileSize!==void 0&&(this.options.maxFileSize=t.maxFileSize),t.broadcastChannel!==void 0&&(this.broadcastChannel&&this.options.broadcastChannel!==t.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.options.broadcastChannel=t.broadcastChannel)}async ensureMounted(){if(!this.root){if(this.mountingPromise){await this.mountingPromise;return}throw new a.OPFSError("OPFS not mounted","NOT_MOUNTED")}}async getDirectoryHandle(t,e=!1,r=this.root){if(!r)throw new a.OPFSNotMountedError;const i=Array.isArray(t)?t:a.splitPath(t);let s=r;for(const o of i)s=await s.getDirectoryHandle(o,{create:e});return s}async getFileHandle(t,e=!1,r=this.root){if(!r)throw new a.OPFSNotMountedError;const i=a.splitPath(t);if(i.length===0)throw new a.PathError("Path must not be empty",Array.isArray(t)?t.join("/"):t);const s=i.pop();return(await this.getDirectoryHandle(i,e,r)).getFileHandle(s,{create:e})}async index(){const t=new Map,e=async r=>{const i=await this.readDir(r);for(const s of i){const o=`${r==="/"?"":r}/${s.name}`;try{const n=await this.stat(o);t.set(o,n),n.isDirectory&&await e(o)}catch(n){console.warn(`Skipping broken entry: ${o}`,n)}}};return t.set("/",{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0}),await e("/"),t}async readFile(t,e="utf-8"){await this.ensureMounted();try{const r=await this.getFileHandle(t,!1),i=await a.readFileData(r);return e==="binary"?i:a.decodeBuffer(i,e)}catch(r){throw console.error(r),new a.FileNotFoundError(t)}}async writeFile(t,e,r){await this.ensureMounted();const i=await this.getFileHandle(t,!0);await a.writeFileData(i,e,r,{truncate:!0}),await this.notifyChange({path:t,type:"changed",isDirectory:!1})}async appendFile(t,e,r){await this.ensureMounted();const i=await this.getFileHandle(t,!0);await a.writeFileData(i,e,r,{append:!0}),await this.notifyChange({path:t,type:"changed",isDirectory:!1})}async mkdir(t,e){if(await this.ensureMounted(),!this.root)throw new a.OPFSNotMountedError;const r=e?.recursive??!1,i=a.splitPath(t);let s=this.root;for(let o=0;o<i.length;o++){const n=i[o];try{s=await s.getDirectoryHandle(n,{create:r||o===i.length-1})}catch(c){throw c.name==="NotFoundError"?new a.OPFSError(`Parent directory does not exist: ${a.joinPath(i.slice(0,o+1))}`,"ENOENT"):c.name==="TypeMismatchError"?new a.OPFSError(`Path segment is not a directory: ${n}`,"ENOTDIR"):new a.OPFSError("Failed to create directory","MKDIR_FAILED")}}await this.notifyChange({path:t,type:"added",isDirectory:!0})}async stat(t){if(await this.ensureMounted(),t==="/")return{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0};const e=a.basename(t),r=await this.getDirectoryHandle(a.dirname(t),!1),i=this.options.hashAlgorithm!==null;try{const o=await(await r.getFileHandle(e,{create:!1})).getFile(),n={kind:"file",size:o.size,mtime:new Date(o.lastModified).toISOString(),ctime:new Date(o.lastModified).toISOString(),isFile:!0,isDirectory:!1};if(i&&this.options.hashAlgorithm)try{const c=await a.calculateFileHash(o,this.options.hashAlgorithm,this.options.maxFileSize);n.hash=c}catch(c){console.warn(`Failed to calculate hash for ${t}:`,c)}return n}catch(s){if(s.name!=="TypeMismatchError"&&s.name!=="NotFoundError")throw new a.OPFSError("Failed to stat (file)","STAT_FAILED")}try{return await r.getDirectoryHandle(e,{create:!1}),{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0}}catch(s){throw s.name==="NotFoundError"?new a.OPFSError(`No such file or directory: ${t}`,"ENOENT"):new a.OPFSError("Failed to stat (directory)","STAT_FAILED")}}async readDir(t){await this.ensureMounted();const e=await this.getDirectoryHandle(t,!1),r=[];for await(const[i,s]of e.entries()){const o=s.kind==="file";r.push({name:i,kind:s.kind,isFile:o,isDirectory:!o})}return r}async exists(t){if(await this.ensureMounted(),t==="/")return!0;const e=a.basename(t);let r=null;try{r=await this.getDirectoryHandle(a.dirname(t),!1)}catch(i){throw(i.name==="NotFoundError"||i.name==="TypeMismatchError")&&(r=null),i}if(!r||!e)return!1;try{return await r.getFileHandle(e,{create:!1}),!0}catch(i){if(i.name!=="NotFoundError"&&i.name!=="TypeMismatchError")throw i}try{return await r.getDirectoryHandle(e,{create:!1}),!0}catch(i){if(i.name!=="NotFoundError"&&i.name!=="TypeMismatchError")throw i}return!1}async clear(t="/"){await this.ensureMounted();try{const e=await this.readDir(t);for(const r of e){const i=`${t==="/"?"":t}/${r.name}`;await this.remove(i,{recursive:!0})}await this.notifyChange({path:t,type:"changed",isDirectory:!0})}catch(e){throw e instanceof a.OPFSError?e:new a.OPFSError(`Failed to clear directory: ${t}`,"CLEAR_FAILED")}}async remove(t,e){await this.ensureMounted();const r=e?.recursive??!1,i=e?.force??!1;if(t==="/")throw new a.OPFSError("Cannot remove root directory","EROOT");const s=a.basename(t);if(!s)throw new a.PathError("Invalid path",t);const o=await this.getDirectoryHandle(a.dirname(t),!1);try{await o.removeEntry(s,{recursive:r})}catch(n){if(n.name==="NotFoundError"){if(!i)throw new a.OPFSError(`No such file or directory: ${t}`,"ENOENT")}else throw n.name==="InvalidModificationError"?new a.OPFSError(`Directory not empty: ${t}. Use recursive option to force removal.`,"ENOTEMPTY"):n.name==="TypeMismatchError"&&!r?new a.OPFSError(`Cannot remove directory without recursive option: ${t}`,"EISDIR"):new a.OPFSError(`Failed to remove path: ${t}`,"RM_FAILED")}await this.notifyChange({path:t,type:"removed",isDirectory:!1})}async realpath(t){await this.ensureMounted();try{const e=a.resolvePath(t);if(!await this.exists(e))throw new a.FileNotFoundError(e);return e}catch(e){throw e instanceof a.OPFSError?e:new a.OPFSError(`Failed to resolve path: ${t}`,"REALPATH_FAILED")}}async rename(t,e){await this.ensureMounted();try{if(!await this.exists(t))throw new a.FileNotFoundError(t);await this.copy(t,e,{recursive:!0}),await this.remove(t,{recursive:!0}),await this.notifyChange({path:t,type:"removed",isDirectory:!1}),await this.notifyChange({path:e,type:"added",isDirectory:!1})}catch(r){throw r instanceof a.OPFSError?r:new a.OPFSError(`Failed to rename from ${t} to ${e}`,"RENAME_FAILED")}}async copy(t,e,r){await this.ensureMounted();try{const i=r?.recursive??!1,s=r?.force??!0;if(!await this.exists(t))throw new a.OPFSError(`Source does not exist: ${t}`,"ENOENT");if(await this.exists(e)&&!s)throw new a.OPFSError(`Destination already exists: ${e}`,"EEXIST");if((await this.stat(t)).isFile){const h=await this.readFile(t,"binary");await this.writeFile(e,h)}else{if(!i)throw new a.OPFSError(`Cannot copy directory without recursive option: ${t}`,"EISDIR");await this.mkdir(e,{recursive:!0});const h=await this.readDir(t);for(const l of h){const d=`${t}/${l.name}`,f=`${e}/${l.name}`;await this.copy(d,f,{recursive:!0,force:s})}}await this.notifyChange({path:e,type:"added",isDirectory:!1})}catch(i){throw i instanceof a.OPFSError?i:new a.OPFSError(`Failed to copy from ${t} to ${e}`,"CP_FAILED")}}async watch(t){await this.ensureMounted();const e=a.normalizePath(t),r=await this.buildSnapshot(e);this.watchers.set(e,r),this.watchTimer||(this.watchTimer=setInterval(()=>{this.scanWatches()},this.options.watchInterval))}unwatch(t){const e=a.normalizePath(t);this.watchers.delete(e),this.watchers.size===0&&this.watchTimer&&(clearInterval(this.watchTimer),this.watchTimer=null)}dispose(){this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.watchTimer&&(clearInterval(this.watchTimer),this.watchTimer=null),this.watchers.clear()}async buildSnapshot(t){const e=new Map,r=async i=>{const s=await this.stat(i);if(e.set(i,s),s.isDirectory){const o=await this.readDir(i);for(const n of o){const c=`${i==="/"?"":i}/${n.name}`;await r(c)}}};return await r(t),e}async scanWatches(){if(!this.scanning){this.scanning=!0;try{await Promise.all([...this.watchers.entries()].map(async([t,e])=>{let r;try{r=await this.buildSnapshot(t)}catch{r=new Map}for(const[i,s]of r){const o=e.get(i);o?(o.mtime!==s.mtime||o.size!==s.size)&&await this.notifyChange({path:i,type:"changed",isDirectory:s.isDirectory}):await this.notifyChange({path:i,type:"added",isDirectory:s.isDirectory})}for(const i of e.keys())if(!r.has(i)){const s=e.get(i);await this.notifyChange({path:i,type:"removed",isDirectory:s?.isDirectory??!1})}this.watchers.set(t,r)}))}finally{this.scanning=!1}}}async sync(t,e){await this.ensureMounted();try{(e?.cleanBefore??!1)&&await this.clear("/");for(const[i,s]of t){const o=a.normalizePath(i);let n;s instanceof Blob?n=await a.convertBlobToUint8Array(s):n=s,await this.writeFile(o,n)}await this.notifyChange({path:"/",type:"changed",isDirectory:!0})}catch(r){throw r instanceof a.OPFSError?r:new a.OPFSError("Failed to sync file system","SYNC_FAILED")}}}typeof self<"u"&&self.constructor.name==="DedicatedWorkerGlobalScope"&&u.expose(new w);exports.OPFSWorker=w;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("comlink"),a=require("./helpers-B87wz5kv.cjs");class w{root=null;watchers=new Map;watchTimer=null;scanning=!1;mountingPromise=null;broadcastChannel=null;options={watchInterval:1e3,maxFileSize:50*1024*1024,hashAlgorithm:null,broadcastChannel:"opfs-worker"};async notifyChange(t){if(!this.options.broadcastChannel)return;let e;if(this.options.hashAlgorithm&&!t.isDirectory&&t.type!=="removed")try{const r=await this.stat(t.path);r.isFile&&r.hash&&(e=r.hash)}catch(r){console.warn(`Failed to calculate hash for ${t.path}:`,r)}try{this.broadcastChannel||(this.broadcastChannel=new BroadcastChannel(this.options.broadcastChannel));const r={root:this.root.name,timestamp:new Date().toISOString(),...t,...e&&{hash:e}};this.broadcastChannel.postMessage(r)}catch(r){console.warn("Failed to send event via BroadcastChannel:",r)}}constructor(t){a.checkOPFSSupport(),t&&this.setOptions(t),this.mount("/")}async mount(t="/"){return this.mountingPromise&&await this.mountingPromise,this.mountingPromise=new Promise(async(e,r)=>{this.root=null;try{const i=await navigator.storage.getDirectory();t==="/"?this.root=i:this.root=await this.getDirectoryHandle(t,!0,i),e(!0)}catch(i){console.error(i),r(new a.OPFSError("Failed to initialize OPFS","INIT_FAILED"))}finally{this.mountingPromise=null}}),this.mountingPromise}setOptions(t){t.watchInterval!==void 0&&(this.options.watchInterval=t.watchInterval),t.hashAlgorithm!==void 0&&(this.options.hashAlgorithm=t.hashAlgorithm),t.maxFileSize!==void 0&&(this.options.maxFileSize=t.maxFileSize),t.broadcastChannel!==void 0&&(this.broadcastChannel&&this.options.broadcastChannel!==t.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.options.broadcastChannel=t.broadcastChannel)}async ensureMounted(){if(!this.root){if(this.mountingPromise){await this.mountingPromise;return}throw new a.OPFSError("OPFS not mounted","NOT_MOUNTED")}}async getDirectoryHandle(t,e=!1,r=this.root){if(!r)throw new a.OPFSNotMountedError;const i=Array.isArray(t)?t:a.splitPath(t);let s=r;for(const o of i)s=await s.getDirectoryHandle(o,{create:e});return s}async getFileHandle(t,e=!1,r=this.root){if(!r)throw new a.OPFSNotMountedError;const i=a.splitPath(t);if(i.length===0)throw new a.PathError("Path must not be empty",Array.isArray(t)?t.join("/"):t);const s=i.pop();return(await this.getDirectoryHandle(i,e,r)).getFileHandle(s,{create:e})}async index(){const t=new Map,e=async r=>{const i=await this.readDir(r);for(const s of i){const o=`${r==="/"?"":r}/${s.name}`;try{const n=await this.stat(o);t.set(o,n),n.isDirectory&&await e(o)}catch(n){console.warn(`Skipping broken entry: ${o}`,n)}}};return t.set("/",{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0}),await e("/"),t}async readFile(t,e="utf-8"){await this.ensureMounted();try{const r=await this.getFileHandle(t,!1),i=await a.readFileData(r);return e==="binary"?i:a.decodeBuffer(i,e)}catch(r){throw console.error(r),new a.FileNotFoundError(t)}}async writeFile(t,e,r){await this.ensureMounted();const i=await this.getFileHandle(t,!0);await a.writeFileData(i,e,r,{truncate:!0}),await this.notifyChange({path:t,type:"changed",isDirectory:!1})}async appendFile(t,e,r){await this.ensureMounted();const i=await this.getFileHandle(t,!0);await a.writeFileData(i,e,r,{append:!0}),await this.notifyChange({path:t,type:"changed",isDirectory:!1})}async mkdir(t,e){if(await this.ensureMounted(),!this.root)throw new a.OPFSNotMountedError;const r=e?.recursive??!1,i=a.splitPath(t);let s=this.root;for(let o=0;o<i.length;o++){const n=i[o];try{s=await s.getDirectoryHandle(n,{create:r||o===i.length-1})}catch(c){throw c.name==="NotFoundError"?new a.OPFSError(`Parent directory does not exist: ${a.joinPath(i.slice(0,o+1))}`,"ENOENT"):c.name==="TypeMismatchError"?new a.OPFSError(`Path segment is not a directory: ${n}`,"ENOTDIR"):new a.OPFSError("Failed to create directory","MKDIR_FAILED")}}await this.notifyChange({path:t,type:"added",isDirectory:!0})}async stat(t){if(await this.ensureMounted(),t==="/")return{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0};const e=a.basename(t),r=await this.getDirectoryHandle(a.dirname(t),!1),i=this.options.hashAlgorithm!==null;try{const o=await(await r.getFileHandle(e,{create:!1})).getFile(),n={kind:"file",size:o.size,mtime:new Date(o.lastModified).toISOString(),ctime:new Date(o.lastModified).toISOString(),isFile:!0,isDirectory:!1};if(i&&this.options.hashAlgorithm)try{const c=await a.calculateFileHash(o,this.options.hashAlgorithm,this.options.maxFileSize);n.hash=c}catch(c){console.warn(`Failed to calculate hash for ${t}:`,c)}return n}catch(s){if(s.name!=="TypeMismatchError"&&s.name!=="NotFoundError")throw new a.OPFSError("Failed to stat (file)","STAT_FAILED")}try{return await r.getDirectoryHandle(e,{create:!1}),{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0}}catch(s){throw s.name==="NotFoundError"?new a.OPFSError(`No such file or directory: ${t}`,"ENOENT"):new a.OPFSError("Failed to stat (directory)","STAT_FAILED")}}async readDir(t){await this.ensureMounted();const e=await this.getDirectoryHandle(t,!1),r=[];for await(const[i,s]of e.entries()){const o=s.kind==="file";r.push({name:i,kind:s.kind,isFile:o,isDirectory:!o})}return r}async exists(t){if(await this.ensureMounted(),t==="/")return!0;const e=a.basename(t);let r=null;try{r=await this.getDirectoryHandle(a.dirname(t),!1)}catch(i){throw(i.name==="NotFoundError"||i.name==="TypeMismatchError")&&(r=null),i}if(!r||!e)return!1;try{return await r.getFileHandle(e,{create:!1}),!0}catch(i){if(i.name!=="NotFoundError"&&i.name!=="TypeMismatchError")throw i}try{return await r.getDirectoryHandle(e,{create:!1}),!0}catch(i){if(i.name!=="NotFoundError"&&i.name!=="TypeMismatchError")throw i}return!1}async clear(t="/"){await this.ensureMounted();try{const e=await this.readDir(t);for(const r of e){const i=`${t==="/"?"":t}/${r.name}`;await this.remove(i,{recursive:!0})}await this.notifyChange({path:t,type:"changed",isDirectory:!0})}catch(e){throw e instanceof a.OPFSError?e:new a.OPFSError(`Failed to clear directory: ${t}`,"CLEAR_FAILED")}}async remove(t,e){await this.ensureMounted();const r=e?.recursive??!1,i=e?.force??!1;if(t==="/")throw new a.OPFSError("Cannot remove root directory","EROOT");const s=a.basename(t);if(!s)throw new a.PathError("Invalid path",t);const o=await this.getDirectoryHandle(a.dirname(t),!1);try{await o.removeEntry(s,{recursive:r})}catch(n){if(n.name==="NotFoundError"){if(!i)throw new a.OPFSError(`No such file or directory: ${t}`,"ENOENT")}else throw n.name==="InvalidModificationError"?new a.OPFSError(`Directory not empty: ${t}. Use recursive option to force removal.`,"ENOTEMPTY"):n.name==="TypeMismatchError"&&!r?new a.OPFSError(`Cannot remove directory without recursive option: ${t}`,"EISDIR"):new a.OPFSError(`Failed to remove path: ${t}`,"RM_FAILED")}await this.notifyChange({path:t,type:"removed",isDirectory:!1})}async realpath(t){await this.ensureMounted();try{const e=a.resolvePath(t);if(!await this.exists(e))throw new a.FileNotFoundError(e);return e}catch(e){throw e instanceof a.OPFSError?e:new a.OPFSError(`Failed to resolve path: ${t}`,"REALPATH_FAILED")}}async rename(t,e){await this.ensureMounted();try{if(!await this.exists(t))throw new a.FileNotFoundError(t);await this.copy(t,e,{recursive:!0}),await this.remove(t,{recursive:!0}),await this.notifyChange({path:t,type:"removed",isDirectory:!1}),await this.notifyChange({path:e,type:"added",isDirectory:!1})}catch(r){throw r instanceof a.OPFSError?r:new a.OPFSError(`Failed to rename from ${t} to ${e}`,"RENAME_FAILED")}}async copy(t,e,r){await this.ensureMounted();try{const i=r?.recursive??!1,s=r?.force??!0;if(!await this.exists(t))throw new a.OPFSError(`Source does not exist: ${t}`,"ENOENT");if(await this.exists(e)&&!s)throw new a.OPFSError(`Destination already exists: ${e}`,"EEXIST");if((await this.stat(t)).isFile){const h=await this.readFile(t,"binary");await this.writeFile(e,h)}else{if(!i)throw new a.OPFSError(`Cannot copy directory without recursive option: ${t}`,"EISDIR");await this.mkdir(e,{recursive:!0});const h=await this.readDir(t);for(const l of h){const d=`${t}/${l.name}`,f=`${e}/${l.name}`;await this.copy(d,f,{recursive:!0,force:s})}}await this.notifyChange({path:e,type:"added",isDirectory:!1})}catch(i){throw i instanceof a.OPFSError?i:new a.OPFSError(`Failed to copy from ${t} to ${e}`,"CP_FAILED")}}async watch(t){await this.ensureMounted();const e=a.normalizePath(t),r=await this.buildSnapshot(e);this.watchers.set(e,r),this.watchTimer||(this.watchTimer=setInterval(()=>{this.scanWatches()},this.options.watchInterval))}unwatch(t){const e=a.normalizePath(t);this.watchers.delete(e),this.watchers.size===0&&this.watchTimer&&(clearInterval(this.watchTimer),this.watchTimer=null)}dispose(){this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.watchTimer&&(clearInterval(this.watchTimer),this.watchTimer=null),this.watchers.clear()}async buildSnapshot(t){const e=new Map,r=async i=>{const s=await this.stat(i);if(e.set(i,s),s.isDirectory){const o=await this.readDir(i);for(const n of o){const c=`${i==="/"?"":i}/${n.name}`;await r(c)}}};return await r(t),e}async scanWatches(){if(!this.scanning){this.scanning=!0;try{await Promise.all([...this.watchers.entries()].map(async([t,e])=>{let r;try{r=await this.buildSnapshot(t)}catch{r=new Map}for(const[i,s]of r){const o=e.get(i);o?(o.mtime!==s.mtime||o.size!==s.size)&&await this.notifyChange({path:i,type:"changed",isDirectory:s.isDirectory}):await this.notifyChange({path:i,type:"added",isDirectory:s.isDirectory})}for(const i of e.keys())if(!r.has(i)){const s=e.get(i);await this.notifyChange({path:i,type:"removed",isDirectory:s?.isDirectory??!1})}this.watchers.set(t,r)}))}finally{this.scanning=!1}}}async sync(t,e){await this.ensureMounted();try{(e?.cleanBefore??!1)&&await this.clear("/");for(const[i,s]of t){const o=a.normalizePath(i);let n;s instanceof Blob?n=await a.convertBlobToUint8Array(s):n=s,await this.writeFile(o,n)}await this.notifyChange({path:"/",type:"changed",isDirectory:!0})}catch(r){throw r instanceof a.OPFSError?r:new a.OPFSError("Failed to sync file system","SYNC_FAILED")}}}typeof self<"u"&&self.constructor.name==="DedicatedWorkerGlobalScope"&&u.expose(new w);exports.OPFSWorker=w;
|
|
2
2
|
//# sourceMappingURL=raw.cjs.map
|