@opfs-vfs/effect 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +73 -0
- package/README.md +211 -0
- package/dist/coordinator.d.ts +50 -0
- package/dist/errors.d.ts +76 -0
- package/dist/errors.js +159 -0
- package/dist/filesystem.d.ts +9 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +1031 -0
- package/dist/subscriptions-internal.d.ts +11 -0
- package/dist/subscriptions.d.ts +24 -0
- package/dist/volume-BIqpe5Vt.js +357 -0
- package/dist/volume.d.ts +52 -0
- package/dist/volume.js +3 -0
- package/examples/direct.ts +8 -0
- package/examples/encrypted-session.ts +347 -0
- package/examples/encrypted-session.worker.ts +5 -0
- package/examples/filesystem-save.ts +30 -0
- package/examples/filesystem-stream.ts +20 -0
- package/examples/reconciled-view.ts +74 -0
- package/examples/subscriptions.ts +20 -0
- package/examples/worker-session.ts +32 -0
- package/package.json +64 -0
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import { EncryptionError as e, SubscriptionError as t, VolumeError as n, mountError as r, remoteDetails as i, volumeError as a } from "./errors.js";
|
|
2
|
+
import { Cause as o, Context as s, Deferred as c, Effect as l, Exit as u, Layer as d, Schema as f, Scope as p, Semaphore as m } from "effect";
|
|
3
|
+
import { OpfsVfs as h, peekVolume as g } from "@opfs-vfs/opfs-vfs";
|
|
4
|
+
import { VfsCommandError as _, openOpfsVfsWorker as v } from "@opfs-vfs/opfs-vfs/worker";
|
|
5
|
+
import { SUBSCRIPTIONS_COMPATIBILITY_KEY as y } from "@opfs-vfs/plugin-subscriptions/config";
|
|
6
|
+
//#region \0rolldown/runtime.js
|
|
7
|
+
var b = Object.defineProperty, x = (e, t) => {
|
|
8
|
+
let n = {};
|
|
9
|
+
for (var r in e) b(n, r, {
|
|
10
|
+
get: e[r],
|
|
11
|
+
enumerable: !0
|
|
12
|
+
});
|
|
13
|
+
return t || b(n, Symbol.toStringTag, { value: "Module" }), n;
|
|
14
|
+
}, S = "function e(e,t){return Object.assign(Error(t),{code:e})}function t(e){let t=[];for(let n of e.split(`/`))n&&n!==`.`&&(n===`..`?t.pop():t.push(n));return`/${t.join(`/`)}`}var n=16777216,r=e=>`${e.clientId}\\u0000${e.channelId}`,i=(e,t)=>`${r(e)}\\u0000${t}`;function a(e,t){let n=t;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);r<128?n++:r<2048?n+=2:r>=55296&&r<=56319&&t+1<e.length&&(e.charCodeAt(t+1)&64512)==56320?(n+=4,t++):n+=3}return n}var o=(e,t)=>a(t,256)+a(e,0),s=e=>e===`create`?1:e===`update`?2:e===`delete`?4:0,c=(e,t)=>t.startsWith(e.prefix)&&t.indexOf(`/`,e.prefix.length)<0,l=(e,t)=>t.startsWith(e.prefix);function u(t){if(!t||typeof t!=`object`||Array.isArray(t))throw e(`EINVAL`,`Invalid subscription options`);let n=t;if(Reflect.ownKeys(n).some(e=>typeof e!=`string`||![`path`,`scope`,`recursive`,`events`,`match`,`content`].includes(e)))throw e(`EINVAL`,`Invalid subscription options`);if(typeof n.path!=`string`||n.path.includes(`\\0`))throw e(`EINVAL`,`Invalid path`);if(n.scope!==`file`&&n.scope!==`directory`||typeof n.recursive!=`boolean`)throw e(`EINVAL`,`Invalid scope`);if(n.scope===`file`&&n.recursive)throw e(`EINVAL`,`File subscriptions cannot be recursive`);let r=Array.isArray(n.events)?Array.from(n.events):void 0;if(!r||!r.length||r.some(e=>e!==`create`&&e!==`update`&&e!==`delete`))throw e(`EINVAL`,`Invalid events`);let i;if(n.match!==void 0){let t=n.match;if(!t||typeof t!=`object`||Array.isArray(t)||Reflect.ownKeys(t).length!==2||!Reflect.ownKeys(t).includes(`source`)||!Reflect.ownKeys(t).includes(`flags`)||typeof t.source!=`string`||typeof t.flags!=`string`)throw e(`EINVAL`,`Invalid match expression`);i={source:t.source,flags:t.flags}}if(n.content!==!1){let t=n.content?.maxBytes;if(!n.content||typeof n.content!=`object`||Array.isArray(n.content)||Reflect.ownKeys(n.content).length!==1||!Reflect.ownKeys(n.content).includes(`maxBytes`)||typeof t!=`number`||!Number.isSafeInteger(t)||t<=0||t>16777216)throw e(`EINVAL`,`Invalid content options`);return{path:n.path,scope:n.scope,recursive:n.recursive,events:[...new Set(r)],match:i,content:{maxBytes:t}}}return{path:n.path,scope:n.scope,recursive:n.recursive,events:[...new Set(r)],match:i,content:!1}}function d(){return{id:`subscriptions`,contractVersion:1,compatibilityKey:`subscriptions-v1`,logicalChanges:{version:1,create(r){let d=new Map,f=0,p=0,m=0,h=e=>[...d.values()].filter(t=>t.client.clientId===e.clientId).length,g=(e,t)=>{t&&(e.contentBytes-=t.size,m-=t.charge)},_=(e,t)=>{f--,p-=o(e.id,t.frame.change.path),g(e,t.content)},v=e=>{for(let t of e.pending)_(e,t);e.pending.length=0},y=e=>{d.delete(e.key),v(e),e.inflight&&=(_(e,e.inflight),void 0),p-=e.charge},b=(e,t)=>{e.state!==`retiring`&&(v(e),e.state=`retiring`,r.send(e.client,t))},x=e=>{if(e.state!==`active`||e.inflight!==void 0||!e.pending.length)return;let t=e.pending.shift();e.inflight=t,r.send(e.client,t.frame)},S=(e,t,n)=>!(!(e.eventMask&s(n))||!(e.options.scope===`file`?t===e.path:t===e.path||(e.options.recursive?l(e,t):c(e,t)))||e.regex&&(e.regex.lastIndex=0,!e.regex.test(t)));return{control(o,c){let l=i(o,c.subscriptionId);if(c.type===`register`){if(d.has(l))throw e(`EINVAL`,`Subscription already registered`);let i=u(c.options),f=a(i.path,512)+a(c.subscriptionId,0)+a(o.clientId,0)+a(o.channelId,0)+(i.match?a(i.match.source,0)+a(i.match.flags,0):0);if(d.size>=128||h(o)>=32||p+f>n)throw e(`ENOSPC`,`Subscription capacity exhausted`);r.validateTarget(i);let m=t(i.path),g;try{g=i.match?new RegExp(i.match.source,i.match.flags):void 0}catch{throw e(`EINVAL`,`Invalid match expression`)}let _={key:l,client:o,id:c.subscriptionId,options:i,path:m,prefix:m===`/`?`/`:`${m}/`,eventMask:i.events.reduce((e,t)=>e|s(t),0),regex:g,charge:f,state:`held`,nextDeliveryId:1,pending:[],contentBytes:0};return d.set(l,_),p+=f,{type:`registered`,subscriptionId:_.id}}let f=d.get(l);if(!f)return{type:`ok`};if(c.type===`activate`)f.state===`held`&&(f.state=`active`),x(f);else if(c.type===`ack`){if(f.state===`active`&&f.inflight?.frame.deliveryId===c.deliveryId){let e=f.inflight;f.inflight=void 0,_(f,e),x(f)}}else c.type===`cancel`?b(f,{type:`closed`,subscriptionId:f.id}):c.type===`terminal-ack`&&f.state===`retiring`&&y(f);return{type:`ok`}},completed(e){if(!d.size)return;let t=[...d.values()],r;try{for(let i of e.records)for(let a of t){if(a.state===`retiring`||!S(a,i.path,i.type))continue;let t=o(a.id,i.path);if(a.pending.length+(a.inflight===void 0?0:1)>=4096||f>=16384||p+t>n){b(a,{type:`terminal`,subscriptionId:a.id,code:`SUBSCRIPTION_OVERFLOW`});continue}let s,c={status:`omitted`,reason:`disabled`},l=a.options.content;if(l){if(i.type===`delete`)c={status:`omitted`,reason:`deleted`};else if(i.kind!==`file`)c={status:`omitted`,reason:`not-file`};else if(i.size>l.maxBytes)c={status:`omitted`,reason:`too-large`};else{let t=i.size,n=r?.get(i.inodeId),o=t*(a.client.route===`follower-relay`?2:1);if(a.contentBytes+t>33554432||m+(n?0:t)+o>201326592){b(a,{type:`terminal`,subscriptionId:a.id,code:`SUBSCRIPTION_OVERFLOW`});continue}let u=!n;a.contentBytes+=t,m+=o+(u?t:0);let d=()=>{a.contentBytes-=t,m-=o},f;try{f=e.capture(i,l.maxBytes)}catch{f={status:`omitted`,reason:`unavailable`}}if(f.status!==`included`||f.bytes.byteLength!==t)d(),u&&(m-=t),c={status:`omitted`,reason:`unavailable`};else{let e=n;e||(e=f.bytes,(r??=new Map).set(i.inodeId,e));try{let n=e.slice();s={size:t,charge:o},c={status:`included`,bytes:n}}catch{d(),c={status:`omitted`,reason:`unavailable`}}}}}let u={type:`event`,subscriptionId:a.id,deliveryId:a.nextDeliveryId++,change:{type:i.type,path:i.path,kind:i.kind,cursor:i.cursor,content:c}};a.pending.push({frame:u,content:s}),f++,p+=t,x(a)}}finally{for(let e of r?.values()??[])m-=e.byteLength;r=void 0}},invalidated(e,n){let r=e.kind===`paths`?e.paths.map(({path:e,subtree:n})=>{let r=t(e);return{region:r,prefix:r===`/`?`/`:`${r}/`,subtree:n}}):[];for(let t of[...d.values()])(e.kind===`all`||r.some(({region:e,prefix:n,subtree:r})=>(e=>t.options.scope===`file`?e===t.path:e===t.path||(t.options.recursive?l(t,e):c(t,e)))(e)||r&&(t.path===e||e===`/`||t.path.startsWith(n)||t.options.scope===`directory`&&t.options.recursive&&l(t,e))))&&b(t,{type:`terminal`,subscriptionId:t.id,code:n===`record-limit`?`SUBSCRIPTION_OVERFLOW`:`SUBSCRIPTION_RESYNC_REQUIRED`})},clientClosed(e){for(let t of[...d.values()])t.client.clientId===e.clientId&&t.client.channelId===e.channelId&&y(t)},close(){for(let e of[...d.values()])r.send(e.client,{type:`terminal`,subscriptionId:e.id,code:`SUBSCRIPTION_INTERRUPTED`}),y(e)}}}}}}var f=Object.assign((t={})=>{if(!t||typeof t!=`object`||Array.isArray(t)||Reflect.ownKeys(t).length)throw e(`EINVAL`,`Subscriptions accept no configuration`);return d()},{id:`subscriptions`,configure:t=>{if(!t||typeof t!=`object`||Array.isArray(t)||Reflect.ownKeys(t).length)throw e(`EINVAL`,`Subscriptions accept no configuration`);return d()}}),p=Object.freeze({metaLog:3,snapshot:2,dataWal:4}),m=class extends Error{code=`VFS_STORAGE_PLUGIN_REQUIRED`;errno=22;path;constructor(e,t){super(`VFS_STORAGE_PLUGIN_REQUIRED: This volume requires a plugin that owns ${t} (${e})`),this.name=`StoragePluginRequiredError`,this.path=e}},h={EACCES:13,EBADF:9,EBUSY:16,EEXIST:17,EFBIG:27,EINVAL:22,EISDIR:21,ELOOP:40,ENAMETOOLONG:36,ENOENT:2,ENOSPC:28,ENOTDIR:20,ENOTEMPTY:39,ENOTSUP:95,EPERM:1},g={EACCES:`Permission denied`,EBADF:`Bad file descriptor`,EBUSY:`Resource busy`,EEXIST:`File exists`,EFBIG:`File too large`,EINVAL:`Invalid argument`,EISDIR:`Is a directory`,ELOOP:`Too many levels of symbolic links`,ENAMETOOLONG:`File name too long`,ENOENT:`No such file or directory`,ENOSPC:`No space left on device`,ENOTDIR:`Not a directory`,ENOTEMPTY:`Directory not empty`,ENOTSUP:`Operation not supported`,EPERM:`Operation not permitted`},_=e=>typeof e==`string`&&Object.hasOwn(h,e),v=class extends Error{code;errno;path;constructor(e,t,n){let r=n??g[e];super(t?`${e}: ${r} (${t})`:`${e}: ${r}`),this.name=`VfsError`,this.code=e,this.errno=h[e],this.path=t}};function y(e,t,n){return new v(e,t,n)}var b=class extends Error{category;offset;constructor(e,t,n){super(t),this.name=`VfsCorruptionError`,this.category=e,this.offset=n}},x=8,S=4,C=class extends b{constructor(e,t){super(`data-wal`,e,t),this.name=`DataWalCorruptionError`}};function w(e,t,n){t.setUint32(n,e>>>0,!0)}function T(e,t){return e.getUint32(t,!0)}function E(e,t,n){if(!Number.isSafeInteger(e)||e<0)throw new C(`Data WAL u64 value is not a safe unsigned integer: ${e}`,n);t.setBigUint64(n,BigInt(e),!0)}function D(e,t,n){let r=e.getBigUint64(t,!0);if(r>BigInt(2**53-1))throw new C(`Data WAL u64 value exceeds Number.MAX_SAFE_INTEGER`,n);return Number(r)}var ee=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n>>>0}return e})();function O(e){let t=4294967295;for(let n=0;n<e.length;n++)t=ee[(t^e[n])&255]^t>>>8;return(t^4294967295)>>>0}var te=new TextEncoder,ne=new TextDecoder;function re(e,t){switch(e.op){case`write`:return 22+t+e.data.length;case`truncate`:return 18+t;case`delete`:return 10+t}}function ie(e,t,n,r){let i=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(n.op){case`write`:e[t]=S,e[t+1]=1,w(n.inodeId,i,t+2),w(r.length,i,t+6),E(n.offset,i,t+10),w(n.data.length,i,t+18),e.set(r,t+22),e.set(n.data,t+22+r.length);return;case`truncate`:e[t]=S,e[t+1]=2,w(n.inodeId,i,t+2),w(r.length,i,t+6),E(n.size,i,t+10),e.set(r,t+18);return;case`delete`:e[t]=S,e[t+1]=3,w(n.inodeId,i,t+2),w(r.length,i,t+6),e.set(r,t+10);return}}function ae(e,t,n=0){let r=te.encode(e.path??``),i=re(e,r.length);if(t){let a=new Uint8Array(i);ie(a,0,e,r);let o=i+t.overheadBytes,s=new Uint8Array(x+o),c=new DataView(s.buffer,s.byteOffset,s.byteLength);return t.sealInto(a,p.dataWal,n,s,x),w(o,c,0),w(O(s.subarray(x)),c,4),s}let a=new Uint8Array(x+i),o=new DataView(a.buffer,a.byteOffset,a.byteLength);return ie(a,x,e,r),w(i,o,0),w(O(a.subarray(x)),o,4),a}function oe(e,t){if(e.length<2)throw new C(`Data WAL payload too small`,t);let n=e[0];if(n!==S)throw new C(`Unsupported data WAL version: ${n}`,t);let r=e[1],i=new DataView(e.buffer,e.byteOffset,e.byteLength);if(r===1){if(e.length<22)throw new C(`Data WAL write payload too small`,t);let r=T(i,2),a=T(i,6),o=D(i,10,t),s=T(i,18),c=22+a+s;if(e.length!==c)throw new C(`Data WAL write payload length mismatch`,t);let l=ne.decode(e.subarray(22,22+a)),u=e.slice(22+a);return{version:n,op:`write`,inodeId:r,path:l||void 0,offset:o,data:u}}if(r===2){if(e.length<18)throw new C(`Data WAL truncate payload too small`,t);let r=T(i,2),a=T(i,6),o=D(i,10,t);if(e.length!==18+a)throw new C(`Data WAL truncate payload length mismatch`,t);return{version:n,op:`truncate`,inodeId:r,path:ne.decode(e.subarray(18))||void 0,size:o}}if(r===3){if(e.length<10)throw new C(`Data WAL delete payload too small`,t);let r=T(i,2),a=T(i,6);if(e.length!==10+a)throw new C(`Data WAL delete payload length mismatch`,t);return{version:n,op:`delete`,inodeId:r,path:ne.decode(e.subarray(10))||void 0}}throw new C(`Unknown data WAL opcode: ${r}`,t)}function se(e,t,n=0){let r=[],i=[],a=n;for(;a+x<=e.length;){let n=a,o=new DataView(e.buffer,e.byteOffset+a,x),s=T(o,0),c=T(o,4);if(a+=x,a+s>e.length)return{records:r,frameEnds:i,parsedBytes:n,hadPartialTail:!0};let l=e.subarray(a,a+s);if(O(l)!==c)return{records:r,frameEnds:i,parsedBytes:n,hadPartialTail:!1,corruptionOffset:n};let u;if(t)try{u=t.open(l,p.dataWal,n)}catch{return{records:r,frameEnds:i,parsedBytes:n,hadPartialTail:!1,corruptionOffset:n}}else u=l;let d;try{d=oe(u,n)}catch(e){if(e instanceof C)return{records:r,frameEnds:i,parsedBytes:n,hadPartialTail:!1,corruptionOffset:n};throw e}r.push(d),a+=s,i.push(a)}let o=a!==e.length;return{records:r,frameEnds:i,parsedBytes:a,hadPartialTail:o}}function ce(e,t){let n;for(let r=0;r<t.length;r++){let i=t[r];try{i.op===`delete`?e.applyDelete(i.inodeId,i.path):i.op===`truncate`?e.applyTruncate(i.inodeId,i.size,i.path):e.applyWrite(i.inodeId,i.offset,i.data,i.path)}catch(t){n=r,e.onApplyError?.(r,i,t);break}}return{replayedRecords:n??t.length,failedIndex:n}}function k(e){if(e.includes(`\\0`))throw y(`EINVAL`,e,`Path contains NUL byte`);let t=e,n=t.length>1&&t.endsWith(`/`);(t===``||t===`.`||t===`./`)&&(t=`/`);let r=t.split(`/`),i=[];for(let e of r)if(e!==``&&e!==`.`){if(e===`..`){i.pop();continue}i.push(e)}return{path:i.length===0?`/`:`/${i.join(`/`)}`,requiresDirectory:n}}function A(e){if(e===`/`)return`/`;let t=e.lastIndexOf(`/`);return t<=0?`/`:e.substring(0,t)}function j(e){if(e===`/`)return`/`;let t=e.lastIndexOf(`/`);return t<0?e:e.substring(t+1)}var le=1112950355,ue=1,de=2,M=3,fe=4,pe=5,me=new TextEncoder,he=10,ge=40,_e=48,ve=12,ye=16,be=4,xe=10,Se=4294967295,Ce=2147483648,we=33188,Te=16877,Ee=41471;function De(e){let t=e.kind===`symlink`?2:+!!e.isDir;return e.mode<<2|t}function Oe(e){let t=e&3;return t===1?`dir`:t===2?`symlink`:`file`}function ke(e,t){let n=e>>>2;return n===0?t===`dir`?Te:t===`symlink`?Ee:we:n}function Ae(e,t){let n=t&61440;return e===`dir`?n===16384:e===`symlink`?n===40960:n===32768}function je(e){let t=Oe(e),n=ke(e,t);if(Ae(t,n))return{kind:t,mode:n};throw Error(`Unsupported metadata log flags: 0x${e.toString(16)}`)}function Me(e){return e===void 0?0:Math.floor(e/1e3)}function N(e){return e===0?void 0:e*1e3}function Ne(e){let t=e.mtimeMs??e.timestampMs,n=e.atimeMs??t??e.ctimeMs,r=e.ctimeMs??t??n;return{atime:Me(n),mtime:Me(t),ctime:Me(r)}}function Pe(e){let t=0;for(let n=0;n<e.length;n++)(n===0||(e[n-1]===0?e[n]!==0:e[n]!==e[n-1]+1))&&t++;let n=1+t*2<e.length;return{count:e.length|(n?Ce:0),words:n?1+t*2:e.length}}function Fe(e,t,n,r){if(!(r&Ce)){for(let r of n)e.setUint32(t,r,!0),t+=4;return t}let i=t;t+=4;let a=0;for(let r=0;r<n.length;){let i=n[r],o=1;for(;r+o<n.length&&(i===0?n[r+o]===0:n[r+o]===n[r+o-1]+1);)o++;e.setUint32(t,i,!0),e.setUint32(t+4,o,!0),t+=8,a++,r+=o}return e.setUint32(i,a,!0),t}function Ie(e,t,n,r,i){let a=n&2147483647;if(a>1048576)throw Error(`Corrupted binary metadata: block count exceeds file limit`);let o=!!(n&Ce);if(o&&t+4>r)throw Error(`Corrupted binary metadata: truncated extent list`);let s=o?e.getUint32(t,!0):0;o&&(t+=4);let c=o?s*2:a;if(t+c*4>r||o&&(s===0||s>a))throw Error(`Corrupted binary metadata: truncated or invalid block list`);let l=[],u=e=>e<i;for(let n=0;n<(o?s:a);n++){let n=e.getUint32(t,!0);t+=4;let r=o?e.getUint32(t,!0):1;if(o&&(t+=4),r===0||r>a-l.length||n+r>4294967296||!u(n)||!u(n===0?0:n+r-1))throw Error(`Corrupted binary metadata: block ${n} outside the volume or invalid extent`);for(let e=0;e<r;e++)l.push(n===0?0:n+e)}if(l.length!==a)throw Error(`Corrupted binary metadata: extent lengths do not match block count`);return l}function Le(e,t){if(!t)return Array.from(e.keys()).sort();let n=new Set,r=[],i=!1;for(let a of t){if(!e.has(a)||n.has(a)){i=!0;continue}n.add(a),r.push(a)}if(r.length!==e.size){i=!0;for(let t of e.keys())n.has(t)||(n.add(t),r.push(t))}return i&&r.sort(),r}function Re(e,t,n,r,i){let a=Le(e,r),o=new Map;for(let t of a){let n=e.get(t);o.has(n.ino)||o.set(n.ino,n)}let s=Array.from(o.entries()).sort((e,t)=>e[0]-t[0]),c=s.length,l=a.filter(e=>e!==`/`),u=l.length,d=new TextEncoder,f=0,p=0,m=s.map(([,e])=>Pe(e.blocks)),h=Array(c).fill(0),g=Array(u);for(let e=0;e<c;e++){let[,t]=s[e];if(t.size>Se)throw Error(`Inode ${t.ino} size ${t.size} exceeds u32 max (4GB). Binary metadata does not support files >4GB.`);if(t.kind===`symlink`&&t.symlinkTarget){let n=d.encode(t.symlinkTarget).byteLength;h[e]=n,f+=n}p+=m[e].words}for(let e=0;e<u;e++){let t=d.encode(j(l[e])).byteLength;g[e]=t,f+=t}let _=ge+c*_e,v=_+p*4,y=v+u*ye,b=y+f,x=new ArrayBuffer(b),S=new DataView(x),C=new Uint32Array(x,0,(v>>>2)+u*be),w=new Uint8Array(x),T=2;for(let e of o.values()){let t=Number.isInteger(e.ino)&&e.ino>0?e.ino:0;T=Math.max(T,t+1)}C[0]=le,C[1]=he,C[2]=n,C[3]=t,C[4]=c,C[5]=u,C[6]=i??T,C[7]=e.get(`/`)?.ino??1,C[8]=v,C[9]=y;let E=0,D=0;for(let e=0;e<c;e++){let[t,n]=s[e],r=xe+e*ve,i=Ne(n),a=n.kind===`symlink`;C[r+0]=t,C[r+1]=De(n),C[r+2]=n.size,C[r+3]=m[e].count,C[r+4]=n.blocks.length>0?_+E*4:0,C[r+5]=n.nlink??1,C[r+6]=i.atime,C[r+7]=i.mtime,C[r+8]=i.ctime,C[r+9]=a&&h[e]>0?y+D:0,C[r+10]=a?h[e]:0,C[r+11]=0,n.blocks.length>0&&Fe(S,_+E*4,n.blocks,m[e].count),E+=m[e].words,a&&h[e]>0&&(d.encodeInto(n.symlinkTarget,w.subarray(y+D)),D+=h[e])}let ee=v>>>2;for(let t=0;t<u;t++){let n=l[t],r=e.get(n),i=e.get(A(n));if(!i)throw Error(`Missing parent inode for path ${n}`);let a=ee+t*be,o=j(n),s=g[t];C[a+0]=i.ino,C[a+1]=r.ino,C[a+2]=y+D,C[a+3]=s,d.encodeInto(o,w.subarray(y+D)),D+=s}return x}function ze(e){let t=new Uint8Array(e),n=new TextDecoder;if(e.byteLength<ge)throw Error(`Corrupted binary metadata: buffer too small (${e.byteLength} < ${ge})`);let r=new DataView(e,0,ge),i=r.getUint32(0,!0);if(i!==le)throw Error(`Invalid binary metadata magic: 0x${i.toString(16)}`);let a=r.getUint32(4,!0);if(a!==he)throw new b(`format-version`,`Unsupported binary metadata version: ${a} (this build expects ${he})`);let o=r.getUint32(8,!0),s=r.getUint32(12,!0),c=r.getUint32(16,!0),l=r.getUint32(20,!0),u=r.getUint32(24,!0),d=r.getUint32(28,!0),f=r.getUint32(32,!0),p=r.getUint32(36,!0),m=ge,h=m+c*_e;if(o!==4096||s===0||s>2147483648)throw Error(`Corrupted binary metadata: invalid geometry (blockSize ${o}, totalBlocks ${s})`);if(f<h||f>e.byteLength)throw Error(`Corrupted binary metadata: invalid dir entry offset ${f}`);if(p<f||p>e.byteLength)throw Error(`Corrupted binary metadata: invalid string table offset ${p}`);if(f+l*ye>p)throw Error(`Corrupted binary metadata: directory entries overlap string table`);let g=new Map,_=1;for(let r=0;r<c;r++){let i=m+r*_e,a=new DataView(e,i,_e),o=a.getUint32(0,!0),c=a.getUint32(4,!0),l=Oe(c),u=a.getUint32(8,!0),d=a.getUint32(12,!0),v=a.getUint32(16,!0),y=a.getUint32(20,!0),b=N(a.getUint32(24,!0)),x=N(a.getUint32(28,!0)),S=N(a.getUint32(32,!0)),C=a.getUint32(36,!0),w=a.getUint32(40,!0),T=[];if(d>0){if(v<h||v>f)throw Error(`Corrupted binary metadata: block list at inode ${o} overflows buffer`);T=Ie(new DataView(e),v,d,f,s)}let E;if(l===`symlink`&&w>0){let r=C+w;if(C<p||r>e.byteLength)throw Error(`Corrupted binary metadata: symlink target at inode ${o} overflows buffer`);E=n.decode(t.subarray(C,r))}g.set(o,{ino:o,kind:l,isDir:l===`dir`,size:l===`symlink`?w:u,blocks:T,children:[],symlinkTarget:E,mode:ke(c,l),nlink:y||1,atimeMs:b,mtimeMs:x,ctimeMs:S,timestampMs:x}),_=Math.max(_,o)}let v=new Map;for(let r=0;r<l;r++){let i=f+r*ye,a=new DataView(e,i,ye),o=a.getUint32(0,!0),s=a.getUint32(4,!0),c=a.getUint32(8,!0),l=c+a.getUint32(12,!0);if(c<p||l>e.byteLength)throw Error(`Corrupted binary metadata: directory entry ${r} overflows string table`);let u=g.get(o),d=g.get(s);if(!u?.isDir||!d)throw Error(`Corrupted binary metadata: invalid directory entry ${r}`);let m=n.decode(t.subarray(c,l)),h=v.get(o);h||(h=[],v.set(o,h)),h.push({name:m,childId:s})}let y=new Map,x=new Set,S=[[`/`,d||1]];for(;S.length>0;){let[e,t]=S.pop(),n=g.get(t);if(!n)throw Error(`Corrupted binary metadata: missing inode ${t}`);if(n.isDir){if(x.has(t))throw Error(`Corrupted binary metadata: directory inode ${t} linked twice`);x.add(t)}if(y.has(e))throw Error(`Corrupted binary metadata: duplicate path ${e}`);y.set(e,n);let r=v.get(t)??[];for(let n=r.length-1;n>=0;n--){let{name:i,childId:a}=r[n];if(!i||i===`.`||i===`..`||i.includes(`/`)||i.includes(`\\0`))throw Error(`Corrupted binary metadata: invalid entry name under inode ${t}`);S.push([e===`/`?`/${i}`:`${e}/${i}`,a])}}return{totalBlocks:s,blockSize:o,nextInodeNumber:u>1?u:_+1,inodes:y}}function Be(e,t){let n=new TextEncoder,r=n.encode(e);if(t===null){let e=new ArrayBuffer(12+r.byteLength),t=new DataView(e);return t.setUint32(0,de,!0),t.setUint32(4,r.byteLength,!0),t.setUint32(8,0,!0),new Uint8Array(e).set(r,12),new Uint8Array(e)}let i=t.kind===`symlink`,a=0,o=0,s;i&&(s=n.encode(t.symlinkTarget??``),o=s.byteLength,a=s.byteLength);let c=Pe(t.blocks),l=12+c.words*4+4+a+20,u=Ne(t),d=12+r.byteLength+l,f=new ArrayBuffer(d),p=new DataView(f),m=new Uint8Array(f);p.setUint32(0,ue,!0),p.setUint32(4,r.byteLength,!0),p.setUint32(8,l,!0),m.set(r,12);let h=12+r.byteLength;return p.setUint32(h,De(t),!0),h+=4,p.setUint32(h,t.size,!0),h+=4,p.setUint32(h,c.count,!0),h+=4,h=Fe(p,h,t.blocks,c.count),p.setUint32(h,o,!0),h+=4,i&&(m.set(s??new Uint8Array,h),h+=s?.byteLength??0),p.setUint32(h,Number.isInteger(t.ino)&&t.ino>0?t.ino:0,!0),h+=4,p.setUint32(h,t.nlink??1,!0),h+=4,p.setUint32(h,u.atime,!0),h+=4,p.setUint32(h,u.mtime,!0),h+=4,p.setUint32(h,u.ctime,!0),new Uint8Array(f)}function Ve(e,t){let n=me.encode(e),r=new ArrayBuffer(12+n.byteLength+28),i=new DataView(r),a=new Uint8Array(r);i.setUint32(0,pe,!0),i.setUint32(4,n.byteLength,!0),i.setUint32(8,28,!0),a.set(n,12);let o=12+n.byteLength,s=Ne(t);return i.setUint32(o,De(t),!0),o+=4,i.setUint32(o,t.size,!0),o+=4,i.setUint32(o,Number.isInteger(t.ino)&&t.ino>0?t.ino:0,!0),o+=4,i.setUint32(o,t.nlink??1,!0),o+=4,i.setUint32(o,s.atime,!0),o+=4,i.setUint32(o,s.mtime,!0),o+=4,i.setUint32(o,s.ctime,!0),a}function He(e,t){let n=new ArrayBuffer(16),r=new DataView(n);return r.setUint32(0,e,!0),r.setUint32(4,0,!0),r.setUint32(8,4,!0),r.setUint32(12,t,!0),new Uint8Array(n)}function Ue(e,t){let n=new ArrayBuffer(20),r=new DataView(n);return r.setUint32(0,fe,!0),r.setUint32(4,0,!0),r.setUint32(8,8,!0),r.setUint32(12,e,!0),r.setUint32(16,t>>>0,!0),new Uint8Array(n)}function We(e,t,n,r=0,i=0,a=0){let o=He(M,t),s=20+e.reduce((e,t)=>e+t.byteLength,0),c=new Uint8Array(s),l=new DataView(c.buffer);l.setUint32(0,r>>>0,!0),l.setFloat64(4,i,!0),l.setFloat64(12,a,!0);let u=20;for(let t of e)c.set(t,u),u+=t.byteLength;let d=n?n.seal(c,p.metaLog,t>>>0):c,f=o.byteLength+d.byteLength,m=new Uint8Array(f);m.set(o,0),m.set(d,o.byteLength);let h=Ue(t,O(m)),g=new Uint8Array(f+h.byteLength);return g.set(m,0),g.set(h,f),g}function Ge(e){return{...e,blocks:[...e.blocks],children:[...e.children]}}function Ke(e,t){e.ino=t.ino,e.kind=t.kind,e.isDir=t.isDir,e.size=t.size,e.blocks=[...t.blocks],e.children=[...t.children],e.symlinkTarget=t.symlinkTarget,e.mode=t.mode,e.nlink=t.nlink,e.atimeMs=t.atimeMs,e.mtimeMs=t.mtimeMs,e.ctimeMs=t.ctimeMs,e.timestampMs=t.timestampMs}function qe(e,t,n){if(!(n<=0)){for(let r of t.values())if(r.ino===n){e.set(n,r);return}e.delete(n)}}function Je(e,t,n,r){if(e.kind===`delete`){let i=t.get(e.path);t.delete(e.path);let a=0,o=n.length;for(;a<o;){let t=a+o>>>1;n[t]<e.path?a=t+1:o=t}a<n.length&&n[a]===e.path&&n.splice(a,1),i&&qe(r,t,i.ino);return}if(e.kind===`upsert-attr`){let n=t.get(e.path)??(e.ino>0?r.get(e.ino):void 0);if(n){n.kind=e.nodeKind,n.isDir=e.nodeKind===`dir`,n.mode=e.mode,n.size=e.nodeKind===`symlink`?n.size:e.size,e.ino>0&&(n.ino=e.ino),n.nlink=e.nlink,n.atimeMs=e.atimeMs,n.mtimeMs=e.mtimeMs,n.ctimeMs=e.ctimeMs,n.timestampMs=e.mtimeMs,t.set(e.path,n),e.ino>0&&r.set(e.ino,n);return}let i={ino:e.ino,kind:e.nodeKind,isDir:e.nodeKind===`dir`,size:e.size,blocks:[],children:[],symlinkTarget:void 0,mode:e.mode,nlink:e.nlink,atimeMs:e.atimeMs,mtimeMs:e.mtimeMs,ctimeMs:e.ctimeMs,timestampMs:e.mtimeMs};e={kind:`upsert`,path:e.path,inode:i}}let i=t.get(e.path),a=i===void 0,o=e.inode.ino,s;if(o>0){let t=r.get(o)??(i?.ino===o?i:void 0);t?(Ke(t,e.inode),s=t):s=Ge(e.inode),r.set(o,s)}else i?(Ke(i,e.inode),s=i):s=Ge(e.inode);if(t.set(e.path,s),i&&i!==s&&qe(r,t,i.ino),!a)return;let c=0,l=n.length;for(;c<l;){let t=c+l>>>1;n[t]<e.path?c=t+1:l=t}n.splice(c,0,e.path)}function Ye(e,t,n,r,i){if(r+12>e.byteLength)return null;try{let a=e.getUint32(r,!0),o=e.getUint32(r+4,!0),s=e.getUint32(r+8,!0);if(a!==ue&&a!==de&&a!==pe||r+12+o+s>e.byteLength)return null;let c=n.decode(t.subarray(r+12,r+12+o)),l=r+12+o+s;if(a===de)return s===0?{mutation:{kind:`delete`,path:c},nextOffset:l}:null;if(a===pe){if(s!==28)return null;let t=r+12+o,{kind:n,mode:i}=je(e.getUint32(t,!0));t+=4;let a=e.getUint32(t,!0);t+=4;let u=e.getUint32(t,!0);t+=4;let d=e.getUint32(t,!0)||1;t+=4;let f=N(e.getUint32(t,!0));t+=4;let p=N(e.getUint32(t,!0));t+=4;let m=N(e.getUint32(t,!0));return{mutation:{kind:`upsert-attr`,path:c,nodeKind:n,mode:i,size:a,ino:u,nlink:d,atimeMs:f??p,mtimeMs:p,ctimeMs:m??p},nextOffset:l}}if(s<36)return null;let u=l,d=r+12+o,{kind:f,mode:p}=je(e.getUint32(d,!0));d+=4;let m=e.getUint32(d,!0);d+=4;let h=e.getUint32(d,!0);d+=4;let g=Ie(e,d,h,u-24,i);d+=h&Ce?4+e.getUint32(d,!0)*8:(h&2147483647)*4;let _=e.getUint32(d,!0);if(d+=4,f!==`symlink`&&_!==0||d+_+20!==u)return null;let v;f===`symlink`&&(v=n.decode(t.subarray(d,d+_)),d+=_);let y=e.getUint32(d,!0);d+=4;let b=e.getUint32(d,!0)||1;d+=4;let x=N(e.getUint32(d,!0));d+=4;let S=N(e.getUint32(d,!0));d+=4;let C=N(e.getUint32(d,!0));return x===void 0&&(x=S),C===void 0&&(C=S),{mutation:{kind:`upsert`,path:c,inode:{ino:y,kind:f,isDir:f===`dir`,size:f===`symlink`?_:m,blocks:g,children:[],symlinkTarget:v,mode:p,nlink:b,atimeMs:x,mtimeMs:S,ctimeMs:C,timestampMs:S}},nextOffset:l}}catch{return null}}function Xe(e,t){for(let n=t;n+16<=e.byteLength;n++){let t=e.getUint32(n,!0);if(t!==M&&t!==fe)continue;let r=e.getUint32(n+4,!0),i=e.getUint32(n+8,!0);if(r===0&&(t===M?i===4:i===8))return n}return-1}function Ze(e,t,n,r,i=0,a){if(a)return Qe(e,t,n,r,i,a);let o=new DataView(e),s=new Uint8Array(e),c=new TextDecoder,l=new Map;for(let e of t.values())e.ino>0&&!l.has(e.ino)&&l.set(e.ino,e);let u=0,d=0,f,p,m=0;for(;u+16<=e.byteLength&&o.getUint32(u,!0)===M&&o.getUint32(u+4,!0)===0&&o.getUint32(u+8,!0)===4;){let a=o.getUint32(u+12,!0);if(u+36>e.byteLength)break;let h=o.getUint32(u+16,!0),g=o.getFloat64(u+20,!0),_=o.getFloat64(u+28,!0);if(!Number.isSafeInteger(g)||!Number.isSafeInteger(_)||g<0||_<0)break;let v=[],y=u+36,b=-1;for(;y+12<=e.byteLength;){let t=o.getUint32(y,!0);if(t===fe){y+20<=e.byteLength&&o.getUint32(y+4,!0)===0&&o.getUint32(y+8,!0)===8&&o.getUint32(y+12,!0)===a&&O(s.subarray(u,y))===o.getUint32(y+16,!0)&&(b=y+20);break}if(t===M)break;if(h!==i){if(t!==ue&&t!==de&&t!==pe)break;let n=y+12+o.getUint32(y+4,!0)+o.getUint32(y+8,!0);if(n>e.byteLength)break;y=n;continue}let n=Ye(o,s,c,y,r);if(!n)break;v.push(n.mutation),y=n.nextOffset}if(b<0)break;if(h!==i)return{count:m,validEnd:d,physicalDataSize:f,logicalExtent:p,generationMismatch:h<i?`stale`:`newer`};for(let e of v)Je(e,t,n,l);m+=v.length,f=g,p=_,u=b,d=b}return{count:m,validEnd:d,physicalDataSize:f,logicalExtent:p}}function Qe(e,t,n,r,i,a){let o=new DataView(e),s=new Uint8Array(e),c=new TextDecoder,l=new Map;for(let e of t.values())e.ino>0&&!l.has(e.ino)&&l.set(e.ino,e);let u=0,d=0,f,m,h=0;for(;u+16<=e.byteLength;){let g=o.getUint32(u+12,!0);if(o.getUint32(u,!0)!==M||o.getUint32(u+4,!0)!==0||o.getUint32(u+8,!0)!==4||g!==u+1>>>0)break;let _=u+16,v=-1,y=_;for(;y+16<=e.byteLength;){let t=Xe(o,y);if(t<0)break;let n=o.getUint32(t,!0),r=o.getUint32(t+8,!0),i=o.getUint32(t+12,!0);if(n===fe&&r===8&&i===g&&t+20<=e.byteLength){v=t;break}if(n===M&&t!==u)break;y=t+1}if(v<0)break;let b=o.getUint32(v+16,!0);if(O(s.subarray(u,v))!==b)break;let x=s.subarray(_,v),S;try{S=a.open(x,p.metaLog,g>>>0)}catch{break}let C=new DataView(S.buffer,S.byteOffset,S.byteLength);if(S.byteLength<20)break;let w=C.getUint32(0,!0);if(w!==i)return{count:h,validEnd:d,physicalDataSize:f,logicalExtent:m,generationMismatch:w<i?`stale`:`newer`};let T=C.getFloat64(4,!0),E=C.getFloat64(12,!0);if(!Number.isSafeInteger(T)||!Number.isSafeInteger(E)||T<0||E<0)break;let D=20,ee=[],te=!0;for(;D+12<=S.byteLength;){let e=Ye(C,S,c,D,r);if(!e){te=!1;break}ee.push(e.mutation),D=e.nextOffset}if(!te||D!==S.byteLength)break;for(let e of ee)Je(e,t,n,l);h+=ee.length,f=T,m=E,u=v+20,d=u}return{count:h,validEnd:d,physicalDataSize:f,logicalExtent:m}}var $e=class extends b{constructor(e){super(`meta-snapshot`,e??`Meta snapshot is corrupt`),this.name=`MetaSnapshotCorruptionError`}},et=1397637456,P=16,tt=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let n=t;for(let e=0;e<8;e++)n=n&1?3988292384^n>>>1:n>>>1;e[t]=n>>>0}return e})();function nt(e){let t=4294967295;for(let n=0;n<e.length;n++)t=tt[(t^e[n])&255]^t>>>8;return(t^4294967295)>>>0}function rt(e,t,n,r=0,i=0){let a=new Uint8Array(16+e.length),o=new DataView(a.buffer);o.setFloat64(0,r,!0),o.setFloat64(8,i,!0),a.set(e,16);let s=n?n.seal(a,p.snapshot,t>>>0):a,c=new Uint8Array(P+s.length),l=new DataView(c.buffer);return l.setUint32(0,et,!0),l.setUint32(4,t>>>0,!0),l.setUint32(12,s.length,!0),c.set(s,P),l.setUint32(8,nt(c.subarray(16)),!0),c}function it(e,t){if(e.length<P)return null;let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint32(0,!0)!==et)return null;let r=n.getUint32(4,!0),i=n.getUint32(8,!0),a=n.getUint32(12,!0);if(P+a>e.length)return null;let o=e.subarray(P,P+a);if(nt(o)!==i)return null;let s;try{s=t?t.open(o,p.snapshot,r):o}catch{return null}if(s.length<16)return null;let c=new DataView(s.buffer,s.byteOffset,s.byteLength),l=c.getFloat64(0,!0),u=c.getFloat64(8,!0);return!Number.isSafeInteger(l)||!Number.isSafeInteger(u)||l<0||u<0?null:{sequence:r,payload:s.subarray(16),physicalDataSize:l,logicalExtent:u}}var at=16777216,ot=new Set([`create`,`update`,`delete`]),st=new Set([`SUBSCRIPTION_OVERFLOW`,`SUBSCRIPTION_INTERRUPTED`,`SUBSCRIPTION_CALLBACK_FAILED`,`SUBSCRIPTION_RESYNC_REQUIRED`]),ct=new Set([`disabled`,`deleted`,`not-file`,`too-large`,`unavailable`]),F=(e,t,n=Reflect.ownKeys(e))=>n.length===t.length&&n.every(e=>typeof e==`string`&&t.includes(e)),lt=(e,t,n,r=Reflect.ownKeys(e))=>t.every(e=>r.includes(e))&&r.every(e=>typeof e==`string`&&[...t,...n].includes(e)),ut=e=>!!e&&typeof e==`object`&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype,dt=e=>typeof e==`string`&&e.length>0&&e.length<=128,ft=e=>typeof e==`string`&&!e.includes(`\\0`);function pt(e,t){if(t<0)return 1/0;let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i<=127)n++;else if(i<=2047)n+=2;else if(i>=55296&&i<=56319&&r+1<e.length){let t=e.charCodeAt(r+1);t>=56320&&t<=57343?(n+=4,r++):n+=3}else n+=3;if(n>t)return 1/0}return n}var I=e=>Object.freeze(e);function mt(e,t){if(!Number.isSafeInteger(t)||t<0)throw y(`EINVAL`,void 0,`Invalid file change command`);let n=!1;try{if(!ut(e))throw Error();let r=Reflect.ownKeys(e),i=e.type,a=e.subscriptionId;if(!dt(a))throw Error();if(i===`register`&&F(e,[`type`,`subscriptionId`,`options`],r)){let r=e.options;if(!ut(r)||!lt(r,[`path`,`scope`,`recursive`,`events`,`content`],[`match`],Reflect.ownKeys(r)))throw Error();let i=r.path,o=r.scope,s=r.recursive,c=r.events,l=r.match,u=r.content;if(!ft(i)||o!==`file`&&o!==`directory`||typeof s!=`boolean`||!Array.isArray(c))throw Error();let d=c.length;if(!Number.isSafeInteger(d)||d<1||d>3)throw Error();let f=[];for(let e=0;e<d;e++)f.push(c[e]);if(f.some(e=>!ot.has(e))||new Set(f).size!==f.length)throw Error();let p,m;if(l!==void 0){if(!ut(l)||!F(l,[`source`,`flags`],Reflect.ownKeys(l)))throw Error();let e=l.source,t=l.flags;if(typeof e!=`string`||typeof t!=`string`)throw Error();p=e,m=t}let h;if(u===!1)h=!1;else{if(!ut(u)||!F(u,[`maxBytes`],Reflect.ownKeys(u)))throw Error();let e=u.maxBytes;if(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0||e>at)throw Error();h=e}let g=512+pt(a,t-512);if(g+=pt(i,t-g),p!==void 0&&(g+=pt(p,t-g),g+=pt(m,t-g)),g>t)n=!0;else return{command:I({type:`register`,subscriptionId:a,options:I({path:i,scope:o,recursive:s,events:I(f),...p===void 0?{}:{match:I({source:p,flags:m})},content:h!==!1&&I({maxBytes:h})})}),charge:g}}if((i===`activate`||i===`cancel`||i===`terminal-ack`)&&F(e,[`type`,`subscriptionId`],r))return{command:I({type:i,subscriptionId:a}),charge:0};if(i===`ack`&&F(e,[`type`,`subscriptionId`,`deliveryId`],r)){let t=e.deliveryId;if(typeof t==`number`&&Number.isSafeInteger(t)&&t>0)return{command:I({type:i,subscriptionId:a,deliveryId:t}),charge:0}}}catch{}throw n?y(`ENOSPC`,void 0,`File change command is too large`):y(`EINVAL`,void 0,`Invalid file change command`)}function ht(e,t){if(!t||typeof t!=`object`||Array.isArray(t))return!1;let n=t;return e.type===`register`?F(n,[`type`,`subscriptionId`])&&n.type===`registered`&&n.subscriptionId===e.subscriptionId:F(n,[`type`])&&n.type===`ok`}function gt(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return;let n=e;if(n.type===`terminal`&&F(n,[`type`,`subscriptionId`,`code`])&&dt(n.subscriptionId)&&typeof n.code==`string`&&st.has(n.code))return I({type:`terminal`,subscriptionId:n.subscriptionId,code:n.code});if(n.type===`closed`&&F(n,[`type`,`subscriptionId`])&&dt(n.subscriptionId))return I({type:`closed`,subscriptionId:n.subscriptionId});if(n.type!==`event`||!F(n,[`type`,`subscriptionId`,`deliveryId`,`change`])||!dt(n.subscriptionId)||!Number.isSafeInteger(n.deliveryId)||n.deliveryId<=0)return;let r=n.change;if(!r||typeof r!=`object`||Array.isArray(r)||!F(r,[`type`,`path`,`kind`,`cursor`,`content`]))return;let i=r;if(!ot.has(i.type)||!ft(i.path)||i.kind!==`file`&&i.kind!==`directory`&&i.kind!==`symlink`)return;let a=i.cursor;if(!a||typeof a!=`object`||Array.isArray(a)||!F(a,[`generation`,`sequence`])||!dt(a.generation)||a.generation!==t||!Number.isSafeInteger(a.sequence)||a.sequence<=0)return;let o=i.content;if(!o||typeof o!=`object`||Array.isArray(o))return;let s=o,c;if(s.status===`included`&&F(s,[`status`,`bytes`])&&s.bytes instanceof Uint8Array&&s.bytes.byteLength<=at)c=I({status:`included`,bytes:s.bytes});else if(s.status===`omitted`&&F(s,[`status`,`reason`])&&typeof s.reason==`string`&&ct.has(s.reason))c=I({status:`omitted`,reason:s.reason});else return;return I({type:`event`,subscriptionId:n.subscriptionId,deliveryId:n.deliveryId,change:I({type:i.type,path:i.path,kind:i.kind,cursor:I({generation:a.generation,sequence:a.sequence}),content:c})})}var _t=new WeakMap,vt=new WeakMap,yt=new WeakMap,bt=new WeakSet,xt=e=>bt.add(e),St=e=>bt.has(e),Ct=new Set([`id`,`contractVersion`,`compatibilityKey`,`requiredOpenMode`,`options`]),wt=[`error-details`,`persistence-status`],Tt=e=>typeof e==`string`&&/^[a-z][a-z0-9.-]*$/.test(e),Et=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Dt=(e,t)=>Reflect.ownKeys(e).every(e=>t.has(String(e)));function Ot(e,t,n){let r=e=>{throw y(`EINVAL`,n,e)};e===void 0&&(e=[]),Array.isArray(e)||r(`Plugin requests must be an array`);let i;try{i=structuredClone(e)}catch{r(`Plugin requests must be structured-cloneable`)}let a=[],o=new Set;for(let e of i){(!Et(e)||!Dt(e,Ct)||!Object.hasOwn(e,`options`))&&r(`Invalid plugin request`);let{id:n,contractVersion:i,compatibilityKey:s,requiredOpenMode:c,options:l}=e;Tt(n)||r(`Invalid plugin id`);let u=n;o.has(u)&&r(`Duplicate plugin id: ${u}`),o.add(u),i!==1&&r(`Unsupported plugin contract: ${u}`),typeof s!=`string`&&r(`Invalid plugin compatibility key: ${u}`),c!==void 0&&c!==`create-new`&&r(`Invalid required open mode: ${u}`),c&&t!==c&&r(`Plugin ${u} requires create-new`),a.length>=2&&r(`Too many plugin requests`),a.push({id:u,contractVersion:1,compatibilityKey:s,...c?{requiredOpenMode:`create-new`}:{},options:l})}return{requests:a,profile:kt(a)}}function kt(e){return{version:2,capabilities:[...new Set(wt)].sort(),plugins:e.map(({id:e,contractVersion:t,compatibilityKey:n})=>({id:e,contractVersion:t,compatibilityKey:n})).sort((e,t)=>e.id.localeCompare(t.id))}}var At=new WeakMap,jt=new Set([`.vault`,`.crypt`,`.crypt.log`]),Mt=new Set([`id`,`contractVersion`,`compatibilityKey`,`requiredOpenMode`,`storage`,`logicalChanges`]),Nt=new Set([`factory`,`sidecars`]),Pt=new WeakSet,Ft=new WeakSet,It=new WeakSet,Lt=(e,t)=>Reflect.ownKeys(e).every(e=>typeof e==`string`&&t.has(e));function Rt(e,t,n){if(e===void 0)return[];let r=e=>{throw y(`EINVAL`,n,e)};Array.isArray(e)||r(`Plugins must be an array`);let i=[],a=new Set,o=new Set,s=0,c=0;for(let n of e){(typeof n!=`object`||!n)&&r(`Invalid configured plugin`);let e=n;Lt(e,Mt)||r(`Unsupported plugin contribution`);let{id:l,contractVersion:u,compatibilityKey:d,requiredOpenMode:f,storage:p,logicalChanges:m}=e;Tt(l)||r(`Invalid plugin id`),a.has(l)&&r(`Duplicate plugin id: ${l}`),a.add(l),u!==1&&r(`Unsupported plugin contract: ${l}`),typeof d!=`string`&&r(`Invalid plugin compatibility key: ${l}`),f!==void 0&&f!==`create-new`&&r(`Invalid required open mode: ${l}`),f&&f!==t&&r(`Plugin ${l} requires create-new`),p===void 0==(m===void 0)&&r(`Plugin ${l} must contribute exactly one capability`);let h={source:e,id:l,contractVersion:1,compatibilityKey:d,...f?{requiredOpenMode:f}:{}};if(p!==void 0){(typeof p!=`object`||!p||Array.isArray(p)||!Lt(p,Nt))&&r(`Plugin ${l} requires a storage factory`);let{factory:e,sidecars:t}=p;typeof e!=`function`&&r(`Plugin ${l} requires a storage factory`),Array.isArray(t)||r(`Plugin ${l} must declare storage sidecars`);let n=[...t];(new Set(n).size!==n.length||n.some(e=>!jt.has(e)))&&r(`Plugin ${l} declared invalid storage sidecars`),++s>1&&r(`Multiple storage plugins are unsupported`),o.has(e)&&r(`Configured plugin factory already used: ${l}`),o.add(e),i.push({...h,storage:{factory:e,sidecars:n}})}else{(typeof m!=`object`||!m||Array.isArray(m)||!Lt(m,new Set([`version`,`create`])))&&r(`Plugin ${l} requires logical changes`);let e=m.version,t=Reflect.get(m,`create`);(e!==1||typeof t!=`function`)&&r(`Plugin ${l} requires logical changes`),++c>1&&r(`Multiple logical-change plugins are unsupported`),o.has(t)&&r(`Configured plugin factory already used: ${l}`),o.add(t),i.push({...h,logicalChanges:{source:m,contribution:{version:e,create:t},create:t}})}}return i}function zt(e,t){for(let n of e){let e=n.storage?n.storage.factory:n.logicalChanges.create,r=n.logicalChanges?.source;if(Pt.has(n.source)||Ft.has(e)||r&&It.has(r))throw y(`EINVAL`,t,`Configured plugin already mounted: ${n.id}`);Pt.add(n.source),Ft.add(e),r&&It.add(r)}}function Bt(e,t){for(let n of e){let e=n.storage?n.storage.factory:n.logicalChanges.create,r=n.logicalChanges?.source;if(Pt.has(n.source)||Ft.has(e)||r&&It.has(r))throw y(`EINVAL`,t,`Configured plugin already mounted: ${n.id}`)}}function Vt(e){let t=(t,n,r)=>{let i=0,a=n;do{let o=e[t](a,{at:r+i});if(!Number.isSafeInteger(o)||o<0||o>a.byteLength)throw new DOMException(`OPFS ${t} returned an invalid byte count: ${o}`,`InvalidStateError`);if(o===0&&a.byteLength>0){if(t===`read`&&r+i>=e.getSize())return new Uint8Array(a.buffer,a.byteOffset,a.byteLength).fill(0),i;throw new DOMException(`OPFS ${t} made no progress`,`InvalidStateError`)}if(i+=o,i===n.byteLength)return i;a=new Uint8Array(n.buffer,n.byteOffset+i,n.byteLength-i)}while(i<n.byteLength);return i};return{read:(e,{at:n})=>t(`read`,e,n),write:(e,{at:n})=>t(`write`,e,n),flush:()=>e.flush(),close:()=>e.close(),getSize:()=>e.getSize(),truncate:t=>e.truncate(t)}}var Ht=[`.bin`,`.meta.a`,`.meta.b`,`.bitmap`,`.meta.log`,`.data.log`,`.bootstrap`,`.vault`,`.crypt`,`.crypt.log`,`.meta`,`.importing`],Ut=class extends Error{code=`VOLUME_IMPORTING`;constructor(e){super(`Volume ${e} has an incomplete import`),this.name=`VolumeImportingError`}};function Wt(e){if(typeof e!=`string`||!e.endsWith(`.bin`)||e.length<=4||/[/\\\\]/.test(e))throw y(`EINVAL`,e,`Volume name must be a basename ending in .bin`);return Ht.map(t=>e.slice(0,-4)+t)}function Gt(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`NotFoundError`}async function Kt(e,t){for(let n of t)try{return await e.getFileHandle(n,{create:!1}),n}catch(e){if(!Gt(e))throw e}}var qt=new Map;async function Jt(e){return await qt.get(e),new Promise((t,n)=>{let r=navigator.locks.request(`opfs-vfs-volume-${e}`,{ifAvailable:!0},async n=>{if(!n)throw y(`EBUSY`,e,`Volume is in use`);await new Promise(n=>{let i=!1;t(()=>{if(!i){i=!0,qt.set(e,r);let t=()=>{qt.get(e)===r&&qt.delete(e)};r.then(t,t),n()}return r})})});r.catch(n)})}async function Yt(e){try{await e.closeVfs()}catch(t){try{await e.closeVfs()}catch{}throw t}}var Xt=e=>{try{return new DataView(e),!0}catch{return!1}},L=4096,Zt=16384,Qt=new Uint8Array(L),$t=new TextEncoder,en=1<<20;function tn(e,t){return 256+pt(e,t-256)}var nn=(e,t)=>e===`/`||t===e||t.startsWith(`${e}/`),rn=e=>{let t=0;for(let n=0;n<e.length;n++)e.charCodeAt(n)===47&&t++;return e===`/`?0:t},an=(e,t)=>e<t?-1:+(e>t),on=(e,t)=>e.record.deletePhase-t.record.deletePhase||t.depth-e.depth||an(e.record.path,t.record.path),sn=(e,t)=>e.depth-t.depth||an(e.record.path,t.record.path),cn=(e,t)=>an(e.path,t.path),ln=e=>e instanceof Error&&_(e.code),un=4294967295,dn=255,fn=864e5,pn=4194304;function mn(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.name===`QuotaExceededError`||t.code===22}var hn=1112950355,gn=1,_n=1,vn=2,yn=32,bn=12;function xn(e){let t=2166136261;for(let n=0;n<e.length;n++)t=Math.imul(t^e.charCodeAt(n),16777619);return t>>>0}var Sn=33188,Cn=16877,wn=41471,Tn=3,En=292,Dn=146,On=73,kn=32768,An=16384,jn=40960,Mn=40,Nn=function(e){return e[e.O_RDONLY=0]=`O_RDONLY`,e[e.O_WRONLY=1]=`O_WRONLY`,e[e.O_RDWR=2]=`O_RDWR`,e[e.O_CREAT=64]=`O_CREAT`,e[e.O_EXCL=128]=`O_EXCL`,e[e.O_TRUNC=512]=`O_TRUNC`,e[e.O_APPEND=1024]=`O_APPEND`,e}({}),Pn=class e{bits;totalBlocks;nextFreeHint;constructor(e){this.totalBlocks=e,this.bits=new Uint32Array(Math.ceil(e/32)),this.nextFreeHint=1,this.set(0,!0)}alloc(){let e=this.findFreeFrom(this.nextFreeHint);if(e<0){let e=this.findFreeFrom(0);return e<0||e>=this.nextFreeHint?-1:(this.set(e,!0),this.nextFreeHint=e+1,e)}return this.set(e,!0),this.nextFreeHint=e+1>=this.totalBlocks?1:e+1,e}allocRun(e){if(e<=0)return-1;if(e===1)return this.alloc();let t=this.findRunFrom(this.nextFreeHint,e);if(t<0&&(t=this.findRunFrom(1,e)),t<0)return-1;for(let n=t;n<t+e;n++)this.set(n,!0);return this.nextFreeHint=t+e>=this.totalBlocks?1:t+e,t}findFreeFrom(e){e<1&&(e=1);let t=e;for(;t<this.totalBlocks;){let e=t>>>5,n=this.bits[e]>>>0;if(n===4294967295){t=e+1<<5;continue}let r=~((n|(1<<(t&31))-1)>>>0)>>>0;if(r!==0){let t=r&-r>>>0,n=(e<<5)+(31-Math.clz32(t));return n<this.totalBlocks?n:-1}t=e+1<<5}return-1}findRunFrom(e,t){let n=this.findFreeFrom(e<1?1:e);for(;n>=0&&n+t<=this.totalBlocks;){let e=!0;for(let r=n+1;r<n+t;r++)if(this.get(r)){e=!1,n=this.findFreeFrom(r+1);break}if(e)return n}return-1}free(e){this.set(e,!1),e<this.nextFreeHint&&(this.nextFreeHint=e)}grow(e){let t=new Uint32Array(Math.ceil(e/32));t.set(this.bits),this.bits=t,this.totalBlocks=e}rebuildFrom(e,t,n){this.bits.fill(0),this.set(0,!0),this.nextFreeHint=1;for(let r of e){if(r<0||r>=this.totalBlocks){n?.(r);continue}this.get(r)&&r!==0&&t?.(r),this.set(r,!0)}}getTotalBlocks(){return this.totalBlocks}highestSet(){for(let e=this.bits.length-1;e>=0;e--){let t=this.bits[e]>>>0;if(t!==0)return(e<<5)+(31-Math.clz32(t))}return 0}get(e){return!!(this.bits[e>>>5]&1<<(e&31))}set(e,t){let n=e>>>5,r=e&31;t?this.bits[n]|=1<<r:this.bits[n]&=~(1<<r)}getRawBits(){return this.bits}setRawBits(e){this.bits=e}static fromBinary(t,n){let r=new e(n);return r.bits=t,r}};function Fn(e,t=Sn){let n=Date.now();return{ino:e,kind:`file`,isDir:!1,size:0,blocks:[],children:[],mode:kn|t&4095,nlink:1,atimeMs:n,mtimeMs:n,ctimeMs:n,timestampMs:n}}function In(e,t=Cn){let n=Date.now();return{ino:e,kind:`dir`,isDir:!0,size:0,blocks:[],children:[],mode:An|t&4095,nlink:2,atimeMs:n,mtimeMs:n,ctimeMs:n,timestampMs:n}}function Ln(e,t,n=wn){let r=Date.now();return{ino:e,kind:`symlink`,isDir:!1,size:$t.encode(t).byteLength,blocks:[],children:[],symlinkTarget:t,mode:jn|n&4095,nlink:1,atimeMs:r,mtimeMs:r,ctimeMs:r,timestampMs:r}}function R(e){return e.kind===`symlink`||(e.mode&61440)==40960&&!e.isDir}function Rn(e){let t=e&Tn;return t===0||t===2}function zn(e){let t=e&Tn;return t===1||t===2}var Bn=new WeakMap;async function Vn(e,t,n){let r=t.replace(/\\.bin$/,`.importing`),i;try{i=await e.getFileHandle(r,{create:!1})}catch(e){if(!Gt(e))throw e;if(n)throw new Ut(t);return}if(!n||n.length!==16)throw new Ut(t);try{await e.getFileHandle(t,{create:!1})}catch(e){throw Gt(e)?new Ut(t):e}let a=await i.getFile();if(a.size!==16||!new Uint8Array(await a.arrayBuffer()).every((e,t)=>e===n[t]))throw new Ut(t)}var Hn=class{dataHandle;logHandle;dataLogHandle;bootstrapHandle;flushedDataSize=0;flushedLogicalExtent=0;committedLogicalExtent=0;metaHandleA;metaHandleB;activeMetaSlot=0;metaSnapshotSequence=0;logOffset=0;lastSnapshotSize=0;metaLogFlushPending=!1;dataLogOffset=0;dataWalTruncatePending=!1;dataWalCycleSealer;dirtyInodes=new Set;attrDirtyInodes=new Set;deletedInodes=new Set;inodes;inodeTable=new Map;dirEntries=new Map;pathIndex=new Map;inoToPaths=new Map;bitmap;pendingFree=new Set;zeroBuffer=null;sortedPaths=[];fileData=new Map;openFiles=new Map;nextFd=10+(crypto.getRandomValues(new Uint32Array(1))[0]>>>2);totalBlocks=Zt;dirtyPages=new Map;pendingDeletedInodes=new Set;nextInodeNumber=2;dirtyStructure=!1;dataDirty=!1;_ready;openMode;bufferMode;localDurabilityMode;debugWal=!1;noatime=!1;recoveryMode=`salvage`;storage;sealer;storageHandles=[];maxFileSize;maxNameLength;maxPathDepth;maxFiles;maxTotalBytes;allocatedDataBlocks=0;flushTimer;removeBalancedModeHooks;lastLocalFlushAt;lastLocalCheckpointAt;localPersistenceState=`clean`;lastSalvage;lastError;failureRevision=0;retainedFailure;persistenceListener;wrapSyncAccessHandle;volumeIdentity;firstMountAncillarySidecarsWereEmpty=!1;storageFactory;storageSidecars;logicalChanges;logicalSession;logicalSessionClosed=!1;logicalChangesPoisoned=!1;logicalCaptureToken;logicalCaptureBuffers=new WeakSet;logicalDeliveryBuffers=new WeakSet;logicalSequence=0;logicalOperation;changeGeneration;directChangeClientId=crypto.randomUUID();changeChannels=new Map;changeChannelCounts=new Map;pendingChangeChannels=new Set;changeSubscriptionIds=new Map;changeSubscriptionCount=0;changeTerminalIds=new Set;get recordingLogicalChanges(){return!!this.logicalSession&&!this.logicalChangesPoisoned&&this.changeSubscriptionCount>0}constructor(e,t){if(t&&`encryption`in t)throw y(`EINVAL`,e,`Use the premium package for encryption options`);if(t&&`storageFactory`in t)throw y(`EINVAL`,e,`Use plugins instead of storageFactory`);this.openMode=t?.openMode??`open-or-create`;let n=(t&&At.get(t))??Rt(t?.plugins,this.openMode,e);t&&At.delete(t),zt(n,e);let r=n.find(e=>e.storage)?.storage,i=n.find(e=>e.logicalChanges)?.logicalChanges;this.storageFactory=r?.factory,this.storageSidecars=r?.sidecars??[],this.logicalChanges=i,this.changeGeneration=(t&&_t.get(t))??crypto.randomUUID(),vt.set(this,{open:(e,t,n,r,i,a)=>this.openFileChangeChannelForClient(e,t,n,r,i,a)}),yt.set(this,{read:()=>({state:this.localPersistenceState,failure:this.retainedFailure,failureRevision:this.failureRevision,salvage:this.lastSalvage}),watch:e=>{this.persistenceListener=e}}),this.volumeIdentity=xn(e),this.bufferMode=t?.bufferMode??`disk`,this.localDurabilityMode=t?.localDurabilityMode??`balanced`,this.debugWal=t?.debugWal??!1,this.noatime=t?.noatime??!1,this.recoveryMode=t?.recoveryMode===`fail-stop`?`fail-stop`:`salvage`,this.wrapSyncAccessHandle=t?._wrapSyncAccessHandle;let a=t?.maxFileSize;this.maxFileSize=a!==void 0&&Number.isSafeInteger(a)&&a>=0?Math.min(a,un):un;let o=e=>e!==void 0&&Number.isSafeInteger(e)&&e>=0?e:void 0;this.maxNameLength=o(t?.maxNameLength)??dn,this.maxPathDepth=o(t?.maxPathDepth),this.maxFiles=o(t?.maxFiles),this.maxTotalBytes=o(t?.maxTotalBytes);let s=t&&Bn.get(t);t&&Bn.delete(t),this._ready=this.init(e,s)}get ready(){return this._ready}get walPendingBytes(){return this.dataLogOffset}get hasDirtyMeta(){return this.dirtyStructure||this.dirtyInodes.size>0||this.attrDirtyInodes.size>0||this.deletedInodes.size>0}setLocalPersistenceState(e,t){if(e===this.localPersistenceState&&e!==`error`)return;let n=this.localPersistenceState;if(this.localPersistenceState=e,e===`error`){t!==void 0&&(this.lastError=t);let e=t??this.lastError;(n!==`error`||e!==this.retainedFailure)&&(this.retainedFailure=e,this.failureRevision++,this.persistenceListener?.())}else this.lastError=void 0,n!==e&&this.persistenceListener?.()}getLocalPersistenceStatusSync(){let e=0;for(let t of this.dirtyPages.values())e+=t.size;return{dirtyPages:e,walPendingBytes:this.walPendingBytes,lastLocalFlushAt:this.lastLocalFlushAt,lastLocalCheckpointAt:this.lastLocalCheckpointAt,localPersistenceState:this.localPersistenceState,lastSalvage:this.lastSalvage,lastError:this.localPersistenceState===`error`?this.lastError:void 0}}initializing=!0;closeRequested=!1;closing;releaseVolumeLock;async init(e,t){let n=[];try{let r=Wt(e);if(![`open-or-create`,`create-new`,`open-existing`].includes(this.openMode))throw y(`EINVAL`,e,`Unknown volume open mode`);if(this.releaseVolumeLock=await Jt(e),this.closeRequested)throw y(`EBADF`,e,`Volume closed during initialization`);let i=await navigator.storage.getDirectory();if(await Vn(i,e,t),this.openMode===`create-new`&&await Kt(i,r))throw y(`EEXIST`,e);for(let t of[`.vault`,`.crypt`,`.crypt.log`])if(!this.storageSidecars.includes(t))try{throw await i.getFileHandle(e.replace(/\\.bin$/,t),{create:!1}),new m(e,t)}catch(e){if(!e||typeof e!=`object`||e.name!==`NotFoundError`)throw e}let a=!1;try{a=(await(await i.getFileHandle(e.replace(/\\.bin$/,`.meta`),{create:!1})).getFile()).size>0}catch(e){if(!e||typeof e!=`object`||e.name!==`NotFoundError`)throw e}let o=async(e,t)=>{let r=await e.createSyncAccessHandle();n.push(r);try{return Vt(this.wrapSyncAccessHandle?this.wrapSyncAccessHandle(r,t):r)}catch(e){n.pop();try{r.close()}catch{}throw e}},s=await i.getFileHandle(e,{create:this.openMode!==`open-existing`});if(this.dataHandle=await o(s,`data`),this.openMode===`create-new`&&(this.dataHandle.getSize()>0||await Kt(i,r.slice(1))))throw y(`EEXIST`,e);let c=e.replace(/\\.bin$/,`.meta.a`),l=await i.getFileHandle(c,{create:!0});this.metaHandleA=await o(l,`metaA`);let u=e.replace(/\\.bin$/,`.meta.b`),d=await i.getFileHandle(u,{create:!0});this.metaHandleB=await o(d,`metaB`);let f=e.replace(/\\.bin$/,`.meta.log`),p=await i.getFileHandle(f,{create:!0});this.logHandle=await o(p,`metaLog`);let h=e.replace(/\\.bin$/,`.data.log`),g=await i.getFileHandle(h,{create:!0});if(this.dataLogHandle=await o(g,`dataLog`),this.bufferMode===`disk`&&this.dataLogHandle.getSize()>0)throw y(`EBUSY`,e,`Nonempty memory-mode recovery log; reopen in memory mode and close successfully before switching to disk mode`);let _=e.replace(/\\.bin$/,`.bootstrap`),v=await i.getFileHandle(_,{create:!0});this.bootstrapHandle=await o(v,`bootstrap`),this.hasFirstMountMarker()&&(this.firstMountAncillarySidecarsWereEmpty=!0),await this.openStorage(e,i,o),this.hasFirstMountMarker()&&(this.firstMountAncillarySidecarsWereEmpty&&=this.storage?.isSemanticallyEmpty?.()??!0);let b=this.hasFirstMountMarker(),x=this.loadMetaSnapshotPayload(a),S=x===null&&this.logHandle.getSize()===0;if(x){let e=ze(x.byteOffset===0&&x.byteLength===x.buffer.byteLength?x.buffer:x.slice().buffer);this.totalBlocks=e.totalBlocks,this.inodes=e.inodes,this.nextInodeNumber=e.nextInodeNumber,this.sortedPaths=Array.from(e.inodes.keys()),this.bitmap=new Pn(this.totalBlocks)}else this.bitmap=new Pn(Zt),this.inodes=new Map,this.inodes.set(`/`,In(1)),this.nextInodeNumber=2,this.sortedPaths=[`/`],S&&(this.beginFirstMount(),this.storage?.beforeDataCommit?.(),this.writeMeta(!0),this.finishFirstMount());let C=x!==null&&b;this.logOffset=0;let w=this.logHandle.getSize();if(w>0){let e=new Uint8Array(w);this.logHandle.read(e,{at:0});let t=Ze(e.buffer,this.inodes,this.sortedPaths,this.totalBlocks,this.metaSnapshotSequence,this.sealer);if(t.generationMismatch===`newer`&&this.recoveryMode===`fail-stop`)throw new $e(`Meta log generation is newer than the readable snapshot ${this.metaSnapshotSequence}`);let n=t.validEnd;n<w&&(this.logHandle.truncate(n),this.logHandle.flush()),this.logOffset=n,n>0&&(this.flushedDataSize=t.physicalDataSize??this.flushedDataSize,this.committedLogicalExtent=t.logicalExtent??this.committedLogicalExtent,this.flushedLogicalExtent=this.committedLogicalExtent)}this.normalizeLoadedInodes(),this.rebuildIndexesFromPathMap(),this.storage?.validateAfterMetadata?.([...new Set(this.inodes.values())].some(e=>!e.isDir&&!R(e)&&e.blocks.some(e=>e!==0))),this.hydrateMemoryFileData(),this.replayDataWal();let T=this.bufferMode===`disk`&&this.reconcileDiskState();if(this.rebuildBitmapFromMetadata(),T)try{this.flushVfs()}catch(e){this.logWalDebug(`reconcileDiskState repair flush failed`,e)}if(C&&this.finishFirstMount(),this.closeRequested)throw y(`EBADF`,e,`Volume closed during initialization`);this.createLogicalChangeSession(),this.localDurabilityMode===`balanced`&&this.installBalancedModeHooks()}catch(e){try{this.closeLogicalChangeSession(`initialization-failed`)}catch{}for(let e=n.length-1;e>=0;e--)try{n[e].close()}catch{}try{this.storage?.destroy()}catch{}finally{this.storage=void 0,this.sealer=void 0,this.dataWalCycleSealer=void 0,this.closed=!0;let e=this.releaseVolumeLock;this.releaseVolumeLock=void 0,await e?.()}throw e}finally{this.storageFactory=void 0,this.initializing=!1}}async openStorage(e,t,n){let r=this.storageFactory;if(this.storageFactory=void 0,!r)return;let i=[],a=!1,o;try{o=await r({fileName:e,root:t,data:this.dataHandle,dataSize:this.dataHandle.getSize(),metaSnapshotSizes:[this.metaHandleA.getSize(),this.metaHandleB.getSize()],openSidecar:(r,o=!0)=>{if(a)return Promise.reject(TypeError(`Storage setup has finished`));if(!this.storageSidecars.includes(r))return Promise.reject(TypeError(`Unsupported storage sidecar suffix: ${r}`));let s=(async()=>this.trackStorageHandle(await n(await t.getFileHandle(e.replace(/\\.bin$/,r),{create:o}),`data`)))();return i.push(s),s.catch(()=>{}),s}}),this.storage=o}finally{a=!0,await Promise.allSettled(i)}if(o.recordCodec&&(!o.createDataWalCycle||!o.openDataWalCycle))throw y(`EINVAL`,e,`Record codecs require both WAL cycle hooks`);this.dataHandle=Vt(o.data),this.sealer=o.recordCodec}trackStorageHandle(e){return this.storageHandles.push(e),e}writeAll(e,t,n,r){let i=0;for(;i<t.byteLength;){let a=e.write(t.subarray(i),{at:n+i});if(!Number.isSafeInteger(a)||a<=0||a>t.byteLength-i)throw new DOMException(`${r} short write made no valid progress (${a}/${t.byteLength-i} bytes)`,`InvalidStateError`);i+=a}}firstMountMarker(e){let t=new Uint8Array(yn),n=new DataView(t.buffer);return n.setUint32(0,hn,!0),n.setUint32(4,gn,!0),n.setUint32(8,e,!0),n.setUint32(12,this.volumeIdentity,!0),t.set(crypto.getRandomValues(new Uint8Array(bn)),16),n.setUint32(28,O(t.subarray(0,28)),!0),t}firstMountMarkerState(){if(this.bootstrapHandle.getSize()!==yn)return null;let e=new Uint8Array(yn);if(this.bootstrapHandle.read(e,{at:0})!==e.byteLength)return null;let t=new DataView(e.buffer);if(t.getUint32(0,!0)!==hn||t.getUint32(4,!0)!==gn||t.getUint32(12,!0)!==this.volumeIdentity||t.getUint32(28,!0)!==O(e.subarray(0,28)))return null;let n=t.getUint32(8,!0);return n===_n||n===vn?n:null}hasFirstMountMarker(){return this.firstMountMarkerState()===_n}beginFirstMount(){let e=this.firstMountMarker(_n);this.bootstrapHandle.truncate(0),this.writeAll(this.bootstrapHandle,e,0,`first-mount intent`),this.bootstrapHandle.flush()}finishFirstMount(){let e=this.firstMountMarker(vn);this.bootstrapHandle.truncate(0),this.writeAll(this.bootstrapHandle,e,0,`first-mount retirement`),this.bootstrapHandle.flush()}loadMetaSnapshotPayload(e){let t=e=>{let t=e.getSize();if(t<=0)return{size:0,parsed:null};let n=new Uint8Array(t);return e.read(n,{at:0}),{size:t,parsed:it(n,this.sealer)}},n=t(this.metaHandleA),r=t(this.metaHandleB),i=null;if(n.parsed&&(!r.parsed||n.parsed.sequence>=r.parsed.sequence)?i={...n.parsed,slot:0}:r.parsed&&(i={...r.parsed,slot:1}),i)return this.activeMetaSlot=i.slot,this.metaSnapshotSequence=i.sequence,this.flushedDataSize=i.physicalDataSize,this.flushedLogicalExtent=i.logicalExtent,this.committedLogicalExtent=i.logicalExtent,i.payload;if(n.size>0||r.size>0){if(this.hasFirstMountMarker()&&this.logHandle.getSize()===0&&this.dataLogHandle.getSize()===0&&this.dataHandle.getSize()===0&&this.firstMountAncillarySidecarsWereEmpty)return this.metaHandleA.truncate(0),this.metaHandleA.flush(),this.metaHandleB.truncate(0),this.metaHandleB.flush(),this.activeMetaSlot=0,this.metaSnapshotSequence=0,null;throw new $e(`Meta snapshot present but unreadable (slotA=${n.size}B, slotB=${r.size}B); no valid checksum and no usable fallback.`)}if(e)throw new b(`format-version`,`Unsupported retired metadata snapshot (.meta); reset this development volume to use .meta.a/.meta.b`);if(this.logHandle.getSize()>0)return this.activeMetaSlot=1,this.metaSnapshotSequence=0,null;if(this.dataHandle.getSize()>0)throw new $e(`Meta snapshot and log are both empty but data/bitmap files are non-empty; refusing to mount as a fresh filesystem (would discard the existing namespace).`);return null}reconcileDiskState(){let e=this.dataHandle.getSize(),t=Math.floor(e/L),n=this.committedLogicalExtent,r=r=>r===0?!1:this.storage?.hasPhysicalBlock?!this.storage.hasPhysicalBlock(r,e,n):r>=t,i=0,a=0;for(let[e,t]of this.inodes){if(t.isDir||R(t))continue;let n=t.blocks.length;for(let e=0;e<t.blocks.length;e++)if(r(t.blocks[e])){n=e;break}let o=0;for(;t.blocks.length>n;){let e=t.blocks.pop();e!==0&&(this.bitmap.free(e),a++),o++}let s=t.blocks.length*L,c=Math.min(t.size,s);(c!==t.size||o>0)&&(t.size=c,i++,this.dirtyInodes.add(e))}return i>0||a>0?(this.dirtyStructure=!0,this.logWalDebug(`reconcileDiskState repaired torn state`,{repairedInodes:i,droppedBlocks:a,physicalDataSize:e}),!0):!1}rebuildBitmapFromMetadata(){let e=new Set,t=[],n=-1;for(let r of this.inodes.values())if(!(r.isDir||R(r))&&!e.has(r)){e.add(r);for(let e of r.blocks)e!==0&&(t.push(e),e>n&&(n=e))}if(n>=this.totalBlocks){let e=this.totalBlocks;for(;n>=e;)e*=2;this.bitmap.grow(e),this.totalBlocks=e,this.dirtyStructure=!0}let r=0;this.bitmap.rebuildFrom(t,()=>{r++}),this.allocatedDataBlocks=t.length,r>0&&(this.setLocalPersistenceState(`error`),this.logWalDebug(`rebuildBitmapFromMetadata detected double-claimed blocks`,{doubleClaims:r,totalBlocks:this.totalBlocks}))}hydrateMemoryFileData(){if(this.bufferMode!==`memory`)return;this.fileData.clear();let e=new Map;for(let[t,n]of this.inodes){if(n.isDir||R(n)||n.size<=0)continue;let r=e.get(n);if(r){this.fileData.set(t,r);continue}let i=new Uint8Array(n.size),a=Math.min(n.size,n.blocks.length*L);this.forEachBlockRun(n,0,a,(e,t,n)=>{e!==0&&this.readDataExactly(i.subarray(t,t+n),e)}),this.fileData.set(t,i),e.set(n,i)}}logWalDebug(...e){this.debugWal&&console.debug(`[opfs-vfs:data-wal]`,...e)}replayDataWal(){let e=this.dataLogHandle.getSize();if(this.bufferMode!==`memory`){this.dataLogOffset=0;return}if(e<=0){this.dataLogOffset=0,this.setLocalPersistenceState(`clean`);return}this.setLocalPersistenceState(`recovering`);let t=new Uint8Array(e);this.dataLogHandle.read(t,{at:0});let n=this.storage?.openDataWalCycle?.(t);if(this.storage?.recordCodec&&!n){this.recoverDataWal(`stampless-cycle`,0,e,`protected data WAL has no valid cycle stamp`),this.walPendingBytes>0||this.dirtyPages.size>0?this.setLocalPersistenceState(`dirty`):this.setLocalPersistenceState(`clean`);return}let r=n?.codec??this.sealer;this.dataWalCycleSealer=r;let{records:i,frameEnds:a,parsedBytes:o,hadPartialTail:s,corruptionOffset:c}=se(t,r,n?.prefixBytes??0);s&&c===void 0&&(this.logWalDebug(`truncating partial trailing data WAL record`,{parsedBytes:o,size:e}),this.dataLogHandle.truncate(o),this.dataLogHandle.flush()),this.dataLogOffset=o;for(let e of i)this.nextInodeNumber=Math.max(this.nextInodeNumber,e.inodeId+1);let l=ce({applyWrite:(e,t,n)=>this.applyReplayWrite(e,t,n),applyTruncate:(e,t)=>this.applyReplayTruncate(e,t),applyDelete:()=>{}},i);if(l.failedIndex!==void 0){let t=l.failedIndex===0?0:a[l.failedIndex-1],n=i[l.failedIndex];this.recoverDataWal(`apply-failure`,t,e,`apply of ${n.op} record #${l.failedIndex} failed`)}else c!==void 0&&this.recoverDataWal(`corrupt-frame`,o,e,`corrupt frame at byte ${c}`);this.walPendingBytes>0||this.dirtyPages.size>0?this.setLocalPersistenceState(`dirty`):this.setLocalPersistenceState(`clean`),this.logWalDebug(`replayed data WAL`,{records:i.length,replayedRecords:l.replayedRecords,parsedBytes:o,hadPartialTail:s,failedIndex:l.failedIndex,corruptionOffset:c,pendingBytes:this.walPendingBytes})}recoverDataWal(e,t,n,r){if(this.recoveryMode===`fail-stop`){let n=new C(`data WAL corruption (${e}): ${r}`,t);throw this.setLocalPersistenceState(`error`,n),n}this.salvageDataWal(e,t,n,r)}salvageDataWal(e,t,n,r){this.dataLogHandle.truncate(t),this.dataLogHandle.flush(),this.dataLogOffset=t,this.lastSalvage={reason:e,truncatedAt:t,discardedBytes:Math.max(0,n-t),detail:r,at:Date.now()},this.persistenceListener?.(),this.logWalDebug(`salvaged data WAL`,this.lastSalvage)}markDirtyRange(e,t,n){if(n<=0)return;let r=t/L>>>0,i=(t+n-1)/L>>>0,a=this.dirtyPages.get(e);a||(a=new Set,this.dirtyPages.set(e,a));for(let e=r;e<=i;e++)a.add(e)}markResized(e,t,n){let r=this.dirtyPages.get(e);r||(r=new Set,this.dirtyPages.set(e,r));for(let e=Math.floor(t/L);e<Math.ceil(n/L);e++)r.add(e)}applyReplayWrite(e,t,n){this.ensureDerivedIndexes();let r=this.inodeTable.get(e);if(!r||r.isDir||R(r))return;let i=this.pathForInode(r);if(!i)return;let a=t+n.length;if(!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(a)||a>this.maxFileSize)throw RangeError(`Data WAL replay write out of bounds: offset=${t} end=${a} max=${this.maxFileSize}`);let o=this.lookupFileDataForInode(i,r)??new Uint8Array,s=o;a>o.length&&(s=new Uint8Array(a),s.set(o)),s.set(n,t),this.syncFileDataForInode(r,s),this.updateOpenFileBuffers(r,s);let c=Math.min(t,r.size);r.size=Math.max(r.size,a),this.markDirtyRange(r,c,a-c),this.markAllPathsForInode(r)}applyReplayTruncate(e,t){this.ensureDerivedIndexes();let n=this.inodeTable.get(e);if(!n||n.isDir||R(n))return;let r=this.pathForInode(n);if(!r)return;if(!Number.isSafeInteger(t)||t<0||t>this.maxFileSize)throw RangeError(`Data WAL replay truncate out of bounds: size=${t} max=${this.maxFileSize}`);let i=this.lookupFileDataForInode(r,n)??new Uint8Array,a;t<=i.length?a=i.slice(0,t):(a=new Uint8Array(t),a.set(i)),this.syncFileDataForInode(n,a),this.updateOpenFileBuffers(n,a),this.markResized(n,n.size,t),n.size=t,this.markAllPathsForInode(n)}symlinkSync(e,t,n=wn){return this.recordingLogicalChanges?this.withLogicalOperation(()=>this.symlinkSyncImpl(e,t,n)):this.symlinkSyncImpl(e,t,n)}symlinkSyncImpl(e,t,n){if(e.length===0)throw y(`ENOENT`,t,`Empty symlink target`);if(e.includes(`\\0`))throw y(`EINVAL`,t,`Symlink target contains NUL byte`);if($t.encode(e).byteLength>=4096)throw y(`ENAMETOOLONG`,t);let r=k(t),i=this.resolveInodePath(r.path,!1);if(this.hasPathEntry(i))throw y(`EEXIST`,i);let a=this.resolveInodePath(A(i),!0),o=j(i),s=this.getInodeByPath(a);if(!s)throw y(`ENOENT`,a);if(!s.isDir)throw y(`ENOTDIR`,a);this.assertSearchablePath(a,!0),this.assertDirectoryWritable(a,s),this.assertNameWithinQuota(i),this.assertFileCountWithinQuota(i),this.impact(i,!1);let c=Ln(this.nextInodeNumber++,e,n);this.addDirEntry(s,o,c),this.linkInodePath(i,c),B(this.sortedPaths,i),this.commitNamespaceChange(),this.touchInode(i),this.touchInode(a),this.dirtyInodes.add(i),this.dirtyInodes.add(a),this.flushMemoryNamespaceLog(),this.recordLogicalCreate(i,c)}readlinkSync(e){let t=k(e),n=this.resolveInodePath(t.path,!1),r=this.getInodeByPath(n);if(!r)throw y(`ENOENT`,n);if(!R(r))throw y(`EINVAL`,n,`Path is not a symbolic link`);return this.assertSearchablePath(n,!1),this.touchInodeAccess(n,r),r.symlinkTarget??``}realpathSync(e){let t=k(e),n=this.resolveInodePath(t.path,!0),r=this.getInodeByPath(n);if(!r)throw y(`ENOENT`,n);return this.assertSearchablePath(n,r.isDir),n}resolveSymlinkTarget(e,t){if(t.startsWith(`/`))return k(t).path;let n=A(e);return k(n===`/`?`/${t}`:`${n}/${t}`).path}resolveInodePath(e,t){if(this.closed)throw y(`EBADF`,e,`Volume is closed`);let n=e,r=0;for(;;){let e=n.split(`/`).filter(Boolean);if(e.length===0)return`/`;let i=!1,a=`/`,o=this.getInodeByPath(`/`);o?.isDir&&this.assertDirectoryExecutable(`/`,o);for(let o=0;o<e.length;o++){let s=this.getInodeByPath(a),{path:c,inode:l}=s?.isDir?this.lookupChild(a,s,e[o]):{path:a,inode:void 0},u=o===e.length-1;if(!l){a=c===a?a===`/`?`/${e[o]}`:`${a}/${e[o]}`:c;continue}if(R(l)&&(t||!u)){if(++r>Mn)throw y(`ELOOP`,c);let t=this.resolveSymlinkTarget(c,l.symlinkTarget??``),a=e.slice(o+1).join(`/`);n=a?`${t===`/`?``:t}/${a}`:t,i=!0;break}if(!u){if(!l.isDir)throw y(`ENOTDIR`,c);this.assertDirectoryExecutable(c,l),a=c}}if(!i)return n}}mkdirSync(e,t=Cn){return this.recordingLogicalChanges?this.withLogicalOperation(()=>this.mkdirSyncImpl(e,t)):this.mkdirSyncImpl(e,t)}mkdirSyncImpl(e,t){let n=this.normalizeMkdirOptions(t);if(n.recursive){let t=k(e);if(t.path===`/`)return;let r=t.path.split(`/`).filter(Boolean);for(let e=0;e<r.length;e++){let t=`/${r.slice(0,e+1).join(`/`)}`,i=this.resolveInodePath(t,!1),a=this.getInodeByPath(i);if(a){if(R(a)){let n=this.resolveInodePath(t,!0),a=this.getInodeByPath(n);if(!a)throw y(e===r.length-1?`EEXIST`:`ENOENT`,i);if(!a.isDir)throw y(e===r.length-1?`EEXIST`:`ENOTDIR`,i);e<r.length-1&&this.assertSearchablePath(n,!0);continue}if(!a.isDir)throw y(e===r.length-1?`EEXIST`:`ENOTDIR`,i);e<r.length-1&&this.assertSearchablePath(i,!0);continue}this.mkdirSingleSync(i,n.mode)}return}this.mkdirSingleSync(e,n.mode)}mkdirSingleSync(e,t=Cn){let n=k(e),r=this.resolveInodePath(n.path,!1);if(this.hasPathEntry(r))throw y(`EEXIST`,r);let i=A(r),a=j(r),o=this.getInodeByPath(i);if(!o)throw y(`ENOENT`,i);if(!o.isDir)throw y(`ENOTDIR`,i);this.assertSearchablePath(i,!0),this.assertDirectoryWritable(i,o),this.assertNameWithinQuota(r),this.assertFileCountWithinQuota(r),this.impact(r,!1);let s=In(this.nextInodeNumber++,t);this.addDirEntry(o,a,s),o.nlink=(o.nlink??2)+1,this.linkInodePath(r,s),B(this.sortedPaths,r),this.commitNamespaceChange(),this.touchInode(r),this.touchInode(i),this.dirtyInodes.add(r),this.dirtyInodes.add(i),this.flushMemoryNamespaceLog(),this.recordLogicalCreate(r,s)}openSync(e,t=0,n=Sn){return!(t&576)||!this.recordingLogicalChanges?this.openSyncImpl(e,t,n):this.withLogicalOperation(()=>this.openSyncImpl(e,t,n))}openSyncImpl(e,t,n){let r=k(e);if(t&512&&!zn(t))throw y(`EINVAL`,r.path,`O_TRUNC requires a writable descriptor`);let i=!!(t&64)&&!!(t&128);if(i&&this.getInodeByPath(this.resolveInodePath(r.path,!1)))throw y(`EEXIST`,r.path);let a=this.resolveInodePath(r.path,!0),o=this.getInodeByPath(a);if(r.requiresDirectory&&!o?.isDir)throw y(`ENOTDIR`,a);if(o){if(this.assertSearchablePath(a,r.requiresDirectory||o.isDir),o.isDir)throw y(`EISDIR`,a);if(Rn(t)&&this.assertFilePermission(a,o,En),zn(t)&&this.assertFilePermission(a,o,Dn),i)throw y(`EEXIST`,a)}else{if(!(t&64))throw y(`ENOENT`,a);let e=A(a),r=j(a),i=this.getInodeByPath(e);if(!i)throw y(`ENOENT`,e);if(!i.isDir)throw y(`ENOTDIR`,e);this.assertSearchablePath(e,!0),this.assertDirectoryWritable(e,i),this.assertNameWithinQuota(a),this.assertFileCountWithinQuota(a),this.impact(a,!1);let s=Fn(this.nextInodeNumber++,n);this.addDirEntry(i,r,s),this.linkInodePath(a,s),B(this.sortedPaths,a),this.bufferMode===`memory`&&this.fileData.set(a,new Uint8Array),this.commitNamespaceChange(),this.dirtyInodes.add(a),this.dirtyInodes.add(e),this.touchInode(a),this.touchInode(e),this.flushMemoryNamespaceLog(),o=this.getInodeByPath(a),this.recordLogicalCreate(a,o)}t&512&&(this.truncateSync(a,0),o=this.getInodeByPath(a));let s=this.nextFd++;return this.openFiles.set(s,{path:a,cursor:0,inodeId:o.ino,inode:o,data:this.bufferMode===`memory`?this.lookupFileDataForInode(a,o)??new Uint8Array:void 0,flags:t,readable:Rn(t),writable:zn(t),append:!!(t&1024)}),s}assertValidOffset(e,t,n){if(!Number.isSafeInteger(e)||e<0)throw y(`EINVAL`,t,`Invalid ${n}`)}assertWithinMaxFileSize(e,t){if(e>this.maxFileSize)throw y(`EFBIG`,t,`File size ${e} exceeds maximum ${this.maxFileSize}`)}assertNameWithinQuota(e){if(j(e).length>this.maxNameLength)throw y(`ENAMETOOLONG`,e,`Name exceeds maximum length ${this.maxNameLength}`);if(this.maxPathDepth!==void 0){let t=e===`/`?0:e.split(`/`).filter(Boolean).length;if(t>this.maxPathDepth)throw y(`ENOSPC`,e,`Path depth ${t} exceeds maximum ${this.maxPathDepth}`)}}assertFileCountWithinQuota(e){if(this.maxFiles!==void 0&&this.inodes.size>=this.maxFiles)throw y(`ENOSPC`,e,`File count ${this.inodes.size} would exceed maximum ${this.maxFiles}`)}computeLiveDataBytes(){let e=0,t=new Set;for(let n of this.inodes.values())n.isDir||R(n)||t.has(n.ino)||(t.add(n.ino),e+=n.size);for(let n of this.pendingDeletedInodes)n.isDir||R(n)||t.has(n.ino)||(t.add(n.ino),e+=n.size);return e}assertTotalBytesWithinQuota(e,t,n){if(this.maxTotalBytes===void 0||this.bufferMode===`disk`)return;let r=t-(e?.size??0);if(r<=0)return;let i=this.computeLiveDataBytes()+r;if(i>this.maxTotalBytes)throw y(`ENOSPC`,n,`Total bytes ${i} would exceed maximum ${this.maxTotalBytes}`)}assertDiskBlocksWithinQuota(e,t){if(e===0||this.maxTotalBytes===void 0)return;let n=(this.allocatedDataBlocks+e)*L;if(n>this.maxTotalBytes)throw y(`ENOSPC`,t,`Total bytes ${n} would exceed maximum ${this.maxTotalBytes}`)}assertWholeFileQuota(e,t,n,r){if(this.maxTotalBytes!==void 0){if(this.bufferMode===`memory`){this.assertTotalBytesWithinQuota(e,t,r);return}this.assertDiskBlocksWithinQuota(this.diskWriteHoleCount(e,t,n),r)}}diskWriteHoleCount(e,t,n){if(t<=n)return 0;let r=0;for(let i=Math.floor(n/L);i<Math.ceil(t/L);i++)e?.blocks[i]||r++;return r}writeSync(e,t,n){return this.recordingLogicalChanges?this.withLogicalOperation(()=>this.writeSyncImpl(e,t,n)):this.writeSyncImpl(e,t,n)}writeSyncImpl(e,t,n){let r=this.openFiles.get(e);if(!r)throw y(`EBADF`);if(!r.writable)throw y(`EBADF`,r.path,`Descriptor is not open for writing`);if(!(t instanceof Uint8Array))throw y(`EINVAL`,r.path,`Write data must be a Uint8Array`);if(t.length===0)return 0;n!==void 0&&this.assertValidOffset(n,r.path,`file offset`);let i=n===void 0||r.append,a=r.cursor,o=r.append?r.inode.size:n??r.cursor,s=o+t.length,c=r.inode;if(this.assertWithinMaxFileSize(s,r.path),this.assertTotalBytesWithinQuota(c,s,r.path),this.bufferMode===`disk`){let e=c.size,n=c.blocks.length,l=[];this.assertDiskBlocksWithinQuota(this.diskWriteHoleCount(c,s,o),r.path),this.impactInode(c);try{this.withQuotaMapped(()=>{this.ensureDiskBlocks(r.path,c,s,o,l),o>e&&this.zeroDiskRange(c,e,o),this.forEachBlockRun(c,o,t.length,(e,n,r)=>{this.dataHandle.write(t.subarray(n,n+r),{at:e})})},r.path)}catch(e){throw this.rollbackNewBlocks(c,n,l),this.setLocalPersistenceState(`error`,e),e}return this.markDataDirty(),s>c.size&&(c.size=s),this.touchInode(r.path,Date.now(),c),r.cursor=i?s:a,this.recordLogicalUpdate(c),t.length}let l=r.data??this.lookupFileDataForInode(r.path,c)??new Uint8Array,u=r.unlinked?void 0:r.path,d=s>l.length?new Uint8Array(Math.max(s,l.length*2,4096)):void 0;this.impactInode(c),this.appendDataWal({version:1,op:`write`,inodeId:r.inode.ino,path:r.path,offset:o,data:t}),d&&(d.set(l),l=d,this.syncFileDataForInode(c,l,u),this.updateOpenFileBuffers(c,l)),l.set(t,o),r.data=l,this.syncFileDataForInode(c,l,u);let f=Math.min(o,c.size);return s>c.size&&(c.size=s),this.touchInode(r.path,Date.now(),c),r.cursor=i?s:a,this.markDirtyRange(c,f,s-f),this.recordLogicalUpdate(c),t.length}writeFileBufferSync(e,t,n={}){return this.recordingLogicalChanges?this.withLogicalOperation(()=>this.writeFileBufferSyncImpl(e,t,n)):this.writeFileBufferSyncImpl(e,t,n)}writeFileBufferSyncImpl(e,t,n={}){if(typeof e!=`string`)throw y(`EINVAL`);if(!n||typeof n!=`object`||Array.isArray(n))throw y(`EINVAL`,e);for(let t of Object.keys(n))if(t!==`exclusive`&&t!==`expected`&&t!==`append`)throw y(`EINVAL`,e);if(!(t instanceof Uint8Array))throw y(`EINVAL`,e);if(t.byteLength>16777216)throw y(`EFBIG`,e);if(n.expected!==void 0&&!(n.expected instanceof Uint8Array))throw y(`EINVAL`,e);if(n.expected&&n.expected.byteLength>16777216)throw y(`EFBIG`,e);if(n.exclusive!==void 0&&typeof n.exclusive!=`boolean`||n.append!==void 0&&typeof n.append!=`boolean`||n.exclusive&&n.expected!==void 0)throw y(`EINVAL`,e);let r=k(e),i=this.resolveInodePath(r.path,!0),a=this.getInodeByPath(i);if(a&&n.exclusive)throw y(`EEXIST`,i);let o=(n.append?a?.size??0:0)+t.byteLength;if(o>16777216)throw y(`EFBIG`,i);this.assertWithinMaxFileSize(o,i),this.assertWholeFileQuota(a,o,n.append?a?.size??0:0,i);let s=(n.expected===void 0?65:2)|(n.exclusive?128:0)|(n.append?1024:0),c=this.openSync(e,s);try{let e=this.fstatSync(c).size;if(n.expected!==void 0){if(e!==n.expected.byteLength)throw y(`EBUSY`,i,`File changed since it was read`);let t=this.readSync(c,e,0);if(t.read!==e||n.expected.some((e,n)=>e!==t.buffer[n]))throw y(`EBUSY`,i,`File changed since it was read`)}if(this.writeSync(c,t,0)!==t.byteLength)throw Error(`Incomplete file write; the file may be partially written`);n.append||this.ftruncateSync(c,t.byteLength)}finally{this.closeSync(c)}}readSync(e,t,n){let r=this.openFiles.get(e);if(!r)throw y(`EBADF`);if(!r.readable)throw y(`EBADF`,r.path,`Descriptor is not open for reading`);this.assertValidOffset(t,r.path,`read size`),n!==void 0&&this.assertValidOffset(n,r.path,`file offset`);let i=n===void 0?r.cursor:n,a=n===void 0,o=r.inode,s=o.size,c=i>=s?0:s-i,l=Math.min(t,c);if(l===0)return{buffer:new Uint8Array,read:0};if(this.bufferMode===`disk`){let e=new Uint8Array(l);return this.readBlocks(o,i,e),a&&(r.cursor=i+l),this.touchInodeAccess(r.path,o),{buffer:e,read:l}}let u=(r.data??this.fileData.get(r.path)??new Uint8Array).slice(i,i+l);return a&&(r.cursor=i+l),this.touchInodeAccess(r.path,o),{buffer:u,read:l}}readInto(e,t,n){let r=this.openFiles.get(e);if(!r)throw y(`EBADF`);if(!r.readable)throw y(`EBADF`,r.path,`Descriptor is not open for reading`);if(!(t instanceof Uint8Array))throw y(`EINVAL`,r.path,`Read target must be a Uint8Array`);n!==void 0&&this.assertValidOffset(n,r.path,`file offset`);let i=n===void 0?r.cursor:n,a=n===void 0,o=r.inode,s=o.size,c=i>=s?0:s-i,l=Math.min(t.length,c);if(l===0)return 0;if(this.bufferMode===`disk`)return this.readBlocks(o,i,t.subarray(0,l)),a&&(r.cursor=i+l),this.touchInodeAccess(r.path,o),l;let u=r.data??this.fileData.get(r.path)??new Uint8Array;return t.set(u.subarray(i,i+l)),a&&(r.cursor=i+l),this.touchInodeAccess(r.path,o),l}forEachBlockRun(e,t,n,r){let i=0,a=t;for(;i<n;){let t=a/L>>>0,o=a%L,s=e.blocks[t];if(s===void 0)throw y(`EINVAL`,void 0,`Corrupted inode block table`);let c=Math.min(L-o,n-i),l=t+1,u=s;for(;i+c<n;){let t=e.blocks[l];if(t===void 0)throw y(`EINVAL`,void 0,`Corrupted inode block table`);if(s===0?t!==0:t!==u+1)break;let r=Math.min(L,n-i-c);c+=r,u=t,l++}r(s===0?0:s*L+o,i,c),i+=c,a+=c}}readBlocks(e,t,n){this.forEachBlockRun(e,t,n.length,(e,t,r)=>{e===0?n.fill(0,t,t+r):this.readDataExactly(n.subarray(t,t+r),e)})}readDataExactly(e,t){let n=this.dataHandle.read(e,{at:t});if(n!==e.byteLength)throw new DOMException(`OPFS data read ended early (${n}/${e.byteLength} bytes)`,`InvalidStateError`)}seekSync(e,t,n){let r=this.openFiles.get(e);if(!r)throw y(`EBADF`);if(!Number.isSafeInteger(t))throw y(`EINVAL`,r.path,`Invalid seek offset`);let i=r.inode,a;switch(n){case 0:a=t;break;case 1:a=r.cursor+t;break;case 2:a=i.size+t;break;default:throw y(`EINVAL`,r.path,`Invalid whence`)}if(!Number.isSafeInteger(a)||a<0)throw y(`EINVAL`,r.path,`Invalid seek offset`);return this.assertWithinMaxFileSize(a,r.path),r.cursor=a,r.cursor}closeSync(e){let t=this.openFiles.get(e);if(!t)throw y(`EBADF`);if(this.openFiles.delete(e),this.pendingDeletedInodes.has(t.inode)&&!this.hasOpenHandleForInode(t.inode)){this.pendingDeletedInodes.delete(t.inode),this.invalidateFlush();for(let e of t.inode.blocks)e!==0&&this.releaseBlock(e);t.inode.blocks=[],t.inode.size=0}}toStat(e){return{ino:e.ino,mode:e.mode,nlink:e.nlink??1,size:e.size,blksize:L,blocks:this.bufferMode===`disk`?e.blocks.reduce((e,t)=>e+(t===0?0:L/512),0):Math.ceil(e.size/512),atimeMs:e.atimeMs,mtimeMs:e.mtimeMs,ctimeMs:e.ctimeMs,timestampMs:e.mtimeMs??e.timestampMs,is_dir:e.isDir,is_file:!e.isDir&&!R(e)}}fstatSync(e){let t=this.openFiles.get(e);if(!t)throw y(`EBADF`);return this.toStat(t.inode)}fsyncSync(e){if(!this.openFiles.has(e))throw y(`EBADF`);this.syncSync()}chmodSync(e,t){return this.recordingLogicalChanges?this.withLogicalOperation(()=>this.chmodSyncImpl(e,t)):this.chmodSyncImpl(e,t)}chmodSyncImpl(e,t){let n=k(e),r=this.resolveInodePath(n.path,!0),{requiresDirectory:i}=n,a=this.getInodeByPath(r);if(!a)throw y(`ENOENT`,r);if(i&&!a.isDir)throw y(`ENOTDIR`,r);this.assertSearchablePath(r,i||a.isDir);let o=a.mode&61440|t&4095;a.mode!==o&&(this.impactInode(a),this.invalidateFlush(),a.mode=o,this.touchInodeMetadata(r),this.recordLogicalUpdate(a))}utimesSync(e,t,n){return this.recordingLogicalChanges?this.withLogicalOperation(()=>this.utimesSyncImpl(e,t,n)):this.utimesSyncImpl(e,t,n)}utimesSyncImpl(e,t,n){if(!Number.isFinite(t)||!Number.isFinite(n))throw y(`EINVAL`,e,`Invalid time`);let r=k(e),i=this.resolveInodePath(r.path,!0),{requiresDirectory:a}=r,o=this.getInodeByPath(i);if(!o)throw y(`ENOENT`,i);if(a&&!o.isDir)throw y(`ENOTDIR`,i);this.assertSearchablePath(i,a||o.isDir),(o.atimeMs!==t||o.mtimeMs!==n)&&(this.impactInode(o),this.invalidateFlush(),o.atimeMs=t,o.mtimeMs=n,o.ctimeMs=Date.now(),o.timestampMs=o.mtimeMs,this.dirtyInodes.add(i),this.recordLogicalUpdate(o))}linkSync(e,t){return this.recordingLogicalChanges?this.withLogicalOperation(()=>this.linkSyncImpl(e,t)):this.linkSyncImpl(e,t)}linkSyncImpl(e,t){let n=k(e),r=k(t),i=this.resolveInodePath(n.path,!1),a=this.getInodeByPath(i);if(!a)throw y(`ENOENT`,i);if(n.requiresDirectory&&!a.isDir)throw y(`ENOTDIR`,i);if(a.isDir)throw y(`EPERM`,i,`Hard links to directories are not supported`);let o=this.resolveInodePath(r.path,!1);if(this.hasPathEntry(o))throw y(`EEXIST`,o);if(r.requiresDirectory&&!a.isDir)throw y(`ENOTDIR`,o);let s=A(o),c=j(o),l=this.getInodeByPath(s);if(!l)throw y(`ENOENT`,s);if(!l.isDir)throw y(`ENOTDIR`,s);if(this.assertSearchablePath(i,n.requiresDirectory||a.isDir),this.assertSearchablePath(s,!0),this.assertDirectoryWritable(s,l),this.assertNameWithinQuota(o),this.assertFileCountWithinQuota(o),this.impact(o,!1),this.invalidateFlush(),a.nlink=(a.nlink??1)+1,this.addDirEntry(l,c,a),this.linkInodePath(o,a),B(this.sortedPaths,o),this.bufferMode===`memory`){let e=this.lookupFileDataForInode(i,a);e&&this.fileData.set(o,e)}this.commitNamespaceChange(),this.markAllPathsForInode(a);let u=Date.now();a.ctimeMs=u,a.timestampMs=a.mtimeMs??a.timestampMs,this.touchInode(s,u),this.dirtyInodes.add(i),this.dirtyInodes.add(o),this.flushMemoryNamespaceLog(),this.recordLogicalCreate(o,a)}unlinkSync(e){return this.recordingLogicalChanges?this.withLogicalOperation(()=>this.unlinkSyncImpl(e)):this.unlinkSyncImpl(e)}unlinkSyncImpl(e){let t=k(e),n=this.resolveInodePath(t.path,!1),{requiresDirectory:r}=t,i=this.getInodeByPath(n);if(!i)throw y(`ENOENT`,n);if(r&&!i.isDir)throw y(`ENOTDIR`,n);if(i.isDir)throw y(`EISDIR`,n);let a=A(n),o=this.getInodeByPath(a);this.assertSearchablePath(a,!0),o&&this.assertDirectoryWritable(a,o),this.impact(n,!1),o&&this.removeDirEntry(o,j(n)),this.markOpenFilesUnlinked(n),this.recordLogicalDelete(n,i),this.removeNamespaceEntry(n,i),this.commitNamespaceChange(),this.markAllPathsForInode(i),this.touchInode(a),this.dirtyInodes.add(a),this.flushMemoryNamespaceLog()}rmdirSync(e){return this.recordingLogicalChanges?this.withLogicalOperation(()=>this.rmdirSyncImpl(e)):this.rmdirSyncImpl(e)}rmdirSyncImpl(e){let t=k(e),n=this.resolveInodePath(t.path,!1),{requiresDirectory:r}=t;if(n===`/`)throw y(`EPERM`,n);let i=this.getInodeByPath(n);if(!i)throw y(`ENOENT`,n);if(r&&!i.isDir||!i.isDir)throw y(`ENOTDIR`,n);if(this.assertSearchablePath(n,!0),this.listDirNames(i).length>0)throw y(`ENOTEMPTY`,n);if(this.hasOpenFilesInSubtree(n))throw y(`EBUSY`,n);let a=A(n),o=this.getInodeByPath(a);o&&this.assertDirectoryWritable(a,o),this.impact(n,!0),o&&(this.removeDirEntry(o,j(n)),o.nlink=Math.max(2,(o.nlink??2)-1)),this.deleteSubtree(n),this.commitNamespaceChange(),this.touchInode(a),this.dirtyInodes.add(a),this.flushMemoryNamespaceLog()}removeSync(e){return this.recordingLogicalChanges?this.withLogicalOperation(()=>this.removeSyncImpl(e)):this.removeSyncImpl(e)}removeSyncImpl(e){let t=k(e),n=this.resolveInodePath(t.path,!1),r=this.getInodeByPath(n);if(!r)throw y(`ENOENT`,n);if(t.requiresDirectory&&!r.isDir)throw y(`ENOTDIR`,n);if(r.isDir){if(n===`/`)throw y(`EPERM`,n);if(this.hasOpenFilesInSubtree(n))throw y(`EBUSY`,n);this.assertSearchablePath(n,!0);let e=A(n),t=this.getInodeByPath(e);t&&this.assertDirectoryWritable(e,t),this.impact(n,!0),t&&(this.removeDirEntry(t,j(n)),t.nlink=Math.max(2,(t.nlink??2)-1)),this.deleteSubtree(n),this.commitNamespaceChange(),this.touchInode(e),this.dirtyInodes.add(e),this.flushMemoryNamespaceLog();return}this.unlinkSync(n)}renameSync(e,t){return this.recordingLogicalChanges?this.withLogicalOperation(()=>this.renameSyncImpl(e,t)):this.renameSyncImpl(e,t)}renameSyncImpl(e,t){let n=k(e),r=k(t),i=this.resolveInodePath(n.path,!1),a=this.resolveInodePath(r.path,!1),o=this.getInodeByPath(i);if(!o)throw y(`ENOENT`,i);if(n.requiresDirectory&&!o.isDir)throw y(`ENOTDIR`,i);if(r.requiresDirectory&&!o.isDir)throw y(`ENOTDIR`,a);if(this.getInodeByPath(a)===o)return;if(i===`/`)throw y(`EPERM`,i);if(this.assertSearchablePath(i,n.requiresDirectory||o.isDir),o.isDir&&a.startsWith(`${i}/`))throw y(`EINVAL`,a,`Cannot move directory into its own subtree`);let s=A(i),c=j(i),l=this.getInodeByPath(s),u=A(a),d=j(a),f=this.getInodeByPath(u);if(!f)throw y(`ENOENT`,u);if(!f.isDir)throw y(`ENOTDIR`,u);if(l&&(this.assertSearchablePath(s,!0),this.assertDirectoryWritable(s,l)),this.assertSearchablePath(u,!0),this.assertDirectoryWritable(u,f),this.assertNameWithinQuota(a),this.maxPathDepth!==void 0&&o.isDir){let e=e=>e.split(`/`).filter(Boolean).length,t=this.collectSubtreePaths(i).reduce((t,n)=>Math.max(t,e(n)),0)-e(i)+e(a);if(t>this.maxPathDepth)throw y(`ENOSPC`,a,`Path depth ${t} exceeds maximum ${this.maxPathDepth}`)}let p=this.getInodeByPath(a);if(p){if(this.assertSearchablePath(a,p.isDir||r.requiresDirectory),o.isDir!==p.isDir)throw y(p.isDir?`EISDIR`:`ENOTDIR`,a);if(p.isDir){if(this.listDirNames(p).length>0)throw y(`ENOTEMPTY`,a);if(this.hasOpenFilesInSubtree(a))throw y(`EBUSY`,a)}}this.impact(i,!0),this.impact(a,!0),this.markLinkedInodeDirty(o),p&&(p.isDir||this.markOpenFilesUnlinked(a),this.deleteSubtree(a,0)),s===u?l&&(this.removeDirEntry(l,c),this.addDirEntry(l,d,o),o.isDir&&p?.isDir&&(l.nlink=Math.max(2,(l.nlink??2)-1)),this.touchInode(s)):(l&&(this.removeDirEntry(l,c),o.isDir&&(l.nlink=Math.max(2,(l.nlink??2)-1))),this.removeDirEntry(f,d),this.addDirEntry(f,d,o),o.isDir&&!p?.isDir&&(f.nlink=(f.nlink??2)+1),this.touchInode(s),this.touchInode(u));let m=this.collectSubtreePaths(i),h=new Map;for(let e of m)h.set(e,e===i?a:`${a}${e.slice(i.length)}`);let g=m.map(e=>({oldPath:e,inode:this.getInodeByPath(e)}));for(let{oldPath:e}of g){if(this.recordLogicalDelete(e,this.getInodeByPath(e)),this.unlinkInodePath(e),this.bufferMode===`memory`){let t=this.fileData.get(e);this.fileData.delete(e);let n=h.get(e);t&&this.fileData.set(n,t)}this.deletedInodes.add(e),this.dirtyInodes.delete(e)}for(let{oldPath:e,inode:t}of g){let n=h.get(e);this.linkInodePath(n,t),this.dirtyInodes.add(n),this.recordLogicalCreate(n,t)}this.moveSortedSubtree(i,a),this.commitNamespaceChange(),this.getInodeByPath(a)&&this.touchInodeMetadata(a);for(let e of this.openFiles.values()){let t=h.get(e.path);t&&(e.path=t)}this.dirtyInodes.add(s),u!==s&&this.dirtyInodes.add(u),this.flushMemoryNamespaceLog()}ftruncateSync(e,t){return this.recordingLogicalChanges?this.withLogicalOperation(()=>this.ftruncateSyncImpl(e,t)):this.ftruncateSyncImpl(e,t)}ftruncateSyncImpl(e,t){let n=this.openFiles.get(e);if(!n)throw y(`EBADF`);if(!n.writable)throw y(`EBADF`,n.path,`Descriptor is not open for writing`);this.truncateInode(n.path,n.inode,t)}truncateInode(e,t,n){if(this.assertValidOffset(n,e,`truncate size`),this.assertWithinMaxFileSize(n,e),this.assertTotalBytesWithinQuota(t,n,e),t.isDir)throw y(`EISDIR`,e);let r=t.size!==n;r&&this.impactInode(t),this.invalidateFlush();let i=t.size;if(this.bufferMode===`memory`&&this.appendDataWal({version:1,op:`truncate`,inodeId:t.ino,path:e,size:n}),this.bufferMode===`disk`){if(n>i){let r=Math.min(n,Math.ceil(i/L)*L);r>i&&this.withQuotaMapped(()=>this.zeroDiskRange(t,i,r),e);let a=Math.ceil(n/L);for(;t.blocks.length<a;)t.blocks.push(0)}let r=n===0?0:Math.ceil(n/L);for(;t.blocks.length>r;){let e=t.blocks.pop();e!==0&&this.releaseBlock(e)}}if(t.size=n,this.markAllPathsForInode(t),this.touchInode(e,Date.now(),t),r&&this.recordLogicalUpdate(t),this.bufferMode===`memory`){let e=this.pathForInode(t),r=this.lookupFileDataForInode(e,t),a=Array.from(this.openFiles.values()).find(e=>e.inode===t)?.data,o=r??a??new Uint8Array,s;n<=o.length?s=o.slice(0,n):(s=new Uint8Array(n),s.set(o)),this.syncFileDataForInode(t,s),this.updateOpenFileBuffers(t,s),this.markResized(t,i,n)}}truncateSync(e,t){return this.recordingLogicalChanges?this.withLogicalOperation(()=>this.truncateSyncImpl(e,t)):this.truncateSyncImpl(e,t)}truncateSyncImpl(e,t){let n=k(e),r=this.resolveInodePath(n.path,!0),{requiresDirectory:i}=n,a=this.getInodeByPath(r);if(!a)throw y(`ENOENT`,r);if(i&&!a.isDir)throw y(`ENOTDIR`,r);this.assertSearchablePath(r,i||a.isDir),this.assertInodeWritable(r,a),this.truncateInode(r,a,t)}existsSync(e){let t=k(e),n;try{n=this.resolveInodePath(t.path,!0)}catch(e){let t=e.code;if(t===`ENOTDIR`||t===`ELOOP`||t===`EACCES`)return!1;throw e}let{requiresDirectory:r}=t,i=this.getInodeByPath(n);return i?!r||i.isDir:!1}statSync(e){let t=k(e),n=this.resolveInodePath(t.path,!0),{requiresDirectory:r}=t,i=this.getInodeByPath(n);if(!i)throw y(`ENOENT`,n);if(r&&!i.isDir)throw y(`ENOTDIR`,n);return this.assertSearchablePath(n,r||i.isDir),this.toStat(i)}lstatSync(e){let t=k(e),n=this.resolveInodePath(t.path,!1),r=this.getInodeByPath(n);if(!r)throw y(`ENOENT`,n);if(t.requiresDirectory&&!r.isDir)throw y(`ENOTDIR`,n);return this.assertSearchablePath(n,t.requiresDirectory||r.isDir),this.toStat(r)}readdirSync(e){let t=this.resolveInodePath(k(e).path,!0),n=this.getInodeByPath(t);if(!n)throw y(`ENOENT`,t);if(!n.isDir)throw y(`ENOTDIR`,t);return this.assertSearchablePath(t,!0),this.assertDirectoryReadable(t,n),this.touchInodeAccess(t,n),[`.`,`..`,...this.listDirNames(n)]}readdirNamesSync(e){let t=this.resolveInodePath(k(e).path,!0),n=this.getInodeByPath(t);if(!n)throw y(`ENOENT`,t);if(!n.isDir)throw y(`ENOTDIR`,t);return this.assertSearchablePath(t,!0),this.assertDirectoryReadable(t,n),this.touchInodeAccess(t,n),this.listDirNames(n).slice().sort()}readdirEntriesSync(e){let t=this.resolveInodePath(k(e).path,!0),n=this.getInodeByPath(t);if(!n)throw y(`ENOENT`,t);if(!n.isDir)throw y(`ENOTDIR`,t);return this.assertSearchablePath(t,!0),this.assertDirectoryReadable(t,n),this.touchInodeAccess(t,n),this.listDirNames(n).slice().sort().map(e=>{let r=this.lookupChild(t,n,e).inode;if(!r)throw y(`ENOENT`,t);return{name:e,mode:r.mode,is_dir:r.isDir,is_file:!r.isDir&&!R(r)}})}listPathsSync(){if(this.closed)throw y(`EBADF`,void 0,`Volume is closed`);return this.ensureDerivedIndexes(),[...this.sortedPaths]}syncSync(){if(!this.closed){this.setLocalPersistenceState(`flushing`);try{if(this.bufferMode===`disk`){let e=this.hasDirtyMeta;if(!this.dataDirty&&!e){this.setLocalPersistenceState(`clean`);return}this.storage?.beforeDataCommit?.(),this.flushData(),e&&this.writeMeta(),this.lastLocalFlushAt=Date.now(),this.setLocalPersistenceState(`clean`);return}if(this.dirtyPages.size===0&&!this.dataDirty&&!this.hasDirtyMeta&&!this.metaLogFlushPending&&!this.walPendingBytes){this.setLocalPersistenceState(`clean`);return}this.flushRecoveryLogs(),this.persistToOpfs();let e=this.hasDirtyMeta;this.storage?.beforeDataCommit?.(),this.flushData(),e&&this.writeMeta(),this.flushPendingMetaLog(),this.lastLocalFlushAt=Date.now(),this.checkpointDataWal(),this.setLocalPersistenceState(`clean`)}catch(e){throw this.setLocalPersistenceState(`error`,e),e}}}flushed=!1;closed=!1;invalidateFlush(){this.flushed=!1,this.markLocalDirty()}markDataDirty(){this.dataDirty=!0,this.markLocalDirty()}markLocalDirty(){this.setLocalPersistenceState(`dirty`),this.localDurabilityMode===`balanced`&&this.scheduleBalancedFlush()}ensureDataWalCycle(){if(this.dataLogOffset!==0)return;let e=this.storage?.createDataWalCycle?.();e&&(this.withQuotaMapped(()=>this.dataLogHandle.write(e.prefix,{at:0})),this.dataLogOffset=e.prefix.byteLength,this.dataWalCycleSealer=e.codec)}appendDataWal(e){try{this.appendDataWalRecord(e)}catch(e){throw this.setLocalPersistenceState(`error`,e),e}}appendDataWalRecord(e){if(this.bufferMode!==`memory`)return;this.dataWalTruncatePending&&this.checkpointDataWal(),this.ensureDataWalCycle();let t=ae(e,this.dataWalCycleSealer??this.sealer,this.dataLogOffset),n=`path`in e?e.path:void 0;this.withQuotaMapped(()=>this.dataLogHandle.write(t,{at:this.dataLogOffset}),n),this.dataLogOffset+=t.byteLength,this.localDurabilityMode===`strict`&&this.dataLogHandle.flush(),this.markLocalDirty(),this.logWalDebug(`append`,e.op,{bytes:t.byteLength,pendingBytes:this.walPendingBytes})}checkpointDataWal(){try{this.checkpointDataWalRecords()}catch(e){throw this.setLocalPersistenceState(`error`,e),e}}checkpointDataWalRecords(){this.bufferMode===`memory`&&(this.dataWalTruncatePending||this.walPendingBytes!==0||this.dataLogHandle.getSize()!==0)&&(this.dataWalTruncatePending=!0,this.dataLogHandle.truncate(0),this.dataLogHandle.flush(),this.dataWalTruncatePending=!1,this.dataLogOffset=0,this.dataWalCycleSealer=void 0,this.lastLocalCheckpointAt=Date.now(),this.logWalDebug(`checkpoint`))}installBalancedModeHooks(){let e=globalThis,t=()=>{try{this.flushVfs()}catch(e){this.setLocalPersistenceState(`error`,e),this.logWalDebug(`balanced flush hook failed`,e)}};e.addEventListener?.(`pagehide`,t),e.addEventListener?.(`beforeunload`,t),this.removeBalancedModeHooks=()=>{e.removeEventListener?.(`pagehide`,t),e.removeEventListener?.(`beforeunload`,t)}}scheduleBalancedFlush(){this.flushTimer||=setTimeout(()=>{if(this.flushTimer=void 0,!this.closed)try{this.syncSync()}catch(e){this.setLocalPersistenceState(`error`,e),this.logWalDebug(`balanced scheduled sync failed`,e)}},150)}flushData(e=!1){(e||this.dataDirty)&&(this.dataHandle?.flush(),this.dataDirty=!1,this.flushedDataSize=this.dataHandle.getSize(),this.flushedLogicalExtent=(this.bitmap.highestSet()+1)*L)}flushVfs(){if(!(this.closed||this.flushed)){this.setLocalPersistenceState(`flushing`);try{this.bufferMode===`memory`&&(this.flushRecoveryLogs(),this.persistToOpfs()),this.storage?.beforeDataCommit?.(),this.flushData(!0),this.writeMeta(!0),this.bufferMode===`memory`&&this.checkpointDataWal(),this.lastLocalFlushAt=Date.now(),this.flushed=!0,this.setLocalPersistenceState(`clean`)}catch(e){throw this.setLocalPersistenceState(`error`,e),e}}}closeVfs(){if(this.initializing)return this.closeRequested=!0,this.closing??=this._ready.then(()=>void 0,()=>void 0),this.closing;if(this.closed)return this.closing;this.flushTimer&&=(clearTimeout(this.flushTimer),void 0);let e=[];try{this.flushed||this.flushVfs()}catch(t){e.push(t)}finally{try{this.closeLogicalChangeSession(St(this)?`replacement`:`close`)}catch(t){e.push(t)}for(let t of[this.dataLogHandle,this.logHandle,this.metaHandleA,this.metaHandleB,this.bootstrapHandle,this.dataHandle,...this.storageHandles])try{t?.close()}catch(t){e.push(t)}try{this.storage?.destroy()}catch(t){e.push(t)}try{this.removeBalancedModeHooks?.()}catch(t){e.push(t)}this.removeBalancedModeHooks=void 0,this.openFiles.clear(),this.storage=void 0,this.storageHandles=[],this.sealer=void 0,this.dataWalCycleSealer=void 0,this.closed=!0;let t=this.releaseVolumeLock;this.releaseVolumeLock=void 0,this.closing=t?.()}if(e.length>0){let t=e.length===1?e[0]:AggregateError(e,`VFS close failed`,{cause:e[0]});throw this.setLocalPersistenceState(`error`,t),t}return this.closing}async openFileChangeChannel(e,t,n){return this.openFileChangeChannelForClient(this.directChangeClientId,`local`,e,t,n)}async openFileChangeChannelForClient(e,t,n,r,i,a){if(typeof n!=`function`||typeof r!=`function`||typeof i!=`function`)throw y(`EINVAL`,void 0,`Invalid file change channel callbacks`);let o=a??crypto.randomUUID();if(typeof o!=`string`||!o||o.length>128||this.changeChannels.has(o)||this.pendingChangeChannels.has(o))throw y(`EINVAL`,void 0,`Invalid file change channel`);if(typeof e!=`string`||!e||e.length>128||t!==`local`&&t!==`follower-relay`)throw y(`EINVAL`,void 0,`Invalid file change client`);if(this.changeChannels.size+this.pendingChangeChannels.size>=128||(this.changeChannelCounts.get(e)??0)>=32)throw y(`EBUSY`,void 0,`Too many file change channels`);this.pendingChangeChannels.add(o),this.changeChannelCounts.set(e,(this.changeChannelCounts.get(e)??0)+1);try{if(await this.ready,this.closed)throw y(`EBADF`,void 0,`Volume is closed`);if(!this.logicalSession||this.logicalChangesPoisoned)throw y(`ENOTSUP`,void 0,`Logical changes unavailable`);let a=Object.freeze({clientId:e,channelId:o,route:t}),s={client:a,receive:n,interrupted:r,closedCallback:i,closed:!1,clientDisposed:!1};return this.pendingChangeChannels.delete(o),this.changeChannels.set(o,s),{generation:this.changeGeneration,request:async e=>{if(s.closed||(await Promise.resolve(),s.closed))throw y(`EBADF`,void 0,`File change channel is closed`);let t=mt(e,16777216).command,n=JSON.stringify([a.clientId,a.channelId,t.subscriptionId]),r=!1;if(t.type===`register`){let e=this.changeSubscriptionIds.get(a.clientId)??new Set;if(e.has(n))throw y(`EINVAL`,void 0,`Duplicate file change subscription`);if(e.size>=32||this.changeSubscriptionCount>=128)throw y(`ENOSPC`,void 0,`Too many file change subscriptions`);e.add(n),this.changeSubscriptionIds.set(a.clientId,e),this.changeSubscriptionCount++,r=!0}let i=this.logicalSession;if(!i||this.logicalChangesPoisoned)throw y(`ENOTSUP`,void 0,`Logical changes unavailable`);try{let e=i.control(a,t);if(ht(t,e))return t.type===`terminal-ack`&&this.changeTerminalIds.delete(n)&&this.releaseChangeSubscription(a,n),t.type===`register`?{type:`registered`,subscriptionId:t.subscriptionId}:{type:`ok`};throw e&&typeof e.then==`function`&&Promise.resolve(e).catch(()=>{}),this.poisonLogicalChanges(),y(`EINVAL`,void 0,`Invalid file change reply`)}catch(e){throw r&&this.releaseChangeSubscription(a,n),(t.type!==`register`||!ln(e))&&this.poisonLogicalChanges(),e}},close:()=>this.closeChangeChannel(o,s)}}catch(t){if(this.pendingChangeChannels.delete(o)){let t=this.changeChannelCounts.get(e)??1;t<=1?this.changeChannelCounts.delete(e):this.changeChannelCounts.set(e,t-1)}throw t}}createLogicalChangeSession(){let e=this.logicalChanges;if(!e)return;let t={generation:this.changeGeneration,validateTarget:e=>{if(this.closed||this.logicalSessionClosed)throw y(`EBADF`,void 0,`Volume is closed`);this.validateChangeTarget(e)},send:(e,t)=>this.sendChangeFrame(e,t)},n=e.create.call(e.contribution,t);if(!n||typeof n!=`object`||typeof n.control!=`function`||typeof n.completed!=`function`||typeof n.invalidated!=`function`||typeof n.clientClosed!=`function`||typeof n.close!=`function`){if(n&&typeof n==`object`&&typeof n.close==`function`)try{n.close(`initialization-failed`)}catch{}throw n&&typeof n.then==`function`&&Promise.resolve(n).catch(()=>{}),y(`EINVAL`,void 0,`Invalid logical change session`)}this.logicalSession=n}closeLogicalChangeSession(e){if(!this.logicalSession&&!this.logicalChanges||this.logicalSessionClosed)return;this.logicalSessionClosed=!0;let t=this.logicalSession;this.logicalSession=void 0;let n=[...this.changeChannels.values()];for(let e of n)e.closed=!0;this.changeChannels.clear(),this.changeChannelCounts.clear(),this.pendingChangeChannels.clear(),this.changeSubscriptionIds.clear(),this.changeSubscriptionCount=0,this.changeTerminalIds.clear();try{t?.close(e)}finally{if(e===`close`||e===`replacement`)for(let t of n)queueMicrotask(()=>{if(!t.clientDisposed)try{e===`close`?t.closedCallback():t.interrupted(`SUBSCRIPTION_INTERRUPTED`)}catch{}})}}poisonLogicalChanges(e=`SUBSCRIPTION_RESYNC_REQUIRED`){if(this.logicalChangesPoisoned)return;this.logicalChangesPoisoned=!0;let t=this.logicalSession;this.logicalSession=void 0,this.logicalSessionClosed=!0;try{t?.close(`close`)}catch{}let n=[...this.changeChannels.values()];for(let e of n)e.closed=!0;this.changeChannels.clear(),this.changeChannelCounts.clear(),this.pendingChangeChannels.clear(),this.changeSubscriptionIds.clear(),this.changeSubscriptionCount=0,this.changeTerminalIds.clear();for(let t of n)queueMicrotask(()=>{if(!t.clientDisposed)try{t.interrupted(e)}catch{}})}impact(e,t){if(!this.recordingLogicalChanges)return;let n=this.logicalOperation;if(!n||n.impactAll)return;let r=n.impacts;for(let n=0;n<r.length;n++){let i=r[n];if(i.subtree&&nn(i.path,e)||!t&&i.path===e)return}let i=n.impactCharged;if(t)for(let t=r.length-1;t>=0;t--)nn(e,r[t].path)&&(i-=n.impactCharges[t],r.splice(t,1),n.impactCharges.splice(t,1));let a=tn(e,65536-i);if(r.length>=128||!Number.isFinite(a)){n.impactAll=!0,r.length=0,n.impactCharges.length=0;return}r.push({path:e,subtree:t}),n.impactCharges.push(a),n.impactCharged=i+a}impactInode(e){if(!this.recordingLogicalChanges)return;let t=this.logicalOperation;if(!t||t.impactAll)return;let n=this.inoToPaths.get(e.ino);if(!n)return;let r=0,i=t.impactCharged;for(let e of n){let n=!1;for(let r=0;r<t.impacts.length;r++){let i=t.impacts[r];if(i.subtree&&(i.path===`/`||e===i.path||e.startsWith(`${i.path}/`))){n=!0;break}if(i.path===e){n=!0;break}}if(n)continue;r++;let a=tn(e,65536-i);if(t.impacts.length+r>128||!Number.isFinite(a)){t.impactAll=!0,t.impacts.length=0,t.impactCharges.length=0;return}i+=a}for(let e of n)this.impact(e,!1)}recordLogicalNamespace(e,t,n,r=1){if(!this.recordingLogicalChanges)return;let i=this.logicalOperation;if(!i||i.overflow)return;let a=tn(t,4194304-i.charged);if(i.namespace.length+i.changedInodes.size>=4096||!Number.isFinite(a)||i.charged+a>4194304){i.overflow=!0,i.namespace.length=0,i.changedInodes.clear(),i.createdPaths.clear();return}i.charged+=a,i.namespace.push({type:e,path:t,kind:n.isDir?`directory`:R(n)?`symlink`:`file`,inodeId:n.ino,size:n.size,deletePhase:r}),e===`create`&&i.createdPaths.add(t)}recordLogicalUpdate(e){if(!this.recordingLogicalChanges)return;let t=this.logicalOperation;if(t&&!(t.overflow||t.changedInodes.has(e.ino))){if(t.namespace.length+t.changedInodes.size>=4096||t.charged+256>4194304){t.overflow=!0,t.namespace.length=0,t.changedInodes.clear(),t.createdPaths.clear();return}t.changedInodes.add(e.ino),t.charged+=256}}recordLogicalCreate(e,t){this.recordLogicalNamespace(`create`,e,t)}recordLogicalDelete(e,t,n=1){this.recordLogicalNamespace(`delete`,e,t,n)}withLogicalOperation(e){if(this.logicalOperation||(this.logicalCaptureToken=void 0),!this.recordingLogicalChanges)return e();let t=!this.logicalOperation,n=this.logicalOperation??={depth:0,failed:!1,overflow:!1,charged:0,impactCharged:0,impacts:[],impactCharges:[],impactAll:!1,namespace:[],changedInodes:new Set,createdPaths:new Set};n.depth++;try{return e()}catch(e){throw n.failed=!0,e}finally{n.depth--,t&&n.depth===0&&(this.logicalOperation=void 0,n.failed?(n.impactAll||n.impacts.length>0)&&this.callLogicalInvalidated(n.impactAll?{kind:`all`}:{kind:`paths`,paths:n.impacts},`partial-mutation`):n.overflow?this.callLogicalInvalidated(n.impactAll?{kind:`all`}:{kind:`paths`,paths:n.impacts},`record-limit`):this.completeLogicalOperation(n))}}completeLogicalOperation(e){let t=this.logicalSession;if(!t)return;let n=e.namespace.length,r=e.charged-e.changedInodes.size*256;for(let t of e.changedInodes){let i=this.inoToPaths.get(t);if(i)for(let t of i){if(e.createdPaths.has(t))continue;let i=tn(t,4194304-r);if(!Number.isFinite(i)){this.callLogicalInvalidated(e.impactAll?{kind:`all`}:{kind:`paths`,paths:e.impacts},`record-limit`);return}if(n++,r+=i,n>4096||r>4194304){this.callLogicalInvalidated(e.impactAll?{kind:`all`}:{kind:`paths`,paths:e.impacts},`record-limit`);return}}}if(n===0)return;if(this.logicalSequence>2**53-1-n){this.poisonLogicalChanges(`SUBSCRIPTION_INTERRUPTED`);return}let i=()=>Object.freeze({generation:this.changeGeneration,sequence:++this.logicalSequence}),a=e=>e.isDir?`directory`:R(e)?`symlink`:`file`,o=[],s=n===1?e.namespace[0]:void 0;if(s){let e=s.type===`create`?this.inodeTable.get(s.inodeId):void 0;o.push({type:s.type,path:s.path,kind:e?a(e):s.kind,inodeId:s.inodeId,size:e?.size??s.size,cursor:i()})}else if(n===1)for(let t of e.changedInodes){let n=this.inodeTable.get(t),r=this.inoToPaths.get(t);if(n&&r){for(let s of r)if(!e.createdPaths.has(s)){o.push({type:`update`,path:s,kind:a(n),inodeId:t,size:n.size,cursor:i()});break}if(o.length)break}}else{let t=[],n=[];for(let r of e.namespace){let e={record:r,depth:rn(r.path)};r.type===`delete`?t.push(e):n.push(e)}t.sort(on),n.sort(sn);let r=[];for(let t of e.changedInodes){let n=this.inodeTable.get(t),i=this.inoToPaths.get(t);if(n&&i)for(let a of i)e.createdPaths.has(a)||r.push({path:a,inode:n,inodeId:t})}r.sort(cn);for(let{record:e}of t)o.push({type:e.type,path:e.path,kind:e.kind,inodeId:e.inodeId,size:e.size,cursor:i()});for(let{record:e}of n){let t=this.inodeTable.get(e.inodeId);o.push({type:e.type,path:e.path,kind:t?a(t):e.kind,inodeId:e.inodeId,size:t?.size??e.size,cursor:i()})}for(let{path:e,inode:t,inodeId:n}of r)o.push({type:`update`,path:e,kind:a(t),inodeId:n,size:t.size,cursor:i()})}for(let e of o)Object.freeze(e);Object.freeze(o);let c,l,u={};try{this.logicalCaptureToken=u,t.completed({records:o,capture:(e,t)=>{try{let n=this.captureLogicalContent(e,t,u,c??=new WeakSet(o),l??=new Map);return n.status===`included`&&n.bytes.buffer instanceof ArrayBuffer&&this.logicalCaptureBuffers.add(n.bytes.buffer),n}catch{return{status:`omitted`,reason:`unavailable`}}}})}catch{this.poisonLogicalChanges()}finally{this.logicalCaptureToken=void 0}}captureLogicalContent(e,t,n,r,i){let a={status:`omitted`,reason:`unavailable`};if(this.logicalCaptureToken!==n||!r.has(e)||!Number.isSafeInteger(t)||t<=0||t>16777216)return a;if(e.type===`delete`)return{status:`omitted`,reason:`deleted`};if(e.kind!==`file`)return{status:`omitted`,reason:`not-file`};if(e.size>t)return{status:`omitted`,reason:`too-large`};try{let t=this.getInodeByPath(e.path);if(!t||t!==this.inodeTable.get(e.inodeId)||t.isDir||R(t)||t.size!==e.size||(this.assertSearchablePath(e.path,!1),this.assertFilePermission(e.path,t,En),this.logicalCaptureToken!==n))return a;if(i.has(t)){let e=i.get(t);return this.logicalCaptureToken===n&&e?{status:`included`,bytes:e}:a}let r;if(this.bufferMode===`memory`){let n=this.lookupFileDataForInode(e.path,t);if(e.size>0&&(!n||n.byteLength<e.size))return a;r=n?n.slice(0,e.size):new Uint8Array}else r=new Uint8Array(e.size),this.readBlocks(t,0,r);return this.logicalCaptureToken===n?(i.set(t,r),{status:`included`,bytes:r}):a}catch{return a}}callLogicalInvalidated(e,t){try{this.logicalSession?.invalidated(e,t)}catch{this.poisonLogicalChanges()}}closeChangeChannel(e,t){if(t.clientDisposed=!0,t.closed)return;t.closed=!0,this.changeChannels.delete(e);let n=this.changeChannelCounts.get(t.client.clientId)??1;n<=1?this.changeChannelCounts.delete(t.client.clientId):this.changeChannelCounts.set(t.client.clientId,n-1),this.releaseChangeSubscriptionsForChannel(t.client);let r=this.logicalSession;if(r&&!this.logicalChangesPoisoned)try{r.clientClosed(t.client)}catch{this.poisonLogicalChanges()}}sendChangeFrame(e,t){let n=this.changeChannels.get(e.channelId);if(!n||n.closed||n.client.clientId!==e.clientId||this.logicalChangesPoisoned)return;let r=gt(t,this.changeGeneration),i=r?.type===`event`&&r.change.content.status===`included`?r.change.content.bytes:void 0;if(!r||i&&(!(i.buffer instanceof ArrayBuffer)||i.byteOffset!==0||i.byteLength!==i.buffer.byteLength||!Xt(i.buffer)||this.logicalCaptureBuffers.has(i.buffer)||this.logicalDeliveryBuffers.has(i.buffer))){this.poisonLogicalChanges();return}if(i&&this.logicalDeliveryBuffers.add(i.buffer),r.type===`terminal`||r.type===`closed`){let t=JSON.stringify([e.clientId,e.channelId,r.subscriptionId]);this.changeSubscriptionIds.get(e.clientId)?.has(t)&&this.changeTerminalIds.add(t)}queueMicrotask(()=>{if(!n.closed&&!this.logicalChangesPoisoned)try{n.receive(r)}catch{}})}releaseChangeSubscription(e,t){let n=this.changeSubscriptionIds.get(e.clientId);n?.delete(t)&&(this.changeSubscriptionCount--,n.size===0&&this.changeSubscriptionIds.delete(e.clientId))}releaseChangeSubscriptionsForChannel(e){for(let t of[this.changeSubscriptionIds.get(e.clientId)])if(t)for(let n of[...t])n.startsWith(`${JSON.stringify([e.clientId,e.channelId]).slice(0,-1)},`)&&(this.changeTerminalIds.delete(n),this.releaseChangeSubscription(e,n))}validateChangeTarget(e){if(!e||typeof e.path!=`string`||e.scope!==`file`&&e.scope!==`directory`||typeof e.recursive!=`boolean`||e.scope===`file`&&e.recursive)throw y(`EINVAL`,void 0,`Invalid subscription target`);let t=k(e.path);if(t.requiresDirectory&&e.scope!==`directory`)throw y(`EINVAL`,t.path,`Trailing slash requires directory scope`);let n=`/`,r=this.getInodeByPath(`/`);r?.isDir&&this.assertDirectoryExecutable(`/`,r);let i=t.path.split(`/`).filter(Boolean);for(let e=0;e<i.length-1;e++){if(!r?.isDir)throw y(`ENOTDIR`,n);let t=this.lookupChild(n,r,i[e]);if(n=t.path,r=t.inode,!r)return;if(R(r))throw y(`EINVAL`,n,`Subscription target traverses symlink`);if(!r.isDir)throw y(`ENOTDIR`,n);this.assertDirectoryExecutable(n,r)}if(i.length===0){if(e.scope===`file`)throw y(`EINVAL`,t.path,`Root requires directory scope`);return}if(!r?.isDir)throw y(`ENOTDIR`,n);let a=this.lookupChild(n,r,i[i.length-1]).inode;if(a){if(e.scope===`file`&&a.isDir)throw y(`EINVAL`,t.path,`Directory conflicts with file scope`);if(e.scope===`directory`&&!a.isDir)throw y(`EINVAL`,t.path,`Non-directory conflicts with directory scope`);a.isDir&&this.assertDirectoryExecutable(t.path,a)}}growStorage(){let e=this.totalBlocks*2;this.bitmap.grow(e),this.totalBlocks=e,this.dirtyStructure=!0}withQuotaMapped(e,t){try{return e()}catch(e){if(mn(e)){let e=y(`ENOSPC`,t,`Browser storage quota exceeded`);throw this.setLocalPersistenceState(`error`,e),e}throw e}}async getStorageEstimate(){try{return typeof navigator>`u`||!navigator.storage?.estimate?void 0:await navigator.storage.estimate()}catch{return}}releaseBlock(e){e!==0&&(this.bufferMode===`disk`?this.pendingFree.add(e):this.bitmap.free(e))}drainPendingFree(){if(this.pendingFree.size!==0){for(let e of this.pendingFree)this.bitmap.free(e),this.allocatedDataBlocks--;this.pendingFree.clear()}}allocDiskBlock(){let e=this.bitmap.alloc();if(e>=0||this.pendingFree.size>0&&(this.storage?.beforeDataCommit?.(),this.flushData(),this.writeMeta(!0),e=this.bitmap.alloc(),e>=0))return e;if(this.growStorage(),e=this.bitmap.alloc(),e<0)throw y(`ENOSPC`);return e}ensureDiskBlocks(e,t,n,r,i){let a=Math.ceil(n/L),o=Math.floor(r/L);this.assertDiskBlocksWithinQuota(this.diskWriteHoleCount(t,n,r),e);let s=[];for(let e=o;e<a;e++)t.blocks[e]||s.push(e);let c=[];try{for(let e=0;e<s.length;){let t=1;for(;e+t<s.length&&s[e+t]===s[e]+t;)t++;let n=this.bitmap.allocRun(t);if(n>=0)for(let e=0;e<t;e++)c.push(n+e);else for(let e=0;e<t;e++)c.push(this.allocDiskBlock());e+=t}for(let e=0;e<s.length;e++){let t=s[e]*L,i=Math.min(L,Math.max(0,r-t)),a=Math.min(L,Math.max(0,t+L-n));i>0&&this.dataHandle.write(this.zeroSource(i),{at:c[e]*L}),a>0&&this.dataHandle.write(this.zeroSource(a),{at:(c[e]+1)*L-a})}}catch(e){for(let e of c)this.bitmap.free(e);throw e}for(;t.blocks.length<a;)t.blocks.push(0);for(let e=0;e<s.length;e++)t.blocks[s[e]]=c[e],i.push(s[e]);this.allocatedDataBlocks+=c.length,c.length>0&&(this.markDataDirty(),this.markAllPathsForInode(t))}rollbackNewBlocks(e,t,n){for(let t of n)this.bitmap.free(e.blocks[t]),e.blocks[t]=0;this.allocatedDataBlocks-=n.length,e.blocks.length=t}zeroDiskRange(e,t,n){n<=t||this.forEachBlockRun(e,t,n-t,(e,t,n)=>{if(e!==0){for(let t=0;t<n;t+=en){let r=Math.min(en,n-t);this.dataHandle.write(this.zeroSource(r),{at:e+t})}this.markDataDirty()}})}zeroSource(e){return e<=L?Qt.subarray(0,e):(this.zeroBuffer||=new Uint8Array(en),this.zeroBuffer.subarray(0,e))}moveSortedSubtree(e,t){let n=this.sortedPaths;Un(n,e);let r=`${e}/`,i=z(n,r),a=i;for(;a<n.length&&n[a].startsWith(r);)a++;let o=n.splice(i,a-i).map(n=>t+n.slice(e.length));B(n,t);let s=z(n,`${t}/`);this.sortedPaths=n.slice(0,s).concat(o,n.slice(s))}collectSubtreePaths(e){let t=e===`/`?`/`:`${e}/`,n=this.inodes.has(e)&&e!==`/`?[e]:[];for(let e=z(this.sortedPaths,t);e<this.sortedPaths.length;e++){let r=this.sortedPaths[e];if(!r.startsWith(t))break;n.push(r)}return n}markOpenFilesUnlinked(e){for(let t of this.openFiles.values())t.path===e&&(t.unlinked=!0)}hasOpenFilesInSubtree(e){let t=e===`/`?`/`:`${e}/`;for(let n of this.openFiles.values())if(!n.unlinked&&(n.path===e||n.path.startsWith(t)))return!0;return!1}deleteSubtree(e,t=1){let n=this.collectSubtreePaths(e).sort((e,t)=>t.length-e.length),r=new Set;for(let e of n){let n=this.inodes.get(e);n&&(this.recordLogicalDelete(e,n,t),(n.nlink??1)>1&&r.add(n),n.nlink=n.isDir?0:Math.max(0,(n.nlink??1)-1),n.ctimeMs=Date.now(),n.timestampMs=n.mtimeMs??n.timestampMs,n.nlink===0&&this.releaseUnlinkedInode(n),this.dropInodeEntries(n),this.unlinkInodePath(e),Un(this.sortedPaths,e),this.bufferMode===`memory`&&this.fileData.delete(e),this.deletedInodes.add(e),this.dirtyInodes.delete(e))}this.commitNamespaceChange();for(let e of r)this.markAllPathsForInode(e)}removeNamespaceEntry(e,t){this.invalidateFlush(),this.unlinkInodePath(e),Un(this.sortedPaths,e),this.bufferMode===`memory`&&this.fileData.delete(e),this.deletedInodes.add(e),this.dirtyInodes.delete(e),t.nlink=Math.max(0,(t.nlink??1)-1),t.ctimeMs=Date.now(),t.timestampMs=t.mtimeMs??t.timestampMs,t.nlink===0&&this.releaseUnlinkedInode(t),this.dropInodeEntries(t),this.commitNamespaceChange()}releaseUnlinkedInode(e){if(this.hasOpenHandleForInode(e)){this.pendingDeletedInodes.add(e);return}for(let t of e.blocks)t!==0&&this.releaseBlock(t);e.blocks=[],e.size=0}normalizeLoadedInodes(){let e=Date.now(),t=1,n=2,r=new Set,i=new Set;for(let a of this.inodes.values()){if(i.has(a))continue;i.add(a),a.kind===void 0&&(a.kind=a.isDir?`dir`:R(a)?`symlink`:`file`),a.kind===`symlink`?(a.isDir=!1,a.mode=a.mode&511|40960||wn,a.size=$t.encode(a.symlinkTarget??``).byteLength):a.isDir=a.kind===`dir`,a.kind!==`symlink`&&!(a.mode&61440)&&(a.mode|=a.isDir?An:kn);let o=a.mtimeMs??a.timestampMs??e;if(a.atimeMs===void 0&&(a.atimeMs=o),a.mtimeMs===void 0&&(a.mtimeMs=o),a.ctimeMs===void 0&&(a.ctimeMs=o),a.timestampMs=a.mtimeMs,(!Number.isInteger(a.nlink)||a.nlink===void 0||a.nlink<0)&&(a.nlink=a.isDir?2:1),!Number.isInteger(a.ino)||a.ino<=0||r.has(a.ino)){for(;r.has(n);)n++;a.ino=n++}r.add(a.ino),t=Math.max(t,a.ino)}let a=new Map;for(let[e,t]of this.inodes)e!==`/`&&a.set(t.ino,(a.get(t.ino)??0)+1);for(let e of this.inodes.values())e.nlink=e.isDir?2:Math.max(1,a.get(e.ino)??e.nlink??1);for(let[e,t]of this.inodes){if(e===`/`||!t.isDir)continue;let n=this.inodes.get(A(e));n?.isDir&&(n.nlink=(n.nlink??2)+1)}let o=this.inodes.get(`/`);o&&(o.kind=`dir`,o.ino=1,o.nlink=Math.max(2,o.nlink??2)),this.nextInodeNumber=Math.max(this.nextInodeNumber,t+1,n)}rebuildIndexesFromPathMap(){this.initializeDerivedIndexes(),this.inodeTable.clear(),this.dirEntries.clear(),this.pathIndex.clear(),this.inoToPaths.clear();for(let[e,t]of this.inodes){this.pathIndex.set(e,t.ino);let n=this.inoToPaths.get(t.ino);n||(n=new Set,this.inoToPaths.set(t.ino,n)),n.add(e),this.inodeTable.has(t.ino)||this.inodeTable.set(t.ino,t),t.isDir&&!this.dirEntries.has(t.ino)&&this.dirEntries.set(t.ino,new Map)}for(let[e,t]of this.inodes){if(e===`/`)continue;let n=A(e),r=this.inodes.get(n);if(!r?.isDir)continue;let i=this.dirEntries.get(r.ino);i||(i=new Map,this.dirEntries.set(r.ino,i)),i.set(j(e),t.ino)}}linkInodePath(e,t){this.inodes.set(e,t),this.pathIndex.set(e,t.ino);let n=this.inoToPaths.get(t.ino);n||(n=new Set,this.inoToPaths.set(t.ino,n)),n.add(e),this.inodeTable.has(t.ino)||this.inodeTable.set(t.ino,t),t.isDir&&!this.dirEntries.has(t.ino)&&this.dirEntries.set(t.ino,new Map)}unlinkInodePath(e){let t=this.pathIndex.get(e);if(this.inodes.delete(e),this.pathIndex.delete(e),t===void 0)return;let n=this.inoToPaths.get(t);n&&(n.delete(e),n.size===0&&(this.inoToPaths.delete(t),this.inodeTable.delete(t)))}dropInodeEntries(e){(e.nlink??1)===0&&this.dirEntries.delete(e.ino)}commitNamespaceChange(){}hasPathEntry(e){return this.ensureDerivedIndexes(),this.pathIndex.has(e)||this.inodes.has(e)}getInodeByPath(e){this.ensureDerivedIndexes();let t=this.pathIndex.get(e);return t===void 0?this.inodes.get(e):this.inodeTable.get(t)}getDirEntries(e){this.ensureDerivedIndexes();let t=this.dirEntries.get(e.ino);if(t)return t;let n=new Map;return this.dirEntries.set(e.ino,n),n}listDirNames(e){return[...this.getDirEntries(e).keys()]}addDirEntry(e,t,n){this.getDirEntries(e).set(t,n.ino)}removeDirEntry(e,t){this.getDirEntries(e).delete(t)}lookupChild(e,t,n){this.ensureDerivedIndexes();let r=e===`/`?`/${n}`:`${e}/${n}`,i=this.getDirEntries(t).get(n);return i===void 0?{path:r,inode:this.inodes.get(r)}:{path:r,inode:this.inodeTable.get(i)}}initializeDerivedIndexes(){this.inodeTable instanceof Map||(this.inodeTable=new Map),this.dirEntries instanceof Map||(this.dirEntries=new Map),this.pathIndex instanceof Map||(this.pathIndex=new Map),this.inoToPaths instanceof Map||(this.inoToPaths=new Map)}ensureDerivedIndexes(){this.initializeDerivedIndexes(),this.inodes instanceof Map&&this.pathIndex.size===0&&this.inodes.size>0&&(this.normalizeLoadedInodes(),this.rebuildIndexesFromPathMap())}touchInode(e,t=Date.now(),n=this.lookupInodeByPathHint(e)){n&&(this.invalidateFlush(),this.markLinkedInodeDirty(n,!0),n.mtimeMs=t,n.ctimeMs=t,n.atimeMs===void 0&&(n.atimeMs=t),n.timestampMs=n.mtimeMs,this.getInodeByPath(e)===n?this.markInodeAttrDirty(e):this.markAllPathsForInode(n,!0))}touchInodeAccess(e,t,n=Date.now()){if(this.noatime)return;let r=t.atimeMs;if(r!==void 0){let e=t.mtimeMs??0,i=t.ctimeMs??0;if(!(r<e||r<i||n-r>=fn))return}this.invalidateFlush(),this.markLinkedInodeDirty(t,!0),t.atimeMs=n,t.timestampMs=t.mtimeMs??t.timestampMs,this.getInodeByPath(e)===t&&this.markInodeAttrDirty(e)}touchInodeMetadata(e,t=Date.now()){let n=this.lookupInodeByPathHint(e);n&&(this.invalidateFlush(),this.markLinkedInodeDirty(n,!0),n.ctimeMs=t,n.mtimeMs===void 0&&(n.mtimeMs=t),n.atimeMs===void 0&&(n.atimeMs=n.mtimeMs),n.timestampMs=n.mtimeMs,this.markInodeAttrDirty(e))}updateOpenFileBuffers(e,t){for(let n of this.openFiles.values())n.inode===e&&(n.data=t)}pathForInode(e){return this.pathsForInode(e)[0]}pathsForInode(e){this.ensureDerivedIndexes();let t=this.inoToPaths.get(e.ino);return t&&this.inodeTable.get(e.ino)===e?[...t]:[]}lookupFileDataForInode(e,t){if(e){let t=this.fileData.get(e);if(t)return t}for(let e of this.pathsForInode(t)){let t=this.fileData.get(e);if(t)return t}}syncFileDataForInode(e,t,n){if((e.nlink??1)<=1&&n!==void 0){this.fileData.set(n,t);return}for(let n of this.pathsForInode(e))this.fileData.set(n,t)}lookupInodeByPathHint(e){return this.getInodeByPath(e)??Array.from(this.openFiles.values()).find(t=>t.path===e)?.inode}assertSearchablePath(e,t){let n=this.getInodeByPath(`/`);if(n&&this.assertDirectoryExecutable(`/`,n),e===`/`)return;let r=e.split(`/`).filter(Boolean),i=t?r.length:Math.max(r.length-1,0),a=`/`,o=n;for(let e=0;e<i;e++){if(!o?.isDir)throw y(`ENOTDIR`,a);let t=this.lookupChild(a,o,r[e]);a=t.path;let n=t.inode;if(!n)throw y(`ENOENT`,a);if(!n.isDir)throw y(`ENOTDIR`,a);this.assertDirectoryExecutable(a,n),o=n}}assertInodeWritable(e,t){if(t.isDir){this.assertDirectoryWritable(e,t);return}this.assertFilePermission(e,t,Dn)}assertDirectoryReadable(e,t){if((t.mode&En)===0)throw y(`EACCES`,e)}assertDirectoryWritable(e,t){if((t.mode&Dn)===0||(t.mode&On)===0)throw y(`EACCES`,e)}assertDirectoryExecutable(e,t){if((t.mode&On)===0)throw y(`EACCES`,e)}assertFilePermission(e,t,n){if((t.mode&n)===0)throw y(`EACCES`,e)}hasOpenHandleForInode(e){for(let t of this.openFiles.values())if(t.inode===e)return!0;return!1}normalizeMkdirOptions(e){return typeof e==`number`?{mode:e,recursive:!1}:{mode:e?.mode??Cn,recursive:e?.recursive??!1}}markAllPathsForInode(e,t=!1){for(let n of this.pathsForInode(e))t?this.markInodeAttrDirty(n):this.dirtyInodes.add(n)}markLinkedInodeDirty(e,t=!1){(e.nlink??1)>1&&this.markAllPathsForInode(e,t)}markInodeAttrDirty(e){this.dirtyInodes.has(e)||this.attrDirtyInodes.add(e)}flushMemoryNamespaceLog(){this.bufferMode===`memory`&&this.writeMeta(!1,this.localDurabilityMode!==`strict`)}flushRecoveryLogs(){this.walPendingBytes>0&&this.localDurabilityMode!==`strict`&&this.dataLogHandle.flush(),this.flushPendingMetaLog()}flushPendingMetaLog(){this.metaLogFlushPending&&=(this.logHandle.flush(),!1)}persistToOpfs(){if(this.dirtyPages.size!==0){for(let[e,t]of this.dirtyPages){let n=this.pathForInode(e);if(!n||e.isDir||R(e))continue;let r=this.lookupFileDataForInode(n,e);if(!r)continue;let i=e.size===0?0:Math.ceil(e.size/L),a=e.blocks.length,o=i-e.blocks.length;if(o>1){let t=this.bitmap.allocRun(o);if(t>=0)for(let n=0;n<o;n++)e.blocks.push(t+n)}for(;e.blocks.length<i;){let t=this.bitmap.alloc();if(t<0&&(this.growStorage(),t=this.bitmap.alloc(),t<0))throw y(`ENOSPC`);e.blocks.push(t)}for(;e.blocks.length>i;){let t=e.blocks.pop();t!==0&&this.releaseBlock(t)}for(let o of t){if(o>=Math.min(a,i)||e.blocks[o]!==0||!r.subarray(o*L,Math.min((o+1)*L,e.size)).some(e=>e!==0))continue;let s=this.bitmap.alloc();if(s<0&&(this.growStorage(),s=this.bitmap.alloc(),s<0))throw y(`ENOSPC`);e.blocks[o]=s,t.add(o),this.dirtyInodes.add(n)}e.blocks.length!==a&&this.dirtyInodes.add(n);for(let e=a;e<i;e++)t.add(e);let s=Array.from(t).filter(t=>t<e.blocks.length&&e.blocks[t]!==0).sort((e,t)=>e-t);for(let t=0;t<s.length;){let n=s[t],i=e.blocks[n],a=t,o=n;for(;a+1<s.length&&s[a+1]===o+1&&e.blocks[s[a+1]]===e.blocks[o]+1&&(o+1)*L<=e.size;)a++,o=s[a];let c=n*L,l=Math.min((o+1)*L,e.size),u=l-c;if(u>0){this.dataHandle.write(r.subarray(c,c+u),{at:i*L});let e=l%L;e>0&&this.dataHandle.getSize()<(i+o-n+1)*L&&this.dataHandle.write(this.zeroSource(L-e),{at:i*L+u}),this.markDataDirty()}t=a+1}}this.dirtyPages.clear()}}writeMeta(e=!1,t=!1){try{this.writeMetaRecords(e,t)}catch(e){throw this.setLocalPersistenceState(`error`,e),e}}writeMetaRecords(e,t){let n=this.dirtyInodes.size>0||this.attrDirtyInodes.size>0||this.deletedInodes.size>0;if(!e&&!this.dirtyStructure&&!n)return;let r=Math.max(pn,(this.lastSnapshotSize||0)*2),i=this.logOffset>=r;if(e||this.dirtyStructure||i){let e=new Uint8Array(Re(this.inodes,this.totalBlocks,L,this.sortedPaths,this.nextInodeNumber));this.lastSnapshotSize=e.byteLength;let t=this.metaSnapshotSequence+1>>>0,n=rt(e,t,this.sealer,this.flushedDataSize,this.flushedLogicalExtent),r=+(this.activeMetaSlot===0),i=r===0?this.metaHandleA:this.metaHandleB;this.withQuotaMapped(()=>{i.truncate(0),this.writeAll(i,n,0,`metadata snapshot`),i.flush()}),this.activeMetaSlot=r,this.metaSnapshotSequence=t,this.dirtyStructure=!0;let a=We([],1,this.sealer,t,this.flushedDataSize,this.flushedLogicalExtent);this.withQuotaMapped(()=>{this.logHandle.truncate(0),this.writeAll(this.logHandle,a,0,`metadata log`),this.logHandle.flush()}),this.logOffset=a.byteLength,this.committedLogicalExtent=this.flushedLogicalExtent,this.metaLogFlushPending=!1}else{let e=[];for(let t of this.deletedInodes)e.push(Be(t,null));for(let t of this.dirtyInodes){let n=this.inodes.get(t);n&&e.push(Be(t,n))}for(let t of this.attrDirtyInodes){if(this.dirtyInodes.has(t)||this.deletedInodes.has(t))continue;let n=this.inodes.get(t);n&&e.push(Ve(t,n))}if(e.length>0){let n=We(e,this.logOffset+1,this.sealer,this.metaSnapshotSequence,this.flushedDataSize,this.flushedLogicalExtent);this.withQuotaMapped(()=>this.logHandle.write(n,{at:this.logOffset})),this.logOffset+=n.byteLength,this.committedLogicalExtent=this.flushedLogicalExtent,t?this.metaLogFlushPending=!0:(this.logHandle.flush(),this.metaLogFlushPending=!1)}}this.dirtyStructure=!1,this.dirtyInodes.clear(),this.attrDirtyInodes.clear(),this.deletedInodes.clear(),this.drainPendingFree()}};function z(e,t){let n=0,r=e.length;for(;n<r;){let i=n+r>>>1;e[i]<t?n=i+1:r=i}return n}function B(e,t){e.splice(z(e,t),0,t)}function Un(e,t){let n=z(e,t);n<e.length&&e[n]===t&&e.splice(n,1)}var Wn=/^[A-Za-z][A-Za-z0-9_]{0,63}$/,Gn=/^[A-Z][A-Z0-9_]{0,63}$/,Kn=new Set([`meta-snapshot`,`data-wal`,`bitmap`,`meta-log`,`format-version`]);function qn(e){if(e.length<=1024)return e;let t=1023,n=e.charCodeAt(t-1);return n>=55296&&n<=56319&&t--,`${e.slice(0,t)}…`}function V(e,t){try{return e[t]}catch{return}}function Jn(e,t){let n=t?V(t,`message`):void 0;if(typeof n==`string`)return qn(n);try{return qn(String(e))}catch{return`Unknown VFS error`}}function Yn(e){let t=typeof e==`object`&&e?e:null,n=Jn(e,t),r=t?V(t,`name`):void 0,i=t?V(t,`code`):void 0,a=t?V(t,`errno`):void 0,o=t?V(t,`category`):void 0,s=t?V(t,`offset`):void 0;return Object.freeze({message:n,...typeof r==`string`&&r!==`Error`&&Wn.test(r)?{name:r}:{},...typeof i==`string`&&Gn.test(i)?{code:i}:{},...typeof a==`number`&&Number.isSafeInteger(a)?{errno:a}:{},...typeof o==`string`&&Kn.has(o)?{category:o}:{},...typeof s==`number`&&Number.isSafeInteger(s)&&s>=0?{offset:s}:{}})}function Xn(e){let{message:t,...n}=Yn(e);return{error:t,...n}}function Zn(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t,n;try{t=Object.getPrototypeOf(e),n=Reflect.ownKeys(e)}catch{return null}if(t!==Object.prototype&&t!==null)return null;let r=new Set([`error`,`name`,`code`,`errno`,`category`,`offset`]);if(!n.every(e=>typeof e==`string`&&r.has(e))||!n.includes(`error`))return null;let i=e,a,o,s,c,l,u,d=n.includes(`name`),f=n.includes(`code`),p=n.includes(`errno`),m=n.includes(`category`),h=n.includes(`offset`);try{a=i.error,d&&(o=i.name),f&&(s=i.code),p&&(c=i.errno),m&&(l=i.category),h&&(u=i.offset)}catch{return null}return typeof a!=`string`||a.length>1024||d&&(typeof o!=`string`||!Wn.test(o))||f&&(typeof s!=`string`||!Gn.test(s))||p&&(typeof c!=`number`||!Number.isSafeInteger(c))||m&&(typeof l!=`string`||!Kn.has(l))||h&&(typeof u!=`number`||!Number.isSafeInteger(u)||u<0)?null:Object.freeze({message:a,...d?{name:o}:{},...f?{code:s}:{},...p?{errno:c}:{},...m?{category:l}:{},...h?{offset:u}:{}})}function Qn(e){let{message:t,name:n,...r}=e,i=Object.assign(Error(t),r);return n!==void 0&&(i.name=n),i}var $n=4194304,H=64,U=0,er=1,W=2,tr=3,nr=1e3,rr=5e3,ir=new TextEncoder,ar=new TextDecoder,or=new WeakSet;function sr(e){return e instanceof Error?e.message:String(e)}function cr(e,t,n=0,r=$n){if(t<0||n<0)throw Error(`${e} has invalid payload lengths`);if(t>r)throw Error(`${e} header exceeds SAB capacity (${t} > ${r})`);if(t+n>r)throw Error(`${e} payload exceeds SAB capacity (${t+n} > ${r})`)}var lr=class{sab;int32;callCount=0;constructor(e){if(typeof SharedArrayBuffer>`u`)throw Error(`SharedArrayBuffer is not supported.`);this.sab=e||new SharedArrayBuffer(4194368),this.int32=new Int32Array(this.sab)}get buffer(){return this.sab}get payloadCapacity(){return this.sab.byteLength-H}get maxDataBytesPerCall(){return Math.max(0,this.payloadCapacity-1024)}ensureFits(e,t,n=0){cr(e,t,n,this.payloadCapacity)}encodeBoundedErrorHeader(e){let t=this.payloadCapacity,{error:n,...r}=Xn(e);for(let e of[r,r.code===void 0?{}:{code:r.code}]){let r=t=>ir.encode(JSON.stringify({error:t,...e})),i=r(n);if(i.length<=t)return i;let a=r(``);if(a.length>t)continue;let o=0,s=n.length;for(;o<=s;){let e=o+s>>1,i=r(n.slice(0,e)+(e<n.length?`…`:``));i.length<=t?(a=i,o=e+1):s=e-1}return a}return ir.encode(`{}`).subarray(0,Math.max(0,t))}makeRemoteError(e){let t=Zn(e);if(!t)return Error(`Invalid VFS error response`);let n=Qn(t);return or.add(n),n}call(e,t,n,r){try{if(typeof window<`u`&&typeof document<`u`)throw Error(`Atomics.wait cannot be called on the main thread.`);if(Atomics.load(this.int32,U)!==0){if(this.waitForStatusChange(1,nr)===`timed-out`&&Atomics.load(this.int32,U)===1)throw Error(`SyncMessenger is poisoned: a prior call timed out and the worker is still busy.`);Atomics.store(this.int32,U,0)}let i=JSON.stringify({type:e,payload:t}),a=ir.encode(i);this.ensureFits(`SyncMessenger.call(${e}) request`,a.length,n?.length??0),this.callCount=this.callCount+1|0;let o=this.callCount;if(this.int32[tr]=o,this.int32[er]=a.length,new Uint8Array(this.sab,H).set(a),n&&n.length>0?(this.int32[W]=n.length,new Uint8Array(this.sab,H+a.length).set(n)):this.int32[W]=0,Atomics.store(this.int32,U,1),Atomics.notify(this.int32,U),this.waitForStatusChange(1,3e4)===`timed-out`)throw Error(`VFS worker did not respond within 30s (command: ${e})`);let s=Atomics.load(this.int32,U),c,l,u;try{if(s!==2&&s!==3)throw Error(`SyncMessenger protocol desync: invalid response status ${s}`);u=this.int32[tr];let t=this.int32[er],n=this.int32[W];this.ensureFits(`SyncMessenger.call(${e}) response`,t,n);let i=new Uint8Array(t);if(i.set(new Uint8Array(this.sab,H,t)),c=JSON.parse(ar.decode(i)),n>0){let e=new Uint8Array(this.sab,H+t,n);r?.dataSink?r.dataSink.set(e.subarray(0,Math.min(n,r.dataSink.length))):(l=new Uint8Array(n),l.set(e))}}finally{Atomics.store(this.int32,U,0),Atomics.notify(this.int32,U)}if(u!==o)throw Error(`SyncMessenger protocol desync: expected call ID ${o} but got ${u} (stale response after a timeout?)`);if(s===3)throw this.makeRemoteError(c);return l?c.result&&typeof c.result==`object`?{...c.result,data:l}:{result:c.result,data:l}:c.result}catch(t){throw typeof t==`object`&&t&&(or.has(t)||`code`in t&&typeof t.code==`string`)?t:Error(`SyncMessenger.call(${e}) failed: ${sr(t)}`)}}waitForStatusChange(e,t){let n=performance.now()+t;for(;Atomics.load(this.int32,U)===e;){let t=n-performance.now();if(t<=0)return`timed-out`;Atomics.wait(this.int32,U,e,t)}return`not-equal`}listen(e,t){let n=t?.blocking??!1,r=t?.once??!1,i=t?.signal,a=e=>this.int32[tr]!==e||Atomics.load(this.int32,U)!==1,o=(e,t)=>{if(a(t))return;let n=this.encodeBoundedErrorHeader(e);this.int32[er]=n.length,new Uint8Array(this.sab,H,n.length).set(n),this.int32[W]=0,Atomics.store(this.int32,U,3),Atomics.notify(this.int32,U)},s=(e,t,n,r)=>{if(a(r))return;let i=ir.encode(JSON.stringify(t));this.ensureFits(`SyncMessenger.listen response`,i.length,n?.length??0),this.int32[er]=i.length,new Uint8Array(this.sab,H).set(i),n&&n.length>0?(this.int32[W]=n.length,new Uint8Array(this.sab,H+i.length).set(n)):this.int32[W]=0,Atomics.store(this.int32,U,e),Atomics.notify(this.int32,U)},c=async(e,t)=>{if(n)return Atomics.wait(this.int32,U,e,t);if(typeof Atomics.waitAsync!=`function`){let n=performance.now()+t;for(;Atomics.load(this.int32,U)===e&&!i?.aborted;){let e=n-performance.now();if(e<=0)return`timed-out`;await new Promise(t=>setTimeout(t,Math.min(1,e)))}return`ok`}{let n=Atomics.waitAsync(this.int32,U,e,t);return n.async?await n.value:(await new Promise(e=>setTimeout(e,0)),n.value)}};(async()=>{for(;;){if(i?.aborted)return;try{let t=Atomics.load(this.int32,U);if(t!==1){if(t===2||t===3)await c(t,rr)===`timed-out`&&Atomics.compareExchange(this.int32,U,t,0)===t&&Atomics.notify(this.int32,U);else{let e=await c(t,rr);t!==0&&e===`timed-out`&&(Atomics.compareExchange(this.int32,U,t,0),Atomics.notify(this.int32,U))}continue}let n=this.int32[tr],i=this.int32[er],a=this.int32[W];try{this.ensureFits(`SyncMessenger.listen request`,i,a);let t=new Uint8Array(i);t.set(new Uint8Array(this.sab,H,i));let o=JSON.parse(ar.decode(t));if(!o||typeof o!=`object`||Array.isArray(o)||typeof o.type!=`string`)throw Error(`Invalid SyncMessenger request header`);let{type:c,payload:l}=o,u;a>0&&(u=new Uint8Array(a),u.set(new Uint8Array(this.sab,H+i,a)));let d=await e(c,l,u);if(s(2,{result:d.result},d.data,n),r)return}catch(e){if(o(e,n),r)return}}catch(e){console.error(`SyncMessenger loop error:`,e),await new Promise(e=>setTimeout(e,10))}}})()}},ur=`PERSISTENCE_STATUS`,dr=`PERSISTENCE_FRAME`;function fr(e,t,n){let r=n.salvage;return{version:1,generation:e,sequence:t,state:n.state,failureRevision:n.failureRevision,lastError:n.failureRevision===0?null:Xn(n.failure??Error(`Local persistence failed`)),lastSalvage:r?{reason:r.reason,truncatedAt:r.truncatedAt,discardedBytes:r.discardedBytes,detail:r.detail,at:r.at}:null}}function pr(e){return e.code!==`ENOENT`&&e.code!==`ENOTDIR`}var G,K=null,mr=null,hr=!1,gr=!1,_r=null,vr=!1,yr=null,br=!1,q=null,J,xr=0,Y=new Map,X=new Map,Sr=(e,t)=>JSON.stringify([e,t]),Cr=e=>typeof e==`string`&&e.length>0&&e.length<=128;function wr(){Y.clear(),X.clear()}function Tr(e){let t=Sr(e.clientId,e.channelId);if(Y.get(t)!==e)return;Y.delete(t);let n=X.get(e.clientId)??1;n<=1?X.delete(e.clientId):X.set(e.clientId,n-1)}function Er(e){return e.state===`open`&&Y.get(Sr(e.clientId,e.channelId))===e&&K===e.mount&&q===e.generation}function Dr(e,t=!1){if(e.queued=!1,K!==e.mount||q!==e.generation)return;let n=yt.get(e.mount)?.read();if(!n||!t&&e.last?.state===n.state&&e.last.failureRevision===n.failureRevision)return;let r=fr(e.generation,++e.sequence,n);return e.last={state:n.state,failureRevision:n.failureRevision},r}function Or(e){if(xr>0)return;let t=Dr(e);if(t)try{G.postMessage({type:dr,payload:t})}catch{}}function kr(e,t){let n={mount:e,generation:t,sequence:0,enabled:!1,queued:!1};J=n,yt.get(e)?.watch(()=>{n.enabled&&!n.queued&&(n.queued=!0,queueMicrotask(()=>Or(n)))})}function Ar(e){if(typeof e!=`object`||!e||Array.isArray(e))throw y(`EINVAL`,void 0,`Invalid persistence status request`);try{let t=Object.getPrototypeOf(e),n=Reflect.ownKeys(e);if(t!==Object.prototype&&t!==null||n.length!==2||n.some(e=>e!==`version`&&e!==`generation`))throw y(`EINVAL`,void 0,`Invalid persistence status request`);let{version:r,generation:i}=e;if(r!==1||typeof i!=`string`||i.length<1||i.length>128)throw y(`EINVAL`,void 0,`Invalid persistence status request`);return i}catch{throw y(`EINVAL`,void 0,`Invalid persistence status request`)}}function jr(...e){hr&&console.log(...e)}function Z(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Expected string payload field: ${t}`);return n}function Q(e,t,n){let r=e[t];if(typeof r!=`number`||!Number.isSafeInteger(r)||!n?.signed&&r<0)throw y(`EINVAL`,void 0,`Invalid numeric payload field: ${t}`);return r}function $(e,t){if(e[t]!==void 0)return Q(e,t)}function Mr(e,t){let n=e[t];return typeof n==`boolean`?n:void 0}var Nr=new Set([`fileName`,`sab`,`debug`,`plugins`,`openMode`,`bufferMode`,`localDurabilityMode`,`debugWal`,`noatime`,`recoveryMode`,`maxFileSize`,`maxNameLength`,`maxPathDepth`,`maxFiles`,`maxTotalBytes`,`generation`]);function Pr(e){if(typeof e!=`object`||!e||Array.isArray(e))throw y(`EINVAL`,void 0,`Invalid INIT payload`);let t=e;for(let e of Reflect.ownKeys(t))if(!Nr.has(String(e)))throw y(`EINVAL`,void 0,`Unsupported INIT field: ${String(e)}`);let n=t.fileName;if(typeof n!=`string`)throw y(`EINVAL`,void 0,`Invalid INIT fileName`);Wt(n);let r=e=>{throw y(`EINVAL`,n,`Invalid INIT field: ${e}`)};(typeof t.generation!=`string`||!t.generation)&&r(`generation`);let i=t.sab;i!==void 0&&(typeof SharedArrayBuffer!=`function`||!(i instanceof SharedArrayBuffer)||i.byteLength<=64||i.byteLength%4!=0)&&r(`sab`),t.debug!==void 0&&typeof t.debug!=`boolean`&&r(`debug`);for(let[e,n]of Object.entries({openMode:[`open-or-create`,`create-new`,`open-existing`],bufferMode:[`disk`,`memory`],localDurabilityMode:[`balanced`,`strict`,`relaxed`],recoveryMode:[`fail-stop`,`salvage`]})){let i=t[e];i!==void 0&&!n.includes(i)&&r(e)}for(let e of[`debugWal`,`noatime`])t[e]!==void 0&&typeof t[e]!=`boolean`&&r(e);for(let e of[`maxFileSize`,`maxNameLength`,`maxPathDepth`,`maxFiles`,`maxTotalBytes`]){let n=t[e];n!==void 0&&(typeof n!=`number`||!Number.isSafeInteger(n)||n<0)&&r(e)}let a={openMode:t.openMode,bufferMode:t.bufferMode,localDurabilityMode:t.localDurabilityMode,debugWal:t.debugWal,noatime:t.noatime,recoveryMode:t.recoveryMode,maxFileSize:t.maxFileSize,maxNameLength:t.maxNameLength,maxPathDepth:t.maxPathDepth,maxFiles:t.maxFiles,maxTotalBytes:t.maxTotalBytes};return{fileName:n,sab:i,debug:t.debug===!0,options:a,plugins:t.plugins,generation:t.generation}}function Fr(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw y(`EINVAL`,void 0,`Invalid file change channel`);let n=e,r=t===`FILE_CHANGES_COMMAND`?[`version`,`generation`,`clientId`,`channelId`,`route`,`command`]:[`version`,`generation`,`clientId`,`channelId`,`route`],i=Reflect.ownKeys(n);if(i.length!==r.length||i.some(e=>!r.includes(String(e)))||n.version!==1||!Cr(n.generation)||!Cr(n.clientId)||!Cr(n.channelId)||n.route!==`local`&&n.route!==`follower-relay`||t===`FILE_CHANGES_COMMAND`&&(typeof n.command!=`object`||n.command===null||Array.isArray(n.command)))throw y(`EINVAL`,void 0,`Invalid file change channel`);return{generation:n.generation,clientId:n.clientId,channelId:n.channelId,route:n.route,command:n.command}}function Ir(e){return e===`FILE_CHANGES_OPEN`||e===`FILE_CHANGES_COMMAND`||e===`FILE_CHANGES_CLOSE`}function Lr(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw y(`EINVAL`,void 0,`Invalid file change request`);let n=e,r=Reflect.ownKeys(n);if(r.length!==4||r.some(e=>![`id`,`type`,`payload`,`data`].includes(String(e)))||!Number.isSafeInteger(n.id)||n.id<=0||n.type!==t||n.data!==void 0)throw y(`EINVAL`,void 0,`Invalid file change request`)}function Rr(e){if(Er(e)){e.state=`closed`,Tr(e),e.channel?.close();try{G.postMessage({type:`FILE_CHANGES_INTERRUPTED`,payload:{version:1,generation:e.generation,clientId:e.clientId,channelId:e.channelId,route:e.route,code:`SUBSCRIPTION_INTERRUPTED`}})}catch{}}}function zr(e,t,n={}){if(!Er(e))return;let r=n.frame,i=r?.type===`event`&&r.change.content.status===`included`?r.change.content.bytes:void 0,a={type:t,payload:{version:1,generation:e.generation,clientId:e.clientId,channelId:e.channelId,route:e.route,...n}};try{i?G.postMessage(a,{transfer:[i.buffer]}):G.postMessage(a)}catch{Rr(e)}}async function Br(e,t,n){let r=n=>G.postMessage({id:t,type:e,result:n}),i=Fr(n,e),a=K;if(!a||q!==i.generation)throw y(`EBADF`,void 0,`File change channel is closed`);let o=Sr(i.clientId,i.channelId);if(e===`FILE_CHANGES_OPEN`){if(Y.has(o)||(X.get(i.clientId)??0)>=32||Y.size>=128)throw y(`ENOSPC`,void 0,`Too many file change channels`);let e=vt.get(a);if(!e)throw y(`ENOTSUP`,void 0,`Logical changes unavailable`);let t={...i,mount:a,state:`opening`};Y.set(o,t),X.set(i.clientId,(X.get(i.clientId)??0)+1);try{let n=await e.open(t.clientId,t.route,e=>zr(t,`FILE_CHANGES_FRAME`,{frame:e}),e=>zr(t,`FILE_CHANGES_INTERRUPTED`,{code:e}),()=>zr(t,t.route===`follower-relay`?`FILE_CHANGES_INTERRUPTED`:`FILE_CHANGES_CLOSED`,t.route===`follower-relay`?{code:`SUBSCRIPTION_INTERRUPTED`}:{}),t.channelId);if(Y.get(o)!==t||t.state===`closed`||K!==a||q!==t.generation||n.generation!==t.generation)throw n.close(),y(`EBADF`,void 0,`File change channel is closed`);t.channel=n,t.state=`open`,r({generation:n.generation})}catch(e){throw Tr(t),e}return}let s=Y.get(o);if(!s||s.generation!==i.generation||s.route!==i.route)throw y(`EBADF`,void 0,`File change channel is closed`);if(e===`FILE_CHANGES_CLOSE`){s.state=`closed`,Tr(s),s.channel?.close(),r(`OK`);return}if(s.state!==`open`||!s.channel)throw y(`EBADF`,void 0,`File change channel is closed`);let c=await s.channel.request(i.command);if(!Er(s))throw y(`EBADF`,void 0,`File change channel is closed`);r(c)}function Vr({plugins:e=[],endpoint:t=self}={}){if(gr)throw Error(`VFS worker already started`);if(!Array.isArray(e))throw Error(`Worker plugins must be an array`);let n=new Map;for(let t of e){if(typeof t!=`object`&&typeof t!=`function`||t===null||typeof t.id!=`string`||!Tt(t.id)||typeof t.configure!=`function`||n.has(t.id))throw Error(`Invalid or duplicate worker plugin registration`);n.set(t.id,t)}gr=!0,G=t,G.onmessage=async e=>{let t=e.data,r=t?.id,i=t?.type,a=t?.payload,o=t?.data,s=!1;if(jr(`VFS Worker message:`,i,r),i===`PING`){G.postMessage({id:r,type:`PONG`});return}try{if(Ir(i)){Lr(t,i),await Br(i,r,a);return}switch(i){case`INIT`:{let{fileName:e,sab:t,debug:i,options:o,plugins:s,generation:c}=Pr(a);if(br)throw y(`EBUSY`,e,`VFS initialization already in progress`);if(vr&&c===yr)throw y(`EINVAL`,e,`VFS owner generation already mounted`);br=!0;try{let{requests:a}=Ot(s,o.openMode,e),l=a.map(t=>{let r=n.get(t.id);if(!r)throw y(`EINVAL`,e,`Unknown worker plugin: ${t.id}`);return r}),u=Rt(a.map((t,n)=>{try{return l[n].configure(t.options)}catch(n){let r=`EINVAL`;if(typeof n==`object`&&n)try{r=n.code}catch{}let i=typeof r==`string`&&/^[A-Z][A-Z0-9_]{0,63}$/.test(r)?r:`EINVAL`,a=y(`EINVAL`,e,`Invalid worker plugin options: ${t.id}`);throw a.code=i,a}}),o.openMode??`open-or-create`,e);Bt(u,e);for(let t=0;t<a.length;t++){let n=a[t],r=u[t];if(r.id!==n.id||r.contractVersion!==n.contractVersion||r.compatibilityKey!==n.compatibilityKey||r.requiredOpenMode!==n.requiredOpenMode)throw y(`EINVAL`,e,`Worker plugin request mismatch: ${n.id}`)}let d=kt(u);if(hr=i,vr){_r?.abort(),_r=null,mr=null;for(let e of Y.values())e.state===`opening`&&(e.state=`closed`);try{K&&(xt(K),await Yt(K))}catch{}queueMicrotask(wr),K=null,q=null,J=void 0,vr=!1}try{At.set(o,u),_t.set(o,c),K=new Hn(e,o),await K.ready,q=c,kr(K,c)}catch(e){let t=Xn(e),n=`VFS init failed: ${t.error}`,{error:i,...a}=t;console.error(n),G.postMessage({id:r,type:`ERROR`,result:Xn({message:n,...a})});return}vr=!0,yr=c,G.postMessage({id:r,type:`INIT`,result:{profile:d}}),typeof SharedArrayBuffer==`function`&&t instanceof SharedArrayBuffer&&(_r=new AbortController,mr=new lr(t),mr.listen(Hr,{signal:_r.signal}))}finally{br=!1}break}case ur:{let e=Ar(a),t=J;if(!K||!t||e!==q)throw y(`EBADF`,void 0,`VFS persistence status is unavailable`);t.enabled=!0,t.queued=!1;let n=Dr(t,!0);if(!n)throw y(`EBADF`,void 0,`VFS persistence status is unavailable`);G.postMessage({id:r,type:i,result:n});break}default:{s=!0,xr++;let{result:e,data:t}=await Hr(i,a,o),n=J?.queued?Dr(J):void 0;G.postMessage({id:r,type:i,result:e,data:t,...n===void 0?{}:{persistence:n}},t?[t.buffer]:[]);break}}}catch(e){let t=Xn(e),n=Ir(i)?`File change control failed: ${t.code??`EIO`}`:t.error;pr({code:t.code,message:n,payload:a,type:i})&&console.error(`VFS Worker error:`,n);let o=i!==`INIT`&&i!==`PERSISTENCE_STATUS`&&!Ir(i)&&J?.queued?Dr(J):void 0;G.postMessage({id:r,type:`ERROR`,result:Ir(i)?{...t,error:n}:t,...o===void 0?{}:{persistence:o}})}finally{let e=J;s&&--xr===0&&e?.queued&&queueMicrotask(()=>Or(e))}}}async function Hr(e,t,n){if(!K)throw Error(`VFS not initialized`);if(typeof t!=`object`||!t)throw Error(`Invalid payload for command: ${e}`);let r=t;switch(e){case`READ_FILE_BUFFER`:{let e=Z(r,`path`),t=Q(r,`limit`);if(t>16777216)throw y(`EFBIG`,e);let n=K.openSync(e,Nn.O_RDONLY);try{let{size:r}=K.fstatSync(n);if(r>t)throw y(`EFBIG`,e);let{buffer:i,read:a}=K.readSync(n,r,0);return{result:{read:a},data:i.subarray(0,a)}}finally{K.closeSync(n)}}case`WRITE_FILE_BUFFER`:{let e=Z(r,`path`);if(!(n instanceof Uint8Array))throw y(`EINVAL`,e);let t=r.expected;if(t!==void 0&&!(t instanceof Uint8Array)||r.exclusive!==void 0&&typeof r.exclusive!=`boolean`||r.append!==void 0&&typeof r.append!=`boolean`)throw y(`EINVAL`,e);return K.writeFileBufferSync(e,n,{exclusive:r.exclusive,expected:t,append:r.append}),{result:`OK`}}case`RENAME_NO_REPLACE`:{let e=Z(r,`oldPath`),t=Z(r,`newPath`);try{K.lstatSync(t)}catch(n){if(!(n instanceof Error)||!(`code`in n)||n.code!==`ENOENT`)throw n;return K.renameSync(e,t),{result:`OK`}}throw y(`EEXIST`,t)}case`MKDIR`:return K.mkdirSync(Z(r,`path`),Mr(r,`recursive`)?{recursive:!0,mode:$(r,`mode`)}:$(r,`mode`)),{result:`OK`};case`OPEN`:return{result:K.openSync(Z(r,`path`),$(r,`flags`),$(r,`mode`))};case`WRITE`:return{result:K.writeSync(Q(r,`fd`),n??new Uint8Array,$(r,`offset`))};case`READ`:{let{buffer:e,read:t}=K.readSync(Q(r,`fd`),Q(r,`size`),$(r,`offset`));return{result:{read:t},data:e}}case`SEEK`:return{result:K.seekSync(Q(r,`fd`),Q(r,`offset`,{signed:!0}),Q(r,`whence`))};case`CLOSE`:return K.closeSync(Q(r,`fd`)),{result:`OK`};case`FSTAT`:return{result:K.fstatSync(Q(r,`fd`))};case`FSYNC`:return K.fsyncSync(Q(r,`fd`)),{result:`OK`};case`FTRUNCATE`:return K.ftruncateSync(Q(r,`fd`),Q(r,`size`)),{result:`OK`};case`CHMOD`:return K.chmodSync(Z(r,`path`),Q(r,`mode`)),{result:`OK`};case`UTIMES`:return K.utimesSync(Z(r,`path`),Q(r,`atimeMs`),Q(r,`mtimeMs`)),{result:`OK`};case`SYMLINK`:return K.symlinkSync(Z(r,`target`),Z(r,`path`),$(r,`mode`)),{result:`OK`};case`LINK`:return K.linkSync(Z(r,`existingPath`),Z(r,`newPath`)),{result:`OK`};case`READLINK`:return{result:K.readlinkSync(Z(r,`path`))};case`REALPATH`:return{result:K.realpathSync(Z(r,`path`))};case`UNLINK`:return K.unlinkSync(Z(r,`path`)),{result:`OK`};case`RMDIR`:return K.rmdirSync(Z(r,`path`)),{result:`OK`};case`REMOVE`:return K.removeSync(Z(r,`path`)),{result:`OK`};case`RENAME`:return K.renameSync(Z(r,`oldPath`),Z(r,`newPath`)),{result:`OK`};case`TRUNCATE`:return K.truncateSync(Z(r,`path`),Q(r,`size`)),{result:`OK`};case`EXISTS`:return{result:K.existsSync(Z(r,`path`))};case`STAT`:return{result:K.statSync(Z(r,`path`))};case`LSTAT`:return{result:K.lstatSync(Z(r,`path`))};case`READDIR`:return{result:K.readdirSync(Z(r,`path`))};case`READDIR_NAMES`:return{result:K.readdirNamesSync(Z(r,`path`))};case`READDIR_ENTRIES`:return{result:K.readdirEntriesSync(Z(r,`path`))};case`LIST_PATHS`:return{result:K.listPathsSync()};case`SYNC`:return K.syncSync(),{result:`OK`};case`FLUSH`:return K.flushVfs(),{result:`OK`};case`CLOSE_VFS`:try{return await Yt(K),yr=null,{result:`OK`}}finally{queueMicrotask(wr)}default:throw Error(`Unknown command: ${e}`)}}Vr({plugins:[f]});", C = typeof self < "u" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", S], { type: "text/javascript;charset=utf-8" });
|
|
15
|
+
function w(e) {
|
|
16
|
+
let t;
|
|
17
|
+
try {
|
|
18
|
+
if (t = C && (self.URL || self.webkitURL).createObjectURL(C), !t) throw "";
|
|
19
|
+
let n = new Worker(t, {
|
|
20
|
+
type: "module",
|
|
21
|
+
name: e?.name
|
|
22
|
+
});
|
|
23
|
+
return n.addEventListener("error", () => {
|
|
24
|
+
(self.URL || self.webkitURL).revokeObjectURL(t);
|
|
25
|
+
}), n;
|
|
26
|
+
} catch {
|
|
27
|
+
return new Worker("data:text/javascript;charset=utf-8," + encodeURIComponent(S), {
|
|
28
|
+
type: "module",
|
|
29
|
+
name: e?.name
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
//#region src/coordinator.ts
|
|
35
|
+
var T = /* @__PURE__ */ new WeakMap(), E = (e) => ({
|
|
36
|
+
...e,
|
|
37
|
+
gate: m.makeUnsafe(1),
|
|
38
|
+
terminalSignal: c.makeUnsafe(),
|
|
39
|
+
files: /* @__PURE__ */ new Set(),
|
|
40
|
+
subscriptionSetups: /* @__PURE__ */ new Map(),
|
|
41
|
+
subscriptionUnknown: /* @__PURE__ */ new Map(),
|
|
42
|
+
continuity: { _tag: "clean" }
|
|
43
|
+
}), D = (e, t) => {
|
|
44
|
+
T.set(e, t);
|
|
45
|
+
}, O = (e) => T.get(e), k = (e, t) => {
|
|
46
|
+
c.isDoneUnsafe(e.terminalSignal) || l.runSync(c.succeed(e.terminalSignal, t));
|
|
47
|
+
}, A = /* @__PURE__ */ x({
|
|
48
|
+
Volume: () => j,
|
|
49
|
+
errorOf: () => $,
|
|
50
|
+
inspect: () => R,
|
|
51
|
+
layer: () => Y,
|
|
52
|
+
layerDirect: () => H,
|
|
53
|
+
make: () => J,
|
|
54
|
+
makeDirect: () => V,
|
|
55
|
+
unsafeBackend: () => X,
|
|
56
|
+
withSync: () => M
|
|
57
|
+
}), j = class extends s.Service()("@opfs-vfs/effect/Volume") {}, M = (e) => l.gen(function* () {
|
|
58
|
+
let t = yield* j;
|
|
59
|
+
return yield* l.tap(e, () => t.sync);
|
|
60
|
+
}), N = (e) => l.forEach([...e?.files ?? []], (e) => l.exit(e()), { concurrency: 1 }).pipe(l.flatMap((e) => {
|
|
61
|
+
let t;
|
|
62
|
+
for (let n of e) u.isFailure(n) && (t = t ? o.combine(t, n.cause) : n.cause);
|
|
63
|
+
return t ? l.failCause(t) : l.void;
|
|
64
|
+
})), P = (e, t) => {
|
|
65
|
+
let n = u.isFailure(e) ? u.isFailure(t) ? o.combine(e.cause, t.cause) : e.cause : u.isFailure(t) ? t.cause : void 0;
|
|
66
|
+
return n ? l.failCause(n) : l.void;
|
|
67
|
+
}, F = (e) => typeof e != "string" || e.length <= 4 || !e.endsWith(".bin") || /[/\\]/.test(e), I = () => Object.assign(/* @__PURE__ */ Error("Worker factory failed"), { code: "VFS_WORKER_FACTORY_FAILED" }), L = (e) => (...t) => {
|
|
68
|
+
try {
|
|
69
|
+
return e(...t);
|
|
70
|
+
} catch {
|
|
71
|
+
throw I();
|
|
72
|
+
}
|
|
73
|
+
}, R = (e) => F(e) ? l.fail(a(/* @__PURE__ */ TypeError("Volume name must be a basename ending in .bin"), e, "inspect", "configuration", "not-applied")) : l.tryPromise({
|
|
74
|
+
try: () => g(e),
|
|
75
|
+
catch: (t) => a(t, e, "inspect", "filesystem", "not-applied")
|
|
76
|
+
}), z = (e) => l.uninterruptibleMask((t) => l.gen(function* () {
|
|
77
|
+
let n = yield* l.scope, i = yield* p.fork(n, "sequential"), o = yield* p.make("sequential"), s = !1, c, d, f, m, g = !1, _ = (e) => s || i.state._tag === "Closed" ? l.fail(a(/* @__PURE__ */ Error("Volume scope is closed"), e, "acquire", "lifecycle", "not-applied")) : l.void, v = () => (s = !0, m && k(m, a(/* @__PURE__ */ Error("Volume is closed"), null, "close", "lifecycle", "unknown")), f && Q.add(f), c && (d ??= Promise.resolve().then(() => c.closeVfs()).then(() => void 0)), d ?? Promise.resolve()), y, b = yield* l.cached(l.suspend(() => p.close(o, y))), x = (e) => (y ??= e, b);
|
|
78
|
+
return yield* p.addFinalizerExit(i, x), yield* _(null), yield* l.gen(function* () {
|
|
79
|
+
let n = yield* t(l.isEffect(e) ? l.provideService(e, p.Scope, o) : l.succeed(e));
|
|
80
|
+
yield* _(null);
|
|
81
|
+
let i;
|
|
82
|
+
if (n.plugins) try {
|
|
83
|
+
i = n.plugins();
|
|
84
|
+
} catch {
|
|
85
|
+
return yield* l.fail(a(/* @__PURE__ */ Error("Plugin configuration failed"), n.fileName, "configure plugins", "configuration", "not-applied"));
|
|
86
|
+
}
|
|
87
|
+
g = i?.some((e) => e.logicalChanges?.version === 1) ?? !1;
|
|
88
|
+
let { fileName: u, plugins: d, ...y } = n;
|
|
89
|
+
if (yield* _(u), F(u)) return yield* l.fail(a(/* @__PURE__ */ TypeError("Volume name must be a basename ending in .bin"), u, "configure", "configuration", "not-applied"));
|
|
90
|
+
try {
|
|
91
|
+
c = new h(u, {
|
|
92
|
+
...y,
|
|
93
|
+
plugins: i
|
|
94
|
+
});
|
|
95
|
+
} catch (e) {
|
|
96
|
+
return yield* l.fail(typeof e == "object" && e && "code" in e && e.code === "EINVAL" ? a(e, u, "mount", "configuration", "not-applied") : r(e, u, "mount"));
|
|
97
|
+
}
|
|
98
|
+
return yield* p.addFinalizer(o, l.gen(function* () {
|
|
99
|
+
return s = !0, m && k(m, a(/* @__PURE__ */ Error("Volume is closed"), null, "close", "lifecycle", "unknown")), yield* P(yield* l.exit(N(m)), yield* l.exit(l.tryPromise({
|
|
100
|
+
try: v,
|
|
101
|
+
catch: (e) => r(e, u, "close", "lifecycle")
|
|
102
|
+
}).pipe(l.orDie)));
|
|
103
|
+
})), yield* _(u), yield* t(l.tryPromise({
|
|
104
|
+
try: () => c.ready,
|
|
105
|
+
catch: (e) => r(e, u, "initialize", "filesystem")
|
|
106
|
+
})), yield* _(u), m = E({
|
|
107
|
+
fileName: u,
|
|
108
|
+
scope: o,
|
|
109
|
+
readinessTimeout: Infinity,
|
|
110
|
+
subscriptionsAvailable: g,
|
|
111
|
+
backend: c,
|
|
112
|
+
isClosed: () => s,
|
|
113
|
+
currentGeneration: () => s ? void 0 : "direct",
|
|
114
|
+
canRecapture: () => !1,
|
|
115
|
+
terminal: () => void 0,
|
|
116
|
+
awaitReady: (e, t) => s ? l.fail(a(/* @__PURE__ */ Error("Volume is closed"), u, t, "lifecycle", "not-applied")) : l.succeed("direct")
|
|
117
|
+
}), f = B(c, u, () => s, m), D(f, m), Z.set(f, c), yield* p.addFinalizer(o, l.sync(() => {
|
|
118
|
+
s = !0, f && Q.add(f);
|
|
119
|
+
})), yield* _(u), f;
|
|
120
|
+
}).pipe(l.onExit((e) => u.isFailure(e) ? l.gen(function* () {
|
|
121
|
+
let t = yield* l.exit(x(e));
|
|
122
|
+
if (yield* l.exit(p.close(i, e)), u.isFailure(t)) return yield* l.failCause(t.cause);
|
|
123
|
+
}) : l.void));
|
|
124
|
+
})), B = (t, o, s, u) => {
|
|
125
|
+
let d = (e) => s() ? a(/* @__PURE__ */ Error("Volume is closed"), o, e, "lifecycle", "not-applied") : void 0;
|
|
126
|
+
return {
|
|
127
|
+
fileName: o,
|
|
128
|
+
sync: l.uninterruptibleMask((i) => l.gen(function* () {
|
|
129
|
+
let s = yield* i(u.awaitReady({ remaining: Infinity }, "sync"));
|
|
130
|
+
yield* l.scoped(l.gen(function* () {
|
|
131
|
+
yield* i(l.raceFirst(l.acquireRelease(m.take(u.gate, 1), () => m.release(u.gate, 1), { interruptible: !0 }), c.await(u.terminalSignal).pipe(l.flatMap((e) => l.fail(q(e))))));
|
|
132
|
+
let f = d("sync");
|
|
133
|
+
if (f) return yield* l.fail(q(f));
|
|
134
|
+
if (u.continuity._tag === "lost" || u.continuity._tag === "pending" && u.continuity.generation !== s) return u.continuity = {
|
|
135
|
+
_tag: "lost",
|
|
136
|
+
generation: u.continuity.generation
|
|
137
|
+
}, yield* l.fail(a(Object.assign(/* @__PURE__ */ Error("Writes accepted by a previous owner may not be durable"), { code: "VFS_SYNC_OWNER_CHANGED" }), o, "sync", "persistence", "unknown"));
|
|
138
|
+
yield* l.try({
|
|
139
|
+
try: () => t.syncSync(),
|
|
140
|
+
catch: (t) => t instanceof e || t instanceof n ? t : r(t, o, "sync", "persistence")
|
|
141
|
+
}), u.continuity._tag === "pending" && (u.continuity = { _tag: "clean" });
|
|
142
|
+
}));
|
|
143
|
+
})),
|
|
144
|
+
persistence: l.try({
|
|
145
|
+
try: () => {
|
|
146
|
+
let e = d("persistence");
|
|
147
|
+
if (e) throw e;
|
|
148
|
+
let n = t.getLocalPersistenceStatusSync();
|
|
149
|
+
return {
|
|
150
|
+
state: n.localPersistenceState,
|
|
151
|
+
error: n.localPersistenceState === "error" && n.lastError !== void 0 ? i(n.lastError) : null
|
|
152
|
+
};
|
|
153
|
+
},
|
|
154
|
+
catch: (e) => e instanceof n ? e : a(e, o, "persistence", "lifecycle")
|
|
155
|
+
}),
|
|
156
|
+
acknowledgeOwnerChange: l.uninterruptibleMask((e) => l.scoped(l.gen(function* () {
|
|
157
|
+
yield* e(l.raceFirst(l.acquireRelease(m.take(u.gate, 1), () => m.release(u.gate, 1), { interruptible: !0 }), c.await(u.terminalSignal).pipe(l.flatMap(l.fail))));
|
|
158
|
+
let t = d("acknowledgeOwnerChange");
|
|
159
|
+
if (t) return yield* l.fail(t);
|
|
160
|
+
})))
|
|
161
|
+
};
|
|
162
|
+
};
|
|
163
|
+
function V(e) {
|
|
164
|
+
return z(e);
|
|
165
|
+
}
|
|
166
|
+
function H(e) {
|
|
167
|
+
return d.effect(j, z(e));
|
|
168
|
+
}
|
|
169
|
+
var U = (t) => l.uninterruptibleMask((i) => l.gen(function* () {
|
|
170
|
+
let o = yield* l.scope, s = yield* p.fork(o, "sequential"), c = yield* p.make("sequential"), d = !1, m, h, g, _, b, x, S, C, T = new AbortController(), A = (e) => d || s.state._tag === "Closed" ? l.fail(a(/* @__PURE__ */ Error("Volume scope is closed"), e, "acquire", "lifecycle", "not-applied")) : l.void, j = (e) => h === e ? g : (h = e, C && k(C, a(/* @__PURE__ */ Error("Volume is closed"), null, "close", "lifecycle", "unknown")), g = Promise.resolve().then(() => e.closeVfs()), g), M = () => (T.abort(), _ ? b ??= _.then((e) => h === e ? g.then(() => void 0, () => void 0) : j(e), () => void 0) : Promise.resolve()), I, R = yield* l.cached(l.suspend(() => p.close(c, I))), z = (e) => (I ??= e, R);
|
|
171
|
+
return yield* p.addFinalizerExit(s, z), yield* p.addFinalizer(c, l.tryPromise({
|
|
172
|
+
try: M,
|
|
173
|
+
catch: (e) => r(e, null, "close", "lifecycle")
|
|
174
|
+
}).pipe(l.catch((e) => l.die(e)))), yield* p.addFinalizer(c, l.sync(() => {
|
|
175
|
+
d = !0, T.abort(), C && k(C, a(/* @__PURE__ */ Error("Volume is closed"), null, "close", "lifecycle", "unknown"));
|
|
176
|
+
})), yield* A(null), yield* l.gen(function* () {
|
|
177
|
+
let o = yield* i(l.isEffect(t) ? l.provideService(t, p.Scope, c) : l.succeed(t));
|
|
178
|
+
yield* A(o.fileName);
|
|
179
|
+
let { fileName: s, plugins: u, ...h } = o, g = h.initTimeout || 15e3;
|
|
180
|
+
if (F(s)) return yield* l.fail(a(/* @__PURE__ */ TypeError("Volume name must be a basename ending in .bin"), s, "configure", "configuration", "not-applied"));
|
|
181
|
+
let b;
|
|
182
|
+
try {
|
|
183
|
+
b = [...typeof u == "function" ? u() : u ?? []];
|
|
184
|
+
} catch {
|
|
185
|
+
return yield* l.fail(a(/* @__PURE__ */ Error("Plugin configuration failed"), s, "configure plugins", "configuration", "not-applied"));
|
|
186
|
+
}
|
|
187
|
+
let M = b.some((e) => e.id === "subscriptions" && e.contractVersion === 1 && e.compatibilityKey === y);
|
|
188
|
+
yield* A(s);
|
|
189
|
+
let I = L(h.worker ?? (() => new w())), R = h.sharedWorker ? L(h.sharedWorker) : void 0;
|
|
190
|
+
_ = Promise.resolve().then(() => v(s, {
|
|
191
|
+
...h,
|
|
192
|
+
worker: I,
|
|
193
|
+
sharedWorker: R,
|
|
194
|
+
plugins: b,
|
|
195
|
+
signal: T.signal
|
|
196
|
+
})), m = yield* i(l.tryPromise({
|
|
197
|
+
try: () => _,
|
|
198
|
+
catch: (e) => typeof e == "object" && e && "code" in e && e.code === "EINVAL" ? a(e, s, "mount", "configuration") : r(e, s, "mount", "filesystem")
|
|
199
|
+
})), yield* A(s), yield* p.addFinalizer(c, l.gen(function* () {
|
|
200
|
+
return d = !0, T.abort(), C && k(C, a(/* @__PURE__ */ Error("Volume is closed"), null, "close", "lifecycle", "unknown")), yield* P(yield* l.exit(N(C)), yield* l.exit(l.tryPromise({
|
|
201
|
+
try: () => (x && Q.add(x), j(m)),
|
|
202
|
+
catch: (e) => r(e, s, "close", "lifecycle")
|
|
203
|
+
}).pipe(l.catch((e) => l.die(e)))));
|
|
204
|
+
})), yield* A(s);
|
|
205
|
+
let z = () => {
|
|
206
|
+
let e = m.getStatus();
|
|
207
|
+
if (!S && (e.state === "closing" || e.state === "failed" || e.state === "closed") && (S = W(e, s, "worker")), S && x) {
|
|
208
|
+
let e = O(x);
|
|
209
|
+
e && k(e, S);
|
|
210
|
+
}
|
|
211
|
+
}, B = m.subscribeStatus(z);
|
|
212
|
+
return yield* p.addFinalizer(c, l.sync(B)), z(), yield* i(l.tryPromise({
|
|
213
|
+
try: () => m.ready,
|
|
214
|
+
catch: (t) => (z(), S && f.is(e)(S.cause) || S && f.is(n)(S.cause) && S.cause.kind === "configuration" ? S.cause : S ?? r(t, s, "initialize", "filesystem"))
|
|
215
|
+
})), yield* A(s), z(), S ? f.is(e)(S.cause) ? yield* l.fail(S.cause) : yield* l.fail(S) : (C = E({
|
|
216
|
+
fileName: s,
|
|
217
|
+
scope: c,
|
|
218
|
+
readinessTimeout: g,
|
|
219
|
+
subscriptionsAvailable: M,
|
|
220
|
+
backend: m,
|
|
221
|
+
isClosed: () => d,
|
|
222
|
+
currentGeneration: () => {
|
|
223
|
+
z();
|
|
224
|
+
let e = m.getStatus();
|
|
225
|
+
return e.state === "ready" ? e.ownerGeneration ?? void 0 : void 0;
|
|
226
|
+
},
|
|
227
|
+
canRecapture: () => !d && !S && m.getStatus().transport === "dedicated",
|
|
228
|
+
terminal: () => (z(), S),
|
|
229
|
+
awaitReady: (e, t) => K(m, s, t, e, () => (z(), S)).pipe(l.map((e) => e.ownerGeneration), l.mapError((e) => e))
|
|
230
|
+
}), x = G(m, s, () => d, () => (z(), S), g, C), D(x, C), Z.set(x, m), yield* A(s), x);
|
|
231
|
+
}).pipe(l.onExit((e) => u.isFailure(e) ? l.gen(function* () {
|
|
232
|
+
let t = yield* l.exit(z(e));
|
|
233
|
+
if (yield* l.exit(p.close(s, e)), u.isFailure(t)) return yield* l.failCause(t.cause);
|
|
234
|
+
}) : l.void));
|
|
235
|
+
})), W = (e, t, i) => {
|
|
236
|
+
let o = e.error ? r(Object.assign(Error(e.error.message), e.error), t, i) : a(/* @__PURE__ */ Error("Worker client closed"), t, i, "lifecycle"), s = o.details ?? null;
|
|
237
|
+
return new n({
|
|
238
|
+
kind: "lifecycle",
|
|
239
|
+
fileName: t,
|
|
240
|
+
operation: i,
|
|
241
|
+
...s?.code ? { code: s.code } : {},
|
|
242
|
+
outcome: "unknown",
|
|
243
|
+
details: s,
|
|
244
|
+
cause: o
|
|
245
|
+
});
|
|
246
|
+
}, G = (e, t, o, s, u, d) => {
|
|
247
|
+
let f = (e) => o() ? a(/* @__PURE__ */ Error("Volume is closed"), t, e, "lifecycle", "not-applied") : s(), p = l.try({
|
|
248
|
+
try: () => {
|
|
249
|
+
let t = f("persistence");
|
|
250
|
+
if (t) throw t;
|
|
251
|
+
let n = e.getStatus().persistence;
|
|
252
|
+
return n ? {
|
|
253
|
+
state: n.state,
|
|
254
|
+
error: n.state === "error" ? n.lastError : null
|
|
255
|
+
} : {
|
|
256
|
+
state: "unknown",
|
|
257
|
+
error: null
|
|
258
|
+
};
|
|
259
|
+
},
|
|
260
|
+
catch: (e) => e instanceof n ? e : a(e, t, "persistence", "lifecycle")
|
|
261
|
+
});
|
|
262
|
+
return {
|
|
263
|
+
fileName: t,
|
|
264
|
+
sync: l.uninterruptibleMask((n) => l.gen(function* () {
|
|
265
|
+
let o = f("sync");
|
|
266
|
+
if (o) return yield* l.fail(q(o));
|
|
267
|
+
let p = yield* n(K(e, t, "sync", { remaining: u }, s, (e) => e.code === "VFS_OWNER_READY_TIMEOUT" && d.continuity._tag !== "clean" ? a(e, t, "sync", "lifecycle", "unknown") : q(e)));
|
|
268
|
+
yield* l.scoped(l.gen(function* () {
|
|
269
|
+
yield* n(l.raceFirst(l.acquireRelease(m.take(d.gate, 1), () => m.release(d.gate, 1), { interruptible: !0 }), c.await(d.terminalSignal).pipe(l.flatMap((e) => l.fail(q(e))))));
|
|
270
|
+
let o = e.getStatus(), s = f("sync");
|
|
271
|
+
if (s) return yield* l.fail(q(s));
|
|
272
|
+
let u = p.ownerGeneration;
|
|
273
|
+
if (o.state !== "ready") return yield* l.fail(a(Object.assign(/* @__PURE__ */ Error("Owner is not ready before SYNC dispatch"), { code: "VFS_ATTACHMENT_LOST" }), t, "sync", "lifecycle", "not-applied"));
|
|
274
|
+
if (o.ownerGeneration !== u) return d.continuity._tag === "pending" ? (d.continuity = {
|
|
275
|
+
_tag: "lost",
|
|
276
|
+
generation: d.continuity.generation
|
|
277
|
+
}, yield* l.fail(a(Object.assign(/* @__PURE__ */ Error("Writes accepted by a previous owner may not be durable"), { code: "VFS_SYNC_OWNER_CHANGED" }), t, "sync", "persistence", "unknown"))) : yield* l.fail(a(Object.assign(/* @__PURE__ */ Error("Owner changed before SYNC dispatch"), { code: "VFS_ATTACHMENT_LOST" }), t, "sync", "lifecycle", "not-applied"));
|
|
278
|
+
if (d.continuity._tag === "lost" || d.continuity._tag === "pending" && d.continuity.generation !== u) return d.continuity = {
|
|
279
|
+
_tag: "lost",
|
|
280
|
+
generation: d.continuity.generation
|
|
281
|
+
}, yield* l.fail(a(Object.assign(/* @__PURE__ */ Error("Writes accepted by a previous owner may not be durable"), { code: "VFS_SYNC_OWNER_CHANGED" }), t, "sync", "persistence", "unknown"));
|
|
282
|
+
yield* l.tryPromise({
|
|
283
|
+
try: () => e.forGeneration(u).sync(),
|
|
284
|
+
catch: (e) => {
|
|
285
|
+
let n = f("sync");
|
|
286
|
+
if (n) return q(n);
|
|
287
|
+
let o = e instanceof _ ? e.dispatch : void 0, s = e instanceof _ ? e.cause : e, c = i(s).code;
|
|
288
|
+
return o === "refused" && c === "VFS_ATTACHMENT_LOST" && d.continuity._tag === "pending" ? (d.continuity = {
|
|
289
|
+
_tag: "lost",
|
|
290
|
+
generation: d.continuity.generation
|
|
291
|
+
}, a(Object.assign(/* @__PURE__ */ Error("Writes accepted by a previous owner may not be durable"), { code: "VFS_SYNC_OWNER_CHANGED" }), t, "sync", "persistence", "unknown")) : r(s, t, "sync", void 0, o === "refused" ? "not-applied" : "unknown");
|
|
292
|
+
}
|
|
293
|
+
}), d.continuity._tag === "pending" && (d.continuity = { _tag: "clean" });
|
|
294
|
+
}));
|
|
295
|
+
})),
|
|
296
|
+
persistence: p,
|
|
297
|
+
acknowledgeOwnerChange: l.uninterruptibleMask((n) => l.gen(function* () {
|
|
298
|
+
let r = f("acknowledgeOwnerChange");
|
|
299
|
+
if (r) return yield* l.fail(r);
|
|
300
|
+
let i = yield* n(K(e, t, "acknowledgeOwnerChange", { remaining: u }, s));
|
|
301
|
+
yield* l.scoped(l.gen(function* () {
|
|
302
|
+
yield* n(l.raceFirst(l.acquireRelease(m.take(d.gate, 1), () => m.release(d.gate, 1), { interruptible: !0 }), c.await(d.terminalSignal).pipe(l.flatMap(l.fail))));
|
|
303
|
+
let r = f("acknowledgeOwnerChange");
|
|
304
|
+
if (r) return yield* l.fail(r);
|
|
305
|
+
let o = e.getStatus();
|
|
306
|
+
if (o.state !== "ready" || o.ownerGeneration !== i.ownerGeneration) return yield* l.fail(a(Object.assign(/* @__PURE__ */ Error("Owner changed before acknowledgment"), { code: "VFS_ACK_OWNER_CHANGED" }), t, "acknowledgeOwnerChange", "persistence", "not-applied"));
|
|
307
|
+
(d.continuity._tag === "lost" || d.continuity._tag === "pending" && d.continuity.generation !== i.ownerGeneration) && (d.continuity = {
|
|
308
|
+
_tag: "pending",
|
|
309
|
+
generation: i.ownerGeneration
|
|
310
|
+
});
|
|
311
|
+
}));
|
|
312
|
+
}))
|
|
313
|
+
};
|
|
314
|
+
}, K = (e, t, n, r, i, o = ((e) => e)) => {
|
|
315
|
+
let s = l.callback((r) => {
|
|
316
|
+
let a = !1, s = () => {}, c = (e) => {
|
|
317
|
+
a || (a = !0, s(), r(e));
|
|
318
|
+
}, u = () => {
|
|
319
|
+
let r = e.getStatus();
|
|
320
|
+
r.state === "ready" && r.ownerGeneration ? c(l.succeed(r)) : (r.state === "closing" || r.state === "failed" || r.state === "closed") && c(l.fail(o(i() ?? W(r, t, n))));
|
|
321
|
+
};
|
|
322
|
+
return s = e.subscribeStatus(u), u(), l.sync(s);
|
|
323
|
+
});
|
|
324
|
+
return l.gen(function* () {
|
|
325
|
+
let e = a(Object.assign(/* @__PURE__ */ Error("Ready owner wait timed out"), { code: "VFS_OWNER_READY_TIMEOUT" }), t, n, "lifecycle", "not-applied");
|
|
326
|
+
if (r.remaining <= 0) return yield* l.fail(o(e));
|
|
327
|
+
let i = yield* l.clockWith((e) => e.currentTimeMillis), c = l.sleep(r.remaining).pipe(l.andThen(l.fail(o(e))));
|
|
328
|
+
return yield* l.raceFirst(s, c).pipe(l.onExit(() => l.clockWith((e) => e.currentTimeMillis).pipe(l.flatMap((e) => l.sync(() => {
|
|
329
|
+
r.remaining = Math.max(0, r.remaining - Math.max(0, e - i));
|
|
330
|
+
})))));
|
|
331
|
+
});
|
|
332
|
+
}, q = (t) => f.is(e)(t.cause) ? t.cause : t;
|
|
333
|
+
function J(e) {
|
|
334
|
+
return U(e);
|
|
335
|
+
}
|
|
336
|
+
function Y(e) {
|
|
337
|
+
return d.effect(j, U(e));
|
|
338
|
+
}
|
|
339
|
+
var X = (e) => {
|
|
340
|
+
let t = Z.get(e);
|
|
341
|
+
if (!t) throw TypeError("Volume service was not created by this adapter");
|
|
342
|
+
if (Q.has(e)) throw a(/* @__PURE__ */ Error("Volume scope is closed"), e.fileName, "unsafeBackend", "lifecycle", "not-applied");
|
|
343
|
+
return t;
|
|
344
|
+
}, Z = /* @__PURE__ */ new WeakMap(), Q = /* @__PURE__ */ new WeakSet(), $ = (r) => {
|
|
345
|
+
try {
|
|
346
|
+
let i = r.reason?.cause;
|
|
347
|
+
if (f.is(n)(i) && i.kind === "lifecycle" && i.cause !== void 0) {
|
|
348
|
+
let r = i.cause;
|
|
349
|
+
if (f.is(n)(r) || f.is(e)(r) || f.is(t)(r)) return r;
|
|
350
|
+
}
|
|
351
|
+
if (f.is(n)(i) || f.is(e)(i) || f.is(t)(i)) return i;
|
|
352
|
+
} catch {
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
};
|
|
356
|
+
//#endregion
|
|
357
|
+
export { H as a, X as c, O as d, x as f, Y as i, A as l, $ as n, J as o, R as r, V as s, j as t, M as u };
|