opfs-worker 0.2.0 → 0.2.1
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-ChfzBM-o.js.map +1 -0
- package/dist/helpers-Co-qCBmA.js +224 -0
- package/dist/helpers-Co-qCBmA.js.map +1 -0
- package/dist/helpers-hEpet7x7.cjs +2 -0
- package/dist/helpers-hEpet7x7.cjs.map +1 -0
- package/dist/index.cjs +217 -205
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +4 -19
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -16
- package/dist/index.js.map +1 -1
- package/dist/raw.cjs +1 -1
- package/dist/raw.cjs.map +1 -1
- package/dist/raw.js +187 -347
- package/dist/raw.js.map +1 -1
- package/dist/types.d.ts +4 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/encoder.d.ts.map +1 -1
- package/dist/utils/encoder.js +0 -3
- package/dist/utils/helpers.d.ts +108 -0
- package/dist/utils/helpers.d.ts.map +1 -1
- package/dist/utils/helpers.js +151 -1
- package/dist/worker.d.ts.map +1 -1
- package/dist/worker.js +12 -59
- package/package.json +9 -9
- package/dist/assets/worker-D5GbafFH.js.map +0 -1
- package/dist/test/setup.d.ts +0 -2
- package/dist/test/setup.d.ts.map +0 -1
- package/dist/test/setup.js +0 -148
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../src/index.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../src/index.ts"],"sourcesContent":["import { wrap } from 'comlink';\n\nimport WorkerCtor from './worker?worker&inline';\n\nimport type { OPFSWorker, RemoteOPFSWorker } 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 * @returns Promise resolving to the file system interface\n */\nexport function createWorker(): RemoteOPFSWorker {\n return wr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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qdAeO,SAASA,GAAiC,CAC7C,OAAOC,EAAAA,KAAiB,IAAIC,CAAY,CAC5C"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,23 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
* Main export for OPFS Worker library
|
|
3
|
-
*
|
|
4
|
-
* This is the main entry point for the library, providing both the inline worker
|
|
5
|
-
* functionality and all the necessary types and interfaces.
|
|
6
|
-
*
|
|
7
|
-
* @example
|
|
8
|
-
* ```typescript
|
|
9
|
-
* import { createWorker, type OPFSWorker } from 'opfs-worker';
|
|
10
|
-
*
|
|
11
|
-
* const fs = await createWorker();
|
|
12
|
-
* await fs.mount('/my-app');
|
|
13
|
-
* await fs.writeFile('/test.txt', 'Hello World');
|
|
14
|
-
* ```
|
|
15
|
-
*/
|
|
16
|
-
import { type Remote } from 'comlink';
|
|
17
|
-
import type { OPFSWorker } from './types';
|
|
1
|
+
import type { RemoteOPFSWorker } from './types';
|
|
18
2
|
export * from './types';
|
|
19
|
-
export
|
|
20
|
-
export
|
|
3
|
+
export * from './utils/errors';
|
|
4
|
+
export * from './utils/helpers';
|
|
5
|
+
export * from './utils/encoder';
|
|
21
6
|
/**
|
|
22
7
|
* Creates a new file system instance with inline worker
|
|
23
8
|
* @returns Promise resolving to the file system interface
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAc,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAE5D,cAAc,SAAS,CAAC;AACxB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,iBAAiB,CAAC;AAEhC;;;GAGG;AACH,wBAAgB,YAAY,IAAI,gBAAgB,CAE/C"}
|
package/dist/index.js
CHANGED
|
@@ -1,22 +1,9 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Main export for OPFS Worker library
|
|
3
|
-
*
|
|
4
|
-
* This is the main entry point for the library, providing both the inline worker
|
|
5
|
-
* functionality and all the necessary types and interfaces.
|
|
6
|
-
*
|
|
7
|
-
* @example
|
|
8
|
-
* ```typescript
|
|
9
|
-
* import { createWorker, type OPFSWorker } from 'opfs-worker';
|
|
10
|
-
*
|
|
11
|
-
* const fs = await createWorker();
|
|
12
|
-
* await fs.mount('/my-app');
|
|
13
|
-
* await fs.writeFile('/test.txt', 'Hello World');
|
|
14
|
-
* ```
|
|
15
|
-
*/
|
|
16
1
|
import { wrap } from 'comlink';
|
|
17
2
|
import WorkerCtor from './worker?worker&inline';
|
|
18
|
-
// Export all types
|
|
19
3
|
export * from './types';
|
|
4
|
+
export * from './utils/errors';
|
|
5
|
+
export * from './utils/helpers';
|
|
6
|
+
export * from './utils/encoder';
|
|
20
7
|
/**
|
|
21
8
|
* Creates a new file system instance with inline worker
|
|
22
9
|
* @returns Promise resolving to the file system interface
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import { wrap } from 'comlink';\n\nimport WorkerCtor from './worker?worker&inline';\n\nimport type { OPFSWorker, RemoteOPFSWorker } 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 * @returns Promise resolving to the file system interface\n */\nexport function createWorker(): RemoteOPFSWorker {\n return wrap<OPFSWorker>(new WorkerCtor());\n}\n"],"names":["createWorker","wrap","WorkerCtor"],"mappings":";;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeO,SAASA,IAAiC;AAC7C,SAAOC,EAAiB,IAAIC,GAAY;AAC5C;"}
|
package/dist/raw.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S=require("comlink");class o extends Error{constructor(e,t,r){super(e),this.code=t,this.path=r,this.name="OPFSError"}}class A extends o{constructor(){super("OPFS is not supported in this browser","OPFS_NOT_SUPPORTED")}}class y extends o{constructor(){super("OPFS is not mounted","OPFS_NOT_MOUNTED")}}class g extends o{constructor(e,t){super(e,"INVALID_PATH",t)}}class m extends o{constructor(e){super(`File not found: ${e}`,"FILE_NOT_FOUND",e)}}function D(a,e="utf-8"){switch(e){case"utf8":case"utf-8":return new TextEncoder().encode(a);case"utf16le":case"ucs2":case"ucs-2":return I(a);case"ascii":return N(a);case"latin1":return $(a);case"binary":return Uint8Array.from(a,t=>t.charCodeAt(0));case"base64":return Uint8Array.from(atob(a),t=>t.charCodeAt(0));case"hex":if(!/^[\da-f]+$/i.test(a)||a.length%2!==0)throw new o("Invalid hex string","INVALID_HEX_FORMAT");return Uint8Array.from(a.match(/.{1,2}/g).map(t=>parseInt(t,16)));default:return console.warn("Encoding not supported, falling back to UTF-8"),new TextEncoder().encode(a)}}function T(a,e="utf-8"){switch(e){case"utf8":case"utf-8":return new TextDecoder().decode(a);case"utf16le":case"ucs2":case"ucs-2":return v(a);case"latin1":return String.fromCharCode(...a);case"binary":return String.fromCharCode(...a);case"ascii":return String.fromCharCode(...a.map(t=>t&127));case"base64":return btoa(String.fromCharCode(...a));case"hex":return Array.from(a).map(t=>t.toString(16).padStart(2,"0")).join("");default:return console.warn("Unsupported encoding, falling back to UTF-8"),new TextDecoder().decode(a)}}function I(a){const e=new Uint8Array(a.length*2);for(let t=0;t<a.length;t++){const r=a.charCodeAt(t);e[t*2]=r&255,e[t*2+1]=r>>8}return e}function v(a){a.length%2!==0&&(console.warn("Invalid UTF-16LE buffer length, truncating last byte"),a=a.slice(0,a.length-1));const e=new Uint16Array(a.buffer,a.byteOffset,a.byteLength/2);return String.fromCharCode(...e)}function $(a){const e=new Uint8Array(a.length);for(let t=0;t<a.length;t++)e[t]=a.charCodeAt(t)&255;return e}function N(a){const e=new Uint8Array(a.length);for(let t=0;t<a.length;t++)e[t]=a.charCodeAt(t)&127;return e}function O(){if(!("storage"in navigator)||!("getDirectory"in navigator.storage))throw new A}function f(a){return Array.isArray(a)?a:a.split("/").filter(Boolean)}function p(a){return typeof a=="string"?a??"/":`/${a.join("/")}`}function H(a,e="utf-8"){return typeof a=="string"?D(a,e):a instanceof Uint8Array?a:new Uint8Array(a)}async function x(a){const e=await a.createSyncAccessHandle();try{const t=e.getSize(),r=new Uint8Array(t);return e.read(r,{at:0}),r}finally{e.close()}}async function F(a,e,t,r={}){let n=null;try{n=await a.createSyncAccessHandle();const i=H(e,t),s=r.append?n.getSize():0;n.write(i,{at:s}),r.truncate&&!r.append&&n.truncate(i.byteLength),n.flush()}catch(i){console.error(i);const s=r.append?"append":"write";throw new o(`Failed to ${s} file`,`${s.toUpperCase()}_FAILED`)}finally{if(n)try{n.close()}catch{}}}async function P(a,e="SHA-1"){try{const t=new Uint8Array(a),r=await crypto.subtle.digest(e,t);return Array.from(new Uint8Array(r)).map(i=>i.toString(16).padStart(2,"0")).join("")}catch(t){throw console.warn(`Failed to calculate ${e} hash:`,t),t}}class E{root=null;watchCallback=null;watchers=new Map;watchTimer=null;watchInterval=1e3;scanning=!1;constructor(){O()}async mount(e="/",t,r){try{const n=await navigator.storage.getDirectory();return this.root=await this.getDirectoryHandle(e,!0,n),t&&(this.watchCallback=t,r?.watchInterval&&(this.watchInterval=r.watchInterval)),!0}catch(n){throw console.error(n),new o("Failed to initialize OPFS","INIT_FAILED")}}async getDirectoryHandle(e,t=!1,r=this.root){if(!r)throw new y;const n=Array.isArray(e)?e:f(e);let i=r;for(const s of n)i=await i.getDirectoryHandle(s,{create:t});return i}async getFileHandle(e,t=!1,r=this.root){if(!r)throw new y;const n=f(e);if(n.length===0)throw new g("Path must not be empty",Array.isArray(e)?e.join("/"):e);const i=n.pop();return(await this.getDirectoryHandle(n,t,r)).getFileHandle(i,{create:t})}async index(e){const t=new Map,r=async n=>{const i=await this.readdir(n,{withFileTypes:!0});for(const s of i){const c=`${n==="/"?"":n}/${s.name}`;try{const l=await this.stat(c,e);t.set(c,l),l.isDirectory&&await r(c)}catch(l){console.warn(`Skipping broken entry: ${c}`,l)}}};return t.set("/",{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0}),await r("/"),t}async readFile(e,t="utf-8"){try{const r=await this.getFileHandle(e,!1),n=await x(r);return t==="binary"?n:T(n,t)}catch(r){throw console.error(r),new m(e)}}async writeFile(e,t,r){const n=await this.getFileHandle(e,!0);await F(n,t,r,{truncate:!0})}async appendFile(e,t,r){const n=await this.getFileHandle(e,!0);await F(n,t,r,{append:!0})}async mkdir(e,t){if(!this.root)throw new y;const r=t?.recursive??!1,n=f(e);let i=this.root;for(let s=0;s<n.length;s++){const c=n[s];try{i=await i.getDirectoryHandle(c,{create:r||s===n.length-1})}catch(l){throw l.name==="NotFoundError"?new o(`Parent directory does not exist: ${p(n.slice(0,s+1))}`,"ENOENT"):l.name==="TypeMismatchError"?new o(`Path segment is not a directory: ${c}`,"ENOTDIR"):new o("Failed to create directory","MKDIR_FAILED")}}}async stat(e,t){const r=f(e),n=r.pop(),i=await this.getDirectoryHandle(r,!1),s=t?.includeHash??!1,c=t?.hashAlgorithm??"SHA-1";try{const h=await(await i.getFileHandle(n,{create:!1})).getFile(),w={kind:"file",size:h.size,mtime:new Date(h.lastModified).toISOString(),ctime:new Date(h.lastModified).toISOString(),isFile:!0,isDirectory:!1};if(s)try{const u=new Uint8Array(await h.arrayBuffer()),d=await P(u,c);w.hash=d}catch(u){console.warn(`Failed to calculate hash for ${e}:`,u)}return w}catch(l){if(l.name!=="TypeMismatchError"&&l.name!=="NotFoundError")throw new o("Failed to stat (file)","STAT_FAILED")}try{return await i.getDirectoryHandle(n,{create:!1}),{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0}}catch(l){throw l.name==="NotFoundError"?new o(`No such file or directory: ${e}`,"ENOENT"):new o("Failed to stat (directory)","STAT_FAILED")}}async readdir(e,t){const r=t?.withFileTypes??!1,n=await this.getDirectoryHandle(e,!1);if(r){const i=[];for await(const[s,c]of n.entries()){const l=c.kind==="file";i.push({name:s,kind:c.kind,isFile:l,isDirectory:!l})}return i}else{const i=[];for await(const[s]of n.entries())i.push(s);return i}}async exists(e){const t=f(e),r=t.pop();let n=null;try{n=await this.getDirectoryHandle(t,!1)}catch(i){throw(i.name==="NotFoundError"||i.name==="TypeMismatchError")&&(n=null),i}if(!n||!r)return!1;try{return await n.getFileHandle(r,{create:!1}),!0}catch(i){if(i.name!=="NotFoundError"&&i.name!=="TypeMismatchError")throw i}try{return await n.getDirectoryHandle(r,{create:!1}),!0}catch(i){if(i.name!=="NotFoundError"&&i.name!=="TypeMismatchError")throw i}return!1}async clear(e="/"){try{const t=await this.readdir(e,{withFileTypes:!0});for(const r of t){const n=`${e==="/"?"":e}/${r.name}`;await this.remove(n,{recursive:!0})}}catch(t){throw t instanceof o?t:new o(`Failed to clear directory: ${e}`,"CLEAR_FAILED")}}async remove(e,t){const r=t?.recursive??!1,n=t?.force??!1,i=f(e),s=i.pop();if(!s)throw new g("Invalid path",e);const c=await this.getDirectoryHandle(i,!1);try{await c.removeEntry(s,{recursive:r})}catch(l){if(l.name==="NotFoundError"){if(!n)throw new o(`No such file or directory: ${e}`,"ENOENT")}else throw l.name==="InvalidModificationError"?new o(`Directory not empty: ${e}. Use recursive option to force removal.`,"ENOTEMPTY"):l.name==="TypeMismatchError"&&!r?new o(`Cannot remove directory without recursive option: ${e}`,"EISDIR"):new o(`Failed to remove path: ${e}`,"RM_FAILED")}}async realpath(e){try{const t=f(e),r=[];for(const s of t)if(!(s==="."||s===""))if(s===".."){if(r.length===0)throw new o("Path escapes root","EINVAL");r.length>0&&r.pop()}else r.push(s);const n=p(r);if(!await this.exists(n))throw new m(n);return n}catch(t){throw t instanceof o?t:new o(`Failed to resolve path: ${e}`,"REALPATH_FAILED")}}async rename(e,t){try{if(!await this.exists(e))throw new m(e);await this.copy(e,t,{recursive:!0}),await this.remove(e,{recursive:!0})}catch(r){throw r instanceof o?r:new o(`Failed to rename from ${e} to ${t}`,"RENAME_FAILED")}}async copy(e,t,r){try{const n=r?.recursive??!1,i=r?.force??!0;if(!await this.exists(e))throw new o(`Source does not exist: ${e}`,"ENOENT");if(await this.exists(t)&&!i)throw new o(`Destination already exists: ${t}`,"EEXIST");if((await this.stat(e)).isFile){const h=await this.readFile(e,"binary");await this.writeFile(t,h)}else{if(!n)throw new o(`Cannot copy directory without recursive option: ${e}`,"EISDIR");await this.mkdir(t,{recursive:!0});const h=await this.readdir(e,{withFileTypes:!0});for(const w of h){const u=`${e}/${w.name}`,d=`${t}/${w.name}`;await this.copy(u,d,{recursive:!0,force:i})}}}catch(n){throw n instanceof o?n:new o(`Failed to copy from ${e} to ${t}`,"CP_FAILED")}}async watch(e){const t=e.startsWith("/")?e:`/${e}`,r=await this.buildSnapshot(t);this.watchers.set(t,r),this.watchTimer||(this.watchTimer=setInterval(()=>{this.scanWatches()},this.watchInterval))}unwatch(e){const t=e.startsWith("/")?e:`/${e}`;this.watchers.delete(t),this.watchers.size===0&&this.watchTimer&&(clearInterval(this.watchTimer),this.watchTimer=null)}async buildSnapshot(e){const t=new Map,r=async n=>{const i=await this.stat(n);if(t.set(n,i),i.isDirectory){const s=await this.readdir(n,{withFileTypes:!0});for(const c of s){const l=`${n==="/"?"":n}/${c.name}`;await r(l)}}};return await r(e),t}async scanWatches(){if(!this.scanning){this.scanning=!0;try{await Promise.all([...this.watchers.entries()].map(async([e,t])=>{let r;try{r=await this.buildSnapshot(e)}catch{r=new Map}const n=[];for(const[i,s]of r){const c=t.get(i);c?(c.mtime!==s.mtime||c.size!==s.size)&&n.push({path:i,type:"change"}):n.push({path:i,type:"create"})}for(const i of t.keys())r.has(i)||n.push({path:i,type:"delete"});if(n.length&&this.watchCallback)for(const i of n)this.watchCallback(i);this.watchers.set(e,r)}))}finally{this.scanning=!1}}}async sync(e,t){try{(t?.cleanBefore??!1)&&await this.clear("/");for(const[n,i]of e){const s=n.startsWith("/")?n:`/${n}`;let c;if(i instanceof Blob){const l=await i.arrayBuffer();c=new Uint8Array(l)}else c=i;await this.writeFile(s,c)}}catch(r){throw r instanceof o?r:new o("Failed to sync file system","SYNC_FAILED")}}}typeof self<"u"&&self.constructor.name==="DedicatedWorkerGlobalScope"&&S.expose(new E);exports.OPFSWorker=E;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("comlink"),i=require("./helpers-hEpet7x7.cjs");class f{root=null;watchCallback=null;watchers=new Map;watchTimer=null;watchInterval=1e3;scanning=!1;constructor(){i.checkOPFSSupport()}async mount(t="/",e,a){try{const r=await navigator.storage.getDirectory();return this.root=await this.getDirectoryHandle(t,!0,r),e&&(this.watchCallback=e,a?.watchInterval&&(this.watchInterval=a.watchInterval)),!0}catch(r){throw console.error(r),new i.OPFSError("Failed to initialize OPFS","INIT_FAILED")}}async getDirectoryHandle(t,e=!1,a=this.root){if(!a)throw new i.OPFSNotMountedError;const r=Array.isArray(t)?t:i.splitPath(t);let s=a;for(const n of r)s=await s.getDirectoryHandle(n,{create:e});return s}async getFileHandle(t,e=!1,a=this.root){if(!a)throw new i.OPFSNotMountedError;const r=i.splitPath(t);if(r.length===0)throw new i.PathError("Path must not be empty",Array.isArray(t)?t.join("/"):t);const s=r.pop();return(await this.getDirectoryHandle(r,e,a)).getFileHandle(s,{create:e})}async index(t){const e=new Map,a=async r=>{const s=await this.readdir(r,{withFileTypes:!0});for(const n of s){const o=`${r==="/"?"":r}/${n.name}`;try{const c=await this.stat(o,t);e.set(o,c),c.isDirectory&&await a(o)}catch(c){console.warn(`Skipping broken entry: ${o}`,c)}}};return e.set("/",{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0}),await a("/"),e}async readFile(t,e="utf-8"){try{const a=await this.getFileHandle(t,!1),r=await i.readFileData(a);return e==="binary"?r:i.decodeBuffer(r,e)}catch(a){throw console.error(a),new i.FileNotFoundError(t)}}async writeFile(t,e,a){const r=await this.getFileHandle(t,!0);await i.writeFileData(r,e,a,{truncate:!0})}async appendFile(t,e,a){const r=await this.getFileHandle(t,!0);await i.writeFileData(r,e,a,{append:!0})}async mkdir(t,e){if(!this.root)throw new i.OPFSNotMountedError;const a=e?.recursive??!1,r=i.splitPath(t);let s=this.root;for(let n=0;n<r.length;n++){const o=r[n];try{s=await s.getDirectoryHandle(o,{create:a||n===r.length-1})}catch(c){throw c.name==="NotFoundError"?new i.OPFSError(`Parent directory does not exist: ${i.joinPath(r.slice(0,n+1))}`,"ENOENT"):c.name==="TypeMismatchError"?new i.OPFSError(`Path segment is not a directory: ${o}`,"ENOTDIR"):new i.OPFSError("Failed to create directory","MKDIR_FAILED")}}}async stat(t,e){const a=i.basename(t),r=await this.getDirectoryHandle(i.dirname(t),!1),s=e?.includeHash??!1,n=e?.hashAlgorithm??"SHA-1";try{const c=await(await r.getFileHandle(a,{create:!1})).getFile(),l={kind:"file",size:c.size,mtime:new Date(c.lastModified).toISOString(),ctime:new Date(c.lastModified).toISOString(),isFile:!0,isDirectory:!1};if(s)try{const h=new Uint8Array(await c.arrayBuffer()),w=await i.calculateFileHash(h,n);l.hash=w}catch(h){console.warn(`Failed to calculate hash for ${t}:`,h)}return l}catch(o){if(o.name!=="TypeMismatchError"&&o.name!=="NotFoundError")throw new i.OPFSError("Failed to stat (file)","STAT_FAILED")}try{return await r.getDirectoryHandle(a,{create:!1}),{kind:"directory",size:0,mtime:new Date(0).toISOString(),ctime:new Date(0).toISOString(),isFile:!1,isDirectory:!0}}catch(o){throw o.name==="NotFoundError"?new i.OPFSError(`No such file or directory: ${t}`,"ENOENT"):new i.OPFSError("Failed to stat (directory)","STAT_FAILED")}}async readdir(t,e){const a=e?.withFileTypes??!1,r=await this.getDirectoryHandle(t,!1);if(a){const s=[];for await(const[n,o]of r.entries()){const c=o.kind==="file";s.push({name:n,kind:o.kind,isFile:c,isDirectory:!c})}return s}else{const s=[];for await(const[n]of r.entries())s.push(n);return s}}async exists(t){const e=i.basename(t);let a=null;try{a=await this.getDirectoryHandle(i.dirname(t),!1)}catch(r){throw(r.name==="NotFoundError"||r.name==="TypeMismatchError")&&(a=null),r}if(!a||!e)return!1;try{return await a.getFileHandle(e,{create:!1}),!0}catch(r){if(r.name!=="NotFoundError"&&r.name!=="TypeMismatchError")throw r}try{return await a.getDirectoryHandle(e,{create:!1}),!0}catch(r){if(r.name!=="NotFoundError"&&r.name!=="TypeMismatchError")throw r}return!1}async clear(t="/"){try{const e=await this.readdir(t,{withFileTypes:!0});for(const a of e){const r=`${t==="/"?"":t}/${a.name}`;await this.remove(r,{recursive:!0})}}catch(e){throw e instanceof i.OPFSError?e:new i.OPFSError(`Failed to clear directory: ${t}`,"CLEAR_FAILED")}}async remove(t,e){const a=e?.recursive??!1,r=e?.force??!1,s=i.basename(t);if(!s)throw new i.PathError("Invalid path",t);const n=await this.getDirectoryHandle(i.dirname(t),!1);try{await n.removeEntry(s,{recursive:a})}catch(o){if(o.name==="NotFoundError"){if(!r)throw new i.OPFSError(`No such file or directory: ${t}`,"ENOENT")}else throw o.name==="InvalidModificationError"?new i.OPFSError(`Directory not empty: ${t}. Use recursive option to force removal.`,"ENOTEMPTY"):o.name==="TypeMismatchError"&&!a?new i.OPFSError(`Cannot remove directory without recursive option: ${t}`,"EISDIR"):new i.OPFSError(`Failed to remove path: ${t}`,"RM_FAILED")}}async realpath(t){try{const e=i.resolvePath(t);if(!await this.exists(e))throw new i.FileNotFoundError(e);return e}catch(e){throw e instanceof i.OPFSError?e:new i.OPFSError(`Failed to resolve path: ${t}`,"REALPATH_FAILED")}}async rename(t,e){try{if(!await this.exists(t))throw new i.FileNotFoundError(t);await this.copy(t,e,{recursive:!0}),await this.remove(t,{recursive:!0})}catch(a){throw a instanceof i.OPFSError?a:new i.OPFSError(`Failed to rename from ${t} to ${e}`,"RENAME_FAILED")}}async copy(t,e,a){try{const r=a?.recursive??!1,s=a?.force??!0;if(!await this.exists(t))throw new i.OPFSError(`Source does not exist: ${t}`,"ENOENT");if(await this.exists(e)&&!s)throw new i.OPFSError(`Destination already exists: ${e}`,"EEXIST");if((await this.stat(t)).isFile){const l=await this.readFile(t,"binary");await this.writeFile(e,l)}else{if(!r)throw new i.OPFSError(`Cannot copy directory without recursive option: ${t}`,"EISDIR");await this.mkdir(e,{recursive:!0});const l=await this.readdir(t,{withFileTypes:!0});for(const h of l){const w=`${t}/${h.name}`,d=`${e}/${h.name}`;await this.copy(w,d,{recursive:!0,force:s})}}}catch(r){throw r instanceof i.OPFSError?r:new i.OPFSError(`Failed to copy from ${t} to ${e}`,"CP_FAILED")}}async watch(t){const e=i.normalizePath(t),a=await this.buildSnapshot(e);this.watchers.set(e,a),this.watchTimer||(this.watchTimer=setInterval(()=>{this.scanWatches()},this.watchInterval))}unwatch(t){const e=i.normalizePath(t);this.watchers.delete(e),this.watchers.size===0&&this.watchTimer&&(clearInterval(this.watchTimer),this.watchTimer=null)}async buildSnapshot(t){const e=new Map,a=async r=>{const s=await this.stat(r);if(e.set(r,s),s.isDirectory){const n=await this.readdir(r,{withFileTypes:!0});for(const o of n){const c=`${r==="/"?"":r}/${o.name}`;await a(c)}}};return await a(t),e}async scanWatches(){if(!this.scanning){this.scanning=!0;try{await Promise.all([...this.watchers.entries()].map(async([t,e])=>{let a;try{a=await this.buildSnapshot(t)}catch{a=new Map}const r=[];for(const[s,n]of a){const o=e.get(s);o?(o.mtime!==n.mtime||o.size!==n.size)&&r.push({path:s,type:"change"}):r.push({path:s,type:"create"})}for(const s of e.keys())a.has(s)||r.push({path:s,type:"delete"});if(r.length&&this.watchCallback)for(const s of r)this.watchCallback(s);this.watchers.set(t,a)}))}finally{this.scanning=!1}}}async sync(t,e){try{(e?.cleanBefore??!1)&&await this.clear("/");for(const[r,s]of t){const n=i.normalizePath(r);let o;s instanceof Blob?o=await i.convertBlobToUint8Array(s):o=s,await this.writeFile(n,o)}}catch(a){throw a instanceof i.OPFSError?a:new i.OPFSError("Failed to sync file system","SYNC_FAILED")}}}typeof self<"u"&&self.constructor.name==="DedicatedWorkerGlobalScope"&&y.expose(new f);exports.OPFSWorker=f;
|
|
2
2
|
//# sourceMappingURL=raw.cjs.map
|
package/dist/raw.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"raw.cjs","sources":["../src/utils/errors.ts","../src/utils/encoder.ts","../src/utils/helpers.ts","../src/worker.ts"],"sourcesContent":["/**\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 // For binary encoding, treat the string as raw bytes\n // This assumes the string contains raw byte values\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 // For binary encoding, return raw byte values as string\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\nexport function checkOPFSSupport(): void {\n if (!('storage' in navigator) || !('getDirectory' in (navigator.storage as any))) {\n throw new OPFSNotSupportedError();\n }\n}\n\nexport function splitPath(path: string | string[]): string[] {\n if (Array.isArray(path)) {\n return path;\n }\n\n return path.split('/').filter(Boolean);\n}\n\nexport function joinPath(segments: string[] | string): string {\n return typeof segments === 'string'\n ? (segments ?? '/')\n : `/${ segments.join('/') }`;\n}\n\nexport function createBuffer(data: string | Uint8Array | ArrayBuffer, encoding: BufferEncoding = 'utf-8'): Uint8Array {\n if (typeof data === 'string') {\n return encodeString(data, encoding);\n }\n\n return data instanceof Uint8Array ? data : new Uint8Array(data);\n}\n\n\n/**\n * Read raw binary data from a file using a file handle\n *\n * @param fileHandle - The file handle to read from\n * @returns The raw binary data as Uint8Array\n */\nexport async function readFileData(fileHandle: FileSystemFileHandle): Promise<Uint8Array> {\n const handle = await fileHandle.createSyncAccessHandle();\n\n try {\n const size = handle.getSize();\n const buffer = new Uint8Array(size);\n\n handle.read(buffer, { at: 0 });\n\n return buffer;\n }\n finally {\n handle.close();\n }\n}\n\n/**\n * Write data to a file using a file handle\n *\n * @param fileHandle - The file handle to write to\n * @param data - The data to write to the file\n * @param encoding - The encoding to use\n * @param options - Write options (truncate or append)\n */\nexport async function writeFileData(\n fileHandle: FileSystemFileHandle,\n data: string | Uint8Array | ArrayBuffer,\n encoding?: BufferEncoding,\n options: { truncate?: boolean; append?: boolean } = {}\n): Promise<void> {\n let handle: FileSystemSyncAccessHandle | null = null;\n\n try {\n handle = await fileHandle.createSyncAccessHandle();\n\n const buffer = createBuffer(data, encoding);\n const writeOffset = options.append ? handle.getSize() : 0;\n\n handle.write(buffer, { at: writeOffset });\n\n if (options.truncate && !options.append) {\n handle.truncate(buffer.byteLength);\n }\n\n handle.flush();\n }\n catch (error) {\n console.error(error);\n const operation = options.append ? 'append' : 'write';\n\n throw new OPFSError(`Failed to ${ operation } file`, `${ operation.toUpperCase() }_FAILED`);\n }\n finally {\n if (handle) {\n try {\n handle.close();\n }\n catch { /* ~ */ }\n }\n }\n}\n\n/**\n * Calculate file hash using Web Crypto API\n * \n * @param buffer - The file content as Uint8Array\n * @param algorithm - Hash algorithm to use (default: 'SHA-1')\n * @returns Promise that resolves to the hash string\n */\nexport async function calculateFileHash(buffer: Uint8Array, algorithm: string = 'SHA-1'): Promise<string> {\n try {\n // Ensure buffer is properly typed for crypto.subtle.digest\n const bufferSource = new Uint8Array(buffer);\n const hashBuffer = await crypto.subtle.digest(algorithm, bufferSource);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n\n return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n }\n catch (error) {\n console.warn(`Failed to calculate ${ algorithm } hash:`, error);\n\n throw error;\n }\n}\n","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 { calculateFileHash, checkOPFSSupport, joinPath, readFileData, splitPath, writeFileData } from './utils/helpers';\n\nimport type { DirentData, FileStat, WatchEvent } from './types';\nimport type { BufferEncoding } from 'typescript';\n\n/**\n * OPFS (Origin Private File System) File System implementation\n * \n * This class provides a high-level interface for working with the browser's\n * Origin Private File System API, offering file and directory operations\n * similar to Node.js fs module.\n * \n * @example\n * ```typescript\n * const fs = new OPFSFileSystem();\n * await fs.init('/my-app');\n * await fs.writeFile('/data/config.json', JSON.stringify({ theme: 'dark' }));\n * const config = await fs.readFile('/data/config.json');\n * ```\n */\nexport class OPFSWorker {\n /** Root directory handle for the file system */\n private root: FileSystemDirectoryHandle | null = null;\n\n /** Watch event callback */\n private watchCallback: ((event: WatchEvent) => void) | null = null;\n\n /** Map of watched paths to their last known state */\n private watchers = new Map<string, Map<string, FileStat>>();\n\n /** Interval handle for polling watched paths */\n private watchTimer: ReturnType<typeof setInterval> | null = null;\n\n /** Polling interval in milliseconds */\n private watchInterval = 1000;\n\n /** Flag to avoid concurrent scans */\n private scanning = false;\n\n /**\n * Creates a new OPFSFileSystem instance\n * \n * @throws {OPFSError} If OPFS is not supported in the current browser\n */\n constructor() {\n checkOPFSSupport();\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 * It must be called before any other file system operations.\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 * const success = await fs.init('/my-app');\n * ```\n */\n async mount(root: string = '/', watchCallback?: (event: WatchEvent) => void, options?: { watchInterval?: number }): Promise<boolean> {\n try {\n const rootDir = await navigator.storage.getDirectory();\n\n this.root = await this.getDirectoryHandle(root, true, rootDir);\n\n if (watchCallback) {\n this.watchCallback = watchCallback;\n if (options?.watchInterval) {\n this.watchInterval = options.watchInterval;\n }\n }\n\n return true;\n }\n catch (error) {\n console.error(error);\n\n throw new OPFSError('Failed to initialize OPFS', 'INIT_FAILED');\n }\n }\n\n /**\n * Get a directory handle from a path\n * \n * Navigates through the directory structure to find or create a directory\n * at the specified path.\n * \n * @param path - The path to the directory (string or array of segments)\n * @param create - Whether to create the directory if it doesn't exist (default: false)\n * @param from - The directory to start from (default: root directory)\n * @returns Promise that resolves to the directory handle\n * @throws {OPFSError} If the directory cannot be accessed or created\n * \n * @example\n * ```typescript\n * const docsDir = await fs.getDirectoryHandle('/users/john/documents', true);\n * const docsDir2 = await fs.getDirectoryHandle(['users', 'john', 'documents'], true);\n * ```\n */\n private async getDirectoryHandle(path: string | string[], create: boolean = false, from: FileSystemDirectoryHandle | null = this.root): Promise<FileSystemDirectoryHandle> {\n if (!from) {\n throw new OPFSNotMountedError();\n }\n\n const segments = Array.isArray(path) ? path : splitPath(path);\n let current = from;\n\n for (const segment of segments) {\n current = await current.getDirectoryHandle(segment, { create });\n }\n\n return current;\n }\n\n /**\n * Get a file handle from a path\n * \n * Navigates to the parent directory and retrieves or creates a file handle\n * for the specified file path.\n * \n * @param path - The path to the file (string or array of segments)\n * @param create - Whether to create the file if it doesn't exist (default: false)\n * @param from - The directory to start from (default: root directory)\n * @returns Promise that resolves to the file handle\n * @throws {PathError} If the path is empty\n * @throws {OPFSError} If the file cannot be accessed or created\n * \n * @example\n * ```typescript\n * const fileHandle = await fs.getFileHandle('/config/settings.json', true);\n * const fileHandle2 = await fs.getFileHandle(['config', 'settings.json'], true);\n * ```\n */\n private async getFileHandle(path: string | string[], create = false, from: FileSystemDirectoryHandle | null = this.root): Promise<FileSystemFileHandle> {\n if (!from) {\n throw new OPFSNotMountedError();\n }\n\n const segments = splitPath(path);\n\n if (segments.length === 0) {\n throw new PathError('Path must not be empty', Array.isArray(path) ? path.join('/') : path);\n }\n\n const fileName = segments.pop()!;\n const dir = await this.getDirectoryHandle(segments, create, from);\n\n return dir.getFileHandle(fileName, { create });\n }\n\n\n /**\n * Recursively list all files and directories with their stats\n * \n * Traverses the entire file system starting from the root and returns\n * a Map containing all paths and their corresponding file statistics.\n * \n * @param options - Options for indexing\n * @param options.includeHash - Whether to calculate file hash (default: false)\n * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)\n * @returns Promise that resolves to a Map of path => FileStat\n * @throws {OPFSError} If the indexing operation fails\n * \n * @example\n * ```typescript\n * // Basic index without hash\n * const index = await fs.index();\n * \n * // Index with file hash\n * const indexWithHash = await fs.index({ \n * includeHash: true,\n * hashAlgorithm: 'SHA-1'\n * });\n * \n * // Iterate through all files and directories\n * for (const [path, stat] of index) {\n * console.log(`${path}: ${stat.isFile ? 'file' : 'directory'} (${stat.size} bytes)`);\n * if (stat.hash) console.log(` Hash: ${stat.hash}`);\n * }\n * \n * // Get specific file stats\n * const fileStats = index.get('/data/config.json');\n * if (fileStats) {\n * console.log(`File size: ${fileStats.size} bytes`);\n * if (fileStats.hash) console.log(`Hash: ${fileStats.hash}`);\n * }\n * ```\n */\n async index(options?: { includeHash?: boolean; hashAlgorithm?: 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512' }): Promise<Map<string, FileStat>> {\n const result = new Map<string, FileStat>();\n\n const walk = async(dirPath: string) => {\n const items = await this.readdir(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = `${ dirPath === '/' ? '' : dirPath }/${ item.name }`;\n\n try {\n const stat = await this.stat(fullPath, options);\n\n result.set(fullPath, stat);\n\n if (stat.isDirectory) {\n await walk(fullPath);\n }\n }\n catch (err) {\n console.warn(`Skipping broken entry: ${ fullPath }`, err);\n }\n }\n };\n\n // Add root directory\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 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 const fileHandle = await this.getFileHandle(path, true);\n\n await writeFileData(fileHandle, data, encoding, { truncate: true });\n }\n\n /**\n * Append data to a file\n * \n * Adds data to the end of an existing file. If the file doesn't exist,\n * it will be created.\n * \n * @param path - The path to the file to append to\n * @param data - The data to append to the file (string, Uint8Array, or ArrayBuffer)\n * @param encoding - The encoding to use when appending string data (default: 'utf-8')\n * @returns Promise that resolves when the append operation is complete\n * @throws {OPFSError} If appending to the file fails\n * \n * @example\n * ```typescript\n * // Append text to a log file\n * await fs.appendFile('/logs/app.log', `[${new Date().toISOString()}] User logged in\\n`);\n * \n * // Append binary data\n * const additionalData = new Uint8Array([6, 7, 8]);\n * await fs.appendFile('/data/binary.dat', additionalData);\n * ```\n */\n async appendFile(\n path: string,\n data: string | Uint8Array | ArrayBuffer,\n encoding?: BufferEncoding\n ): Promise<void> {\n const fileHandle = await this.getFileHandle(path, true);\n\n await writeFileData(fileHandle, data, encoding, { append: true });\n }\n\n /**\n * Create a directory\n * \n * Creates a new directory at the specified path. If the recursive option\n * is enabled, parent directories will be created as needed.\n * \n * @param path - The path where the directory should be created\n * @param options - Options for directory creation\n * @param options.recursive - Whether to create parent directories if they don't exist (default: false)\n * @returns Promise that resolves when the directory is created\n * @throws {OPFSError} If the directory cannot be created\n * \n * @example\n * ```typescript\n * // Create a single directory\n * await fs.mkdir('/users/john');\n * \n * // Create nested directories\n * await fs.mkdir('/users/john/documents/projects', { recursive: true });\n * ```\n */\n async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n if (!this.root) {\n throw new OPFSNotMountedError();\n }\n\n const recursive = options?.recursive ?? false;\n const segments = splitPath(path);\n\n let current = this.root;\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n\n try {\n current = await current.getDirectoryHandle(segment!, { create: recursive || i === segments.length - 1 });\n }\n catch (e: any) {\n if (e.name === 'NotFoundError') {\n throw new OPFSError(\n `Parent directory does not exist: ${ joinPath(segments.slice(0, i + 1)) }`,\n 'ENOENT'\n );\n }\n\n if (e.name === 'TypeMismatchError') {\n throw new OPFSError(`Path segment is not a directory: ${ segment }`, 'ENOTDIR');\n }\n\n throw new OPFSError('Failed to create directory', 'MKDIR_FAILED');\n }\n }\n }\n\n /**\n * Get file or directory stats\n * \n * Retrieves metadata about a file or directory, including size, modification time,\n * type information, and optionally file hashes.\n * \n * @param path - The path to the file or directory\n * @param options - Options for stat operation\n * @param options.includeHash - Whether to calculate file hash (default: false, only for files)\n * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)\n * @returns Promise that resolves to file/directory statistics\n * @throws {OPFSError} If the file or directory does not exist or cannot be accessed\n * \n * @example\n * ```typescript\n * // Basic stats\n * const stats = await fs.stat('/config/settings.json');\n * console.log(`File size: ${stats.size} bytes`);\n * console.log(`Is file: ${stats.isFile}`);\n * console.log(`Modified: ${stats.mtime}`);\n * \n * // Stats with hash (SHA-1 is fastest)\n * const statsWithHash = await fs.stat('/config/settings.json', { \n * includeHash: true,\n * hashAlgorithm: 'SHA-1'\n * });\n * console.log(`Hash: ${statsWithHash.hash}`);\n * ```\n */\n async stat(path: string, options?: { includeHash?: boolean; hashAlgorithm?: 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512' }): Promise<FileStat> {\n const segments = splitPath(path);\n const name = segments.pop();\n const parentDir = await this.getDirectoryHandle(segments, false);\n const includeHash = options?.includeHash ?? false;\n const hashAlgorithm = options?.hashAlgorithm ?? 'SHA-1';\n\n // Get as file first\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 // Calculate hash if requested\n if (includeHash) {\n try {\n const buffer = new Uint8Array(await file.arrayBuffer());\n const hash = await calculateFileHash(buffer, hashAlgorithm);\n\n baseStat.hash = hash;\n }\n catch (error) {\n console.warn(`Failed to calculate hash for ${ path }:`, error);\n }\n }\n\n return baseStat;\n }\n catch (e: any) {\n if (e.name !== 'TypeMismatchError' && e.name !== 'NotFoundError') {\n throw new OPFSError('Failed to stat (file)', 'STAT_FAILED');\n }\n }\n\n // Get as directory\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 // Directories don't have hashes\n };\n }\n catch (e: any) {\n if (e.name === 'NotFoundError') {\n throw new OPFSError(`No such file or directory: ${ path }`, 'ENOENT');\n }\n\n throw new OPFSError('Failed to stat (directory)', 'STAT_FAILED');\n }\n }\n\n /**\n * Read a directory's contents\n * \n * Lists all files and subdirectories within the specified directory.\n * \n * @param path - The path to the directory to read\n * @param options - Options for the readdir operation\n * @param options.withFileTypes - Whether to return detailed file information (default: false)\n * @returns Promise that resolves to an array of file/directory names or detailed information\n * @throws {OPFSError} If the directory does not exist or cannot be accessed\n * \n * @example\n * ```typescript\n * // Get simple list of names\n * const files = await fs.readdir('/users/john/documents');\n * console.log('Files:', files); // ['readme.txt', 'config.json', 'images']\n * \n * // Get detailed information\n * const detailed = await fs.readdir('/users/john/documents', { withFileTypes: true });\n * detailed.forEach(item => {\n * console.log(`${item.name} - ${item.isFile ? 'file' : 'directory'}`);\n * });\n * ```\n */\n async readdir(path: string): Promise<string[]>;\n async readdir(path: string, options: { withFileTypes: true }): Promise<DirentData[]>;\n async readdir(path: string, options: { withFileTypes: false }): Promise<string[]>;\n async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirentData[]> {\n const withTypes = options?.withFileTypes ?? false;\n const dir = await this.getDirectoryHandle(path, false);\n\n // Use type assertion to access the entries() method\n if (withTypes) {\n const results: DirentData[] = [];\n\n for await (const [name, handle] of (dir as any).entries()) {\n const isFile = handle.kind === 'file';\n\n results.push({\n name,\n kind: handle.kind,\n isFile,\n isDirectory: !isFile,\n });\n }\n\n return results;\n }\n else {\n const results: string[] = [];\n\n for await (const [name] of (dir as any).entries()) {\n results.push(name);\n }\n\n return results;\n }\n }\n\n /**\n * Check if a file or directory exists\n * \n * Verifies if a file or directory exists at the specified path.\n * \n * @param path - The path to check\n * @returns Promise that resolves to true if the file or directory exists, false otherwise \n * \n * @example\n * ```typescript\n * const exists = await fs.exists('/config/settings.json');\n * console.log(`File exists: ${exists}`);\n * ```\n */\n async exists(path: string): Promise<boolean> {\n const segments = splitPath(path);\n const name = segments.pop();\n let dir: FileSystemDirectoryHandle | null = null;\n\n try {\n dir = await this.getDirectoryHandle(segments, 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 // Get as file\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 // Get as directory\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 try {\n const items = await this.readdir(path, { withFileTypes: true });\n\n for (const item of items) {\n const itemPath = `${ path === '/' ? '' : path }/${ item.name }`;\n\n await this.remove(itemPath, { recursive: true });\n }\n }\n catch (error: any) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to clear directory: ${ path }`, 'CLEAR_FAILED');\n }\n }\n\n /**\n * Remove files and directories\n * \n * Removes files and directories. Similar to Node.js fs.rm().\n * \n * @param path - The path to remove\n * @param options - Options for removal\n * @param options.recursive - Whether to remove directories and their contents recursively (default: false)\n * @param options.force - Whether to ignore errors if the path doesn't exist (default: false)\n * @returns Promise that resolves when the removal is complete\n * @throws {OPFSError} If the removal fails\n * \n * @example\n * ```typescript\n * // Remove a file\n * await fs.rm('/path/to/file.txt');\n * \n * // Remove a directory and all its contents\n * await fs.rm('/path/to/directory', { recursive: true });\n * \n * // Remove with force (ignore if doesn't exist)\n * await fs.rm('/maybe/exists', { force: true });\n * ```\n */\n async remove(path: string, options?: { recursive?: boolean; force?: boolean }): Promise<void> {\n const recursive = options?.recursive ?? false;\n const force = options?.force ?? false;\n\n const segments = splitPath(path);\n const name = segments.pop();\n\n if (!name) {\n throw new PathError('Invalid path', path);\n }\n\n const parent = await this.getDirectoryHandle(segments, false);\n\n try {\n await parent.removeEntry(name, { recursive });\n }\n catch (e: any) {\n if (e.name === 'NotFoundError') {\n if (!force) {\n throw new OPFSError(`No such file or directory: ${ path }`, 'ENOENT');\n }\n }\n else if (e.name === 'InvalidModificationError') {\n throw new OPFSError(`Directory not empty: ${ path }. Use recursive option to force removal.`, 'ENOTEMPTY');\n }\n else if (e.name === 'TypeMismatchError' && !recursive) {\n throw new OPFSError(`Cannot remove directory without recursive option: ${ path }`, 'EISDIR');\n }\n else {\n throw new OPFSError(`Failed to remove path: ${ path }`, 'RM_FAILED');\n }\n }\n }\n\n /**\n * Resolve a path to an absolute path\n * \n * Resolves relative paths and normalizes path segments (like '..' and '.').\n * Similar to Node.js fs.realpath() but without symlink resolution since OPFS doesn't support symlinks.\n * \n * @param path - The path to resolve\n * @returns Promise that resolves to the absolute normalized path\n * @throws {FileNotFoundError} If the path does not exist\n * @throws {OPFSError} If path resolution fails\n * \n * @example\n * ```typescript\n * // Resolve relative path\n * const absolute = await fs.realpath('./config/../data/file.txt');\n * console.log(absolute); // '/data/file.txt'\n * ```\n */\n async realpath(path: string): Promise<string> {\n try {\n const segments = splitPath(path);\n const normalizedSegments: string[] = [];\n\n for (const segment of segments) {\n if (segment === '.' || segment === '') {\n // Skip current directory references and empty segments\n continue;\n }\n else if (segment === '..') {\n if (normalizedSegments.length === 0) {\n throw new OPFSError('Path escapes root', 'EINVAL');\n }\n\n // Go up one directory\n if (normalizedSegments.length > 0) {\n normalizedSegments.pop();\n }\n }\n else {\n // Regular segment\n normalizedSegments.push(segment);\n }\n }\n\n const normalizedPath = joinPath(normalizedSegments);\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 try {\n // Check if source exists\n const sourceExists = await this.exists(oldPath);\n\n if (!sourceExists) {\n throw new FileNotFoundError(oldPath);\n }\n\n await this.copy(oldPath, newPath, { recursive: true });\n await this.remove(oldPath, { recursive: true });\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to rename from ${ oldPath } to ${ newPath }`, 'RENAME_FAILED');\n }\n }\n\n /**\n * Copy files and directories\n * \n * Copies files and directories. Similar to Node.js fs.cp().\n * \n * @param source - The source path to copy from\n * @param destination - The destination path to copy to\n * @param options - Options for copying\n * @param options.recursive - Whether to copy directories recursively (default: false)\n * @param options.force - Whether to overwrite existing files (default: true)\n * @returns Promise that resolves when the copy operation is complete\n * @throws {OPFSError} If the copy operation fails\n * \n * @example\n * ```typescript\n * // Copy a file\n * await fs.cp('/source/file.txt', '/dest/file.txt');\n * \n * // Copy a directory and all its contents\n * await fs.cp('/source/dir', '/dest/dir', { recursive: true });\n * \n * // Copy without overwriting existing files\n * await fs.cp('/source', '/dest', { recursive: true, force: false });\n * ```\n */\n async copy(source: string, destination: string, options?: { recursive?: boolean; force?: boolean }): Promise<void> {\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 // Check if destination exists and handle accordingly\n const destExists = await this.exists(destination);\n\n if (destExists && !force) {\n throw new OPFSError(`Destination already exists: ${ destination }`, 'EEXIST');\n }\n\n // Get source stats to determine if it's a file or directory\n const sourceStats = await this.stat(source);\n\n if (sourceStats.isFile) {\n // Copy file\n const content = await this.readFile(source, 'binary');\n\n await this.writeFile(destination, content);\n }\n else {\n // Copy directory\n if (!recursive) {\n throw new OPFSError(`Cannot copy directory without recursive option: ${ source }`, 'EISDIR');\n }\n\n // Create destination directory\n await this.mkdir(destination, { recursive: true });\n\n // Copy all contents\n const items = await this.readdir(source, { withFileTypes: true });\n\n for (const item of items) {\n const sourceItemPath = `${ source }/${ item.name }`;\n const destItemPath = `${ destination }/${ item.name }`;\n\n // Recursively copy each item\n await this.copy(sourceItemPath, destItemPath, { recursive: true, force });\n }\n }\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to copy from ${ source } to ${ destination }`, 'CP_FAILED');\n }\n }\n\n /**\n * Start watching a file or directory for changes\n */\n async watch(path: string): Promise<void> {\n const normalizedPath = path.startsWith('/') ? path : `/${ path }`;\n const snapshot = await this.buildSnapshot(normalizedPath);\n this.watchers.set(normalizedPath, snapshot);\n\n if (!this.watchTimer) {\n this.watchTimer = setInterval(() => {\n void this.scanWatches();\n }, this.watchInterval);\n }\n }\n\n /**\n * Stop watching a previously watched path\n */\n unwatch(path: string): void {\n const normalizedPath = path.startsWith('/') ? path : `/${ path }`;\n this.watchers.delete(normalizedPath);\n\n if (this.watchers.size === 0 && this.watchTimer) {\n clearInterval(this.watchTimer);\n this.watchTimer = null;\n }\n }\n\n private async buildSnapshot(rootPath: string): Promise<Map<string, FileStat>> {\n const result = new Map<string, FileStat>();\n\n const walk = async (current: string) => {\n const stat = await this.stat(current);\n result.set(current, stat);\n\n if (stat.isDirectory) {\n const entries = await this.readdir(current, { withFileTypes: true });\n for (const entry of entries) {\n const child = `${ current === '/' ? '' : current }/${ entry.name }`;\n await walk(child);\n }\n }\n };\n\n await walk(rootPath);\n return result;\n }\n\n private async scanWatches(): Promise<void> {\n if (this.scanning) {\n return;\n }\n\n this.scanning = true;\n\n try {\n await Promise.all(\n [...this.watchers.entries()].map(async ([rootPath, prev]) => {\n let next: Map<string, FileStat>;\n\n try {\n next = await this.buildSnapshot(rootPath);\n }\n catch {\n next = new Map();\n }\n\n const events: WatchEvent[] = [];\n\n for (const [p, stat] of next) {\n const old = prev.get(p);\n if (!old) {\n events.push({ path: p, type: 'create' });\n }\n else if (old.mtime !== stat.mtime || old.size !== stat.size) {\n events.push({ path: p, type: 'change' });\n }\n }\n\n for (const p of prev.keys()) {\n if (!next.has(p)) {\n events.push({ path: p, type: 'delete' });\n }\n }\n\n if (events.length && this.watchCallback) {\n for (const event of events) {\n this.watchCallback(event);\n }\n }\n\n this.watchers.set(rootPath, next);\n })\n );\n }\n finally {\n this.scanning = false;\n }\n }\n\n /**\n * Synchronize the file system with external data\n * \n * Syncs the file system with an array of entries containing paths and data.\n * This is useful for importing data from external sources or syncing with remote data.\n * \n * @param entries - Array of [path, data] tuples to sync\n * @param options - Options for synchronization\n * @param options.cleanBefore - Whether to clear the file system before syncing (default: false)\n * @returns Promise that resolves when synchronization is complete\n * @throws {OPFSError} If the synchronization fails\n * \n * @example\n * ```typescript\n * // Sync with external data\n * const entries: [string, string | Uint8Array | Blob][] = [\n * ['/config.json', JSON.stringify({ theme: 'dark' })],\n * ['/data/binary.dat', new Uint8Array([1, 2, 3, 4])],\n * ['/upload.txt', new Blob(['file content'], { type: 'text/plain' })]\n * ];\n * \n * // Sync without clearing existing files\n * await fs.sync(entries);\n * \n * // Clean file system and then sync\n * await fs.sync(entries, { cleanBefore: true });\n * ```\n */\n async sync(entries: [string, string | Uint8Array | Blob][], options?: { cleanBefore?: boolean }): Promise<void> {\n try {\n const cleanBefore = options?.cleanBefore ?? false;\n\n // Clear file system if requested\n if (cleanBefore) {\n await this.clear('/');\n }\n\n // Process each entry\n for (const [path, data] of entries) {\n // Normalize path to ensure it starts with /\n const normalizedPath = path.startsWith('/') ? path : `/${ path }`;\n\n // Convert data to appropriate format\n let fileData: string | Uint8Array;\n\n if (data instanceof Blob) {\n // Convert Blob to Uint8Array\n const arrayBuffer = await data.arrayBuffer();\n\n fileData = new Uint8Array(arrayBuffer);\n }\n else {\n fileData = data;\n }\n\n // Write the file (this will create directories as needed)\n await this.writeFile(normalizedPath, fileData);\n }\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError('Failed to sync file system', 'SYNC_FAILED');\n }\n }\n}\n\n// Only expose the worker when running in a Web Worker environment\nif (typeof self !== 'undefined' && self.constructor.name === 'DedicatedWorkerGlobalScope') {\n expose(new OPFSWorker());\n}\n"],"names":["OPFSError","message","code","path","OPFSNotSupportedError","OPFSNotMountedError","PathError","FileNotFoundError","encodeString","data","encoding","encodeUtf16LE","encodeAscii","encodeLatin1","char","c","b","decodeBuffer","buffer","decodeUtf16LE","str","buf","i","codeUnits","checkOPFSSupport","splitPath","joinPath","segments","createBuffer","readFileData","fileHandle","handle","size","writeFileData","options","writeOffset","error","operation","calculateFileHash","algorithm","bufferSource","hashBuffer","OPFSWorker","root","watchCallback","rootDir","create","from","current","segment","fileName","result","walk","dirPath","items","item","fullPath","stat","err","recursive","e","name","parentDir","includeHash","hashAlgorithm","file","baseStat","hash","withTypes","dir","results","isFile","itemPath","force","parent","normalizedSegments","normalizedPath","oldPath","newPath","source","destination","content","sourceItemPath","destItemPath","snapshot","rootPath","entries","entry","child","prev","next","events","p","old","event","fileData","arrayBuffer","expose"],"mappings":"2GAGO,MAAMA,UAAkB,KAAM,CACjC,YAAYC,EAAiCC,EAA8BC,EAAe,CACtF,MAAMF,CAAO,EAD4B,KAAA,KAAAC,EAA8B,KAAA,KAAAC,EAEvE,KAAK,KAAO,WAChB,CACJ,CAKO,MAAMC,UAA8BJ,CAAU,CACjD,aAAc,CACV,MAAM,wCAAyC,oBAAoB,CACvE,CACJ,CAMO,MAAMK,UAA4BL,CAAU,CAC/C,aAAc,CACV,MAAM,sBAAuB,kBAAkB,CACnD,CACJ,CAKO,MAAMM,UAAkBN,CAAU,CACrC,YAAYC,EAAiBE,EAAc,CACvC,MAAMF,EAAS,eAAgBE,CAAI,CACvC,CACJ,CAKO,MAAMI,UAA0BP,CAAU,CAC7C,YAAYG,EAAc,CACtB,MAAM,mBAAoBA,CAAK,GAAI,iBAAkBA,CAAI,CAC7D,CACJ,CCzCO,SAASK,EAAaC,EAAcC,EAA2B,QAAqB,CACvF,OAAQA,EAAA,CACJ,IAAK,OACL,IAAK,QACD,OAAO,IAAI,YAAA,EAAc,OAAOD,CAAI,EAExC,IAAK,UACL,IAAK,OACL,IAAK,QACD,OAAOE,EAAcF,CAAI,EAE7B,IAAK,QACD,OAAOG,EAAYH,CAAI,EAE3B,IAAK,SACD,OAAOI,EAAaJ,CAAI,EAE5B,IAAK,SAGD,OAAO,WAAW,KAAKA,KAAcK,EAAK,WAAW,CAAC,CAAC,EAE3D,IAAK,S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CAAC,GACXD,EAAO,KAAK,CAAE,KAAMC,EAAG,KAAM,SAAU,EAI/C,GAAID,EAAO,QAAU,KAAK,cACtB,UAAWG,KAASH,EAChB,KAAK,cAAcG,CAAK,EAIhC,KAAK,SAAS,IAAIT,EAAUK,CAAI,CACpC,CAAC,CAAA,CAET,QAAA,CAEI,KAAK,SAAW,EACpB,EACJ,CA8BA,MAAM,KAAKJ,EAAiDpD,EAAoD,CAC5G,GAAI,EACoBA,GAAS,aAAe,KAIxC,MAAM,KAAK,MAAM,GAAG,EAIxB,SAAW,CAAC/B,EAAMM,CAAI,IAAK6E,EAAS,CAEhC,MAAMV,EAAiBzE,EAAK,WAAW,GAAG,EAAIA,EAAO,IAAKA,CAAK,GAG/D,IAAI4F,EAEJ,GAAItF,aAAgB,KAAM,CAEtB,MAAMuF,EAAc,MAAMvF,EAAK,YAAA,EAE/BsF,EAAW,IAAI,WAAWC,CAAW,CACzC,MAEID,EAAWtF,EAIf,MAAM,KAAK,UAAUmE,EAAgBmB,CAAQ,CACjD,CACJ,OACO3D,EAAO,CACV,MAAIA,aAAiBpC,EACXoC,EAGJ,IAAIpC,EAAU,6BAA8B,aAAa,CACnE,CACJ,CACJ,CAGI,OAAO,KAAS,KAAe,KAAK,YAAY,OAAS,8BAC3DiG,EAAAA,OAAO,IAAIvD,CAAY"}
|
|
1
|
+
{"version":3,"file":"raw.cjs","sources":["../src/worker.ts"],"sourcesContent":["import { expose } from 'comlink';\n\nimport { decodeBuffer } from './utils/encoder';\nimport {\n FileNotFoundError,\n OPFSError,\n OPFSNotMountedError,\n PathError\n} from './utils/errors';\n\nimport { \n calculateFileHash, \n checkOPFSSupport, \n joinPath, \n readFileData, \n splitPath, \n writeFileData,\n basename,\n dirname,\n normalizePath,\n resolvePath,\n convertBlobToUint8Array\n} from './utils/helpers';\n\nimport type { DirentData, FileStat, WatchEvent } from './types';\nimport type { BufferEncoding } from 'typescript';\n\n/**\n * OPFS (Origin Private File System) File System implementation\n * \n * This class provides a high-level interface for working with the browser's\n * Origin Private File System API, offering file and directory operations\n * similar to Node.js fs module.\n * \n * @example\n * ```typescript\n * const fs = new OPFSFileSystem();\n * await fs.init('/my-app');\n * await fs.writeFile('/data/config.json', JSON.stringify({ theme: 'dark' }));\n * const config = await fs.readFile('/data/config.json');\n * ```\n */\nexport class OPFSWorker {\n /** Root directory handle for the file system */\n private root: FileSystemDirectoryHandle | null = null;\n\n /** Watch event callback */\n private watchCallback: ((event: WatchEvent) => void) | null = null;\n\n /** Map of watched paths to their last known state */\n private watchers = new Map<string, Map<string, FileStat>>();\n\n /** Interval handle for polling watched paths */\n private watchTimer: ReturnType<typeof setInterval> | null = null;\n\n /** Polling interval in milliseconds */\n private watchInterval = 1000;\n\n /** Flag to avoid concurrent scans */\n private scanning = false;\n\n /**\n * Creates a new OPFSFileSystem instance\n * \n * @throws {OPFSError} If OPFS is not supported in the current browser\n */\n constructor() {\n checkOPFSSupport();\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 * It must be called before any other file system operations.\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 * const success = await fs.init('/my-app');\n * ```\n */\n async mount(root: string = '/', watchCallback?: (event: WatchEvent) => void, options?: { watchInterval?: number }): Promise<boolean> {\n try {\n const rootDir = await navigator.storage.getDirectory();\n\n this.root = await this.getDirectoryHandle(root, true, rootDir);\n\n if (watchCallback) {\n this.watchCallback = watchCallback;\n if (options?.watchInterval) {\n this.watchInterval = options.watchInterval;\n }\n }\n\n return true;\n }\n catch (error) {\n console.error(error);\n\n throw new OPFSError('Failed to initialize OPFS', 'INIT_FAILED');\n }\n }\n\n /**\n * Get a directory handle from a path\n * \n * Navigates through the directory structure to find or create a directory\n * at the specified path.\n * \n * @param path - The path to the directory (string or array of segments)\n * @param create - Whether to create the directory if it doesn't exist (default: false)\n * @param from - The directory to start from (default: root directory)\n * @returns Promise that resolves to the directory handle\n * @throws {OPFSError} If the directory cannot be accessed or created\n * \n * @example\n * ```typescript\n * const docsDir = await fs.getDirectoryHandle('/users/john/documents', true);\n * const docsDir2 = await fs.getDirectoryHandle(['users', 'john', 'documents'], true);\n * ```\n */\n private async getDirectoryHandle(path: string | string[], create: boolean = false, from: FileSystemDirectoryHandle | null = this.root): Promise<FileSystemDirectoryHandle> {\n if (!from) {\n throw new OPFSNotMountedError();\n }\n\n const segments = Array.isArray(path) ? path : splitPath(path);\n let current = from;\n\n for (const segment of segments) {\n current = await current.getDirectoryHandle(segment, { create });\n }\n\n return current;\n }\n\n /**\n * Get a file handle from a path\n * \n * Navigates to the parent directory and retrieves or creates a file handle\n * for the specified file path.\n * \n * @param path - The path to the file (string or array of segments)\n * @param create - Whether to create the file if it doesn't exist (default: false)\n * @param from - The directory to start from (default: root directory)\n * @returns Promise that resolves to the file handle\n * @throws {PathError} If the path is empty\n * @throws {OPFSError} If the file cannot be accessed or created\n * \n * @example\n * ```typescript\n * const fileHandle = await fs.getFileHandle('/config/settings.json', true);\n * const fileHandle2 = await fs.getFileHandle(['config', 'settings.json'], true);\n * ```\n */\n private async getFileHandle(path: string | string[], create = false, from: FileSystemDirectoryHandle | null = this.root): Promise<FileSystemFileHandle> {\n if (!from) {\n throw new OPFSNotMountedError();\n }\n\n const segments = splitPath(path);\n\n if (segments.length === 0) {\n throw new PathError('Path must not be empty', Array.isArray(path) ? path.join('/') : path);\n }\n\n const fileName = segments.pop()!;\n const dir = await this.getDirectoryHandle(segments, create, from);\n\n return dir.getFileHandle(fileName, { create });\n }\n\n\n /**\n * Recursively list all files and directories with their stats\n * \n * Traverses the entire file system starting from the root and returns\n * a Map containing all paths and their corresponding file statistics.\n * \n * @param options - Options for indexing\n * @param options.includeHash - Whether to calculate file hash (default: false)\n * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)\n * @returns Promise that resolves to a Map of path => FileStat\n * @throws {OPFSError} If the indexing operation fails\n * \n * @example\n * ```typescript\n * // Basic index without hash\n * const index = await fs.index();\n * \n * // Index with file hash\n * const indexWithHash = await fs.index({ \n * includeHash: true,\n * hashAlgorithm: 'SHA-1'\n * });\n * \n * // Iterate through all files and directories\n * for (const [path, stat] of index) {\n * console.log(`${path}: ${stat.isFile ? 'file' : 'directory'} (${stat.size} bytes)`);\n * if (stat.hash) console.log(` Hash: ${stat.hash}`);\n * }\n * \n * // Get specific file stats\n * const fileStats = index.get('/data/config.json');\n * if (fileStats) {\n * console.log(`File size: ${fileStats.size} bytes`);\n * if (fileStats.hash) console.log(`Hash: ${fileStats.hash}`);\n * }\n * ```\n */\n async index(options?: { includeHash?: boolean; hashAlgorithm?: 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512' }): Promise<Map<string, FileStat>> {\n const result = new Map<string, FileStat>();\n\n const walk = async(dirPath: string) => {\n const items = await this.readdir(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = `${ dirPath === '/' ? '' : dirPath }/${ item.name }`;\n\n try {\n const stat = await this.stat(fullPath, options);\n\n result.set(fullPath, stat);\n\n if (stat.isDirectory) {\n await walk(fullPath);\n }\n }\n catch (err) {\n console.warn(`Skipping broken entry: ${ fullPath }`, err);\n }\n }\n };\n\n result.set('/', {\n kind: 'directory',\n size: 0,\n mtime: new Date(0).toISOString(),\n ctime: new Date(0).toISOString(),\n isFile: false,\n isDirectory: true,\n });\n\n await walk('/');\n\n return result;\n }\n\n /**\n * Read a file from the file system\n * \n * Reads the contents of a file and returns it as a string or binary data\n * depending on the specified encoding.\n * \n * @param path - The path to the file to read\n * @param encoding - The encoding to use for reading the file\n * @returns Promise that resolves to the file contents\n * @throws {FileNotFoundError} If the file does not exist\n * @throws {OPFSError} If reading the file fails\n * \n * @example\n * ```typescript\n * // Read as text\n * const content = await fs.readFile('/config/settings.json');\n * \n * // Read as binary\n * const binaryData = await fs.readFile('/images/logo.png', 'binary');\n * \n * // Read with specific encoding\n * const utf8Content = await fs.readFile('/data/utf8.txt', 'utf-8');\n * ```\n */\n async readFile(path: string, encoding: 'binary'): Promise<Uint8Array>;\n async readFile(path: string, encoding?: BufferEncoding): Promise<string>;\n async readFile(\n path: string,\n encoding: BufferEncoding | 'binary' = 'utf-8'\n ): Promise<string | Uint8Array> {\n 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 const fileHandle = await this.getFileHandle(path, true);\n\n await writeFileData(fileHandle, data, encoding, { truncate: true });\n }\n\n /**\n * Append data to a file\n * \n * Adds data to the end of an existing file. If the file doesn't exist,\n * it will be created.\n * \n * @param path - The path to the file to append to\n * @param data - The data to append to the file (string, Uint8Array, or ArrayBuffer)\n * @param encoding - The encoding to use when appending string data (default: 'utf-8')\n * @returns Promise that resolves when the append operation is complete\n * @throws {OPFSError} If appending to the file fails\n * \n * @example\n * ```typescript\n * // Append text to a log file\n * await fs.appendFile('/logs/app.log', `[${new Date().toISOString()}] User logged in\\n`);\n * \n * // Append binary data\n * const additionalData = new Uint8Array([6, 7, 8]);\n * await fs.appendFile('/data/binary.dat', additionalData);\n * ```\n */\n async appendFile(\n path: string,\n data: string | Uint8Array | ArrayBuffer,\n encoding?: BufferEncoding\n ): Promise<void> {\n const fileHandle = await this.getFileHandle(path, true);\n\n await writeFileData(fileHandle, data, encoding, { append: true });\n }\n\n /**\n * Create a directory\n * \n * Creates a new directory at the specified path. If the recursive option\n * is enabled, parent directories will be created as needed.\n * \n * @param path - The path where the directory should be created\n * @param options - Options for directory creation\n * @param options.recursive - Whether to create parent directories if they don't exist (default: false)\n * @returns Promise that resolves when the directory is created\n * @throws {OPFSError} If the directory cannot be created\n * \n * @example\n * ```typescript\n * // Create a single directory\n * await fs.mkdir('/users/john');\n * \n * // Create nested directories\n * await fs.mkdir('/users/john/documents/projects', { recursive: true });\n * ```\n */\n async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n if (!this.root) {\n throw new OPFSNotMountedError();\n }\n\n const recursive = options?.recursive ?? false;\n const segments = splitPath(path);\n\n let current = this.root;\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n\n try {\n current = await current.getDirectoryHandle(segment!, { create: recursive || i === segments.length - 1 });\n }\n catch (e: any) {\n if (e.name === 'NotFoundError') {\n throw new OPFSError(\n `Parent directory does not exist: ${ joinPath(segments.slice(0, i + 1)) }`,\n 'ENOENT'\n );\n }\n\n if (e.name === 'TypeMismatchError') {\n throw new OPFSError(`Path segment is not a directory: ${ segment }`, 'ENOTDIR');\n }\n\n throw new OPFSError('Failed to create directory', 'MKDIR_FAILED');\n }\n }\n }\n\n /**\n * Get file or directory stats\n * \n * Retrieves metadata about a file or directory, including size, modification time,\n * type information, and optionally file hashes.\n * \n * @param path - The path to the file or directory\n * @param options - Options for stat operation\n * @param options.includeHash - Whether to calculate file hash (default: false, only for files)\n * @param options.hashAlgorithm - Hash algorithm to use (default: 'SHA-1', fastest)\n * @returns Promise that resolves to file/directory statistics\n * @throws {OPFSError} If the file or directory does not exist or cannot be accessed\n * \n * @example\n * ```typescript\n * // Basic stats\n * const stats = await fs.stat('/config/settings.json');\n * console.log(`File size: ${stats.size} bytes`);\n * console.log(`Is file: ${stats.isFile}`);\n * console.log(`Modified: ${stats.mtime}`);\n * \n * // Stats with hash (SHA-1 is fastest)\n * const statsWithHash = await fs.stat('/config/settings.json', { \n * includeHash: true,\n * hashAlgorithm: 'SHA-1'\n * });\n * console.log(`Hash: ${statsWithHash.hash}`);\n * ```\n */\n async stat(path: string, options?: { includeHash?: boolean; hashAlgorithm?: 'SHA-1' | 'SHA-256' | 'SHA-384' | 'SHA-512' }): Promise<FileStat> {\n const name = basename(path);\n const parentDir = await this.getDirectoryHandle(dirname(path), false);\n const includeHash = options?.includeHash ?? false;\n const hashAlgorithm = options?.hashAlgorithm ?? 'SHA-1';\n\n try {\n const fileHandle = await parentDir.getFileHandle(name!, { create: false });\n const file = await fileHandle.getFile();\n\n const baseStat: FileStat = {\n kind: 'file',\n size: file.size,\n mtime: new Date(file.lastModified).toISOString(),\n ctime: new Date(file.lastModified).toISOString(),\n isFile: true,\n isDirectory: false,\n };\n\n if (includeHash) {\n try {\n const buffer = new Uint8Array(await file.arrayBuffer());\n const hash = await calculateFileHash(buffer, hashAlgorithm);\n\n baseStat.hash = hash;\n }\n catch (error) {\n console.warn(`Failed to calculate hash for ${ path }:`, error);\n }\n }\n\n return baseStat;\n }\n catch (e: any) {\n if (e.name !== 'TypeMismatchError' && e.name !== 'NotFoundError') {\n throw new OPFSError('Failed to stat (file)', 'STAT_FAILED');\n }\n }\n\n try {\n await parentDir.getDirectoryHandle(name!, { create: false });\n\n return {\n kind: 'directory',\n size: 0,\n mtime: new Date(0).toISOString(),\n ctime: new Date(0).toISOString(),\n isFile: false,\n isDirectory: true,\n };\n }\n catch (e: any) {\n if (e.name === 'NotFoundError') {\n throw new OPFSError(`No such file or directory: ${ path }`, 'ENOENT');\n }\n\n throw new OPFSError('Failed to stat (directory)', 'STAT_FAILED');\n }\n }\n\n /**\n * Read a directory's contents\n * \n * Lists all files and subdirectories within the specified directory.\n * \n * @param path - The path to the directory to read\n * @param options - Options for the readdir operation\n * @param options.withFileTypes - Whether to return detailed file information (default: false)\n * @returns Promise that resolves to an array of file/directory names or detailed information\n * @throws {OPFSError} If the directory does not exist or cannot be accessed\n * \n * @example\n * ```typescript\n * // Get simple list of names\n * const files = await fs.readdir('/users/john/documents');\n * console.log('Files:', files); // ['readme.txt', 'config.json', 'images']\n * \n * // Get detailed information\n * const detailed = await fs.readdir('/users/john/documents', { withFileTypes: true });\n * detailed.forEach(item => {\n * console.log(`${item.name} - ${item.isFile ? 'file' : 'directory'}`);\n * });\n * ```\n */\n async readdir(path: string): Promise<string[]>;\n async readdir(path: string, options: { withFileTypes: true }): Promise<DirentData[]>;\n async readdir(path: string, options: { withFileTypes: false }): Promise<string[]>;\n async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirentData[]> {\n const withTypes = options?.withFileTypes ?? false;\n const dir = await this.getDirectoryHandle(path, false);\n\n if (withTypes) {\n const results: DirentData[] = [];\n\n for await (const [name, handle] of (dir as any).entries()) {\n const isFile = handle.kind === 'file';\n\n results.push({\n name,\n kind: handle.kind,\n isFile,\n isDirectory: !isFile,\n });\n }\n\n return results;\n }\n else {\n const results: string[] = [];\n\n for await (const [name] of (dir as any).entries()) {\n results.push(name);\n }\n\n return results;\n }\n }\n\n /**\n * Check if a file or directory exists\n * \n * Verifies if a file or directory exists at the specified path.\n * \n * @param path - The path to check\n * @returns Promise that resolves to true if the file or directory exists, false otherwise \n * \n * @example\n * ```typescript\n * const exists = await fs.exists('/config/settings.json');\n * console.log(`File exists: ${exists}`);\n * ```\n */\n async exists(path: string): Promise<boolean> {\n 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 try {\n const items = await this.readdir(path, { withFileTypes: true });\n\n for (const item of items) {\n const itemPath = `${ path === '/' ? '' : path }/${ item.name }`;\n\n await this.remove(itemPath, { recursive: true });\n }\n }\n catch (error: any) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to clear directory: ${ path }`, 'CLEAR_FAILED');\n }\n }\n\n /**\n * Remove files and directories\n * \n * Removes files and directories. Similar to Node.js fs.rm().\n * \n * @param path - The path to remove\n * @param options - Options for removal\n * @param options.recursive - Whether to remove directories and their contents recursively (default: false)\n * @param options.force - Whether to ignore errors if the path doesn't exist (default: false)\n * @returns Promise that resolves when the removal is complete\n * @throws {OPFSError} If the removal fails\n * \n * @example\n * ```typescript\n * // Remove a file\n * await fs.rm('/path/to/file.txt');\n * \n * // Remove a directory and all its contents\n * await fs.rm('/path/to/directory', { recursive: true });\n * \n * // Remove with force (ignore if doesn't exist)\n * await fs.rm('/maybe/exists', { force: true });\n * ```\n */\n async remove(path: string, options?: { recursive?: boolean; force?: boolean }): Promise<void> {\n const recursive = options?.recursive ?? false;\n const force = options?.force ?? false;\n\n const name = basename(path);\n\n if (!name) {\n throw new PathError('Invalid path', path);\n }\n\n const parent = await this.getDirectoryHandle(dirname(path), false);\n\n try {\n await parent.removeEntry(name, { recursive });\n }\n catch (e: any) {\n if (e.name === 'NotFoundError') {\n if (!force) {\n throw new OPFSError(`No such file or directory: ${ path }`, 'ENOENT');\n }\n }\n else if (e.name === 'InvalidModificationError') {\n throw new OPFSError(`Directory not empty: ${ path }. Use recursive option to force removal.`, 'ENOTEMPTY');\n }\n else if (e.name === 'TypeMismatchError' && !recursive) {\n throw new OPFSError(`Cannot remove directory without recursive option: ${ path }`, 'EISDIR');\n }\n else {\n throw new OPFSError(`Failed to remove path: ${ path }`, 'RM_FAILED');\n }\n }\n }\n\n /**\n * Resolve a path to an absolute path\n * \n * Resolves relative paths and normalizes path segments (like '..' and '.').\n * Similar to Node.js fs.realpath() but without symlink resolution since OPFS doesn't support symlinks.\n * \n * @param path - The path to resolve\n * @returns Promise that resolves to the absolute normalized path\n * @throws {FileNotFoundError} If the path does not exist\n * @throws {OPFSError} If path resolution fails\n * \n * @example\n * ```typescript\n * // Resolve relative path\n * const absolute = await fs.realpath('./config/../data/file.txt');\n * console.log(absolute); // '/data/file.txt'\n * ```\n */\n async realpath(path: string): Promise<string> {\n 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 try {\n const sourceExists = await this.exists(oldPath);\n\n if (!sourceExists) {\n throw new FileNotFoundError(oldPath);\n }\n\n await this.copy(oldPath, newPath, { recursive: true });\n await this.remove(oldPath, { recursive: true });\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to rename from ${ oldPath } to ${ newPath }`, 'RENAME_FAILED');\n }\n }\n\n /**\n * Copy files and directories\n * \n * Copies files and directories. Similar to Node.js fs.cp().\n * \n * @param source - The source path to copy from\n * @param destination - The destination path to copy to\n * @param options - Options for copying\n * @param options.recursive - Whether to copy directories recursively (default: false)\n * @param options.force - Whether to overwrite existing files (default: true)\n * @returns Promise that resolves when the copy operation is complete\n * @throws {OPFSError} If the copy operation fails\n * \n * @example\n * ```typescript\n * // Copy a file\n * await fs.cp('/source/file.txt', '/dest/file.txt');\n * \n * // Copy a directory and all its contents\n * await fs.cp('/source/dir', '/dest/dir', { recursive: true });\n * \n * // Copy without overwriting existing files\n * await fs.cp('/source', '/dest', { recursive: true, force: false });\n * ```\n */\n async copy(source: string, destination: string, options?: { recursive?: boolean; force?: boolean }): Promise<void> {\n try {\n const recursive = options?.recursive ?? false;\n const force = options?.force ?? true;\n\n const sourceExists = await this.exists(source);\n\n if (!sourceExists) {\n throw new OPFSError(`Source does not exist: ${ source }`, 'ENOENT');\n }\n\n const destExists = await this.exists(destination);\n\n if (destExists && !force) {\n throw new OPFSError(`Destination already exists: ${ destination }`, 'EEXIST');\n }\n\n const sourceStats = await this.stat(source);\n\n if (sourceStats.isFile) {\n const content = await this.readFile(source, 'binary');\n\n await this.writeFile(destination, content);\n }\n else {\n if (!recursive) {\n throw new OPFSError(`Cannot copy directory without recursive option: ${ source }`, 'EISDIR');\n }\n\n await this.mkdir(destination, { recursive: true });\n\n const items = await this.readdir(source, { withFileTypes: true });\n\n for (const item of items) {\n const sourceItemPath = `${ source }/${ item.name }`;\n const destItemPath = `${ destination }/${ item.name }`;\n\n await this.copy(sourceItemPath, destItemPath, { recursive: true, force });\n }\n }\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError(`Failed to copy from ${ source } to ${ destination }`, 'CP_FAILED');\n }\n }\n\n /**\n * Start watching a file or directory for changes\n */\n async watch(path: string): Promise<void> {\n const normalizedPath = normalizePath(path);\n const snapshot = await this.buildSnapshot(normalizedPath);\n this.watchers.set(normalizedPath, snapshot);\n\n if (!this.watchTimer) {\n this.watchTimer = setInterval(() => {\n void this.scanWatches();\n }, this.watchInterval);\n }\n }\n\n /**\n * Stop watching a previously watched path\n */\n unwatch(path: string): void {\n const normalizedPath = normalizePath(path);\n this.watchers.delete(normalizedPath);\n\n if (this.watchers.size === 0 && this.watchTimer) {\n clearInterval(this.watchTimer);\n this.watchTimer = null;\n }\n }\n\n private async buildSnapshot(rootPath: string): Promise<Map<string, FileStat>> {\n const result = new Map<string, FileStat>();\n\n const walk = async (current: string) => {\n const stat = await this.stat(current);\n result.set(current, stat);\n\n if (stat.isDirectory) {\n const entries = await this.readdir(current, { withFileTypes: true });\n for (const entry of entries) {\n const child = `${ current === '/' ? '' : current }/${ entry.name }`;\n await walk(child);\n }\n }\n };\n\n await walk(rootPath);\n return result;\n }\n\n private async scanWatches(): Promise<void> {\n if (this.scanning) {\n return;\n }\n\n this.scanning = true;\n\n try {\n await Promise.all(\n [...this.watchers.entries()].map(async ([rootPath, prev]) => {\n let next: Map<string, FileStat>;\n\n try {\n next = await this.buildSnapshot(rootPath);\n }\n catch {\n next = new Map();\n }\n\n const events: WatchEvent[] = [];\n\n for (const [p, stat] of next) {\n const old = prev.get(p);\n if (!old) {\n events.push({ path: p, type: 'create' });\n }\n else if (old.mtime !== stat.mtime || old.size !== stat.size) {\n events.push({ path: p, type: 'change' });\n }\n }\n\n for (const p of prev.keys()) {\n if (!next.has(p)) {\n events.push({ path: p, type: 'delete' });\n }\n }\n\n if (events.length && this.watchCallback) {\n for (const event of events) {\n this.watchCallback(event);\n }\n }\n\n this.watchers.set(rootPath, next);\n })\n );\n }\n finally {\n this.scanning = false;\n }\n }\n\n /**\n * Synchronize the file system with external data\n * \n * Syncs the file system with an array of entries containing paths and data.\n * This is useful for importing data from external sources or syncing with remote data.\n * \n * @param entries - Array of [path, data] tuples to sync\n * @param options - Options for synchronization\n * @param options.cleanBefore - Whether to clear the file system before syncing (default: false)\n * @returns Promise that resolves when synchronization is complete\n * @throws {OPFSError} If the synchronization fails\n * \n * @example\n * ```typescript\n * // Sync with external data\n * const entries: [string, string | Uint8Array | Blob][] = [\n * ['/config.json', JSON.stringify({ theme: 'dark' })],\n * ['/data/binary.dat', new Uint8Array([1, 2, 3, 4])],\n * ['/upload.txt', new Blob(['file content'], { type: 'text/plain' })]\n * ];\n * \n * // Sync without clearing existing files\n * await fs.sync(entries);\n * \n * // Clean file system and then sync\n * await fs.sync(entries, { cleanBefore: true });\n * ```\n */\n async sync(entries: [string, string | Uint8Array | Blob][], options?: { cleanBefore?: boolean }): Promise<void> {\n try {\n const cleanBefore = options?.cleanBefore ?? false;\n\n if (cleanBefore) {\n await this.clear('/');\n }\n\n for (const [path, data] of entries) {\n const normalizedPath = normalizePath(path);\n\n let fileData: string | Uint8Array;\n\n if (data instanceof Blob) {\n fileData = await convertBlobToUint8Array(data);\n }\n else {\n fileData = data;\n }\n\n await this.writeFile(normalizedPath, fileData);\n }\n }\n catch (error) {\n if (error instanceof OPFSError) {\n throw error;\n }\n\n throw new OPFSError('Failed to sync file system', 'SYNC_FAILED');\n }\n }\n}\n\n// Only expose the worker when running in a Web Worker environment\nif (typeof self !== 'undefined' && self.constructor.name === 'DedicatedWorkerGlobalScope') {\n expose(new OPFSWorker());\n}\n"],"names":["OPFSWorker","checkOPFSSupport","root","watchCallback","options","rootDir","error","OPFSError","path","create","from","OPFSNotMountedError","segments","splitPath","current","segment","PathError","fileName","result","walk","dirPath","items","item","fullPath","stat","err","encoding","fileHandle","buffer","readFileData","decodeBuffer","FileNotFoundError","data","writeFileData","recursive","i","e","joinPath","name","basename","parentDir","dirname","includeHash","hashAlgorithm","file","baseStat","hash","calculateFileHash","withTypes","dir","results","handle","isFile","itemPath","force","parent","normalizedPath","resolvePath","oldPath","newPath","source","destination","content","sourceItemPath","destItemPath","normalizePath","snapshot","rootPath","entries","entry","child","prev","next","events","p","old","event","fileData","convertBlobToUint8Array","expose"],"mappings":"+IA0CO,MAAMA,CAAW,CAEZ,KAAyC,KAGzC,cAAsD,KAGtD,aAAe,IAGf,WAAoD,KAGpD,cAAgB,IAGhB,SAAW,GAOnB,aAAc,CACVC,mBAAA,CACJ,CAkBA,MAAM,MAAMC,EAAe,IAAKC,EAA6CC,EAAwD,CACjI,GAAI,CACA,MAAMC,EAAU,MAAM,UAAU,QAAQ,aAAA,EAExC,YAAK,KAAO,MAAM,KAAK,mBAAmBH,EAAM,GAAMG,CAAO,EAEzDF,IACA,KAAK,cAAgBA,EACjBC,GAAS,gBACT,KAAK,cAAgBA,EAAQ,gBAI9B,EACX,OACOE,EAAO,CACV,cAAQ,MAAMA,CAAK,EAEb,IAAIC,EAAAA,UAAU,4BAA6B,aAAa,CAClE,CACJ,CAoBA,MAAc,mBAAmBC,EAAyBC,EAAkB,GAAOC,EAAyC,KAAK,KAA0C,CACvK,GAAI,CAACA,EACD,MAAM,IAAIC,EAAAA,oBAGd,MAAMC,EAAW,MAAM,QAAQJ,CAAI,EAAIA,EAAOK,EAAAA,UAAUL,CAAI,EAC5D,IAAIM,EAAUJ,EAEd,UAAWK,KAAWH,EAClBE,EAAU,MAAMA,EAAQ,mBAAmBC,EAAS,CAAE,OAAAN,EAAQ,EAGlE,OAAOK,CACX,CAqBA,MAAc,cAAcN,EAAyBC,EAAS,GAAOC,EAAyC,KAAK,KAAqC,CACpJ,GAAI,CAACA,EACD,MAAM,IAAIC,EAAAA,oBAGd,MAAMC,EAAWC,EAAAA,UAAUL,CAAI,EAE/B,GAAII,EAAS,SAAW,EACpB,MAAM,IAAII,EAAAA,UAAU,y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