@zenfs/dom 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- import type { AsyncStoreOptions, Ino } from '@zenfs/core';
2
- import { AsyncTransaction, AsyncStore, AsyncStoreFS } from '@zenfs/core';
1
+ import type { AsyncStore, AsyncStoreOptions, AsyncTransaction, Ino } from '@zenfs/core';
2
+ import { AsyncStoreFS } from '@zenfs/core';
3
3
  /**
4
4
  * @hidden
5
5
  */
@@ -19,7 +19,7 @@ export declare class IndexedDBTransaction implements AsyncTransaction {
19
19
  export declare class IndexedDBStore implements AsyncStore {
20
20
  protected db: IDBDatabase;
21
21
  protected storeName: string;
22
- static create(storeName: string, indexedDB: IDBFactory): Promise<IndexedDBStore>;
22
+ static create(storeName: string, indexedDB?: IDBFactory): Promise<IndexedDBStore>;
23
23
  constructor(db: IDBDatabase, storeName: string);
24
24
  get name(): string;
25
25
  clear(): Promise<void>;
package/dist/IndexedDB.js CHANGED
@@ -1,26 +1,11 @@
1
- import { AsyncStoreFS, ApiError, ErrorCode } from '@zenfs/core';
2
- /**
3
- * Converts a DOMException or a DOMError from an IndexedDB event into a
4
- * standardized ZenFS API error.
5
- * @hidden
6
- */
7
- function convertError(e, message = e.toString()) {
8
- switch (e.name) {
9
- case 'NotFoundError':
10
- return new ApiError(ErrorCode.ENOENT, message);
11
- case 'QuotaExceededError':
12
- return new ApiError(ErrorCode.ENOSPC, message);
13
- default:
14
- // The rest do not seem to map cleanly to standard error codes.
15
- return new ApiError(ErrorCode.EIO, message);
16
- }
17
- }
1
+ import { AsyncStoreFS } from '@zenfs/core';
2
+ import { convertException } from './utils.js';
18
3
  function wrap(request) {
19
4
  return new Promise((resolve, reject) => {
20
5
  request.onsuccess = () => resolve(request.result);
21
6
  request.onerror = e => {
22
7
  e.preventDefault();
23
- reject(new ApiError(ErrorCode.EIO));
8
+ reject(convertException(request.error));
24
9
  };
25
10
  });
26
11
  }
@@ -32,33 +17,18 @@ export class IndexedDBTransaction {
32
17
  this.tx = tx;
33
18
  this.store = store;
34
19
  }
35
- async get(key) {
36
- try {
37
- return await wrap(this.store.get(key.toString()));
38
- }
39
- catch (e) {
40
- throw convertError(e);
41
- }
20
+ get(key) {
21
+ return wrap(this.store.get(key.toString()));
42
22
  }
43
23
  /**
44
24
  * @todo return false when add has a key conflict (no error)
45
25
  */
46
26
  async put(key, data, overwrite) {
47
- try {
48
- await wrap(overwrite ? this.store.put(data, key.toString()) : this.store.add(data, key.toString()));
49
- return true;
50
- }
51
- catch (e) {
52
- throw convertError(e);
53
- }
27
+ await wrap(this.store[overwrite ? 'put' : 'add'](data, key.toString()));
28
+ return true;
54
29
  }
55
- async remove(key) {
56
- try {
57
- await wrap(this.store.delete(key.toString()));
58
- }
59
- catch (e) {
60
- throw convertError(e);
61
- }
30
+ remove(key) {
31
+ return wrap(this.store.delete(key.toString()));
62
32
  }
63
33
  async commit() {
64
34
  return;
@@ -68,12 +38,12 @@ export class IndexedDBTransaction {
68
38
  this.tx.abort();
69
39
  }
70
40
  catch (e) {
71
- throw convertError(e);
41
+ throw convertException(e);
72
42
  }
73
43
  }
74
44
  }
75
45
  export class IndexedDBStore {
76
- static async create(storeName, indexedDB) {
46
+ static async create(storeName, indexedDB = globalThis.indexedDB) {
77
47
  const req = indexedDB.open(storeName, 1);
78
48
  req.onupgradeneeded = () => {
79
49
  const db = req.result;
@@ -94,23 +64,11 @@ export class IndexedDBStore {
94
64
  return IndexedDB.name + ':' + this.storeName;
95
65
  }
96
66
  clear() {
97
- return new Promise((resolve, reject) => {
98
- try {
99
- const req = this.db.transaction(this.storeName, 'readwrite').objectStore(this.storeName).clear();
100
- req.onsuccess = () => resolve();
101
- req.onerror = e => {
102
- e.preventDefault();
103
- reject(new ApiError(ErrorCode.EIO));
104
- };
105
- }
106
- catch (e) {
107
- reject(convertError(e));
108
- }
109
- });
67
+ return wrap(this.db.transaction(this.storeName, 'readwrite').objectStore(this.storeName).clear());
110
68
  }
111
69
  beginTransaction() {
112
- const tx = this.db.transaction(this.storeName, 'readwrite'), objectStore = tx.objectStore(this.storeName);
113
- return new IndexedDBTransaction(tx, objectStore);
70
+ const tx = this.db.transaction(this.storeName, 'readwrite');
71
+ return new IndexedDBTransaction(tx, tx.objectStore(this.storeName));
114
72
  }
115
73
  }
116
74
  /**
package/dist/Storage.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import type { Ino } from '@zenfs/core';
2
- import { SyncStore, SimpleSyncStore, SimpleSyncTransaction, SyncStoreFS } from '@zenfs/core';
1
+ import type { Ino, SimpleSyncStore, SyncStore } from '@zenfs/core';
2
+ import { SimpleSyncTransaction, SyncStoreFS } from '@zenfs/core';
3
3
  /**
4
4
  * A synchronous key-value store backed by Storage.
5
5
  */
package/dist/Storage.js CHANGED
@@ -1,4 +1,4 @@
1
- import { SimpleSyncTransaction, SyncStoreFS, ApiError, ErrorCode, encode, decode } from '@zenfs/core';
1
+ import { ApiError, ErrorCode, SimpleSyncTransaction, SyncStoreFS, decode, encode } from '@zenfs/core';
2
2
  /**
3
3
  * A synchronous key-value store backed by Storage.
4
4
  */
package/dist/access.d.ts CHANGED
@@ -44,7 +44,6 @@ export declare class WebAccessFS extends WebAccessFS_base {
44
44
  * @hidden
45
45
  */
46
46
  _sync: FileSystem;
47
- ready(): Promise<this>;
48
47
  constructor({ handle }: WebAccessOptions);
49
48
  metadata(): FileSystemMetadata;
50
49
  sync(p: string, data: Uint8Array, stats: Stats): Promise<void>;
@@ -54,7 +53,7 @@ export declare class WebAccessFS extends WebAccessFS_base {
54
53
  stat(path: string): Promise<Stats>;
55
54
  openFile(path: string, flag: string): Promise<PreloadFile<this>>;
56
55
  unlink(path: string): Promise<void>;
57
- link(): Promise<void>;
56
+ link(srcpath: string): Promise<void>;
58
57
  rmdir(path: string): Promise<void>;
59
58
  mkdir(path: string): Promise<void>;
60
59
  readdir(path: string): Promise<string[]>;
package/dist/access.js CHANGED
@@ -1,15 +1,7 @@
1
1
  import { ApiError, Async, ErrorCode, FileSystem, FileType, InMemory, PreloadFile, Stats } from '@zenfs/core';
2
2
  import { basename, dirname, join } from '@zenfs/core/emulation/path.js';
3
- const handleError = (path = '', syscall, error) => {
4
- if (error.name === 'NotFoundError') {
5
- throw ApiError.With('ENOENT', path, syscall);
6
- }
7
- throw error;
8
- };
3
+ import { convertException } from './utils.js';
9
4
  export class WebAccessFS extends Async(FileSystem) {
10
- async ready() {
11
- return this;
12
- }
13
5
  constructor({ handle }) {
14
6
  super();
15
7
  this._handles = new Map();
@@ -58,8 +50,8 @@ export class WebAccessFS extends Async(FileSystem) {
58
50
  writable.close();
59
51
  await this.unlink(oldPath);
60
52
  }
61
- catch (err) {
62
- handleError(oldPath, 'rename', err);
53
+ catch (ex) {
54
+ throw convertException(ex, oldPath, 'rename');
63
55
  }
64
56
  }
65
57
  async writeFile(fname, data) {
@@ -104,13 +96,13 @@ export class WebAccessFS extends Async(FileSystem) {
104
96
  try {
105
97
  await handle.removeEntry(basename(path), { recursive: true });
106
98
  }
107
- catch (e) {
108
- handleError(path, 'unlink', e);
99
+ catch (ex) {
100
+ throw convertException(ex, path, 'unlink');
109
101
  }
110
102
  }
111
103
  }
112
- async link() {
113
- throw new ApiError(ErrorCode.ENOTSUP);
104
+ async link(srcpath) {
105
+ throw ApiError.With('ENOSYS', srcpath, 'WebAccessFS.link');
114
106
  }
115
107
  async rmdir(path) {
116
108
  return this.unlink(path);
@@ -140,40 +132,34 @@ export class WebAccessFS extends Async(FileSystem) {
140
132
  if (this._handles.has(path)) {
141
133
  return this._handles.get(path);
142
134
  }
143
- let walkedPath = '/';
144
- const [, ...pathParts] = path.split('/');
145
- const getHandleParts = async ([pathPart, ...remainingPathParts]) => {
146
- const walkingPath = join(walkedPath, pathPart);
147
- const continueWalk = (handle) => {
148
- walkedPath = walkingPath;
149
- this._handles.set(walkedPath, handle);
150
- if (remainingPathParts.length === 0) {
151
- return this._handles.get(path);
152
- }
153
- getHandleParts(remainingPathParts);
154
- };
155
- const handle = this._handles.get(walkedPath);
135
+ let walked = '/';
136
+ for (const part of path.split('/').slice(1)) {
137
+ const handle = this._handles.get(walked);
138
+ if (!(handle instanceof FileSystemDirectoryHandle)) {
139
+ throw ApiError.With('ENOTDIR', walked, 'getHandle');
140
+ }
141
+ walked = join(walked, part);
156
142
  try {
157
- return continueWalk(await handle.getDirectoryHandle(pathPart));
143
+ const dirHandle = await handle.getDirectoryHandle(part);
144
+ this._handles.set(walked, dirHandle);
158
145
  }
159
- catch (error) {
160
- if (error.name === 'TypeMismatchError') {
146
+ catch (ex) {
147
+ if (ex.name == 'TypeMismatchError') {
161
148
  try {
162
- return continueWalk(await handle.getFileHandle(pathPart));
149
+ const fileHandle = await handle.getFileHandle(part);
150
+ this._handles.set(walked, fileHandle);
163
151
  }
164
- catch (err) {
165
- handleError(walkingPath, 'getHandle', err);
152
+ catch (ex) {
153
+ convertException(ex, walked, 'getHandle');
166
154
  }
167
155
  }
168
- else if (error.message === 'Name is not allowed.') {
169
- throw new ApiError(ErrorCode.ENOENT, error.message, walkingPath);
170
- }
171
- else {
172
- handleError(walkingPath, 'getHandle', error);
156
+ if (ex.name === 'TypeError') {
157
+ throw new ApiError(ErrorCode.ENOENT, ex.message, walked, 'getHandle');
173
158
  }
159
+ convertException(ex, walked, 'getHandle');
174
160
  }
175
- };
176
- return await getHandleParts(pathParts);
161
+ }
162
+ return this._handles.get(path);
177
163
  }
178
164
  }
179
165
  export const WebAccess = {
@@ -1,2 +1,2 @@
1
- var ZenFS_DOM=(()=>{var D=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var R=Object.prototype.hasOwnProperty;var a=(n,e)=>D(n,"name",{value:e,configurable:!0});var j=(n,e)=>{for(var t in e)D(n,t,{get:e[t],enumerable:!0})},q=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of U(e))!R.call(n,i)&&i!==t&&D(n,i,{get:()=>e[i],enumerable:!(r=C(e,i))||r.enumerable});return n};var L=n=>q(D({},"__esModule",{value:!0}),n);var X={};j(X,{IndexedDB:()=>z,IndexedDBStore:()=>m,IndexedDBTransaction:()=>I,WebAccess:()=>Q,WebAccessFS:()=>w,WebStorage:()=>M,WebStorageStore:()=>x});var J=ZenFS,{ActionType:K,ApiError:c,Async:A,AsyncFileIndexFS:V,AsyncStoreFS:H,BigIntStats:ee,BigIntStatsFs:te,Dir:ne,Dirent:re,ErrorCode:d,ErrorStrings:ie,File:se,FileIndex:oe,FileIndexFS:ae,FileSystem:T,FileType:E,InMemory:B,InMemoryStore:le,IndexDirInode:ce,IndexFileInode:de,IndexInode:fe,Inode:ue,LockedFS:me,Mutex:ye,NoSyncFile:Se,Overlay:ge,OverlayFS:he,PreloadFile:O,ReadStream:pe,Readonly:we,SimpleSyncTransaction:_,Stats:k,StatsCommon:be,StatsFs:Fe,Sync:Ie,SyncFileIndexFS:xe,SyncStoreFS:N,UnlockedOverlayFS:De,WriteStream:Ee,_toUnixTimestamp:ke,access:ve,accessSync:Ae,appendFile:He,appendFileSync:Te,checkOptions:Be,chmod:Oe,chmodSync:_e,chown:Ne,chownSync:Pe,close:$e,closeSync:ze,configure:Me,constants:We,copyFile:Ce,copyFileSync:Ue,cp:Re,cpSync:je,createBackend:qe,createReadStream:Le,createWriteStream:Ye,decode:P,decodeDirListing:Ze,encode:$,encodeDirListing:Qe,exists:Xe,existsSync:Ge,fchmod:Je,fchmodSync:Ke,fchown:Ve,fchownSync:et,fdatasync:tt,fdatasyncSync:nt,flagToMode:rt,flagToNumber:it,flagToString:st,fs:ot,fstat:at,fstatSync:lt,fsync:ct,fsyncSync:dt,ftruncate:ft,ftruncateSync:ut,futimes:mt,futimesSync:yt,isAppendable:St,isBackend:gt,isBackendConfig:ht,isExclusive:pt,isReadable:wt,isSynchronous:bt,isTruncating:Ft,isWriteable:It,lchmod:xt,lchmodSync:Dt,lchown:Et,lchownSync:kt,levenshtein:vt,link:At,linkSync:Ht,lopenSync:Tt,lstat:Bt,lstatSync:Ot,lutimes:_t,lutimesSync:Nt,mkdir:Pt,mkdirSync:$t,mkdirpSync:zt,mkdtemp:Mt,mkdtempSync:Wt,mount:Ct,mountMapping:Ut,mounts:Rt,open:jt,openAsBlob:qt,openSync:Lt,opendir:Yt,opendirSync:Zt,parseFlag:Qt,pathExistsAction:Xt,pathNotExistsAction:Gt,promises:Jt,randomIno:Kt,read:Vt,readFile:en,readFileSync:tn,readSync:nn,readdir:rn,readdirSync:sn,readlink:on,readlinkSync:an,readv:ln,readvSync:cn,realpath:dn,realpathSync:fn,rename:un,renameSync:mn,resolveMountConfig:yn,rm:Sn,rmSync:gn,rmdir:hn,rmdirSync:pn,rootCred:wn,rootIno:bn,setImmediate:Fn,size_max:In,stat:xn,statSync:Dn,statfs:En,statfsSync:kn,symlink:vn,symlinkSync:An,truncate:Hn,truncateSync:Tn,umount:Bn,unlink:On,unlinkSync:_n,unwatchFile:Nn,utimes:Pn,utimesSync:$n,wait:zn,watch:Mn,watchFile:Wn,write:Cn,writeFile:Un,writeFileSync:Rn,writeSync:jn,writev:qn,writevSync:Ln}=ZenFS;function S(n,e){if(typeof n!="string")throw new TypeError(`"${e}" is not a string`)}a(S,"validateString");function Y(n,e){let t="",r=0,i=-1,s=0,l="\0";for(let o=0;o<=n.length;++o){if(o<n.length)l=n[o];else{if(l=="/")break;l="/"}if(l=="/"){if(!(i===o-1||s===1))if(s===2){if(t.length<2||r!==2||t.at(-1)!=="."||t.at(-2)!=="."){if(t.length>2){let u=t.lastIndexOf("/");u===-1?(t="",r=0):(t=t.slice(0,u),r=t.length-1-t.lastIndexOf("/")),i=o,s=0;continue}else if(t.length!==0){t="",r=0,i=o,s=0;continue}}e&&(t+=t.length>0?"/..":"..",r=2)}else t.length>0?t+="/"+n.slice(i+1,o):t=n.slice(i+1,o),r=o-i-1;i=o,s=0}else l==="."&&s!==-1?++s:s=-1}return t}a(Y,"normalizeString");function Z(n){if(S(n,"path"),n.length===0)return".";let e=n[0]==="/",t=n.at(-1)==="/";return n=Y(n,!e),n.length===0?e?"/":t?"./":".":(t&&(n+="/"),e?`/${n}`:n)}a(Z,"normalize");function g(...n){if(n.length===0)return".";let e;for(let t=0;t<n.length;++t){let r=n[t];S(r,"path"),r.length>0&&(e===void 0?e=r:e+=`/${r}`)}return e===void 0?".":Z(e)}a(g,"join");function h(n){if(S(n,"path"),n.length===0)return".";let e=n[0]==="/",t=-1,r=!0;for(let i=n.length-1;i>=1;--i)if(n[i]==="/"){if(!r){t=i;break}}else r=!1;return t===-1?e?"/":".":e&&t===1?"//":n.slice(0,t)}a(h,"dirname");function p(n,e){e!==void 0&&S(e,"ext"),S(n,"path");let t=0,r=-1,i=!0;if(e!==void 0&&e.length>0&&e.length<=n.length){if(e===n)return"";let s=e.length-1,l=-1;for(let o=n.length-1;o>=0;--o)if(n[o]==="/"){if(!i){t=o+1;break}}else l===-1&&(i=!1,l=o+1),s>=0&&(n[o]===e[s]?--s===-1&&(r=o):(s=-1,r=l));return t===r?r=l:r===-1&&(r=n.length),n.slice(t,r)}for(let s=n.length-1;s>=0;--s)if(n[s]==="/"){if(!i){t=s+1;break}}else r===-1&&(i=!1,r=s+1);return r===-1?"":n.slice(t,r)}a(p,"basename");var v=a((n="",e,t)=>{throw t.name==="NotFoundError"?c.With("ENOENT",n,e):t},"handleError"),w=class extends A(T){_handles=new Map;_sync;async ready(){return this}constructor({handle:e}){super(),this._handles.set("/",e),this._sync=B.create({name:"accessfs-cache"})}metadata(){return{...super.metadata(),name:"WebAccess"}}async sync(e,t,r){let i=await this.stat(e);r.mtime!==i.mtime&&await this.writeFile(e,t)}async rename(e,t){try{let r=await this.getHandle(e);if(r instanceof FileSystemDirectoryHandle){let y=await this.readdir(e);if(await this.mkdir(t),y.length==0)await this.unlink(e);else for(let f of y)await this.rename(g(e,f),g(t,f)),await this.unlink(e)}if(!(r instanceof FileSystemFileHandle))return;let i=await r.getFile(),s=await this.getHandle(h(t));if(!(s instanceof FileSystemDirectoryHandle))return;let o=await(await s.getFileHandle(p(t),{create:!0})).createWritable(),u=await i.arrayBuffer();await o.write(u),o.close(),await this.unlink(e)}catch(r){v(e,"rename",r)}}async writeFile(e,t){let r=await this.getHandle(h(e));if(!(r instanceof FileSystemDirectoryHandle))return;let s=await(await r.getFileHandle(p(e),{create:!0})).createWritable();await s.write(t),await s.close()}async createFile(e,t){return await this.writeFile(e,new Uint8Array),this.openFile(e,t)}async stat(e){let t=await this.getHandle(e);if(!t)throw c.With("ENOENT",e,"stat");if(t instanceof FileSystemDirectoryHandle)return new k({mode:511|E.DIRECTORY,size:4096});if(t instanceof FileSystemFileHandle){let{lastModified:r,size:i}=await t.getFile();return new k({mode:511|E.FILE,size:i,mtimeMs:r})}}async openFile(e,t){let r=await this.getHandle(e);if(r instanceof FileSystemFileHandle){let i=await r.getFile(),s=new Uint8Array(await i.arrayBuffer()),l=new k({mode:511|E.FILE,size:i.size,mtimeMs:i.lastModified});return new O(this,e,t,l,s)}}async unlink(e){let t=await this.getHandle(h(e));if(t instanceof FileSystemDirectoryHandle)try{await t.removeEntry(p(e),{recursive:!0})}catch(r){v(e,"unlink",r)}}async link(){throw new c(d.ENOTSUP)}async rmdir(e){return this.unlink(e)}async mkdir(e){if(await this.getHandle(e))throw c.With("EEXIST",e,"mkdir");let r=await this.getHandle(h(e));r instanceof FileSystemDirectoryHandle&&await r.getDirectoryHandle(p(e),{create:!0})}async readdir(e){let t=await this.getHandle(e);if(!(t instanceof FileSystemDirectoryHandle))throw c.With("ENOTDIR",e,"readdir");let r=[];for await(let i of t.keys())r.push(g(e,i));return r}async getHandle(e){if(this._handles.has(e))return this._handles.get(e);let t="/",[,...r]=e.split("/"),i=a(async([s,...l])=>{let o=g(t,s),u=a(f=>{if(t=o,this._handles.set(t,f),l.length===0)return this._handles.get(e);i(l)},"continueWalk"),y=this._handles.get(t);try{return u(await y.getDirectoryHandle(s))}catch(f){if(f.name==="TypeMismatchError")try{return u(await y.getFileHandle(s))}catch(W){v(o,"getHandle",W)}else{if(f.message==="Name is not allowed.")throw new c(d.ENOENT,f.message,o);v(o,"getHandle",f)}}},"getHandleParts");return await i(r)}};a(w,"WebAccessFS");var Q={name:"WebAccess",options:{handle:{type:"object",required:!0,description:"The directory handle to use for the root"}},isAvailable(){return typeof FileSystemHandle=="function"},create(n){return new w(n)}};function b(n,e=n.toString()){switch(n.name){case"NotFoundError":return new c(d.ENOENT,e);case"QuotaExceededError":return new c(d.ENOSPC,e);default:return new c(d.EIO,e)}}a(b,"convertError");function F(n){return new Promise((e,t)=>{n.onsuccess=()=>e(n.result),n.onerror=r=>{r.preventDefault(),t(new c(d.EIO))}})}a(F,"wrap");var I=class{constructor(e,t){this.tx=e;this.store=t}async get(e){try{return await F(this.store.get(e.toString()))}catch(t){throw b(t)}}async put(e,t,r){try{return await F(r?this.store.put(t,e.toString()):this.store.add(t,e.toString())),!0}catch(i){throw b(i)}}async remove(e){try{await F(this.store.delete(e.toString()))}catch(t){throw b(t)}}async commit(){}async abort(){try{this.tx.abort()}catch(e){throw b(e)}}};a(I,"IndexedDBTransaction");var m=class{constructor(e,t){this.db=e;this.storeName=t}static async create(e,t){let r=t.open(e,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(e)&&s.deleteObjectStore(e),s.createObjectStore(e)};let i=await F(r);return new m(i,e)}get name(){return z.name+":"+this.storeName}clear(){return new Promise((e,t)=>{try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();r.onsuccess=()=>e(),r.onerror=i=>{i.preventDefault(),t(new c(d.EIO))}}catch(r){t(b(r))}})}beginTransaction(){let e=this.db.transaction(this.storeName,"readwrite"),t=e.objectStore(this.storeName);return new I(e,t)}};a(m,"IndexedDBStore");var z={name:"IndexedDB",options:{storeName:{type:"string",required:!1,description:"The name of this file system. You can have multiple IndexedDB file systems operating at once, but each must have a different name."},cacheSize:{type:"number",required:!1,description:"The size of the inode cache. Defaults to 100. A size of 0 or below disables caching."},idbFactory:{type:"object",required:!1,description:"The IDBFactory to use. Defaults to globalThis.indexedDB."}},async isAvailable(n=globalThis.indexedDB){try{if(!(n instanceof IDBFactory))return!1;let e=n.open("__zenfs_test");return await F(e),n.deleteDatabase("__zenfs_test"),!0}catch{return n.deleteDatabase("__zenfs_test"),!1}},create(n){let e=m.create(n.storeName||"zenfs",n.idbFactory);return new H({...n,store:e})}};var x=class{constructor(e){this._storage=e}get name(){return M.name}clear(){this._storage.clear()}beginTransaction(){return new _(this)}get(e){let t=this._storage.getItem(e.toString());if(typeof t=="string")return $(t)}put(e,t,r){try{return!r&&this._storage.getItem(e.toString())!==null?!1:(this._storage.setItem(e.toString(),P(t)),!0)}catch{throw new c(d.ENOSPC,"Storage is full.")}}remove(e){try{this._storage.removeItem(e.toString())}catch(t){throw new c(d.EIO,"Unable to delete key "+e+": "+t)}}};a(x,"WebStorageStore");var M={name:"WebStorage",options:{storage:{type:"object",required:!1,description:"The Storage to use. Defaults to globalThis.localStorage."}},isAvailable(n=globalThis.localStorage){return n instanceof globalThis.Storage},create({storage:n=globalThis.localStorage}){return new N({store:new x(n)})}};return L(X);})();
1
+ var ZenFS_DOM=(()=>{var F=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var W=Object.getOwnPropertyNames;var U=Object.prototype.hasOwnProperty;var a=(r,e)=>F(r,"name",{value:e,configurable:!0});var $=(r,e)=>{for(var t in e)F(r,t,{get:e[t],enumerable:!0})},R=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of W(e))!U.call(r,i)&&i!==t&&F(r,i,{get:()=>e[i],enumerable:!(n=C(e,i))||n.enumerable});return r};var j=r=>R(F({},"__esModule",{value:!0}),r);var X={};$(X,{IndexedDB:()=>P,IndexedDBStore:()=>u,IndexedDBTransaction:()=>b,WebAccess:()=>V,WebAccessFS:()=>h,WebStorage:()=>z,WebStorageStore:()=>w});var Q=ZenFS,{ActionType:G,ApiError:l,Async:T,AsyncIndexFS:J,AsyncStoreFS:v,BigIntStats:K,BigIntStatsFs:ee,Dir:te,Dirent:re,ErrorCode:d,File:ne,FileIndex:ie,FileSystem:A,FileType:I,InMemory:H,InMemoryStore:se,IndexDirInode:oe,IndexFS:ae,IndexFileInode:ce,IndexInode:le,Inode:de,LockedFS:fe,Mutex:ue,NoSyncFile:me,Overlay:ye,OverlayFS:Se,PreloadFile:O,ReadStream:ge,Readonly:pe,SimpleSyncTransaction:N,Stats:x,StatsCommon:he,StatsFs:be,Sync:we,SyncIndexFS:Ee,SyncStoreFS:B,UnlockedOverlayFS:Fe,WriteStream:Ie,_toUnixTimestamp:xe,access:De,accessSync:ke,appendFile:Te,appendFileSync:ve,checkOptions:Ae,chmod:He,chmodSync:Oe,chown:Ne,chownSync:Be,close:Me,closeSync:_e,configure:Pe,constants:ze,copyFile:Ce,copyFileSync:We,cp:Ue,cpSync:$e,createBackend:Re,createReadStream:je,createWriteStream:Le,decode:M,decodeDirListing:qe,encode:_,encodeDirListing:Ye,errorMessages:Ve,exists:Xe,existsSync:Ze,fchmod:Qe,fchmodSync:Ge,fchown:Je,fchownSync:Ke,fdatasync:et,fdatasyncSync:tt,flagToMode:rt,flagToNumber:nt,flagToString:it,fs:st,fstat:ot,fstatSync:at,fsync:ct,fsyncSync:lt,ftruncate:dt,ftruncateSync:ft,futimes:ut,futimesSync:mt,isAppendable:yt,isBackend:St,isBackendConfig:gt,isExclusive:pt,isReadable:ht,isSynchronous:bt,isTruncating:wt,isWriteable:Et,lchmod:Ft,lchmodSync:It,lchown:xt,lchownSync:Dt,levenshtein:kt,link:Tt,linkSync:vt,lopenSync:At,lstat:Ht,lstatSync:Ot,lutimes:Nt,lutimesSync:Bt,mkdir:Mt,mkdirSync:_t,mkdirpSync:Pt,mkdtemp:zt,mkdtempSync:Ct,mount:Wt,mountMapping:Ut,mounts:$t,nop:Rt,normalizeMode:jt,normalizeOptions:Lt,normalizePath:qt,normalizeTime:Yt,open:Vt,openAsBlob:Xt,openSync:Zt,opendir:Qt,opendirSync:Gt,parseFlag:Jt,pathExistsAction:Kt,pathNotExistsAction:er,promises:tr,randomIno:rr,read:nr,readFile:ir,readFileSync:sr,readSync:or,readdir:ar,readdirSync:cr,readlink:lr,readlinkSync:dr,readv:fr,readvSync:ur,realpath:mr,realpathSync:yr,rename:Sr,renameSync:gr,resolveMountConfig:pr,rm:hr,rmSync:br,rmdir:wr,rmdirSync:Er,rootCred:Fr,rootIno:Ir,setImmediate:xr,size_max:Dr,stat:kr,statSync:Tr,statfs:vr,statfsSync:Ar,symlink:Hr,symlinkSync:Or,truncate:Nr,truncateSync:Br,umount:Mr,unlink:_r,unlinkSync:Pr,unwatchFile:zr,utimes:Cr,utimesSync:Wr,watch:Ur,watchFile:$r,write:Rr,writeFile:jr,writeFileSync:Lr,writeSync:qr,writev:Yr,writevSync:Vr}=ZenFS;function y(r,e){if(typeof r!="string")throw new TypeError(`"${e}" is not a string`)}a(y,"validateString");function L(r,e){let t="",n=0,i=-1,s=0,c="\0";for(let o=0;o<=r.length;++o){if(o<r.length)c=r[o];else{if(c=="/")break;c="/"}if(c=="/"){if(!(i===o-1||s===1))if(s===2){if(t.length<2||n!==2||t.at(-1)!=="."||t.at(-2)!=="."){if(t.length>2){let E=t.lastIndexOf("/");E===-1?(t="",n=0):(t=t.slice(0,E),n=t.length-1-t.lastIndexOf("/")),i=o,s=0;continue}else if(t.length!==0){t="",n=0,i=o,s=0;continue}}e&&(t+=t.length>0?"/..":"..",n=2)}else t.length>0?t+="/"+r.slice(i+1,o):t=r.slice(i+1,o),n=o-i-1;i=o,s=0}else c==="."&&s!==-1?++s:s=-1}return t}a(L,"normalizeString");function q(r){if(y(r,"path"),r.length===0)return".";let e=r[0]==="/",t=r.at(-1)==="/";return r=L(r,!e),r.length===0?e?"/":t?"./":".":(t&&(r+="/"),e?`/${r}`:r)}a(q,"normalize");function S(...r){if(r.length===0)return".";let e;for(let t=0;t<r.length;++t){let n=r[t];y(n,"path"),n.length>0&&(e===void 0?e=n:e+=`/${n}`)}return e===void 0?".":q(e)}a(S,"join");function g(r){if(y(r,"path"),r.length===0)return".";let e=r[0]==="/",t=-1,n=!0;for(let i=r.length-1;i>=1;--i)if(r[i]==="/"){if(!n){t=i;break}}else n=!1;return t===-1?e?"/":".":e&&t===1?"//":r.slice(0,t)}a(g,"dirname");function p(r,e){e!==void 0&&y(e,"ext"),y(r,"path");let t=0,n=-1,i=!0;if(e!==void 0&&e.length>0&&e.length<=r.length){if(e===r)return"";let s=e.length-1,c=-1;for(let o=r.length-1;o>=0;--o)if(r[o]==="/"){if(!i){t=o+1;break}}else c===-1&&(i=!1,c=o+1),s>=0&&(r[o]===e[s]?--s===-1&&(n=o):(s=-1,n=c));return t===n?n=c:n===-1&&(n=r.length),r.slice(t,n)}for(let s=r.length-1;s>=0;--s)if(r[s]==="/"){if(!i){t=s+1;break}}else n===-1&&(i=!1,n=s+1);return n===-1?"":r.slice(t,n)}a(p,"basename");function Y(r){switch(r.name){case"IndexSizeError":case"HierarchyRequestError":case"InvalidCharacterError":case"InvalidStateError":case"SyntaxError":case"NamespaceError":case"TypeMismatchError":case"ConstraintError":case"VersionError":case"URLMismatchError":case"InvalidNodeTypeError":return"EINVAL";case"WrongDocumentError":return"EXDEV";case"NoModificationAllowedError":case"InvalidModificationError":case"InvalidAccessError":case"SecurityError":case"NotAllowedError":return"EACCES";case"NotFoundError":return"ENOENT";case"NotSupportedError":return"ENOTSUP";case"InUseAttributeError":return"EBUSY";case"NetworkError":return"ENETDOWN";case"AbortError":return"EINTR";case"QuotaExceededError":return"ENOSPC";case"TimeoutError":return"ETIMEDOUT";case"ReadOnlyError":return"EROFS";case"DataCloneError":case"EncodingError":case"NotReadableError":case"DataError":case"TransactionInactiveError":case"OperationError":case"UnknownError":default:return"EIO"}}a(Y,"errnoForDOMException");function f(r,e,t){if(r instanceof l)return r;let n=r instanceof DOMException?d[Y(r)]:d.EIO,i=new l(n,r.message,e,t);return i.stack=r.stack,i.cause=r.cause,i}a(f,"convertException");var h=class extends T(A){_handles=new Map;_sync;constructor({handle:e}){super(),this._handles.set("/",e),this._sync=H.create({name:"accessfs-cache"})}metadata(){return{...super.metadata(),name:"WebAccess"}}async sync(e,t,n){let i=await this.stat(e);n.mtime!==i.mtime&&await this.writeFile(e,t)}async rename(e,t){try{let n=await this.getHandle(e);if(n instanceof FileSystemDirectoryHandle){let D=await this.readdir(e);if(await this.mkdir(t),D.length==0)await this.unlink(e);else for(let k of D)await this.rename(S(e,k),S(t,k)),await this.unlink(e)}if(!(n instanceof FileSystemFileHandle))return;let i=await n.getFile(),s=await this.getHandle(g(t));if(!(s instanceof FileSystemDirectoryHandle))return;let o=await(await s.getFileHandle(p(t),{create:!0})).createWritable(),E=await i.arrayBuffer();await o.write(E),o.close(),await this.unlink(e)}catch(n){throw f(n,e,"rename")}}async writeFile(e,t){let n=await this.getHandle(g(e));if(!(n instanceof FileSystemDirectoryHandle))return;let s=await(await n.getFileHandle(p(e),{create:!0})).createWritable();await s.write(t),await s.close()}async createFile(e,t){return await this.writeFile(e,new Uint8Array),this.openFile(e,t)}async stat(e){let t=await this.getHandle(e);if(!t)throw l.With("ENOENT",e,"stat");if(t instanceof FileSystemDirectoryHandle)return new x({mode:511|I.DIRECTORY,size:4096});if(t instanceof FileSystemFileHandle){let{lastModified:n,size:i}=await t.getFile();return new x({mode:511|I.FILE,size:i,mtimeMs:n})}}async openFile(e,t){let n=await this.getHandle(e);if(n instanceof FileSystemFileHandle){let i=await n.getFile(),s=new Uint8Array(await i.arrayBuffer()),c=new x({mode:511|I.FILE,size:i.size,mtimeMs:i.lastModified});return new O(this,e,t,c,s)}}async unlink(e){let t=await this.getHandle(g(e));if(t instanceof FileSystemDirectoryHandle)try{await t.removeEntry(p(e),{recursive:!0})}catch(n){throw f(n,e,"unlink")}}async link(e){throw l.With("ENOSYS",e,"WebAccessFS.link")}async rmdir(e){return this.unlink(e)}async mkdir(e){if(await this.getHandle(e))throw l.With("EEXIST",e,"mkdir");let n=await this.getHandle(g(e));n instanceof FileSystemDirectoryHandle&&await n.getDirectoryHandle(p(e),{create:!0})}async readdir(e){let t=await this.getHandle(e);if(!(t instanceof FileSystemDirectoryHandle))throw l.With("ENOTDIR",e,"readdir");let n=[];for await(let i of t.keys())n.push(S(e,i));return n}async getHandle(e){if(this._handles.has(e))return this._handles.get(e);let t="/";for(let n of e.split("/").slice(1)){let i=this._handles.get(t);if(!(i instanceof FileSystemDirectoryHandle))throw l.With("ENOTDIR",t,"getHandle");t=S(t,n);try{let s=await i.getDirectoryHandle(n);this._handles.set(t,s)}catch(s){if(s.name=="TypeMismatchError")try{let c=await i.getFileHandle(n);this._handles.set(t,c)}catch(c){f(c,t,"getHandle")}if(s.name==="TypeError")throw new l(d.ENOENT,s.message,t,"getHandle");f(s,t,"getHandle")}}return this._handles.get(e)}};a(h,"WebAccessFS");var V={name:"WebAccess",options:{handle:{type:"object",required:!0,description:"The directory handle to use for the root"}},isAvailable(){return typeof FileSystemHandle=="function"},create(r){return new h(r)}};function m(r){return new Promise((e,t)=>{r.onsuccess=()=>e(r.result),r.onerror=n=>{n.preventDefault(),t(f(r.error))}})}a(m,"wrap");var b=class{constructor(e,t){this.tx=e;this.store=t}get(e){return m(this.store.get(e.toString()))}async put(e,t,n){return await m(this.store[n?"put":"add"](t,e.toString())),!0}remove(e){return m(this.store.delete(e.toString()))}async commit(){}async abort(){try{this.tx.abort()}catch(e){throw f(e)}}};a(b,"IndexedDBTransaction");var u=class{constructor(e,t){this.db=e;this.storeName=t}static async create(e,t=globalThis.indexedDB){let n=t.open(e,1);n.onupgradeneeded=()=>{let s=n.result;s.objectStoreNames.contains(e)&&s.deleteObjectStore(e),s.createObjectStore(e)};let i=await m(n);return new u(i,e)}get name(){return P.name+":"+this.storeName}clear(){return m(this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear())}beginTransaction(){let e=this.db.transaction(this.storeName,"readwrite");return new b(e,e.objectStore(this.storeName))}};a(u,"IndexedDBStore");var P={name:"IndexedDB",options:{storeName:{type:"string",required:!1,description:"The name of this file system. You can have multiple IndexedDB file systems operating at once, but each must have a different name."},cacheSize:{type:"number",required:!1,description:"The size of the inode cache. Defaults to 100. A size of 0 or below disables caching."},idbFactory:{type:"object",required:!1,description:"The IDBFactory to use. Defaults to globalThis.indexedDB."}},async isAvailable(r=globalThis.indexedDB){try{if(!(r instanceof IDBFactory))return!1;let e=r.open("__zenfs_test");return await m(e),r.deleteDatabase("__zenfs_test"),!0}catch{return r.deleteDatabase("__zenfs_test"),!1}},create(r){let e=u.create(r.storeName||"zenfs",r.idbFactory);return new v({...r,store:e})}};var w=class{constructor(e){this._storage=e}get name(){return z.name}clear(){this._storage.clear()}beginTransaction(){return new N(this)}get(e){let t=this._storage.getItem(e.toString());if(typeof t=="string")return _(t)}put(e,t,n){try{return!n&&this._storage.getItem(e.toString())!==null?!1:(this._storage.setItem(e.toString(),M(t)),!0)}catch{throw new l(d.ENOSPC,"Storage is full.")}}remove(e){try{this._storage.removeItem(e.toString())}catch(t){throw new l(d.EIO,"Unable to delete key "+e+": "+t)}}};a(w,"WebStorageStore");var z={name:"WebStorage",options:{storage:{type:"object",required:!1,description:"The Storage to use. Defaults to globalThis.localStorage."}},isAvailable(r=globalThis.localStorage){return r instanceof globalThis.Storage},create({storage:r=globalThis.localStorage}){return new B({store:new w(r)})}};return j(X);})();
2
2
  //# sourceMappingURL=browser.min.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/index.ts", "global-externals:@zenfs/core", "../node_modules/@zenfs/core/dist/emulation/path.js", "../src/access.ts", "../src/IndexedDB.ts", "../src/Storage.ts"],
4
- "sourcesContent": ["export * from './access.js';\nexport * from './IndexedDB.js';\nexport * from './Storage.js';\n", "export default ZenFS;\nconst { ActionType, ApiError, Async, AsyncFileIndexFS, AsyncStoreFS, BigIntStats, BigIntStatsFs, Dir, Dirent, ErrorCode, ErrorStrings, File, FileIndex, FileIndexFS, FileSystem, FileType, InMemory, InMemoryStore, IndexDirInode, IndexFileInode, IndexInode, Inode, LockedFS, Mutex, NoSyncFile, Overlay, OverlayFS, PreloadFile, ReadStream, Readonly, SimpleSyncTransaction, Stats, StatsCommon, StatsFs, Sync, SyncFileIndexFS, SyncStoreFS, UnlockedOverlayFS, WriteStream, _toUnixTimestamp, access, accessSync, appendFile, appendFileSync, checkOptions, chmod, chmodSync, chown, chownSync, close, closeSync, configure, constants, copyFile, copyFileSync, cp, cpSync, createBackend, createReadStream, createWriteStream, decode, decodeDirListing, encode, encodeDirListing, exists, existsSync, fchmod, fchmodSync, fchown, fchownSync, fdatasync, fdatasyncSync, flagToMode, flagToNumber, flagToString, fs, fstat, fstatSync, fsync, fsyncSync, ftruncate, ftruncateSync, futimes, futimesSync, isAppendable, isBackend, isBackendConfig, isExclusive, isReadable, isSynchronous, isTruncating, isWriteable, lchmod, lchmodSync, lchown, lchownSync, levenshtein, link, linkSync, lopenSync, lstat, lstatSync, lutimes, lutimesSync, mkdir, mkdirSync, mkdirpSync, mkdtemp, mkdtempSync, mount, mountMapping, mounts, open, openAsBlob, openSync, opendir, opendirSync, parseFlag, pathExistsAction, pathNotExistsAction, promises, randomIno, read, readFile, readFileSync, readSync, readdir, readdirSync, readlink, readlinkSync, readv, readvSync, realpath, realpathSync, rename, renameSync, resolveMountConfig, rm, rmSync, rmdir, rmdirSync, rootCred, rootIno, setImmediate, size_max, stat, statSync, statfs, statfsSync, symlink, symlinkSync, truncate, truncateSync, umount, unlink, unlinkSync, unwatchFile, utimes, utimesSync, wait, watch, watchFile, write, writeFile, writeFileSync, writeSync, writev, writevSync } = ZenFS;\nexport { ActionType, ApiError, Async, AsyncFileIndexFS, AsyncStoreFS, BigIntStats, BigIntStatsFs, Dir, Dirent, ErrorCode, ErrorStrings, File, FileIndex, FileIndexFS, FileSystem, FileType, InMemory, InMemoryStore, IndexDirInode, IndexFileInode, IndexInode, Inode, LockedFS, Mutex, NoSyncFile, Overlay, OverlayFS, PreloadFile, ReadStream, Readonly, SimpleSyncTransaction, Stats, StatsCommon, StatsFs, Sync, SyncFileIndexFS, SyncStoreFS, UnlockedOverlayFS, WriteStream, _toUnixTimestamp, access, accessSync, appendFile, appendFileSync, checkOptions, chmod, chmodSync, chown, chownSync, close, closeSync, configure, constants, copyFile, copyFileSync, cp, cpSync, createBackend, createReadStream, createWriteStream, decode, decodeDirListing, encode, encodeDirListing, exists, existsSync, fchmod, fchmodSync, fchown, fchownSync, fdatasync, fdatasyncSync, flagToMode, flagToNumber, flagToString, fs, fstat, fstatSync, fsync, fsyncSync, ftruncate, ftruncateSync, futimes, futimesSync, isAppendable, isBackend, isBackendConfig, isExclusive, isReadable, isSynchronous, isTruncating, isWriteable, lchmod, lchmodSync, lchown, lchownSync, levenshtein, link, linkSync, lopenSync, lstat, lstatSync, lutimes, lutimesSync, mkdir, mkdirSync, mkdirpSync, mkdtemp, mkdtempSync, mount, mountMapping, mounts, open, openAsBlob, openSync, opendir, opendirSync, parseFlag, pathExistsAction, pathNotExistsAction, promises, randomIno, read, readFile, readFileSync, readSync, readdir, readdirSync, readlink, readlinkSync, readv, readvSync, realpath, realpathSync, rename, renameSync, resolveMountConfig, rm, rmSync, rmdir, rmdirSync, rootCred, rootIno, setImmediate, size_max, stat, statSync, statfs, statfsSync, symlink, symlinkSync, truncate, truncateSync, umount, unlink, unlinkSync, unwatchFile, utimes, utimesSync, wait, watch, watchFile, write, writeFile, writeFileSync, writeSync, writev, writevSync };", "/*\nCopyright Joyent, Inc. and other Node contributors.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\nexport let cwd = '/';\nexport function cd(path) {\n cwd = resolve(cwd, path);\n}\nexport const sep = '/';\nfunction validateString(str, name) {\n if (typeof str != 'string') {\n throw new TypeError(`\"${name}\" is not a string`);\n }\n}\nfunction validateObject(str, name) {\n if (typeof str != 'object') {\n throw new TypeError(`\"${name}\" is not an object`);\n }\n}\n// Resolves . and .. elements in a path with directory names\nexport function normalizeString(path, allowAboveRoot) {\n let res = '';\n let lastSegmentLength = 0;\n let lastSlash = -1;\n let dots = 0;\n let char = '\\x00';\n for (let i = 0; i <= path.length; ++i) {\n if (i < path.length) {\n char = path[i];\n }\n else if (char == '/') {\n break;\n }\n else {\n char = '/';\n }\n if (char == '/') {\n if (lastSlash === i - 1 || dots === 1) {\n // NOOP\n }\n else if (dots === 2) {\n if (res.length < 2 || lastSegmentLength !== 2 || res.at(-1) !== '.' || res.at(-2) !== '.') {\n if (res.length > 2) {\n const lastSlashIndex = res.lastIndexOf('/');\n if (lastSlashIndex === -1) {\n res = '';\n lastSegmentLength = 0;\n }\n else {\n res = res.slice(0, lastSlashIndex);\n lastSegmentLength = res.length - 1 - res.lastIndexOf('/');\n }\n lastSlash = i;\n dots = 0;\n continue;\n }\n else if (res.length !== 0) {\n res = '';\n lastSegmentLength = 0;\n lastSlash = i;\n dots = 0;\n continue;\n }\n }\n if (allowAboveRoot) {\n res += res.length > 0 ? '/..' : '..';\n lastSegmentLength = 2;\n }\n }\n else {\n if (res.length > 0)\n res += '/' + path.slice(lastSlash + 1, i);\n else\n res = path.slice(lastSlash + 1, i);\n lastSegmentLength = i - lastSlash - 1;\n }\n lastSlash = i;\n dots = 0;\n }\n else if (char === '.' && dots !== -1) {\n ++dots;\n }\n else {\n dots = -1;\n }\n }\n return res;\n}\nexport function formatExt(ext) {\n return ext ? `${ext[0] === '.' ? '' : '.'}${ext}` : '';\n}\nexport function resolve(...args) {\n let resolved = '';\n let absolute = false;\n for (let i = args.length - 1; i >= -1 && !absolute; i--) {\n const path = i >= 0 ? args[i] : cwd;\n validateString(path, `paths[${i}]`);\n // Skip empty entries\n if (!path.length) {\n continue;\n }\n resolved = `${path}/${resolved}`;\n absolute = path[0] == '/';\n }\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when cwd fails)\n // Normalize the path\n resolved = normalizeString(resolved, !absolute);\n if (absolute) {\n return `/${resolved}`;\n }\n return resolved.length > 0 ? resolved : '/';\n}\nexport function normalize(path) {\n validateString(path, 'path');\n if (path.length === 0)\n return '.';\n const isAbsolute = path[0] === '/';\n const trailingSeparator = path.at(-1) === '/';\n // Normalize the path\n path = normalizeString(path, !isAbsolute);\n if (path.length === 0) {\n if (isAbsolute)\n return '/';\n return trailingSeparator ? './' : '.';\n }\n if (trailingSeparator)\n path += '/';\n return isAbsolute ? `/${path}` : path;\n}\nexport function isAbsolute(path) {\n validateString(path, 'path');\n return path.length > 0 && path[0] === '/';\n}\nexport function join(...args) {\n if (args.length === 0)\n return '.';\n let joined;\n for (let i = 0; i < args.length; ++i) {\n const arg = args[i];\n validateString(arg, 'path');\n if (arg.length > 0) {\n if (joined === undefined)\n joined = arg;\n else\n joined += `/${arg}`;\n }\n }\n if (joined === undefined)\n return '.';\n return normalize(joined);\n}\nexport function relative(from, to) {\n validateString(from, 'from');\n validateString(to, 'to');\n if (from === to)\n return '';\n // Trim leading forward slashes.\n from = resolve(from);\n to = resolve(to);\n if (from === to)\n return '';\n const fromStart = 1;\n const fromEnd = from.length;\n const fromLen = fromEnd - fromStart;\n const toStart = 1;\n const toLen = to.length - toStart;\n // Compare paths to find the longest common path from root\n const length = fromLen < toLen ? fromLen : toLen;\n let lastCommonSep = -1;\n let i = 0;\n for (; i < length; i++) {\n const fromCode = from[fromStart + i];\n if (fromCode !== to[toStart + i])\n break;\n else if (fromCode === '/')\n lastCommonSep = i;\n }\n if (i === length) {\n if (toLen > length) {\n if (to[toStart + i] === '/') {\n // We get here if `from` is the exact base path for `to`.\n // For example: from='/foo/bar'; to='/foo/bar/baz'\n return to.slice(toStart + i + 1);\n }\n if (i === 0) {\n // We get here if `from` is the root\n // For example: from='/'; to='/foo'\n return to.slice(toStart + i);\n }\n }\n else if (fromLen > length) {\n if (from[fromStart + i] === '/') {\n // We get here if `to` is the exact base path for `from`.\n // For example: from='/foo/bar/baz'; to='/foo/bar'\n lastCommonSep = i;\n }\n else if (i === 0) {\n // We get here if `to` is the root.\n // For example: from='/foo/bar'; to='/'\n lastCommonSep = 0;\n }\n }\n }\n let out = '';\n // Generate the relative path based on the path difference between `to`\n // and `from`.\n for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {\n if (i === fromEnd || from[i] === '/') {\n out += out.length === 0 ? '..' : '/..';\n }\n }\n // Lastly, append the rest of the destination (`to`) path that comes after\n // the common path parts.\n return `${out}${to.slice(toStart + lastCommonSep)}`;\n}\nexport function dirname(path) {\n validateString(path, 'path');\n if (path.length === 0)\n return '.';\n const hasRoot = path[0] === '/';\n let end = -1;\n let matchedSlash = true;\n for (let i = path.length - 1; i >= 1; --i) {\n if (path[i] === '/') {\n if (!matchedSlash) {\n end = i;\n break;\n }\n }\n else {\n // We saw the first non-path separator\n matchedSlash = false;\n }\n }\n if (end === -1)\n return hasRoot ? '/' : '.';\n if (hasRoot && end === 1)\n return '//';\n return path.slice(0, end);\n}\nexport function basename(path, suffix) {\n if (suffix !== undefined)\n validateString(suffix, 'ext');\n validateString(path, 'path');\n let start = 0;\n let end = -1;\n let matchedSlash = true;\n if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {\n if (suffix === path)\n return '';\n let extIdx = suffix.length - 1;\n let firstNonSlashEnd = -1;\n for (let i = path.length - 1; i >= 0; --i) {\n if (path[i] === '/') {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n }\n else {\n if (firstNonSlashEnd === -1) {\n // We saw the first non-path separator, remember this index in case\n // we need it if the extension ends up not matching\n matchedSlash = false;\n firstNonSlashEnd = i + 1;\n }\n if (extIdx >= 0) {\n // Try to match the explicit extension\n if (path[i] === suffix[extIdx]) {\n if (--extIdx === -1) {\n // We matched the extension, so mark this as the end of our path\n // component\n end = i;\n }\n }\n else {\n // Extension does not match, so our result is the entire path\n // component\n extIdx = -1;\n end = firstNonSlashEnd;\n }\n }\n }\n }\n if (start === end)\n end = firstNonSlashEnd;\n else if (end === -1)\n end = path.length;\n return path.slice(start, end);\n }\n for (let i = path.length - 1; i >= 0; --i) {\n if (path[i] === '/') {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n }\n else if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // path component\n matchedSlash = false;\n end = i + 1;\n }\n }\n if (end === -1)\n return '';\n return path.slice(start, end);\n}\nexport function extname(path) {\n validateString(path, 'path');\n let startDot = -1;\n let startPart = 0;\n let end = -1;\n let matchedSlash = true;\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n let preDotState = 0;\n for (let i = path.length - 1; i >= 0; --i) {\n if (path[i] === '/') {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (path[i] === '.') {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1)\n startDot = i;\n else if (preDotState !== 1)\n preDotState = 1;\n }\n else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n if (startDot === -1 ||\n end === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) {\n return '';\n }\n return path.slice(startDot, end);\n}\nexport function format(pathObject) {\n validateObject(pathObject, 'pathObject');\n const dir = pathObject.dir || pathObject.root;\n const base = pathObject.base || `${pathObject.name || ''}${formatExt(pathObject.ext)}`;\n if (!dir) {\n return base;\n }\n return dir === pathObject.root ? `${dir}${base}` : `${dir}/${base}`;\n}\nexport function parse(path) {\n validateString(path, 'path');\n const isAbsolute = path[0] === '/';\n const ret = { root: isAbsolute ? '/' : '', dir: '', base: '', ext: '', name: '' };\n if (path.length === 0)\n return ret;\n const start = isAbsolute ? 1 : 0;\n let startDot = -1;\n let startPart = 0;\n let end = -1;\n let matchedSlash = true;\n let i = path.length - 1;\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n let preDotState = 0;\n // Get non-dir info\n for (; i >= start; --i) {\n if (path[i] === '/') {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (path[i] === '.') {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1)\n startDot = i;\n else if (preDotState !== 1)\n preDotState = 1;\n }\n else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n if (end !== -1) {\n const start = startPart === 0 && isAbsolute ? 1 : startPart;\n if (startDot === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) {\n ret.base = ret.name = path.slice(start, end);\n }\n else {\n ret.name = path.slice(start, startDot);\n ret.base = path.slice(start, end);\n ret.ext = path.slice(startDot, end);\n }\n }\n if (startPart > 0)\n ret.dir = path.slice(0, startPart - 1);\n else if (isAbsolute)\n ret.dir = '/';\n return ret;\n}\n", "import type { Backend, FileSystemMetadata } from '@zenfs/core';\nimport { ApiError, Async, ErrorCode, FileSystem, FileType, InMemory, PreloadFile, Stats } from '@zenfs/core';\nimport { basename, dirname, join } from '@zenfs/core/emulation/path.js';\n\ndeclare global {\n\tinterface FileSystemDirectoryHandle {\n\t\t[Symbol.iterator](): IterableIterator<[string, FileSystemHandle]>;\n\t\tentries(): IterableIterator<[string, FileSystemHandle]>;\n\t\tkeys(): IterableIterator<string>;\n\t\tvalues(): IterableIterator<FileSystemHandle>;\n\t}\n}\n\nexport interface WebAccessOptions {\n\thandle: FileSystemDirectoryHandle;\n}\n\nconst handleError = (path = '', syscall: string, error: Error) => {\n\tif (error.name === 'NotFoundError') {\n\t\tthrow ApiError.With('ENOENT', path, syscall);\n\t}\n\n\tthrow error as ApiError;\n};\n\nexport class WebAccessFS extends Async(FileSystem) {\n\tprivate _handles: Map<string, FileSystemHandle> = new Map();\n\n\t/**\n\t * @hidden\n\t */\n\t_sync: FileSystem;\n\n\tpublic async ready(): Promise<this> {\n\t\treturn this;\n\t}\n\n\tpublic constructor({ handle }: WebAccessOptions) {\n\t\tsuper();\n\t\tthis._handles.set('/', handle);\n\t\tthis._sync = InMemory.create({ name: 'accessfs-cache' });\n\t}\n\n\tpublic metadata(): FileSystemMetadata {\n\t\treturn {\n\t\t\t...super.metadata(),\n\t\t\tname: 'WebAccess',\n\t\t};\n\t}\n\n\tpublic async sync(p: string, data: Uint8Array, stats: Stats): Promise<void> {\n\t\tconst currentStats = await this.stat(p);\n\t\tif (stats.mtime !== currentStats!.mtime) {\n\t\t\tawait this.writeFile(p, data);\n\t\t}\n\t}\n\n\tpublic async rename(oldPath: string, newPath: string): Promise<void> {\n\t\ttry {\n\t\t\tconst handle = await this.getHandle(oldPath);\n\t\t\tif (handle instanceof FileSystemDirectoryHandle) {\n\t\t\t\tconst files = await this.readdir(oldPath);\n\n\t\t\t\tawait this.mkdir(newPath);\n\t\t\t\tif (files.length == 0) {\n\t\t\t\t\tawait this.unlink(oldPath);\n\t\t\t\t} else {\n\t\t\t\t\tfor (const file of files) {\n\t\t\t\t\t\tawait this.rename(join(oldPath, file), join(newPath, file));\n\t\t\t\t\t\tawait this.unlink(oldPath);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!(handle instanceof FileSystemFileHandle)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst oldFile = await handle.getFile(),\n\t\t\t\tdestFolder = await this.getHandle(dirname(newPath));\n\t\t\tif (!(destFolder instanceof FileSystemDirectoryHandle)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst newFile = await destFolder.getFileHandle(basename(newPath), { create: true });\n\t\t\tconst writable = await newFile.createWritable();\n\t\t\tconst buffer = await oldFile.arrayBuffer();\n\t\t\tawait writable.write(buffer);\n\n\t\t\twritable.close();\n\t\t\tawait this.unlink(oldPath);\n\t\t} catch (err) {\n\t\t\thandleError(oldPath, 'rename', err);\n\t\t}\n\t}\n\n\tpublic async writeFile(fname: string, data: Uint8Array): Promise<void> {\n\t\tconst handle = await this.getHandle(dirname(fname));\n\t\tif (!(handle instanceof FileSystemDirectoryHandle)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst file = await handle.getFileHandle(basename(fname), { create: true });\n\t\tconst writable = await file.createWritable();\n\t\tawait writable.write(data);\n\t\tawait writable.close();\n\t}\n\n\tpublic async createFile(path: string, flag: string): Promise<PreloadFile<this>> {\n\t\tawait this.writeFile(path, new Uint8Array());\n\t\treturn this.openFile(path, flag);\n\t}\n\n\tpublic async stat(path: string): Promise<Stats> {\n\t\tconst handle = await this.getHandle(path);\n\t\tif (!handle) {\n\t\t\tthrow ApiError.With('ENOENT', path, 'stat');\n\t\t}\n\t\tif (handle instanceof FileSystemDirectoryHandle) {\n\t\t\treturn new Stats({ mode: 0o777 | FileType.DIRECTORY, size: 4096 });\n\t\t}\n\t\tif (handle instanceof FileSystemFileHandle) {\n\t\t\tconst { lastModified, size } = await handle.getFile();\n\t\t\treturn new Stats({ mode: 0o777 | FileType.FILE, size, mtimeMs: lastModified });\n\t\t}\n\t}\n\n\tpublic async openFile(path: string, flag: string): Promise<PreloadFile<this>> {\n\t\tconst handle = await this.getHandle(path);\n\t\tif (handle instanceof FileSystemFileHandle) {\n\t\t\tconst file = await handle.getFile();\n\t\t\tconst data = new Uint8Array(await file.arrayBuffer());\n\t\t\tconst stats = new Stats({ mode: 0o777 | FileType.FILE, size: file.size, mtimeMs: file.lastModified });\n\t\t\treturn new PreloadFile(this, path, flag, stats, data);\n\t\t}\n\t}\n\n\tpublic async unlink(path: string): Promise<void> {\n\t\tconst handle = await this.getHandle(dirname(path));\n\t\tif (handle instanceof FileSystemDirectoryHandle) {\n\t\t\ttry {\n\t\t\t\tawait handle.removeEntry(basename(path), { recursive: true });\n\t\t\t} catch (e) {\n\t\t\t\thandleError(path, 'unlink', e);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async link(): Promise<void> {\n\t\tthrow new ApiError(ErrorCode.ENOTSUP);\n\t}\n\n\tpublic async rmdir(path: string): Promise<void> {\n\t\treturn this.unlink(path);\n\t}\n\n\tpublic async mkdir(path: string): Promise<void> {\n\t\tconst existingHandle = await this.getHandle(path);\n\t\tif (existingHandle) {\n\t\t\tthrow ApiError.With('EEXIST', path, 'mkdir');\n\t\t}\n\n\t\tconst handle = await this.getHandle(dirname(path));\n\t\tif (handle instanceof FileSystemDirectoryHandle) {\n\t\t\tawait handle.getDirectoryHandle(basename(path), { create: true });\n\t\t}\n\t}\n\n\tpublic async readdir(path: string): Promise<string[]> {\n\t\tconst handle = await this.getHandle(path);\n\t\tif (!(handle instanceof FileSystemDirectoryHandle)) {\n\t\t\tthrow ApiError.With('ENOTDIR', path, 'readdir');\n\t\t}\n\t\tconst _keys: string[] = [];\n\t\tfor await (const key of handle.keys()) {\n\t\t\t_keys.push(join(path, key));\n\t\t}\n\t\treturn _keys;\n\t}\n\n\tprotected async getHandle(path: string): Promise<FileSystemHandle> {\n\t\tif (this._handles.has(path)) {\n\t\t\treturn this._handles.get(path);\n\t\t}\n\n\t\tlet walkedPath = '/';\n\t\tconst [, ...pathParts] = path.split('/');\n\t\tconst getHandleParts = async ([pathPart, ...remainingPathParts]: string[]) => {\n\t\t\tconst walkingPath = join(walkedPath, pathPart);\n\t\t\tconst continueWalk = (handle: FileSystemHandle) => {\n\t\t\t\twalkedPath = walkingPath;\n\t\t\t\tthis._handles.set(walkedPath, handle);\n\n\t\t\t\tif (remainingPathParts.length === 0) {\n\t\t\t\t\treturn this._handles.get(path);\n\t\t\t\t}\n\n\t\t\t\tgetHandleParts(remainingPathParts);\n\t\t\t};\n\t\t\tconst handle = this._handles.get(walkedPath) as FileSystemDirectoryHandle;\n\n\t\t\ttry {\n\t\t\t\treturn continueWalk(await handle.getDirectoryHandle(pathPart));\n\t\t\t} catch (error) {\n\t\t\t\tif (error.name === 'TypeMismatchError') {\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn continueWalk(await handle.getFileHandle(pathPart));\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\thandleError(walkingPath, 'getHandle', err);\n\t\t\t\t\t}\n\t\t\t\t} else if (error.message === 'Name is not allowed.') {\n\t\t\t\t\tthrow new ApiError(ErrorCode.ENOENT, error.message, walkingPath);\n\t\t\t\t} else {\n\t\t\t\t\thandleError(walkingPath, 'getHandle', error);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\treturn await getHandleParts(pathParts);\n\t}\n}\n\nexport const WebAccess = {\n\tname: 'WebAccess',\n\n\toptions: {\n\t\thandle: {\n\t\t\ttype: 'object',\n\t\t\trequired: true,\n\t\t\tdescription: 'The directory handle to use for the root',\n\t\t},\n\t},\n\n\tisAvailable(): boolean {\n\t\treturn typeof FileSystemHandle == 'function';\n\t},\n\n\tcreate(options: WebAccessOptions) {\n\t\treturn new WebAccessFS(options);\n\t},\n} as const satisfies Backend;\n", "import type { AsyncStoreOptions, Backend, Ino } from '@zenfs/core';\nimport { AsyncTransaction, AsyncStore, AsyncStoreFS, ApiError, ErrorCode } from '@zenfs/core';\n\n/**\n * Converts a DOMException or a DOMError from an IndexedDB event into a\n * standardized ZenFS API error.\n * @hidden\n */\nfunction convertError(e: { name: string }, message: string = e.toString()): ApiError {\n\tswitch (e.name) {\n\t\tcase 'NotFoundError':\n\t\t\treturn new ApiError(ErrorCode.ENOENT, message);\n\t\tcase 'QuotaExceededError':\n\t\t\treturn new ApiError(ErrorCode.ENOSPC, message);\n\t\tdefault:\n\t\t\t// The rest do not seem to map cleanly to standard error codes.\n\t\t\treturn new ApiError(ErrorCode.EIO, message);\n\t}\n}\n\nfunction wrap<T>(request: IDBRequest<T>): Promise<T> {\n\treturn new Promise((resolve, reject) => {\n\t\trequest.onsuccess = () => resolve(request.result);\n\t\trequest.onerror = e => {\n\t\t\te.preventDefault();\n\t\t\treject(new ApiError(ErrorCode.EIO));\n\t\t};\n\t});\n}\n\n/**\n * @hidden\n */\nexport class IndexedDBTransaction implements AsyncTransaction {\n\tconstructor(\n\t\tpublic tx: IDBTransaction,\n\t\tpublic store: IDBObjectStore\n\t) {}\n\n\tpublic async get(key: Ino): Promise<Uint8Array> {\n\t\ttry {\n\t\t\treturn await wrap<Uint8Array>(this.store.get(key.toString()));\n\t\t} catch (e) {\n\t\t\tthrow convertError(e);\n\t\t}\n\t}\n\n\t/**\n\t * @todo return false when add has a key conflict (no error)\n\t */\n\tpublic async put(key: Ino, data: Uint8Array, overwrite: boolean): Promise<boolean> {\n\t\ttry {\n\t\t\tawait wrap(overwrite ? this.store.put(data, key.toString()) : this.store.add(data, key.toString()));\n\t\t\treturn true;\n\t\t} catch (e) {\n\t\t\tthrow convertError(e);\n\t\t}\n\t}\n\n\tpublic async remove(key: Ino): Promise<void> {\n\t\ttry {\n\t\t\tawait wrap(this.store.delete(key.toString()));\n\t\t} catch (e) {\n\t\t\tthrow convertError(e);\n\t\t}\n\t}\n\n\tpublic async commit(): Promise<void> {\n\t\treturn;\n\t}\n\n\tpublic async abort(): Promise<void> {\n\t\ttry {\n\t\t\tthis.tx.abort();\n\t\t} catch (e) {\n\t\t\tthrow convertError(e);\n\t\t}\n\t}\n}\n\nexport class IndexedDBStore implements AsyncStore {\n\tpublic static async create(storeName: string, indexedDB: IDBFactory): Promise<IndexedDBStore> {\n\t\tconst req: IDBOpenDBRequest = indexedDB.open(storeName, 1);\n\n\t\treq.onupgradeneeded = () => {\n\t\t\tconst db: IDBDatabase = req.result;\n\t\t\t// This should never happen; we're at version 1. Why does another database exist?\n\t\t\tif (db.objectStoreNames.contains(storeName)) {\n\t\t\t\tdb.deleteObjectStore(storeName);\n\t\t\t}\n\t\t\tdb.createObjectStore(storeName);\n\t\t};\n\n\t\tconst result = await wrap(req);\n\t\treturn new IndexedDBStore(result, storeName);\n\t}\n\n\tconstructor(\n\t\tprotected db: IDBDatabase,\n\t\tprotected storeName: string\n\t) {}\n\n\tpublic get name(): string {\n\t\treturn IndexedDB.name + ':' + this.storeName;\n\t}\n\n\tpublic clear(): Promise<void> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\ttry {\n\t\t\t\tconst req: IDBRequest = this.db.transaction(this.storeName, 'readwrite').objectStore(this.storeName).clear();\n\t\t\t\treq.onsuccess = () => resolve();\n\t\t\t\treq.onerror = e => {\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\treject(new ApiError(ErrorCode.EIO));\n\t\t\t\t};\n\t\t\t} catch (e) {\n\t\t\t\treject(convertError(e));\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic beginTransaction(): IndexedDBTransaction {\n\t\tconst tx = this.db.transaction(this.storeName, 'readwrite'),\n\t\t\tobjectStore = tx.objectStore(this.storeName);\n\t\treturn new IndexedDBTransaction(tx, objectStore);\n\t}\n}\n\n/**\n * Configuration options for the IndexedDB file system.\n */\nexport interface IndexedDBOptions extends Omit<AsyncStoreOptions, 'store'> {\n\t/**\n\t * The name of this file system. You can have multiple IndexedDB file systems operating at once, but each must have a different name.\n\t */\n\tstoreName?: string;\n\n\t/**\n\t * The IDBFactory to use. Defaults to `globalThis.indexedDB`.\n\t */\n\tidbFactory?: IDBFactory;\n}\n\n/**\n * A file system that uses the IndexedDB key value file system.\n */\n\nexport const IndexedDB = {\n\tname: 'IndexedDB',\n\n\toptions: {\n\t\tstoreName: {\n\t\t\ttype: 'string',\n\t\t\trequired: false,\n\t\t\tdescription: 'The name of this file system. You can have multiple IndexedDB file systems operating at once, but each must have a different name.',\n\t\t},\n\t\tcacheSize: {\n\t\t\ttype: 'number',\n\t\t\trequired: false,\n\t\t\tdescription: 'The size of the inode cache. Defaults to 100. A size of 0 or below disables caching.',\n\t\t},\n\t\tidbFactory: {\n\t\t\ttype: 'object',\n\t\t\trequired: false,\n\t\t\tdescription: 'The IDBFactory to use. Defaults to globalThis.indexedDB.',\n\t\t},\n\t},\n\n\tasync isAvailable(idbFactory: IDBFactory = globalThis.indexedDB): Promise<boolean> {\n\t\ttry {\n\t\t\tif (!(idbFactory instanceof IDBFactory)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tconst req = idbFactory.open('__zenfs_test');\n\t\t\tawait wrap(req);\n\t\t\tidbFactory.deleteDatabase('__zenfs_test');\n\t\t\treturn true;\n\t\t} catch (e) {\n\t\t\tidbFactory.deleteDatabase('__zenfs_test');\n\t\t\treturn false;\n\t\t}\n\t},\n\n\tcreate(options: IndexedDBOptions) {\n\t\tconst store = IndexedDBStore.create(options.storeName || 'zenfs', options.idbFactory);\n\t\tconst fs = new AsyncStoreFS({ ...options, store });\n\t\treturn fs;\n\t},\n} as const satisfies Backend;\n", "import type { Backend, Ino } from '@zenfs/core';\nimport { SyncStore, SimpleSyncStore, SimpleSyncTransaction, SyncStoreFS, ApiError, ErrorCode, encode, decode } from '@zenfs/core';\n\n/**\n * A synchronous key-value store backed by Storage.\n */\nexport class WebStorageStore implements SyncStore, SimpleSyncStore {\n\tpublic get name(): string {\n\t\treturn WebStorage.name;\n\t}\n\n\tconstructor(protected _storage: Storage) {}\n\n\tpublic clear(): void {\n\t\tthis._storage.clear();\n\t}\n\n\tpublic beginTransaction(): SimpleSyncTransaction {\n\t\t// No need to differentiate.\n\t\treturn new SimpleSyncTransaction(this);\n\t}\n\n\tpublic get(key: Ino): Uint8Array | undefined {\n\t\tconst data = this._storage.getItem(key.toString());\n\t\tif (typeof data != 'string') {\n\t\t\treturn;\n\t\t}\n\n\t\treturn encode(data);\n\t}\n\n\tpublic put(key: Ino, data: Uint8Array, overwrite: boolean): boolean {\n\t\ttry {\n\t\t\tif (!overwrite && this._storage.getItem(key.toString()) !== null) {\n\t\t\t\t// Don't want to overwrite the key!\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tthis._storage.setItem(key.toString(), decode(data));\n\t\t\treturn true;\n\t\t} catch (e) {\n\t\t\tthrow new ApiError(ErrorCode.ENOSPC, 'Storage is full.');\n\t\t}\n\t}\n\n\tpublic remove(key: Ino): void {\n\t\ttry {\n\t\t\tthis._storage.removeItem(key.toString());\n\t\t} catch (e) {\n\t\t\tthrow new ApiError(ErrorCode.EIO, 'Unable to delete key ' + key + ': ' + e);\n\t\t}\n\t}\n}\n\n/**\n * Options to pass to the StorageFileSystem\n */\nexport interface WebStorageOptions {\n\t/**\n\t * The Storage to use. Defaults to globalThis.localStorage.\n\t */\n\tstorage?: Storage;\n}\n\n/**\n * A synchronous file system backed by a `Storage` (e.g. localStorage).\n */\nexport const WebStorage = {\n\tname: 'WebStorage',\n\n\toptions: {\n\t\tstorage: {\n\t\t\ttype: 'object',\n\t\t\trequired: false,\n\t\t\tdescription: 'The Storage to use. Defaults to globalThis.localStorage.',\n\t\t},\n\t},\n\n\tisAvailable(storage: Storage = globalThis.localStorage): boolean {\n\t\treturn storage instanceof globalThis.Storage;\n\t},\n\n\tcreate({ storage = globalThis.localStorage }: WebStorageOptions) {\n\t\treturn new SyncStoreFS({ store: new WebStorageStore(storage) });\n\t},\n} as const satisfies Backend;\n"],
5
- "mappings": "meAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,eAAAE,EAAA,mBAAAC,EAAA,yBAAAC,EAAA,cAAAC,EAAA,gBAAAC,EAAA,eAAAC,EAAA,oBAAAC,ICAA,IAAOC,EAAQ,MACT,CAAE,WAAAC,EAAY,SAAAC,EAAU,MAAAC,EAAO,iBAAAC,EAAkB,aAAAC,EAAc,YAAAC,GAAa,cAAAC,GAAe,IAAAC,GAAK,OAAAC,GAAQ,UAAAC,EAAW,aAAAC,GAAc,KAAAC,GAAM,UAAAC,GAAW,YAAAC,GAAa,WAAAC,EAAY,SAAAC,EAAU,SAAAC,EAAU,cAAAC,GAAe,cAAAC,GAAe,eAAAC,GAAgB,WAAAC,GAAY,MAAAC,GAAO,SAAAC,GAAU,MAAAC,GAAO,WAAAC,GAAY,QAAAC,GAAS,UAAAC,GAAW,YAAAC,EAAa,WAAAC,GAAY,SAAAC,GAAU,sBAAAC,EAAuB,MAAAC,EAAO,YAAAC,GAAa,QAAAC,GAAS,KAAAC,GAAM,gBAAAC,GAAiB,YAAAC,EAAa,kBAAAC,GAAmB,YAAAC,GAAa,iBAAAC,GAAkB,OAAAC,GAAQ,WAAAC,GAAY,WAAAC,GAAY,eAAAC,GAAgB,aAAAC,GAAc,MAAAC,GAAO,UAAAC,GAAW,MAAAC,GAAO,UAAAC,GAAW,MAAAC,GAAO,UAAAC,GAAW,UAAAC,GAAW,UAAAC,GAAW,SAAAC,GAAU,aAAAC,GAAc,GAAAC,GAAI,OAAAC,GAAQ,cAAAC,GAAe,iBAAAC,GAAkB,kBAAAC,GAAmB,OAAAC,EAAQ,iBAAAC,GAAkB,OAAAC,EAAQ,iBAAAC,GAAkB,OAAAC,GAAQ,WAAAC,GAAY,OAAAC,GAAQ,WAAAC,G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AC/D,CACD",
6
- "names": ["src_exports", "__export", "IndexedDB", "IndexedDBStore", "IndexedDBTransaction", "WebAccess", "WebAccessFS", "WebStorage", "WebStorageStore", "core_default", "ActionType", "ApiError", "Async", "AsyncFileIndexFS", "AsyncStoreFS", "BigIntStats", "BigIntStatsFs", "Dir", "Dirent", "ErrorCode", "ErrorStrings", "File", "FileIndex", "FileIndexFS", "FileSystem", "FileType", "InMemory", "InMemoryStore", "IndexDirInode", "IndexFileInode", "IndexInode", "Inode", "LockedFS", "Mutex", "NoSyncFile", "Overlay", "OverlayFS", "PreloadFile", "ReadStream", "Readonly", "SimpleSyncTransaction", "Stats", "StatsCommon", "StatsFs", "Sync", "SyncFileIndexFS", "SyncStoreFS", "UnlockedOverlayFS", "WriteStream", "_toUnixTimestamp", "access", "accessSync", "appendFile", "appendFileSync", "checkOptions", "chmod", "chmodSync", "chown", "chownSync", "close", "closeSync", "configure", "constants", "copyFile", "copyFileSync", "cp", "cpSync", "createBackend", "createReadStream", "createWriteStream", "decode", "decodeDirListing", "encode", "encodeDirListing", "exists", "existsSync", "fchmod", "fchmodSync", "fchown", "fchownSync", "fdatasync", "fdatasyncSync", "flagToMode", "flagToNumber", "flagToString", "fs", "fstat", "fstatSync", "fsync", "fsyncSync", "ftruncate", "ftruncateSync", "futimes", "futimesSync", "isAppendable", "isBackend", "isBackendConfig", "isExclusive", "isReadable", "isSynchronous", "isTruncating", "isWriteable", "lchmod", "lchmodSync", "lchown", "lchownSync", "levenshtein", "link", "linkSync", "lopenSync", "lstat", "lstatSync", "lutimes", "lutimesSync", "mkdir", "mkdirSync", "mkdirpSync", "mkdtemp", "mkdtempSync", "mount", "mountMapping", "mounts", "open", "openAsBlob", "openSync", "opendir", "opendirSync", "parseFlag", "pathExistsAction", "pathNotExistsAction", "promises", "randomIno", "read", "readFile", "readFileSync", "readSync", "readdir", "readdirSync", "readlink", "readlinkSync", "readv", "readvSync", "realpath", "realpathSync", "rename", "renameSync", "resolveMountConfig", "rm", "rmSync", "rmdir", "rmdirSync", "rootCred", "rootIno", "setImmediate", "size_max", "stat", "statSync", "statfs", "statfsSync", "symlink", "symlinkSync", "truncate", "truncateSync", "umount", "unlink", "unlinkSync", "unwatchFile", "utimes", "utimesSync", "wait", "watch", "watchFile", "write", "writeFile", "writeFileSync", "writeSync", "writev", "writevSync", "validateString", "str", "name", "__name", "normalizeString", "path", "allowAboveRoot", "res", "lastSegmentLength", "lastSlash", "dots", "char", "i", "lastSlashIndex", "__name", "normalize", "path", "validateString", "isAbsolute", "trailingSeparator", "normalizeString", "__name", "join", "args", "joined", "i", "arg", "validateString", "normalize", "__name", "dirname", "path", "validateString", "hasRoot", "end", "matchedSlash", "__name", "basename", "suffix", "start", "extIdx", "firstNonSlashEnd", "i", "handleError", "__name", "path", "syscall", "error", "ApiError", "WebAccessFS", "Async", "FileSystem", "handle", "InMemory", "p", "data", "stats", "currentStats", "oldPath", "newPath", "files", "file", "join", "oldFile", "destFolder", "dirname", "writable", "basename", "buffer", "err", "fname", "flag", "Stats", "FileType", "lastModified", "size", "PreloadFile", "e", "ErrorCode", "_keys", "key", "walkedPath", "pathParts", "getHandleParts", "pathPart", "remainingPathParts", "walkingPath", "continueWalk", "WebAccess", "options", "convertError", "e", "message", "ApiError", "ErrorCode", "__name", "wrap", "request", "resolve", "reject", "IndexedDBTransaction", "tx", "store", "key", "data", "overwrite", "IndexedDBStore", "db", "storeName", "indexedDB", "req", "result", "IndexedDB", "objectStore", "idbFactory", "options", "AsyncStoreFS", "WebStorageStore", "_storage", "WebStorage", "SimpleSyncTransaction", "key", "data", "encode", "overwrite", "decode", "ApiError", "ErrorCode", "e", "__name", "storage", "SyncStoreFS"]
3
+ "sources": ["../src/index.ts", "global-externals:@zenfs/core", "../node_modules/@zenfs/core/dist/emulation/path.js", "../src/utils.ts", "../src/access.ts", "../src/IndexedDB.ts", "../src/Storage.ts"],
4
+ "sourcesContent": ["export * from './access.js';\nexport * from './IndexedDB.js';\nexport * from './Storage.js';\n", "export default ZenFS;\nconst { ActionType, ApiError, Async, AsyncIndexFS, AsyncStoreFS, BigIntStats, BigIntStatsFs, Dir, Dirent, ErrorCode, File, FileIndex, FileSystem, FileType, InMemory, InMemoryStore, IndexDirInode, IndexFS, IndexFileInode, IndexInode, Inode, LockedFS, Mutex, NoSyncFile, Overlay, OverlayFS, PreloadFile, ReadStream, Readonly, SimpleSyncTransaction, Stats, StatsCommon, StatsFs, Sync, SyncIndexFS, SyncStoreFS, UnlockedOverlayFS, WriteStream, _toUnixTimestamp, access, accessSync, appendFile, appendFileSync, checkOptions, chmod, chmodSync, chown, chownSync, close, closeSync, configure, constants, copyFile, copyFileSync, cp, cpSync, createBackend, createReadStream, createWriteStream, decode, decodeDirListing, encode, encodeDirListing, errorMessages, exists, existsSync, fchmod, fchmodSync, fchown, fchownSync, fdatasync, fdatasyncSync, flagToMode, flagToNumber, flagToString, fs, fstat, fstatSync, fsync, fsyncSync, ftruncate, ftruncateSync, futimes, futimesSync, isAppendable, isBackend, isBackendConfig, isExclusive, isReadable, isSynchronous, isTruncating, isWriteable, lchmod, lchmodSync, lchown, lchownSync, levenshtein, link, linkSync, lopenSync, lstat, lstatSync, lutimes, lutimesSync, mkdir, mkdirSync, mkdirpSync, mkdtemp, mkdtempSync, mount, mountMapping, mounts, nop, normalizeMode, normalizeOptions, normalizePath, normalizeTime, open, openAsBlob, openSync, opendir, opendirSync, parseFlag, pathExistsAction, pathNotExistsAction, promises, randomIno, read, readFile, readFileSync, readSync, readdir, readdirSync, readlink, readlinkSync, readv, readvSync, realpath, realpathSync, rename, renameSync, resolveMountConfig, rm, rmSync, rmdir, rmdirSync, rootCred, rootIno, setImmediate, size_max, stat, statSync, statfs, statfsSync, symlink, symlinkSync, truncate, truncateSync, umount, unlink, unlinkSync, unwatchFile, utimes, utimesSync, watch, watchFile, write, writeFile, writeFileSync, writeSync, writev, writevSync } = ZenFS;\nexport { ActionType, ApiError, Async, AsyncIndexFS, AsyncStoreFS, BigIntStats, BigIntStatsFs, Dir, Dirent, ErrorCode, File, FileIndex, FileSystem, FileType, InMemory, InMemoryStore, IndexDirInode, IndexFS, IndexFileInode, IndexInode, Inode, LockedFS, Mutex, NoSyncFile, Overlay, OverlayFS, PreloadFile, ReadStream, Readonly, SimpleSyncTransaction, Stats, StatsCommon, StatsFs, Sync, SyncIndexFS, SyncStoreFS, UnlockedOverlayFS, WriteStream, _toUnixTimestamp, access, accessSync, appendFile, appendFileSync, checkOptions, chmod, chmodSync, chown, chownSync, close, closeSync, configure, constants, copyFile, copyFileSync, cp, cpSync, createBackend, createReadStream, createWriteStream, decode, decodeDirListing, encode, encodeDirListing, errorMessages, exists, existsSync, fchmod, fchmodSync, fchown, fchownSync, fdatasync, fdatasyncSync, flagToMode, flagToNumber, flagToString, fs, fstat, fstatSync, fsync, fsyncSync, ftruncate, ftruncateSync, futimes, futimesSync, isAppendable, isBackend, isBackendConfig, isExclusive, isReadable, isSynchronous, isTruncating, isWriteable, lchmod, lchmodSync, lchown, lchownSync, levenshtein, link, linkSync, lopenSync, lstat, lstatSync, lutimes, lutimesSync, mkdir, mkdirSync, mkdirpSync, mkdtemp, mkdtempSync, mount, mountMapping, mounts, nop, normalizeMode, normalizeOptions, normalizePath, normalizeTime, open, openAsBlob, openSync, opendir, opendirSync, parseFlag, pathExistsAction, pathNotExistsAction, promises, randomIno, read, readFile, readFileSync, readSync, readdir, readdirSync, readlink, readlinkSync, readv, readvSync, realpath, realpathSync, rename, renameSync, resolveMountConfig, rm, rmSync, rmdir, rmdirSync, rootCred, rootIno, setImmediate, size_max, stat, statSync, statfs, statfsSync, symlink, symlinkSync, truncate, truncateSync, umount, unlink, unlinkSync, unwatchFile, utimes, utimesSync, watch, watchFile, write, writeFile, writeFileSync, writeSync, writev, writevSync };", "/*\nCopyright Joyent, Inc. and other Node contributors.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\nexport let cwd = '/';\nexport function cd(path) {\n cwd = resolve(cwd, path);\n}\nexport const sep = '/';\nfunction validateString(str, name) {\n if (typeof str != 'string') {\n throw new TypeError(`\"${name}\" is not a string`);\n }\n}\nfunction validateObject(str, name) {\n if (typeof str != 'object') {\n throw new TypeError(`\"${name}\" is not an object`);\n }\n}\n// Resolves . and .. elements in a path with directory names\nexport function normalizeString(path, allowAboveRoot) {\n let res = '';\n let lastSegmentLength = 0;\n let lastSlash = -1;\n let dots = 0;\n let char = '\\x00';\n for (let i = 0; i <= path.length; ++i) {\n if (i < path.length) {\n char = path[i];\n }\n else if (char == '/') {\n break;\n }\n else {\n char = '/';\n }\n if (char == '/') {\n if (lastSlash === i - 1 || dots === 1) {\n // NOOP\n }\n else if (dots === 2) {\n if (res.length < 2 || lastSegmentLength !== 2 || res.at(-1) !== '.' || res.at(-2) !== '.') {\n if (res.length > 2) {\n const lastSlashIndex = res.lastIndexOf('/');\n if (lastSlashIndex === -1) {\n res = '';\n lastSegmentLength = 0;\n }\n else {\n res = res.slice(0, lastSlashIndex);\n lastSegmentLength = res.length - 1 - res.lastIndexOf('/');\n }\n lastSlash = i;\n dots = 0;\n continue;\n }\n else if (res.length !== 0) {\n res = '';\n lastSegmentLength = 0;\n lastSlash = i;\n dots = 0;\n continue;\n }\n }\n if (allowAboveRoot) {\n res += res.length > 0 ? '/..' : '..';\n lastSegmentLength = 2;\n }\n }\n else {\n if (res.length > 0)\n res += '/' + path.slice(lastSlash + 1, i);\n else\n res = path.slice(lastSlash + 1, i);\n lastSegmentLength = i - lastSlash - 1;\n }\n lastSlash = i;\n dots = 0;\n }\n else if (char === '.' && dots !== -1) {\n ++dots;\n }\n else {\n dots = -1;\n }\n }\n return res;\n}\nexport function formatExt(ext) {\n return ext ? `${ext[0] === '.' ? '' : '.'}${ext}` : '';\n}\nexport function resolve(...args) {\n let resolved = '';\n let absolute = false;\n for (let i = args.length - 1; i >= -1 && !absolute; i--) {\n const path = i >= 0 ? args[i] : cwd;\n validateString(path, `paths[${i}]`);\n // Skip empty entries\n if (!path.length) {\n continue;\n }\n resolved = `${path}/${resolved}`;\n absolute = path[0] == '/';\n }\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when cwd fails)\n // Normalize the path\n resolved = normalizeString(resolved, !absolute);\n if (absolute) {\n return `/${resolved}`;\n }\n return resolved.length > 0 ? resolved : '/';\n}\nexport function normalize(path) {\n validateString(path, 'path');\n if (path.length === 0)\n return '.';\n const isAbsolute = path[0] === '/';\n const trailingSeparator = path.at(-1) === '/';\n // Normalize the path\n path = normalizeString(path, !isAbsolute);\n if (path.length === 0) {\n if (isAbsolute)\n return '/';\n return trailingSeparator ? './' : '.';\n }\n if (trailingSeparator)\n path += '/';\n return isAbsolute ? `/${path}` : path;\n}\nexport function isAbsolute(path) {\n validateString(path, 'path');\n return path.length > 0 && path[0] === '/';\n}\nexport function join(...args) {\n if (args.length === 0)\n return '.';\n let joined;\n for (let i = 0; i < args.length; ++i) {\n const arg = args[i];\n validateString(arg, 'path');\n if (arg.length > 0) {\n if (joined === undefined)\n joined = arg;\n else\n joined += `/${arg}`;\n }\n }\n if (joined === undefined)\n return '.';\n return normalize(joined);\n}\nexport function relative(from, to) {\n validateString(from, 'from');\n validateString(to, 'to');\n if (from === to)\n return '';\n // Trim leading forward slashes.\n from = resolve(from);\n to = resolve(to);\n if (from === to)\n return '';\n const fromStart = 1;\n const fromEnd = from.length;\n const fromLen = fromEnd - fromStart;\n const toStart = 1;\n const toLen = to.length - toStart;\n // Compare paths to find the longest common path from root\n const length = fromLen < toLen ? fromLen : toLen;\n let lastCommonSep = -1;\n let i = 0;\n for (; i < length; i++) {\n const fromCode = from[fromStart + i];\n if (fromCode !== to[toStart + i])\n break;\n else if (fromCode === '/')\n lastCommonSep = i;\n }\n if (i === length) {\n if (toLen > length) {\n if (to[toStart + i] === '/') {\n // We get here if `from` is the exact base path for `to`.\n // For example: from='/foo/bar'; to='/foo/bar/baz'\n return to.slice(toStart + i + 1);\n }\n if (i === 0) {\n // We get here if `from` is the root\n // For example: from='/'; to='/foo'\n return to.slice(toStart + i);\n }\n }\n else if (fromLen > length) {\n if (from[fromStart + i] === '/') {\n // We get here if `to` is the exact base path for `from`.\n // For example: from='/foo/bar/baz'; to='/foo/bar'\n lastCommonSep = i;\n }\n else if (i === 0) {\n // We get here if `to` is the root.\n // For example: from='/foo/bar'; to='/'\n lastCommonSep = 0;\n }\n }\n }\n let out = '';\n // Generate the relative path based on the path difference between `to`\n // and `from`.\n for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {\n if (i === fromEnd || from[i] === '/') {\n out += out.length === 0 ? '..' : '/..';\n }\n }\n // Lastly, append the rest of the destination (`to`) path that comes after\n // the common path parts.\n return `${out}${to.slice(toStart + lastCommonSep)}`;\n}\nexport function dirname(path) {\n validateString(path, 'path');\n if (path.length === 0)\n return '.';\n const hasRoot = path[0] === '/';\n let end = -1;\n let matchedSlash = true;\n for (let i = path.length - 1; i >= 1; --i) {\n if (path[i] === '/') {\n if (!matchedSlash) {\n end = i;\n break;\n }\n }\n else {\n // We saw the first non-path separator\n matchedSlash = false;\n }\n }\n if (end === -1)\n return hasRoot ? '/' : '.';\n if (hasRoot && end === 1)\n return '//';\n return path.slice(0, end);\n}\nexport function basename(path, suffix) {\n if (suffix !== undefined)\n validateString(suffix, 'ext');\n validateString(path, 'path');\n let start = 0;\n let end = -1;\n let matchedSlash = true;\n if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {\n if (suffix === path)\n return '';\n let extIdx = suffix.length - 1;\n let firstNonSlashEnd = -1;\n for (let i = path.length - 1; i >= 0; --i) {\n if (path[i] === '/') {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n }\n else {\n if (firstNonSlashEnd === -1) {\n // We saw the first non-path separator, remember this index in case\n // we need it if the extension ends up not matching\n matchedSlash = false;\n firstNonSlashEnd = i + 1;\n }\n if (extIdx >= 0) {\n // Try to match the explicit extension\n if (path[i] === suffix[extIdx]) {\n if (--extIdx === -1) {\n // We matched the extension, so mark this as the end of our path\n // component\n end = i;\n }\n }\n else {\n // Extension does not match, so our result is the entire path\n // component\n extIdx = -1;\n end = firstNonSlashEnd;\n }\n }\n }\n }\n if (start === end)\n end = firstNonSlashEnd;\n else if (end === -1)\n end = path.length;\n return path.slice(start, end);\n }\n for (let i = path.length - 1; i >= 0; --i) {\n if (path[i] === '/') {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n }\n else if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // path component\n matchedSlash = false;\n end = i + 1;\n }\n }\n if (end === -1)\n return '';\n return path.slice(start, end);\n}\nexport function extname(path) {\n validateString(path, 'path');\n let startDot = -1;\n let startPart = 0;\n let end = -1;\n let matchedSlash = true;\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n let preDotState = 0;\n for (let i = path.length - 1; i >= 0; --i) {\n if (path[i] === '/') {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (path[i] === '.') {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1)\n startDot = i;\n else if (preDotState !== 1)\n preDotState = 1;\n }\n else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n if (startDot === -1 ||\n end === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) {\n return '';\n }\n return path.slice(startDot, end);\n}\nexport function format(pathObject) {\n validateObject(pathObject, 'pathObject');\n const dir = pathObject.dir || pathObject.root;\n const base = pathObject.base || `${pathObject.name || ''}${formatExt(pathObject.ext)}`;\n if (!dir) {\n return base;\n }\n return dir === pathObject.root ? `${dir}${base}` : `${dir}/${base}`;\n}\nexport function parse(path) {\n validateString(path, 'path');\n const isAbsolute = path[0] === '/';\n const ret = { root: isAbsolute ? '/' : '', dir: '', base: '', ext: '', name: '' };\n if (path.length === 0)\n return ret;\n const start = isAbsolute ? 1 : 0;\n let startDot = -1;\n let startPart = 0;\n let end = -1;\n let matchedSlash = true;\n let i = path.length - 1;\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n let preDotState = 0;\n // Get non-dir info\n for (; i >= start; --i) {\n if (path[i] === '/') {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (path[i] === '.') {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1)\n startDot = i;\n else if (preDotState !== 1)\n preDotState = 1;\n }\n else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n if (end !== -1) {\n const start = startPart === 0 && isAbsolute ? 1 : startPart;\n if (startDot === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) {\n ret.base = ret.name = path.slice(start, end);\n }\n else {\n ret.name = path.slice(start, startDot);\n ret.base = path.slice(start, end);\n ret.ext = path.slice(startDot, end);\n }\n }\n if (startPart > 0)\n ret.dir = path.slice(0, startPart - 1);\n else if (isAbsolute)\n ret.dir = '/';\n return ret;\n}\n", "import { ApiError, ErrorCode } from '@zenfs/core';\n\n/**\n * Converts a DOMException into an ErrorCode\n * @see https://developer.mozilla.org/Web/API/DOMException\n */\nfunction errnoForDOMException(ex: DOMException): keyof typeof ErrorCode {\n\tswitch (ex.name) {\n\t\tcase 'IndexSizeError':\n\t\tcase 'HierarchyRequestError':\n\t\tcase 'InvalidCharacterError':\n\t\tcase 'InvalidStateError':\n\t\tcase 'SyntaxError':\n\t\tcase 'NamespaceError':\n\t\tcase 'TypeMismatchError':\n\t\tcase 'ConstraintError':\n\t\tcase 'VersionError':\n\t\tcase 'URLMismatchError':\n\t\tcase 'InvalidNodeTypeError':\n\t\t\treturn 'EINVAL';\n\t\tcase 'WrongDocumentError':\n\t\t\treturn 'EXDEV';\n\t\tcase 'NoModificationAllowedError':\n\t\tcase 'InvalidModificationError':\n\t\tcase 'InvalidAccessError':\n\t\tcase 'SecurityError':\n\t\tcase 'NotAllowedError':\n\t\t\treturn 'EACCES';\n\t\tcase 'NotFoundError':\n\t\t\treturn 'ENOENT';\n\t\tcase 'NotSupportedError':\n\t\t\treturn 'ENOTSUP';\n\t\tcase 'InUseAttributeError':\n\t\t\treturn 'EBUSY';\n\t\tcase 'NetworkError':\n\t\t\treturn 'ENETDOWN';\n\t\tcase 'AbortError':\n\t\t\treturn 'EINTR';\n\t\tcase 'QuotaExceededError':\n\t\t\treturn 'ENOSPC';\n\t\tcase 'TimeoutError':\n\t\t\treturn 'ETIMEDOUT';\n\t\tcase 'ReadOnlyError':\n\t\t\treturn 'EROFS';\n\t\tcase 'DataCloneError':\n\t\tcase 'EncodingError':\n\t\tcase 'NotReadableError':\n\t\tcase 'DataError':\n\t\tcase 'TransactionInactiveError':\n\t\tcase 'OperationError':\n\t\tcase 'UnknownError':\n\t\tdefault:\n\t\t\treturn 'EIO';\n\t}\n}\n\n/**\n * Handles converting errors, then rethrowing them\n */\nexport function convertException(ex: Error | ApiError | DOMException, path?: string, syscall?: string): ApiError {\n\tif (ex instanceof ApiError) {\n\t\treturn ex;\n\t}\n\n\tconst code = ex instanceof DOMException ? ErrorCode[errnoForDOMException(ex)] : ErrorCode.EIO;\n\tconst error = new ApiError(code, ex.message, path, syscall);\n\terror.stack = ex.stack;\n\terror.cause = ex.cause;\n\treturn error;\n}\n", "import type { Backend, FileSystemMetadata } from '@zenfs/core';\nimport { ApiError, Async, ErrorCode, FileSystem, FileType, InMemory, PreloadFile, Stats } from '@zenfs/core';\nimport { basename, dirname, join } from '@zenfs/core/emulation/path.js';\nimport { convertException } from './utils.js';\n\ndeclare global {\n\tinterface FileSystemDirectoryHandle {\n\t\t[Symbol.iterator](): IterableIterator<[string, FileSystemHandle]>;\n\t\tentries(): IterableIterator<[string, FileSystemHandle]>;\n\t\tkeys(): IterableIterator<string>;\n\t\tvalues(): IterableIterator<FileSystemHandle>;\n\t}\n}\n\nexport interface WebAccessOptions {\n\thandle: FileSystemDirectoryHandle;\n}\n\nexport class WebAccessFS extends Async(FileSystem) {\n\tprivate _handles: Map<string, FileSystemHandle> = new Map();\n\n\t/**\n\t * @hidden\n\t */\n\t_sync: FileSystem;\n\n\tpublic constructor({ handle }: WebAccessOptions) {\n\t\tsuper();\n\t\tthis._handles.set('/', handle);\n\t\tthis._sync = InMemory.create({ name: 'accessfs-cache' });\n\t}\n\n\tpublic metadata(): FileSystemMetadata {\n\t\treturn {\n\t\t\t...super.metadata(),\n\t\t\tname: 'WebAccess',\n\t\t};\n\t}\n\n\tpublic async sync(p: string, data: Uint8Array, stats: Stats): Promise<void> {\n\t\tconst currentStats = await this.stat(p);\n\t\tif (stats.mtime !== currentStats!.mtime) {\n\t\t\tawait this.writeFile(p, data);\n\t\t}\n\t}\n\n\tpublic async rename(oldPath: string, newPath: string): Promise<void> {\n\t\ttry {\n\t\t\tconst handle = await this.getHandle(oldPath);\n\t\t\tif (handle instanceof FileSystemDirectoryHandle) {\n\t\t\t\tconst files = await this.readdir(oldPath);\n\n\t\t\t\tawait this.mkdir(newPath);\n\t\t\t\tif (files.length == 0) {\n\t\t\t\t\tawait this.unlink(oldPath);\n\t\t\t\t} else {\n\t\t\t\t\tfor (const file of files) {\n\t\t\t\t\t\tawait this.rename(join(oldPath, file), join(newPath, file));\n\t\t\t\t\t\tawait this.unlink(oldPath);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!(handle instanceof FileSystemFileHandle)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst oldFile = await handle.getFile(),\n\t\t\t\tdestFolder = await this.getHandle(dirname(newPath));\n\t\t\tif (!(destFolder instanceof FileSystemDirectoryHandle)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst newFile = await destFolder.getFileHandle(basename(newPath), { create: true });\n\t\t\tconst writable = await newFile.createWritable();\n\t\t\tconst buffer = await oldFile.arrayBuffer();\n\t\t\tawait writable.write(buffer);\n\n\t\t\twritable.close();\n\t\t\tawait this.unlink(oldPath);\n\t\t} catch (ex) {\n\t\t\tthrow convertException(ex, oldPath, 'rename');\n\t\t}\n\t}\n\n\tpublic async writeFile(fname: string, data: Uint8Array): Promise<void> {\n\t\tconst handle = await this.getHandle(dirname(fname));\n\t\tif (!(handle instanceof FileSystemDirectoryHandle)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst file = await handle.getFileHandle(basename(fname), { create: true });\n\t\tconst writable = await file.createWritable();\n\t\tawait writable.write(data);\n\t\tawait writable.close();\n\t}\n\n\tpublic async createFile(path: string, flag: string): Promise<PreloadFile<this>> {\n\t\tawait this.writeFile(path, new Uint8Array());\n\t\treturn this.openFile(path, flag);\n\t}\n\n\tpublic async stat(path: string): Promise<Stats> {\n\t\tconst handle = await this.getHandle(path);\n\t\tif (!handle) {\n\t\t\tthrow ApiError.With('ENOENT', path, 'stat');\n\t\t}\n\t\tif (handle instanceof FileSystemDirectoryHandle) {\n\t\t\treturn new Stats({ mode: 0o777 | FileType.DIRECTORY, size: 4096 });\n\t\t}\n\t\tif (handle instanceof FileSystemFileHandle) {\n\t\t\tconst { lastModified, size } = await handle.getFile();\n\t\t\treturn new Stats({ mode: 0o777 | FileType.FILE, size, mtimeMs: lastModified });\n\t\t}\n\t}\n\n\tpublic async openFile(path: string, flag: string): Promise<PreloadFile<this>> {\n\t\tconst handle = await this.getHandle(path);\n\t\tif (handle instanceof FileSystemFileHandle) {\n\t\t\tconst file = await handle.getFile();\n\t\t\tconst data = new Uint8Array(await file.arrayBuffer());\n\t\t\tconst stats = new Stats({ mode: 0o777 | FileType.FILE, size: file.size, mtimeMs: file.lastModified });\n\t\t\treturn new PreloadFile(this, path, flag, stats, data);\n\t\t}\n\t}\n\n\tpublic async unlink(path: string): Promise<void> {\n\t\tconst handle = await this.getHandle(dirname(path));\n\t\tif (handle instanceof FileSystemDirectoryHandle) {\n\t\t\ttry {\n\t\t\t\tawait handle.removeEntry(basename(path), { recursive: true });\n\t\t\t} catch (ex) {\n\t\t\t\tthrow convertException(ex, path, 'unlink');\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async link(srcpath: string): Promise<void> {\n\t\tthrow ApiError.With('ENOSYS', srcpath, 'WebAccessFS.link');\n\t}\n\n\tpublic async rmdir(path: string): Promise<void> {\n\t\treturn this.unlink(path);\n\t}\n\n\tpublic async mkdir(path: string): Promise<void> {\n\t\tconst existingHandle = await this.getHandle(path);\n\t\tif (existingHandle) {\n\t\t\tthrow ApiError.With('EEXIST', path, 'mkdir');\n\t\t}\n\n\t\tconst handle = await this.getHandle(dirname(path));\n\t\tif (handle instanceof FileSystemDirectoryHandle) {\n\t\t\tawait handle.getDirectoryHandle(basename(path), { create: true });\n\t\t}\n\t}\n\n\tpublic async readdir(path: string): Promise<string[]> {\n\t\tconst handle = await this.getHandle(path);\n\t\tif (!(handle instanceof FileSystemDirectoryHandle)) {\n\t\t\tthrow ApiError.With('ENOTDIR', path, 'readdir');\n\t\t}\n\t\tconst _keys: string[] = [];\n\t\tfor await (const key of handle.keys()) {\n\t\t\t_keys.push(join(path, key));\n\t\t}\n\t\treturn _keys;\n\t}\n\n\tprotected async getHandle(path: string): Promise<FileSystemHandle> {\n\t\tif (this._handles.has(path)) {\n\t\t\treturn this._handles.get(path);\n\t\t}\n\n\t\tlet walked = '/';\n\n\t\tfor (const part of path.split('/').slice(1)) {\n\t\t\tconst handle = this._handles.get(walked);\n\t\t\tif (!(handle instanceof FileSystemDirectoryHandle)) {\n\t\t\t\tthrow ApiError.With('ENOTDIR', walked, 'getHandle');\n\t\t\t}\n\t\t\twalked = join(walked, part);\n\n\t\t\ttry {\n\t\t\t\tconst dirHandle = await handle.getDirectoryHandle(part);\n\t\t\t\tthis._handles.set(walked, dirHandle);\n\t\t\t} catch (ex) {\n\t\t\t\tif (ex.name == 'TypeMismatchError') {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst fileHandle = await handle.getFileHandle(part);\n\t\t\t\t\t\tthis._handles.set(walked, fileHandle);\n\t\t\t\t\t} catch (ex) {\n\t\t\t\t\t\tconvertException(ex, walked, 'getHandle');\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (ex.name === 'TypeError') {\n\t\t\t\t\tthrow new ApiError(ErrorCode.ENOENT, ex.message, walked, 'getHandle');\n\t\t\t\t}\n\n\t\t\t\tconvertException(ex, walked, 'getHandle');\n\t\t\t}\n\t\t}\n\n\t\treturn this._handles.get(path);\n\t}\n}\n\nexport const WebAccess = {\n\tname: 'WebAccess',\n\n\toptions: {\n\t\thandle: {\n\t\t\ttype: 'object',\n\t\t\trequired: true,\n\t\t\tdescription: 'The directory handle to use for the root',\n\t\t},\n\t},\n\n\tisAvailable(): boolean {\n\t\treturn typeof FileSystemHandle == 'function';\n\t},\n\n\tcreate(options: WebAccessOptions) {\n\t\treturn new WebAccessFS(options);\n\t},\n} as const satisfies Backend;\n", "import type { AsyncStore, AsyncStoreOptions, AsyncTransaction, Backend, Ino } from '@zenfs/core';\nimport { AsyncStoreFS } from '@zenfs/core';\nimport { convertException } from './utils.js';\n\nfunction wrap<T>(request: IDBRequest<T>): Promise<T> {\n\treturn new Promise((resolve, reject) => {\n\t\trequest.onsuccess = () => resolve(request.result);\n\t\trequest.onerror = e => {\n\t\t\te.preventDefault();\n\t\t\treject(convertException(request.error));\n\t\t};\n\t});\n}\n\n/**\n * @hidden\n */\nexport class IndexedDBTransaction implements AsyncTransaction {\n\tconstructor(\n\t\tpublic tx: IDBTransaction,\n\t\tpublic store: IDBObjectStore\n\t) {}\n\n\tpublic get(key: Ino): Promise<Uint8Array> {\n\t\treturn wrap<Uint8Array>(this.store.get(key.toString()));\n\t}\n\n\t/**\n\t * @todo return false when add has a key conflict (no error)\n\t */\n\tpublic async put(key: Ino, data: Uint8Array, overwrite: boolean): Promise<boolean> {\n\t\tawait wrap(this.store[overwrite ? 'put' : 'add'](data, key.toString()));\n\t\treturn true;\n\t}\n\n\tpublic remove(key: Ino): Promise<void> {\n\t\treturn wrap(this.store.delete(key.toString()));\n\t}\n\n\tpublic async commit(): Promise<void> {\n\t\treturn;\n\t}\n\n\tpublic async abort(): Promise<void> {\n\t\ttry {\n\t\t\tthis.tx.abort();\n\t\t} catch (e) {\n\t\t\tthrow convertException(e);\n\t\t}\n\t}\n}\n\nexport class IndexedDBStore implements AsyncStore {\n\tpublic static async create(storeName: string, indexedDB: IDBFactory = globalThis.indexedDB): Promise<IndexedDBStore> {\n\t\tconst req: IDBOpenDBRequest = indexedDB.open(storeName, 1);\n\n\t\treq.onupgradeneeded = () => {\n\t\t\tconst db: IDBDatabase = req.result;\n\t\t\t// This should never happen; we're at version 1. Why does another database exist?\n\t\t\tif (db.objectStoreNames.contains(storeName)) {\n\t\t\t\tdb.deleteObjectStore(storeName);\n\t\t\t}\n\t\t\tdb.createObjectStore(storeName);\n\t\t};\n\n\t\tconst result = await wrap(req);\n\t\treturn new IndexedDBStore(result, storeName);\n\t}\n\n\tconstructor(\n\t\tprotected db: IDBDatabase,\n\t\tprotected storeName: string\n\t) {}\n\n\tpublic get name(): string {\n\t\treturn IndexedDB.name + ':' + this.storeName;\n\t}\n\n\tpublic clear(): Promise<void> {\n\t\treturn wrap(this.db.transaction(this.storeName, 'readwrite').objectStore(this.storeName).clear());\n\t}\n\n\tpublic beginTransaction(): IndexedDBTransaction {\n\t\tconst tx = this.db.transaction(this.storeName, 'readwrite');\n\t\treturn new IndexedDBTransaction(tx, tx.objectStore(this.storeName));\n\t}\n}\n\n/**\n * Configuration options for the IndexedDB file system.\n */\nexport interface IndexedDBOptions extends Omit<AsyncStoreOptions, 'store'> {\n\t/**\n\t * The name of this file system. You can have multiple IndexedDB file systems operating at once, but each must have a different name.\n\t */\n\tstoreName?: string;\n\n\t/**\n\t * The IDBFactory to use. Defaults to `globalThis.indexedDB`.\n\t */\n\tidbFactory?: IDBFactory;\n}\n\n/**\n * A file system that uses the IndexedDB key value file system.\n */\n\nexport const IndexedDB = {\n\tname: 'IndexedDB',\n\n\toptions: {\n\t\tstoreName: {\n\t\t\ttype: 'string',\n\t\t\trequired: false,\n\t\t\tdescription: 'The name of this file system. You can have multiple IndexedDB file systems operating at once, but each must have a different name.',\n\t\t},\n\t\tcacheSize: {\n\t\t\ttype: 'number',\n\t\t\trequired: false,\n\t\t\tdescription: 'The size of the inode cache. Defaults to 100. A size of 0 or below disables caching.',\n\t\t},\n\t\tidbFactory: {\n\t\t\ttype: 'object',\n\t\t\trequired: false,\n\t\t\tdescription: 'The IDBFactory to use. Defaults to globalThis.indexedDB.',\n\t\t},\n\t},\n\n\tasync isAvailable(idbFactory: IDBFactory = globalThis.indexedDB): Promise<boolean> {\n\t\ttry {\n\t\t\tif (!(idbFactory instanceof IDBFactory)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tconst req = idbFactory.open('__zenfs_test');\n\t\t\tawait wrap(req);\n\t\t\tidbFactory.deleteDatabase('__zenfs_test');\n\t\t\treturn true;\n\t\t} catch (e) {\n\t\t\tidbFactory.deleteDatabase('__zenfs_test');\n\t\t\treturn false;\n\t\t}\n\t},\n\n\tcreate(options: IndexedDBOptions) {\n\t\tconst store = IndexedDBStore.create(options.storeName || 'zenfs', options.idbFactory);\n\t\tconst fs = new AsyncStoreFS({ ...options, store });\n\t\treturn fs;\n\t},\n} as const satisfies Backend;\n", "import type { Backend, Ino, SimpleSyncStore, SyncStore } from '@zenfs/core';\nimport { ApiError, ErrorCode, SimpleSyncTransaction, SyncStoreFS, decode, encode } from '@zenfs/core';\n\n/**\n * A synchronous key-value store backed by Storage.\n */\nexport class WebStorageStore implements SyncStore, SimpleSyncStore {\n\tpublic get name(): string {\n\t\treturn WebStorage.name;\n\t}\n\n\tconstructor(protected _storage: Storage) {}\n\n\tpublic clear(): void {\n\t\tthis._storage.clear();\n\t}\n\n\tpublic beginTransaction(): SimpleSyncTransaction {\n\t\t// No need to differentiate.\n\t\treturn new SimpleSyncTransaction(this);\n\t}\n\n\tpublic get(key: Ino): Uint8Array | undefined {\n\t\tconst data = this._storage.getItem(key.toString());\n\t\tif (typeof data != 'string') {\n\t\t\treturn;\n\t\t}\n\n\t\treturn encode(data);\n\t}\n\n\tpublic put(key: Ino, data: Uint8Array, overwrite: boolean): boolean {\n\t\ttry {\n\t\t\tif (!overwrite && this._storage.getItem(key.toString()) !== null) {\n\t\t\t\t// Don't want to overwrite the key!\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tthis._storage.setItem(key.toString(), decode(data));\n\t\t\treturn true;\n\t\t} catch (e) {\n\t\t\tthrow new ApiError(ErrorCode.ENOSPC, 'Storage is full.');\n\t\t}\n\t}\n\n\tpublic remove(key: Ino): void {\n\t\ttry {\n\t\t\tthis._storage.removeItem(key.toString());\n\t\t} catch (e) {\n\t\t\tthrow new ApiError(ErrorCode.EIO, 'Unable to delete key ' + key + ': ' + e);\n\t\t}\n\t}\n}\n\n/**\n * Options to pass to the StorageFileSystem\n */\nexport interface WebStorageOptions {\n\t/**\n\t * The Storage to use. Defaults to globalThis.localStorage.\n\t */\n\tstorage?: Storage;\n}\n\n/**\n * A synchronous file system backed by a `Storage` (e.g. localStorage).\n */\nexport const WebStorage = {\n\tname: 'WebStorage',\n\n\toptions: {\n\t\tstorage: {\n\t\t\ttype: 'object',\n\t\t\trequired: false,\n\t\t\tdescription: 'The Storage to use. Defaults to globalThis.localStorage.',\n\t\t},\n\t},\n\n\tisAvailable(storage: Storage = globalThis.localStorage): boolean {\n\t\treturn storage instanceof globalThis.Storage;\n\t},\n\n\tcreate({ storage = globalThis.localStorage }: WebStorageOptions) {\n\t\treturn new SyncStoreFS({ store: new WebStorageStore(storage) });\n\t},\n} as const satisfies Backend;\n"],
5
+ "mappings": "meAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,eAAAE,EAAA,mBAAAC,EAAA,yBAAAC,EAAA,cAAAC,EAAA,gBAAAC,EAAA,eAAAC,EAAA,oBAAAC,ICAA,IAAOC,EAAQ,MACT,CAAE,WAAAC,EAAY,SAAAC,EAAU,MAAAC,EAAO,aAAAC,EAAc,aAAAC,EAAc,YAAAC,EAAa,cAAAC,GAAe,IAAAC,GAAK,OAAAC,GAAQ,UAAAC,EAAW,KAAAC,GAAM,UAAAC,GAAW,WAAAC,EAAY,SAAAC,EAAU,SAAAC,EAAU,cAAAC,GAAe,cAAAC,GAAe,QAAAC,GAAS,eAAAC,GAAgB,WAAAC,GAAY,MAAAC,GAAO,SAAAC,GAAU,MAAAC,GAAO,WAAAC,GAAY,QAAAC,GAAS,UA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AAU,OAAQ,kBAAkB,CACxD,CACD,CAEO,OAAON,EAAgB,CAC7B,GAAI,CACH,KAAK,SAAS,WAAWA,EAAI,SAAS,CAAC,CACxC,OAASO,EAAP,CACD,MAAM,IAAIF,EAASC,EAAU,IAAK,wBAA0BN,EAAM,KAAOO,CAAC,CAC3E,CACD,CACD,EA7CaC,EAAAZ,EAAA,mBA4DN,IAAME,EAAa,CACzB,KAAM,aAEN,QAAS,CACR,QAAS,CACR,KAAM,SACN,SAAU,GACV,YAAa,0DACd,CACD,EAEA,YAAYW,EAAmB,WAAW,aAAuB,CAChE,OAAOA,aAAmB,WAAW,OACtC,EAEA,OAAO,CAAE,QAAAA,EAAU,WAAW,YAAa,EAAsB,CAChE,OAAO,IAAIC,EAAY,CAAE,MAAO,IAAId,EAAgBa,CAAO,CAAE,CAAC,CAC/D,CACD",
6
+ "names": ["src_exports", "__export", "IndexedDB", "IndexedDBStore", "IndexedDBTransaction", "WebAccess", "WebAccessFS", "WebStorage", "WebStorageStore", "core_default", "ActionType", "ApiError", "Async", "AsyncIndexFS", "AsyncStoreFS", "BigIntStats", "BigIntStatsFs", "Dir", "Dirent", "ErrorCode", "File", "FileIndex", "FileSystem", "FileType", "InMemory", "InMemoryStore", "IndexDirInode", "IndexFS", "IndexFileInode", "IndexInode", "Inode", "LockedFS", "Mutex", "NoSyncFile", "Overlay", "OverlayFS", "PreloadFile", "ReadStream", "Readonly", "SimpleSyncTransaction", "Stats", "StatsCommon", "StatsFs", "Sync", "SyncIndexFS", "SyncStoreFS", "UnlockedOverlayFS", "WriteStream", "_toUnixTimestamp", "access", "accessSync", "appendFile", "appendFileSync", "checkOptions", "chmod", "chmodSync", "chown", "chownSync", "close", "closeSync", "configure", "constants", "copyFile", "copyFileSync", "cp", "cpSync", "createBackend", "createReadStream", "createWriteStream", "decode", "decodeDirListing", "encode", "encodeDirListing", "errorMessages", "exists", "existsSync", "fchmod", "fchmodSync", "fchown", "fchownSync", "fdatasync", "fdatasyncSync", "flagToMode", "flagToNumber", "flagToString", "fs", "fstat", "fstatSync", "fsync", "fsyncSync", "ftruncate", "ftruncateSync", "futimes", "futimesSync", "isAppendable", "isBackend", "isBackendConfig", "isExclusive", "isReadable", "isSynchronous", "isTruncating", "isWriteable", "lchmod", "lchmodSync", "lchown", "lchownSync", "levenshtein", "link", "linkSync", "lopenSync", "lstat", "lstatSync", "lutimes", "lutimesSync", "mkdir", "mkdirSync", "mkdirpSync", "mkdtemp", "mkdtempSync", "mount", "mountMapping", "mounts", "nop", "normalizeMode", "normalizeOptions", "normalizePath", "normalizeTime", "open", "openAsBlob", "openSync", "opendir", "opendirSync", "parseFlag", "pathExistsAction", "pathNotExistsAction", "promises", "randomIno", "read", "readFile", "readFileSync", "readSync", "readdir", "readdirSync", "readlink", "readlinkSync", "readv", "readvSync", "realpath", "realpathSync", "rename", "renameSync", "resolveMountConfig", "rm", "rmSync", "rmdir", "rmdirSync", "rootCred", "rootIno", "setImmediate", "size_max", "stat", "statSync", "statfs", "statfsSync", "symlink", "symlinkSync", "truncate", "truncateSync", "umount", "unlink", "unlinkSync", "unwatchFile", "utimes", "utimesSync", "watch", "watchFile", "write", "writeFile", "writeFileSync", "writeSync", "writev", "writevSync", "validateString", "str", "name", "__name", "normalizeString", "path", "allowAboveRoot", "res", "lastSegmentLength", "lastSlash", "dots", "char", "i", "lastSlashIndex", "__name", "normalize", "path", "validateString", "isAbsolute", "trailingSeparator", "normalizeString", "__name", "join", "args", "joined", "i", "arg", "validateString", "normalize", "__name", "dirname", "path", "validateString", "hasRoot", "end", "matchedSlash", "__name", "basename", "suffix", "start", "extIdx", "firstNonSlashEnd", "i", "errnoForDOMException", "ex", "__name", "convertException", "path", "syscall", "ApiError", "code", "ErrorCode", "error", "WebAccessFS", "Async", "FileSystem", "handle", "InMemory", "p", "data", "stats", "currentStats", "oldPath", "newPath", "files", "file", "join", "oldFile", "destFolder", "dirname", "writable", "basename", "buffer", "ex", "convertException", "fname", "path", "flag", "ApiError", "Stats", "FileType", "lastModified", "size", "PreloadFile", "srcpath", "_keys", "key", "walked", "part", "dirHandle", "fileHandle", "ErrorCode", "__name", "WebAccess", "options", "wrap", "request", "resolve", "reject", "e", "convertException", "__name", "IndexedDBTransaction", "tx", "store", "key", "data", "overwrite", "IndexedDBStore", "db", "storeName", "indexedDB", "req", "result", "IndexedDB", "idbFactory", "options", "AsyncStoreFS", "WebStorageStore", "_storage", "WebStorage", "SimpleSyncTransaction", "key", "data", "encode", "overwrite", "decode", "ApiError", "ErrorCode", "e", "__name", "storage", "SyncStoreFS"]
7
7
  }
@@ -0,0 +1,5 @@
1
+ import { ApiError } from '@zenfs/core';
2
+ /**
3
+ * Handles converting errors, then rethrowing them
4
+ */
5
+ export declare function convertException(ex: Error | ApiError | DOMException, path?: string, syscall?: string): ApiError;
package/dist/utils.js ADDED
@@ -0,0 +1,67 @@
1
+ import { ApiError, ErrorCode } from '@zenfs/core';
2
+ /**
3
+ * Converts a DOMException into an ErrorCode
4
+ * @see https://developer.mozilla.org/Web/API/DOMException
5
+ */
6
+ function errnoForDOMException(ex) {
7
+ switch (ex.name) {
8
+ case 'IndexSizeError':
9
+ case 'HierarchyRequestError':
10
+ case 'InvalidCharacterError':
11
+ case 'InvalidStateError':
12
+ case 'SyntaxError':
13
+ case 'NamespaceError':
14
+ case 'TypeMismatchError':
15
+ case 'ConstraintError':
16
+ case 'VersionError':
17
+ case 'URLMismatchError':
18
+ case 'InvalidNodeTypeError':
19
+ return 'EINVAL';
20
+ case 'WrongDocumentError':
21
+ return 'EXDEV';
22
+ case 'NoModificationAllowedError':
23
+ case 'InvalidModificationError':
24
+ case 'InvalidAccessError':
25
+ case 'SecurityError':
26
+ case 'NotAllowedError':
27
+ return 'EACCES';
28
+ case 'NotFoundError':
29
+ return 'ENOENT';
30
+ case 'NotSupportedError':
31
+ return 'ENOTSUP';
32
+ case 'InUseAttributeError':
33
+ return 'EBUSY';
34
+ case 'NetworkError':
35
+ return 'ENETDOWN';
36
+ case 'AbortError':
37
+ return 'EINTR';
38
+ case 'QuotaExceededError':
39
+ return 'ENOSPC';
40
+ case 'TimeoutError':
41
+ return 'ETIMEDOUT';
42
+ case 'ReadOnlyError':
43
+ return 'EROFS';
44
+ case 'DataCloneError':
45
+ case 'EncodingError':
46
+ case 'NotReadableError':
47
+ case 'DataError':
48
+ case 'TransactionInactiveError':
49
+ case 'OperationError':
50
+ case 'UnknownError':
51
+ default:
52
+ return 'EIO';
53
+ }
54
+ }
55
+ /**
56
+ * Handles converting errors, then rethrowing them
57
+ */
58
+ export function convertException(ex, path, syscall) {
59
+ if (ex instanceof ApiError) {
60
+ return ex;
61
+ }
62
+ const code = ex instanceof DOMException ? ErrorCode[errnoForDOMException(ex)] : ErrorCode.EIO;
63
+ const error = new ApiError(code, ex.message, path, syscall);
64
+ error.stack = ex.stack;
65
+ error.cause = ex.cause;
66
+ return error;
67
+ }
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@zenfs/dom",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "DOM backends for ZenFS",
5
5
  "main": "dist/index.js",
6
- "types": "dist",
6
+ "types": "src/index.ts",
7
7
  "keywords": [
8
8
  "filesystem",
9
9
  "node",
@@ -27,13 +27,6 @@
27
27
  ".": "./dist/index.js",
28
28
  "./*": "./dist/*"
29
29
  },
30
- "typesVersions": {
31
- "*": {
32
- "*": [
33
- "./dist/*"
34
- ]
35
- }
36
- },
37
30
  "scripts": {
38
31
  "format": "prettier --write .",
39
32
  "format:check": "prettier --check .",
@@ -53,6 +46,6 @@
53
46
  "typescript": "5.2.2"
54
47
  },
55
48
  "peerDependencies": {
56
- "@zenfs/core": "^0.7.0"
49
+ "@zenfs/core": "^0.9.4"
57
50
  }
58
51
  }
@@ -0,0 +1,149 @@
1
+ import type { AsyncStore, AsyncStoreOptions, AsyncTransaction, Backend, Ino } from '@zenfs/core';
2
+ import { AsyncStoreFS } from '@zenfs/core';
3
+ import { convertException } from './utils.js';
4
+
5
+ function wrap<T>(request: IDBRequest<T>): Promise<T> {
6
+ return new Promise((resolve, reject) => {
7
+ request.onsuccess = () => resolve(request.result);
8
+ request.onerror = e => {
9
+ e.preventDefault();
10
+ reject(convertException(request.error));
11
+ };
12
+ });
13
+ }
14
+
15
+ /**
16
+ * @hidden
17
+ */
18
+ export class IndexedDBTransaction implements AsyncTransaction {
19
+ constructor(
20
+ public tx: IDBTransaction,
21
+ public store: IDBObjectStore
22
+ ) {}
23
+
24
+ public get(key: Ino): Promise<Uint8Array> {
25
+ return wrap<Uint8Array>(this.store.get(key.toString()));
26
+ }
27
+
28
+ /**
29
+ * @todo return false when add has a key conflict (no error)
30
+ */
31
+ public async put(key: Ino, data: Uint8Array, overwrite: boolean): Promise<boolean> {
32
+ await wrap(this.store[overwrite ? 'put' : 'add'](data, key.toString()));
33
+ return true;
34
+ }
35
+
36
+ public remove(key: Ino): Promise<void> {
37
+ return wrap(this.store.delete(key.toString()));
38
+ }
39
+
40
+ public async commit(): Promise<void> {
41
+ return;
42
+ }
43
+
44
+ public async abort(): Promise<void> {
45
+ try {
46
+ this.tx.abort();
47
+ } catch (e) {
48
+ throw convertException(e);
49
+ }
50
+ }
51
+ }
52
+
53
+ export class IndexedDBStore implements AsyncStore {
54
+ public static async create(storeName: string, indexedDB: IDBFactory = globalThis.indexedDB): Promise<IndexedDBStore> {
55
+ const req: IDBOpenDBRequest = indexedDB.open(storeName, 1);
56
+
57
+ req.onupgradeneeded = () => {
58
+ const db: IDBDatabase = req.result;
59
+ // This should never happen; we're at version 1. Why does another database exist?
60
+ if (db.objectStoreNames.contains(storeName)) {
61
+ db.deleteObjectStore(storeName);
62
+ }
63
+ db.createObjectStore(storeName);
64
+ };
65
+
66
+ const result = await wrap(req);
67
+ return new IndexedDBStore(result, storeName);
68
+ }
69
+
70
+ constructor(
71
+ protected db: IDBDatabase,
72
+ protected storeName: string
73
+ ) {}
74
+
75
+ public get name(): string {
76
+ return IndexedDB.name + ':' + this.storeName;
77
+ }
78
+
79
+ public clear(): Promise<void> {
80
+ return wrap(this.db.transaction(this.storeName, 'readwrite').objectStore(this.storeName).clear());
81
+ }
82
+
83
+ public beginTransaction(): IndexedDBTransaction {
84
+ const tx = this.db.transaction(this.storeName, 'readwrite');
85
+ return new IndexedDBTransaction(tx, tx.objectStore(this.storeName));
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Configuration options for the IndexedDB file system.
91
+ */
92
+ export interface IndexedDBOptions extends Omit<AsyncStoreOptions, 'store'> {
93
+ /**
94
+ * The name of this file system. You can have multiple IndexedDB file systems operating at once, but each must have a different name.
95
+ */
96
+ storeName?: string;
97
+
98
+ /**
99
+ * The IDBFactory to use. Defaults to `globalThis.indexedDB`.
100
+ */
101
+ idbFactory?: IDBFactory;
102
+ }
103
+
104
+ /**
105
+ * A file system that uses the IndexedDB key value file system.
106
+ */
107
+
108
+ export const IndexedDB = {
109
+ name: 'IndexedDB',
110
+
111
+ options: {
112
+ storeName: {
113
+ type: 'string',
114
+ required: false,
115
+ description: 'The name of this file system. You can have multiple IndexedDB file systems operating at once, but each must have a different name.',
116
+ },
117
+ cacheSize: {
118
+ type: 'number',
119
+ required: false,
120
+ description: 'The size of the inode cache. Defaults to 100. A size of 0 or below disables caching.',
121
+ },
122
+ idbFactory: {
123
+ type: 'object',
124
+ required: false,
125
+ description: 'The IDBFactory to use. Defaults to globalThis.indexedDB.',
126
+ },
127
+ },
128
+
129
+ async isAvailable(idbFactory: IDBFactory = globalThis.indexedDB): Promise<boolean> {
130
+ try {
131
+ if (!(idbFactory instanceof IDBFactory)) {
132
+ return false;
133
+ }
134
+ const req = idbFactory.open('__zenfs_test');
135
+ await wrap(req);
136
+ idbFactory.deleteDatabase('__zenfs_test');
137
+ return true;
138
+ } catch (e) {
139
+ idbFactory.deleteDatabase('__zenfs_test');
140
+ return false;
141
+ }
142
+ },
143
+
144
+ create(options: IndexedDBOptions) {
145
+ const store = IndexedDBStore.create(options.storeName || 'zenfs', options.idbFactory);
146
+ const fs = new AsyncStoreFS({ ...options, store });
147
+ return fs;
148
+ },
149
+ } as const satisfies Backend;
package/src/Storage.ts ADDED
@@ -0,0 +1,85 @@
1
+ import type { Backend, Ino, SimpleSyncStore, SyncStore } from '@zenfs/core';
2
+ import { ApiError, ErrorCode, SimpleSyncTransaction, SyncStoreFS, decode, encode } from '@zenfs/core';
3
+
4
+ /**
5
+ * A synchronous key-value store backed by Storage.
6
+ */
7
+ export class WebStorageStore implements SyncStore, SimpleSyncStore {
8
+ public get name(): string {
9
+ return WebStorage.name;
10
+ }
11
+
12
+ constructor(protected _storage: Storage) {}
13
+
14
+ public clear(): void {
15
+ this._storage.clear();
16
+ }
17
+
18
+ public beginTransaction(): SimpleSyncTransaction {
19
+ // No need to differentiate.
20
+ return new SimpleSyncTransaction(this);
21
+ }
22
+
23
+ public get(key: Ino): Uint8Array | undefined {
24
+ const data = this._storage.getItem(key.toString());
25
+ if (typeof data != 'string') {
26
+ return;
27
+ }
28
+
29
+ return encode(data);
30
+ }
31
+
32
+ public put(key: Ino, data: Uint8Array, overwrite: boolean): boolean {
33
+ try {
34
+ if (!overwrite && this._storage.getItem(key.toString()) !== null) {
35
+ // Don't want to overwrite the key!
36
+ return false;
37
+ }
38
+ this._storage.setItem(key.toString(), decode(data));
39
+ return true;
40
+ } catch (e) {
41
+ throw new ApiError(ErrorCode.ENOSPC, 'Storage is full.');
42
+ }
43
+ }
44
+
45
+ public remove(key: Ino): void {
46
+ try {
47
+ this._storage.removeItem(key.toString());
48
+ } catch (e) {
49
+ throw new ApiError(ErrorCode.EIO, 'Unable to delete key ' + key + ': ' + e);
50
+ }
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Options to pass to the StorageFileSystem
56
+ */
57
+ export interface WebStorageOptions {
58
+ /**
59
+ * The Storage to use. Defaults to globalThis.localStorage.
60
+ */
61
+ storage?: Storage;
62
+ }
63
+
64
+ /**
65
+ * A synchronous file system backed by a `Storage` (e.g. localStorage).
66
+ */
67
+ export const WebStorage = {
68
+ name: 'WebStorage',
69
+
70
+ options: {
71
+ storage: {
72
+ type: 'object',
73
+ required: false,
74
+ description: 'The Storage to use. Defaults to globalThis.localStorage.',
75
+ },
76
+ },
77
+
78
+ isAvailable(storage: Storage = globalThis.localStorage): boolean {
79
+ return storage instanceof globalThis.Storage;
80
+ },
81
+
82
+ create({ storage = globalThis.localStorage }: WebStorageOptions) {
83
+ return new SyncStoreFS({ store: new WebStorageStore(storage) });
84
+ },
85
+ } as const satisfies Backend;
package/src/access.ts ADDED
@@ -0,0 +1,224 @@
1
+ import type { Backend, FileSystemMetadata } from '@zenfs/core';
2
+ import { ApiError, Async, ErrorCode, FileSystem, FileType, InMemory, PreloadFile, Stats } from '@zenfs/core';
3
+ import { basename, dirname, join } from '@zenfs/core/emulation/path.js';
4
+ import { convertException } from './utils.js';
5
+
6
+ declare global {
7
+ interface FileSystemDirectoryHandle {
8
+ [Symbol.iterator](): IterableIterator<[string, FileSystemHandle]>;
9
+ entries(): IterableIterator<[string, FileSystemHandle]>;
10
+ keys(): IterableIterator<string>;
11
+ values(): IterableIterator<FileSystemHandle>;
12
+ }
13
+ }
14
+
15
+ export interface WebAccessOptions {
16
+ handle: FileSystemDirectoryHandle;
17
+ }
18
+
19
+ export class WebAccessFS extends Async(FileSystem) {
20
+ private _handles: Map<string, FileSystemHandle> = new Map();
21
+
22
+ /**
23
+ * @hidden
24
+ */
25
+ _sync: FileSystem;
26
+
27
+ public constructor({ handle }: WebAccessOptions) {
28
+ super();
29
+ this._handles.set('/', handle);
30
+ this._sync = InMemory.create({ name: 'accessfs-cache' });
31
+ }
32
+
33
+ public metadata(): FileSystemMetadata {
34
+ return {
35
+ ...super.metadata(),
36
+ name: 'WebAccess',
37
+ };
38
+ }
39
+
40
+ public async sync(p: string, data: Uint8Array, stats: Stats): Promise<void> {
41
+ const currentStats = await this.stat(p);
42
+ if (stats.mtime !== currentStats!.mtime) {
43
+ await this.writeFile(p, data);
44
+ }
45
+ }
46
+
47
+ public async rename(oldPath: string, newPath: string): Promise<void> {
48
+ try {
49
+ const handle = await this.getHandle(oldPath);
50
+ if (handle instanceof FileSystemDirectoryHandle) {
51
+ const files = await this.readdir(oldPath);
52
+
53
+ await this.mkdir(newPath);
54
+ if (files.length == 0) {
55
+ await this.unlink(oldPath);
56
+ } else {
57
+ for (const file of files) {
58
+ await this.rename(join(oldPath, file), join(newPath, file));
59
+ await this.unlink(oldPath);
60
+ }
61
+ }
62
+ }
63
+ if (!(handle instanceof FileSystemFileHandle)) {
64
+ return;
65
+ }
66
+ const oldFile = await handle.getFile(),
67
+ destFolder = await this.getHandle(dirname(newPath));
68
+ if (!(destFolder instanceof FileSystemDirectoryHandle)) {
69
+ return;
70
+ }
71
+ const newFile = await destFolder.getFileHandle(basename(newPath), { create: true });
72
+ const writable = await newFile.createWritable();
73
+ const buffer = await oldFile.arrayBuffer();
74
+ await writable.write(buffer);
75
+
76
+ writable.close();
77
+ await this.unlink(oldPath);
78
+ } catch (ex) {
79
+ throw convertException(ex, oldPath, 'rename');
80
+ }
81
+ }
82
+
83
+ public async writeFile(fname: string, data: Uint8Array): Promise<void> {
84
+ const handle = await this.getHandle(dirname(fname));
85
+ if (!(handle instanceof FileSystemDirectoryHandle)) {
86
+ return;
87
+ }
88
+
89
+ const file = await handle.getFileHandle(basename(fname), { create: true });
90
+ const writable = await file.createWritable();
91
+ await writable.write(data);
92
+ await writable.close();
93
+ }
94
+
95
+ public async createFile(path: string, flag: string): Promise<PreloadFile<this>> {
96
+ await this.writeFile(path, new Uint8Array());
97
+ return this.openFile(path, flag);
98
+ }
99
+
100
+ public async stat(path: string): Promise<Stats> {
101
+ const handle = await this.getHandle(path);
102
+ if (!handle) {
103
+ throw ApiError.With('ENOENT', path, 'stat');
104
+ }
105
+ if (handle instanceof FileSystemDirectoryHandle) {
106
+ return new Stats({ mode: 0o777 | FileType.DIRECTORY, size: 4096 });
107
+ }
108
+ if (handle instanceof FileSystemFileHandle) {
109
+ const { lastModified, size } = await handle.getFile();
110
+ return new Stats({ mode: 0o777 | FileType.FILE, size, mtimeMs: lastModified });
111
+ }
112
+ }
113
+
114
+ public async openFile(path: string, flag: string): Promise<PreloadFile<this>> {
115
+ const handle = await this.getHandle(path);
116
+ if (handle instanceof FileSystemFileHandle) {
117
+ const file = await handle.getFile();
118
+ const data = new Uint8Array(await file.arrayBuffer());
119
+ const stats = new Stats({ mode: 0o777 | FileType.FILE, size: file.size, mtimeMs: file.lastModified });
120
+ return new PreloadFile(this, path, flag, stats, data);
121
+ }
122
+ }
123
+
124
+ public async unlink(path: string): Promise<void> {
125
+ const handle = await this.getHandle(dirname(path));
126
+ if (handle instanceof FileSystemDirectoryHandle) {
127
+ try {
128
+ await handle.removeEntry(basename(path), { recursive: true });
129
+ } catch (ex) {
130
+ throw convertException(ex, path, 'unlink');
131
+ }
132
+ }
133
+ }
134
+
135
+ public async link(srcpath: string): Promise<void> {
136
+ throw ApiError.With('ENOSYS', srcpath, 'WebAccessFS.link');
137
+ }
138
+
139
+ public async rmdir(path: string): Promise<void> {
140
+ return this.unlink(path);
141
+ }
142
+
143
+ public async mkdir(path: string): Promise<void> {
144
+ const existingHandle = await this.getHandle(path);
145
+ if (existingHandle) {
146
+ throw ApiError.With('EEXIST', path, 'mkdir');
147
+ }
148
+
149
+ const handle = await this.getHandle(dirname(path));
150
+ if (handle instanceof FileSystemDirectoryHandle) {
151
+ await handle.getDirectoryHandle(basename(path), { create: true });
152
+ }
153
+ }
154
+
155
+ public async readdir(path: string): Promise<string[]> {
156
+ const handle = await this.getHandle(path);
157
+ if (!(handle instanceof FileSystemDirectoryHandle)) {
158
+ throw ApiError.With('ENOTDIR', path, 'readdir');
159
+ }
160
+ const _keys: string[] = [];
161
+ for await (const key of handle.keys()) {
162
+ _keys.push(join(path, key));
163
+ }
164
+ return _keys;
165
+ }
166
+
167
+ protected async getHandle(path: string): Promise<FileSystemHandle> {
168
+ if (this._handles.has(path)) {
169
+ return this._handles.get(path);
170
+ }
171
+
172
+ let walked = '/';
173
+
174
+ for (const part of path.split('/').slice(1)) {
175
+ const handle = this._handles.get(walked);
176
+ if (!(handle instanceof FileSystemDirectoryHandle)) {
177
+ throw ApiError.With('ENOTDIR', walked, 'getHandle');
178
+ }
179
+ walked = join(walked, part);
180
+
181
+ try {
182
+ const dirHandle = await handle.getDirectoryHandle(part);
183
+ this._handles.set(walked, dirHandle);
184
+ } catch (ex) {
185
+ if (ex.name == 'TypeMismatchError') {
186
+ try {
187
+ const fileHandle = await handle.getFileHandle(part);
188
+ this._handles.set(walked, fileHandle);
189
+ } catch (ex) {
190
+ convertException(ex, walked, 'getHandle');
191
+ }
192
+ }
193
+
194
+ if (ex.name === 'TypeError') {
195
+ throw new ApiError(ErrorCode.ENOENT, ex.message, walked, 'getHandle');
196
+ }
197
+
198
+ convertException(ex, walked, 'getHandle');
199
+ }
200
+ }
201
+
202
+ return this._handles.get(path);
203
+ }
204
+ }
205
+
206
+ export const WebAccess = {
207
+ name: 'WebAccess',
208
+
209
+ options: {
210
+ handle: {
211
+ type: 'object',
212
+ required: true,
213
+ description: 'The directory handle to use for the root',
214
+ },
215
+ },
216
+
217
+ isAvailable(): boolean {
218
+ return typeof FileSystemHandle == 'function';
219
+ },
220
+
221
+ create(options: WebAccessOptions) {
222
+ return new WebAccessFS(options);
223
+ },
224
+ } as const satisfies Backend;
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './access.js';
2
+ export * from './IndexedDB.js';
3
+ export * from './Storage.js';
package/src/utils.ts ADDED
@@ -0,0 +1,70 @@
1
+ import { ApiError, ErrorCode } from '@zenfs/core';
2
+
3
+ /**
4
+ * Converts a DOMException into an ErrorCode
5
+ * @see https://developer.mozilla.org/Web/API/DOMException
6
+ */
7
+ function errnoForDOMException(ex: DOMException): keyof typeof ErrorCode {
8
+ switch (ex.name) {
9
+ case 'IndexSizeError':
10
+ case 'HierarchyRequestError':
11
+ case 'InvalidCharacterError':
12
+ case 'InvalidStateError':
13
+ case 'SyntaxError':
14
+ case 'NamespaceError':
15
+ case 'TypeMismatchError':
16
+ case 'ConstraintError':
17
+ case 'VersionError':
18
+ case 'URLMismatchError':
19
+ case 'InvalidNodeTypeError':
20
+ return 'EINVAL';
21
+ case 'WrongDocumentError':
22
+ return 'EXDEV';
23
+ case 'NoModificationAllowedError':
24
+ case 'InvalidModificationError':
25
+ case 'InvalidAccessError':
26
+ case 'SecurityError':
27
+ case 'NotAllowedError':
28
+ return 'EACCES';
29
+ case 'NotFoundError':
30
+ return 'ENOENT';
31
+ case 'NotSupportedError':
32
+ return 'ENOTSUP';
33
+ case 'InUseAttributeError':
34
+ return 'EBUSY';
35
+ case 'NetworkError':
36
+ return 'ENETDOWN';
37
+ case 'AbortError':
38
+ return 'EINTR';
39
+ case 'QuotaExceededError':
40
+ return 'ENOSPC';
41
+ case 'TimeoutError':
42
+ return 'ETIMEDOUT';
43
+ case 'ReadOnlyError':
44
+ return 'EROFS';
45
+ case 'DataCloneError':
46
+ case 'EncodingError':
47
+ case 'NotReadableError':
48
+ case 'DataError':
49
+ case 'TransactionInactiveError':
50
+ case 'OperationError':
51
+ case 'UnknownError':
52
+ default:
53
+ return 'EIO';
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Handles converting errors, then rethrowing them
59
+ */
60
+ export function convertException(ex: Error | ApiError | DOMException, path?: string, syscall?: string): ApiError {
61
+ if (ex instanceof ApiError) {
62
+ return ex;
63
+ }
64
+
65
+ const code = ex instanceof DOMException ? ErrorCode[errnoForDOMException(ex)] : ErrorCode.EIO;
66
+ const error = new ApiError(code, ex.message, path, syscall);
67
+ error.stack = ex.stack;
68
+ error.cause = ex.cause;
69
+ return error;
70
+ }