@opfs-vfs/effect 0.3.1 → 0.4.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.
@@ -0,0 +1,355 @@
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
+ // \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){return e.split(`/`).some(e=>e===`.`||e===`..`)}function n(e){let t=[];for(let n of e.split(`/`))n&&n!==`.`&&(n===`..`?t.pop():t.push(n));return`/${t.join(`/`)}`}var r=16777216,i=e=>`${e.clientId}\\u0000${e.channelId}`,a=(e,t)=>`${i(e)}\\u0000${t}`;function o(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 s=(e,t)=>o(t,256)+o(e,0),c=e=>e===`create`?1:e===`update`?2:e===`delete`?4:0,l=(e,t)=>t.startsWith(e.prefix)&&t.indexOf(`/`,e.prefix.length)<0,u=(e,t)=>t.startsWith(e.prefix);function d(n){if(!n||typeof n!=`object`||Array.isArray(n))throw e(`EINVAL`,`Invalid subscription options`);let r=n;if(Reflect.ownKeys(r).some(e=>typeof e!=`string`||![`path`,`scope`,`recursive`,`events`,`match`,`content`].includes(e)))throw e(`EINVAL`,`Invalid subscription options`);if(typeof r.path!=`string`||r.path.includes(`\\0`))throw e(`EINVAL`,`Invalid path`);if(t(r.path))throw e(`EINVAL`,`Subscription target must not contain . or .. components`);if(r.scope!==`file`&&r.scope!==`directory`||typeof r.recursive!=`boolean`)throw e(`EINVAL`,`Invalid scope`);if(r.scope===`file`&&r.recursive)throw e(`EINVAL`,`File subscriptions cannot be recursive`);let i=Array.isArray(r.events)?Array.from(r.events):void 0;if(!i||!i.length||i.some(e=>e!==`create`&&e!==`update`&&e!==`delete`))throw e(`EINVAL`,`Invalid events`);let a;if(r.match!==void 0){let t=r.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`);a={source:t.source,flags:t.flags}}if(r.content!==!1){let t=r.content?.maxBytes;if(!r.content||typeof r.content!=`object`||Array.isArray(r.content)||Reflect.ownKeys(r.content).length!==1||!Reflect.ownKeys(r.content).includes(`maxBytes`)||typeof t!=`number`||!Number.isSafeInteger(t)||t<=0||t>16777216)throw e(`EINVAL`,`Invalid content options`);return{path:r.path,scope:r.scope,recursive:r.recursive,events:[...new Set(i)],match:a,content:{maxBytes:t}}}return{path:r.path,scope:r.scope,recursive:r.recursive,events:[...new Set(i)],match:a,content:!1}}function f(){return{id:`subscriptions`,contractVersion:1,compatibilityKey:`subscriptions-v1`,logicalChanges:{version:1,create(t){let i=/* @__PURE__ */ new Map,f=0,p=0,m=0,h=e=>[...i.values()].filter(t=>t.client.clientId===e.clientId).length,g=(e,t)=>{t&&(e.contentBytes-=t.size,m-=t.charge)},_=(e,t)=>{f--,p-=s(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=>{i.delete(e.key),v(e),e.inflight&&=(_(e,e.inflight),void 0),p-=e.charge},b=(e,n)=>{e.state!==`retiring`&&(v(e),e.state=`retiring`,t.send(e.client,n))},x=e=>{if(e.state!==`active`||e.inflight!==void 0||!e.pending.length)return;let n=e.pending.shift();e.inflight=n,t.send(e.client,n.frame)},S=(e,t,n)=>!(!(e.eventMask&c(n))||!(e.options.scope===`file`?t===e.path:t===e.path||(e.options.recursive?u(e,t):l(e,t)))||e.regex&&(e.regex.lastIndex=0,!e.regex.test(t)));return{control(s,l){let u=a(s,l.subscriptionId);if(l.type===`register`){if(i.has(u))throw e(`EINVAL`,`Subscription already registered`);let a=d(l.options),f=o(a.path,512)+o(l.subscriptionId,0)+o(s.clientId,0)+o(s.channelId,0)+(a.match?o(a.match.source,0)+o(a.match.flags,0):0);if(i.size>=128||h(s)>=32||p+f>r)throw e(`ENOSPC`,`Subscription capacity exhausted`);t.validateTarget(a);let m=n(a.path),g;try{g=a.match?new RegExp(a.match.source,a.match.flags):void 0}catch{throw e(`EINVAL`,`Invalid match expression`)}let _={key:u,client:s,id:l.subscriptionId,options:a,path:m,prefix:m===`/`?`/`:`${m}/`,eventMask:a.events.reduce((e,t)=>e|c(t),0),regex:g,charge:f,state:`held`,nextDeliveryId:1,pending:[],contentBytes:0};return i.set(u,_),p+=f,{type:`registered`,subscriptionId:_.id}}let f=i.get(u);if(!f)return{type:`ok`};if(l.type===`activate`)f.state===`held`&&(f.state=`active`),x(f);else if(l.type===`ack`){if(f.state===`active`&&f.inflight?.frame.deliveryId===l.deliveryId){let e=f.inflight;f.inflight=void 0,_(f,e),x(f)}}else l.type===`cancel`?b(f,{type:`closed`,subscriptionId:f.id}):l.type===`terminal-ack`&&f.state===`retiring`&&y(f);return{type:`ok`}},completed(e){if(!i.size)return;let t=[...i.values()],n;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=s(a.id,i.path);if(a.pending.length+(a.inflight===void 0?0:1)>=4096||f>=16384||p+t>r){b(a,{type:`terminal`,subscriptionId:a.id,code:`SUBSCRIPTION_OVERFLOW`});continue}let o,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,r=n?.get(i.inodeId),s=t*(a.client.route===`follower-relay`?2:1);if(a.contentBytes+t>33554432||m+(r?0:t)+s>201326592){b(a,{type:`terminal`,subscriptionId:a.id,code:`SUBSCRIPTION_OVERFLOW`});continue}let u=!r;a.contentBytes+=t,m+=s+(u?t:0);let d=()=>{a.contentBytes-=t,m-=s},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=r;e||(e=f.bytes,(n??=/* @__PURE__ */ new Map).set(i.inodeId,e));try{let n=e.slice();o={size:t,charge:s},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:o}),f++,p+=t,x(a)}}finally{for(let e of n?.values()??[])m-=e.byteLength;n=void 0}},invalidated(e,t){let r=e.kind===`paths`?e.paths.map(({path:e,subtree:t})=>{let r=n(e);return{region:r,prefix:r===`/`?`/`:`${r}/`,subtree:t}}):[];for(let n of[...i.values()])(e.kind===`all`||r.some(({region:e,prefix:t,subtree:r})=>(e=>n.options.scope===`file`?e===n.path:e===n.path||(n.options.recursive?u(n,e):l(n,e)))(e)||r&&(n.path===e||e===`/`||n.path.startsWith(t)||n.options.scope===`directory`&&n.options.recursive&&u(n,e))))&&b(n,{type:`terminal`,subscriptionId:n.id,code:t===`record-limit`?`SUBSCRIPTION_OVERFLOW`:`SUBSCRIPTION_RESYNC_REQUIRED`})},clientClosed(e){for(let t of[...i.values()])t.client.clientId===e.clientId&&t.client.channelId===e.channelId&&y(t)},close(){for(let e of[...i.values()])t.send(e.client,{type:`terminal`,subscriptionId:e.id,code:`SUBSCRIPTION_INTERRUPTED`}),y(e)}}}}}}var p=Object.assign((t={})=>{if(!t||typeof t!=`object`||Array.isArray(t)||Reflect.ownKeys(t).length)throw e(`EINVAL`,`Subscriptions accept no configuration`);return f()},{id:`subscriptions`,configure:t=>{if(!t||typeof t!=`object`||Array.isArray(t)||Reflect.ownKeys(t).length)throw e(`EINVAL`,`Subscriptions accept no configuration`);return f()}}),m=Object.freeze({metaLog:3,snapshot:2,dataWal:4}),h=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}},g={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},_={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`},v=e=>typeof e==`string`&&Object.hasOwn(g,e),y=class extends Error{code;errno;path;constructor(e,t,n){let r=n??_[e];super(t?`${e}: ${r} (${t})`:`${e}: ${r}`),this.name=`VfsError`,this.code=e,this.errno=g[e],this.path=t}};function b(e,t,n){return new y(e,t,n)}var x=class extends Error{category;offset;constructor(e,t,n){super(t),this.name=`VfsCorruptionError`,this.category=e,this.offset=n}},S=8,C=4,w=class extends x{constructor(e,t){super(`data-wal`,e,t),this.name=`DataWalCorruptionError`}};function T(e,t,n){t.setUint32(n,e>>>0,!0)}function E(e,t){return e.getUint32(t,!0)}function D(e,t,n){if(!Number.isSafeInteger(e)||e<0)throw new w(`Data WAL u64 value is not a safe unsigned integer: ${e}`,n);t.setBigUint64(n,BigInt(e),!0)}function O(e,t,n){let r=e.getBigUint64(t,!0);if(r>BigInt(2**53-1))throw new w(`Data WAL u64 value exceeds Number.MAX_SAFE_INTEGER`,n);return Number(r)}var ee=(()=>{let e=/* @__PURE__ */ 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 k(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]=C,e[t+1]=1,T(n.inodeId,i,t+2),T(r.length,i,t+6),D(n.offset,i,t+10),T(n.data.length,i,t+18),e.set(r,t+22),e.set(n.data,t+22+r.length);return;case`truncate`:e[t]=C,e[t+1]=2,T(n.inodeId,i,t+2),T(r.length,i,t+6),D(n.size,i,t+10),e.set(r,t+18);return;case`delete`:e[t]=C,e[t+1]=3,T(n.inodeId,i,t+2),T(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(S+o),c=new DataView(s.buffer,s.byteOffset,s.byteLength);return t.sealInto(a,m.dataWal,n,s,S),T(o,c,0),T(k(s.subarray(S)),c,4),s}let a=new Uint8Array(S+i),o=new DataView(a.buffer,a.byteOffset,a.byteLength);return ie(a,S,e,r),T(i,o,0),T(k(a.subarray(S)),o,4),a}function oe(e,t){if(e.length<2)throw new w(`Data WAL payload too small`,t);let n=e[0];if(n!==C)throw new w(`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 w(`Data WAL write payload too small`,t);let r=E(i,2),a=E(i,6),o=O(i,10,t),s=E(i,18),c=22+a+s;if(e.length!==c)throw new w(`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 w(`Data WAL truncate payload too small`,t);let r=E(i,2),a=E(i,6),o=O(i,10,t);if(e.length!==18+a)throw new w(`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 w(`Data WAL delete payload too small`,t);let r=E(i,2),a=E(i,6);if(e.length!==10+a)throw new w(`Data WAL delete payload length mismatch`,t);return{version:n,op:`delete`,inodeId:r,path:ne.decode(e.subarray(10))||void 0}}throw new w(`Unknown data WAL opcode: ${r}`,t)}function se(e,t,n=0){let r=[],i=[],a=n;for(;a+S<=e.length;){let n=a,o=new DataView(e.buffer,e.byteOffset+a,S),s=E(o,0),c=E(o,4);if(a+=S,s===0&&c===0&&e.subarray(a).every(e=>e===0))return{records:r,frameEnds:i,parsedBytes:n,hadPartialTail:!0};if(a+s>e.length)return de(e,n+1,t)?{records:r,frameEnds:i,parsedBytes:n,hadPartialTail:!1,corruptionOffset:n}:{records:r,frameEnds:i,parsedBytes:n,hadPartialTail:!0};let l=e.subarray(a,a+s);if(k(l)!==c)return de(e,n+1,t)?{records:r,frameEnds:i,parsedBytes:n,hadPartialTail:!1,corruptionOffset:n}:{records:r,frameEnds:i,parsedBytes:n,hadPartialTail:!0};let u;if(t)try{u=t.open(l,m.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 w)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}}var ce=10,le=67108864;function ue(e,t,n){if(n<ce||e[t]!==C)return!1;let r=new DataView(e.buffer,e.byteOffset+t,n),i=e[t+1];return i===1?n>=22&&n===22+E(r,6)+E(r,18):i===2?n>=18&&n===18+E(r,6):i===3&&n===10+E(r,6)}function de(e,t,n){let r=le,i=n?n.overheadBytes+ce:0;for(let a=t;a+S<=e.length;a++){let t=new DataView(e.buffer,e.byteOffset+a,S),o=E(t,0),s=a+S,c=s+o;if(c>e.length)continue;if(n){if(o<i)continue;if(r-=o,r<0)return!1}else if(!ue(e,s,o))continue;let l=e.subarray(s,c);if(k(l)===E(t,4))try{return oe(n?n.open(l,m.dataWal,a):l,a),!0}catch{}}return!1}function fe(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 pe(e){if(e.includes(`\\0`))throw b(`EINVAL`,e,`Path contains NUL byte`);return e.split(`/`).filter(e=>e!==``)}function A(e){let t=pe(e),n=t[t.length-1];return{path:`/${t.join(`/`)}`,requiresDirectory:e.length>1&&e.endsWith(`/`)||n===`.`||n===`..`}}function j(e){if(e===`/`)return`/`;let t=e.lastIndexOf(`/`);return t<=0?`/`:e.substring(0,t)}function M(e){if(e===`/`)return`/`;let t=e.lastIndexOf(`/`);return t<0?e:e.substring(t+1)}var me=1112950355,he=1,ge=2,N=3,_e=4,ve=5,ye=new TextEncoder,be=10,P=40,xe=48,Se=12,Ce=16,we=4,Te=10,Ee=4294967295,De=2147483648,Oe=33188,ke=16877,Ae=41471;function je(e){let t=e.kind===`symlink`?2:+!!e.isDir;return e.mode<<2|t}function Me(e){let t=e&3;return t===1?`dir`:t===2?`symlink`:`file`}function Ne(e,t){let n=e>>>2;return n===0?t===`dir`?ke:t===`symlink`?Ae:Oe:n}function Pe(e,t){let n=t&61440;return e===`dir`?n===16384:e===`symlink`?n===40960:n===32768}function Fe(e){let t=Me(e),n=Ne(e,t);if(Pe(t,n))return{kind:t,mode:n};throw Error(`Unsupported metadata log flags: 0x${e.toString(16)}`)}function Ie(e){return e===void 0?0:Math.floor(e/1e3)}function F(e){return e===0?void 0:e*1e3}function Le(e){let t=e.mtimeMs??e.timestampMs,n=e.atimeMs??t??e.ctimeMs,r=e.ctimeMs??t??n;return{atime:Ie(n),mtime:Ie(t),ctime:Ie(r)}}function Re(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?De:0),words:n?1+t*2:e.length}}function ze(e,t,n,r){if(!(r&De)){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 Be(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&De);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 Ve(e,t){if(!t)return Array.from(e.keys()).sort();let n=/* @__PURE__ */ new Set,r=[],i=!1;for(let a of t)!e.has(a)||n.has(a)?i=!0:(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 He(e,t,n,r,i){let a=Ve(e,r),o=/* @__PURE__ */ 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])=>Re(e.blocks)),h=Array(c).fill(0),g=Array(u);for(let e=0;e<c;e++){let[,t]=s[e];if(t.size>Ee)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(M(l[e])).byteLength;g[e]=t,f+=t}let _=P+c*xe,v=_+p*4,y=v+u*Ce,b=y+f,x=new ArrayBuffer(b),S=new DataView(x),C=new Uint32Array(x,0,(v>>>2)+u*we),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]=me,C[1]=be,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=Te+e*Se,i=Le(n),a=n.kind===`symlink`;C[r+0]=t,C[r+1]=je(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&&ze(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 O=v>>>2;for(let t=0;t<u;t++){let n=l[t],r=e.get(n),i=e.get(j(n));if(!i)throw Error(`Missing parent inode for path ${n}`);if(!i.isDir)throw Error(`Parent of ${n} is not a directory`);let a=O+t*we,o=M(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 Ue(e){let t=new Uint8Array(e),n=new TextDecoder;if(e.byteLength<P)throw Error(`Corrupted binary metadata: buffer too small (${e.byteLength} < ${P})`);let r=new DataView(e,0,P),i=r.getUint32(0,!0);if(i!==me)throw Error(`Invalid binary metadata magic: 0x${i.toString(16)}`);let a=r.getUint32(4,!0);if(a!==be)throw new x(`format-version`,`Unsupported binary metadata version: ${a} (this build expects ${be})`);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=P,h=m+c*xe;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*Ce>p)throw Error(`Corrupted binary metadata: directory entries overlap string table`);let g=/* @__PURE__ */ new Map,_=1;for(let r=0;r<c;r++){let i=m+r*xe,a=new DataView(e,i,xe),o=a.getUint32(0,!0),c=a.getUint32(4,!0),l=Me(c),u=a.getUint32(8,!0),d=a.getUint32(12,!0),v=a.getUint32(16,!0),y=a.getUint32(20,!0),b=F(a.getUint32(24,!0)),x=F(a.getUint32(28,!0)),S=F(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=Be(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:Ne(c,l),nlink:y||1,atimeMs:b,mtimeMs:x,ctimeMs:S,timestampMs:x}),_=Math.max(_,o)}let v=/* @__PURE__ */ new Map;for(let r=0;r<l;r++){let i=f+r*Ce,a=new DataView(e,i,Ce),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=/* @__PURE__ */ new Map,b=/* @__PURE__ */ 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(b.has(t))throw Error(`Corrupted binary metadata: directory inode ${t} linked twice`);b.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 We(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,ge,!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=Re(t.blocks),l=12+c.words*4+4+a+20,u=Le(t),d=12+r.byteLength+l,f=new ArrayBuffer(d),p=new DataView(f),m=new Uint8Array(f);p.setUint32(0,he,!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,je(t),!0),h+=4,p.setUint32(h,t.size,!0),h+=4,p.setUint32(h,c.count,!0),h+=4,h=ze(p,h,t.blocks,c.count),p.setUint32(h,o,!0),h+=4,i&&(m.set(s??/* @__PURE__ */ 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 Ge(e,t){let n=ye.encode(e),r=new ArrayBuffer(12+n.byteLength+28),i=new DataView(r),a=new Uint8Array(r);i.setUint32(0,ve,!0),i.setUint32(4,n.byteLength,!0),i.setUint32(8,28,!0),a.set(n,12);let o=12+n.byteLength,s=Le(t);return i.setUint32(o,je(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 Ke(e,t){let n=/* @__PURE__ */ 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 qe(e,t){let n=/* @__PURE__ */ new ArrayBuffer(20),r=new DataView(n);return r.setUint32(0,_e,!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 Je(e,t,n,r=0,i=0,a=0){let o=Ke(N,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,m.metaLog,t>>>0):c,f=o.byteLength+d.byteLength,p=new Uint8Array(f);p.set(o,0),p.set(d,o.byteLength);let h=qe(t,k(p)),g=new Uint8Array(f+h.byteLength);return g.set(p,0),g.set(h,f),g}function Ye(e){return{...e,blocks:[...e.blocks],children:[...e.children]}}function Xe(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 Ze(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 Qe(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&&Ze(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?(Xe(t,e.inode),s=t):s=Ye(e.inode),r.set(o,s)}else i?(Xe(i,e.inode),s=i):s=Ye(e.inode);if(t.set(e.path,s),i&&i!==s&&Ze(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 $e(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!==he&&a!==ge&&a!==ve||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===ge)return s===0?{mutation:{kind:`delete`,path:c},nextOffset:l}:null;if(a===ve){if(s!==28)return null;let t=r+12+o,{kind:n,mode:i}=Fe(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=F(e.getUint32(t,!0));t+=4;let p=F(e.getUint32(t,!0));t+=4;let m=F(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}=Fe(e.getUint32(d,!0));d+=4;let m=e.getUint32(d,!0);d+=4;let h=e.getUint32(d,!0);d+=4;let g=Be(e,d,h,u-24,i);d+=h&De?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=F(e.getUint32(d,!0));d+=4;let S=F(e.getUint32(d,!0));d+=4;let C=F(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 et(e,t){for(let n=t;n+16<=e.byteLength;n++){let t=e.getUint32(n,!0);if(t!==N&&t!==_e)continue;let r=e.getUint32(n+4,!0),i=e.getUint32(n+8,!0);if(r===0&&(t===N?i===4:i===8))return n}return-1}function tt(e,t,n,r,i=0,a){if(a)return nt(e,t,n,r,i,a);let o=new DataView(e),s=new Uint8Array(e),c=new TextDecoder,l=/* @__PURE__ */ 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)===N&&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===_e){y+20<=e.byteLength&&o.getUint32(y+4,!0)===0&&o.getUint32(y+8,!0)===8&&o.getUint32(y+12,!0)===a&&k(s.subarray(u,y))===o.getUint32(y+16,!0)&&(b=y+20);break}if(t===N)break;if(h!==i){if(t!==he&&t!==ge&&t!==ve)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=$e(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)Qe(e,t,n,l);m+=v.length,f=g,p=_,u=b,d=b}return{count:m,validEnd:d,physicalDataSize:f,logicalExtent:p}}function nt(e,t,n,r,i,a){let o=new DataView(e),s=new Uint8Array(e),c=new TextDecoder,l=/* @__PURE__ */ 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,h=0;for(;u+16<=e.byteLength;){let g=o.getUint32(u+12,!0);if(o.getUint32(u,!0)!==N||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=et(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===_e&&r===8&&i===g&&t+20<=e.byteLength){v=t;break}if(n===N&&t!==u)break;y=t+1}if(v<0)break;let b=o.getUint32(v+16,!0);if(k(s.subarray(u,v))!==b)break;let x=s.subarray(_,v),S;try{S=a.open(x,m.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:p,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,O=[],ee=!0;for(;D+12<=S.byteLength;){let e=$e(C,S,c,D,r);if(!e){ee=!1;break}O.push(e.mutation),D=e.nextOffset}if(!ee||D!==S.byteLength)break;for(let e of O)Qe(e,t,n,l);h+=O.length,f=T,p=E,u=v+20,d=u}return{count:h,validEnd:d,physicalDataSize:f,logicalExtent:p}}var rt=class extends x{constructor(e){super(`meta-snapshot`,e??`Meta snapshot is corrupt`),this.name=`MetaSnapshotCorruptionError`}},it=1397637456,I=16,at=(()=>{let e=/* @__PURE__ */ 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 ot(e){let t=4294967295;for(let n=0;n<e.length;n++)t=at[(t^e[n])&255]^t>>>8;return(t^4294967295)>>>0}function st(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,m.snapshot,t>>>0):a,c=new Uint8Array(I+s.length),l=new DataView(c.buffer);return l.setUint32(0,it,!0),l.setUint32(4,t>>>0,!0),l.setUint32(12,s.length,!0),c.set(s,I),l.setUint32(8,ot(c.subarray(16)),!0),c}function ct(e,t){if(e.length<I)return null;let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(n.getUint32(0,!0)!==it)return null;let r=n.getUint32(4,!0),i=n.getUint32(8,!0),a=n.getUint32(12,!0);if(I+a>e.length)return null;let o=e.subarray(I,I+a);if(ot(o)!==i)return null;let s;try{s=t?t.open(o,m.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 lt=16777216,ut=/* @__PURE__ */ new Set([`create`,`update`,`delete`]),dt=/* @__PURE__ */ new Set([`SUBSCRIPTION_OVERFLOW`,`SUBSCRIPTION_INTERRUPTED`,`SUBSCRIPTION_CALLBACK_FAILED`,`SUBSCRIPTION_RESYNC_REQUIRED`]),ft=/* @__PURE__ */ new Set([`disabled`,`deleted`,`not-file`,`too-large`,`unavailable`]),L=(e,t,n=Reflect.ownKeys(e))=>n.length===t.length&&n.every(e=>typeof e==`string`&&t.includes(e)),pt=(e,t,n,r=Reflect.ownKeys(e))=>t.every(e=>r.includes(e))&&r.every(e=>typeof e==`string`&&[...t,...n].includes(e)),mt=e=>!!e&&typeof e==`object`&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype,ht=e=>typeof e==`string`&&e.length>0&&e.length<=128,gt=e=>typeof e==`string`&&!e.includes(`\\0`);function _t(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 R=e=>Object.freeze(e);function vt(e,t){if(!Number.isSafeInteger(t)||t<0)throw b(`EINVAL`,void 0,`Invalid file change command`);let n=!1;try{if(!mt(e))throw Error();let r=Reflect.ownKeys(e),i=e.type,a=e.subscriptionId;if(!ht(a))throw Error();if(i===`register`&&L(e,[`type`,`subscriptionId`,`options`],r)){let r=e.options;if(!mt(r)||!pt(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(!gt(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=>!ut.has(e))||new Set(f).size!==f.length)throw Error();let p,m;if(l!==void 0){if(!mt(l)||!L(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(!mt(u)||!L(u,[`maxBytes`],Reflect.ownKeys(u)))throw Error();let e=u.maxBytes;if(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0||e>lt)throw Error();h=e}let g=512+_t(a,t-512);if(g+=_t(i,t-g),p!==void 0&&(g+=_t(p,t-g),g+=_t(m,t-g)),g>t)n=!0;else return{command:R({type:`register`,subscriptionId:a,options:R({path:i,scope:o,recursive:s,events:R(f),...p===void 0?{}:{match:R({source:p,flags:m})},content:h!==!1&&R({maxBytes:h})})}),charge:g}}if((i===`activate`||i===`cancel`||i===`terminal-ack`)&&L(e,[`type`,`subscriptionId`],r))return{command:R({type:i,subscriptionId:a}),charge:0};if(i===`ack`&&L(e,[`type`,`subscriptionId`,`deliveryId`],r)){let t=e.deliveryId;if(typeof t==`number`&&Number.isSafeInteger(t)&&t>0)return{command:R({type:i,subscriptionId:a,deliveryId:t}),charge:0}}}catch{}throw n?b(`ENOSPC`,void 0,`File change command is too large`):b(`EINVAL`,void 0,`Invalid file change command`)}function yt(e,t){if(!t||typeof t!=`object`||Array.isArray(t))return!1;let n=t;return e.type===`register`?L(n,[`type`,`subscriptionId`])&&n.type===`registered`&&n.subscriptionId===e.subscriptionId:L(n,[`type`])&&n.type===`ok`}function bt(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return;let n=e;if(n.type===`terminal`&&L(n,[`type`,`subscriptionId`,`code`])&&ht(n.subscriptionId)&&typeof n.code==`string`&&dt.has(n.code))return R({type:`terminal`,subscriptionId:n.subscriptionId,code:n.code});if(n.type===`closed`&&L(n,[`type`,`subscriptionId`])&&ht(n.subscriptionId))return R({type:`closed`,subscriptionId:n.subscriptionId});if(n.type!==`event`||!L(n,[`type`,`subscriptionId`,`deliveryId`,`change`])||!ht(n.subscriptionId)||!Number.isSafeInteger(n.deliveryId)||n.deliveryId<=0)return;let r=n.change;if(!r||typeof r!=`object`||Array.isArray(r)||!L(r,[`type`,`path`,`kind`,`cursor`,`content`]))return;let i=r;if(!ut.has(i.type)||!gt(i.path)||i.kind!==`file`&&i.kind!==`directory`&&i.kind!==`symlink`)return;let a=i.cursor;if(!a||typeof a!=`object`||Array.isArray(a)||!L(a,[`generation`,`sequence`])||!ht(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`&&L(s,[`status`,`bytes`])&&s.bytes instanceof Uint8Array&&s.bytes.byteLength<=lt)c=R({status:`included`,bytes:s.bytes});else if(s.status===`omitted`&&L(s,[`status`,`reason`])&&typeof s.reason==`string`&&ft.has(s.reason))c=R({status:`omitted`,reason:s.reason});else return;return R({type:`event`,subscriptionId:n.subscriptionId,deliveryId:n.deliveryId,change:R({type:i.type,path:i.path,kind:i.kind,cursor:R({generation:a.generation,sequence:a.sequence}),content:c})})}var xt=/* @__PURE__ */ new WeakMap,St=/* @__PURE__ */ new WeakMap,Ct=/* @__PURE__ */ new WeakMap,wt=/* @__PURE__ */ new WeakSet,Tt=e=>wt.add(e),Et=e=>wt.has(e),Dt=/* @__PURE__ */ new Set([`id`,`contractVersion`,`compatibilityKey`,`requiredOpenMode`,`options`]),Ot=[`error-details`,`persistence-status`],kt=e=>typeof e==`string`&&/^[a-z][a-z0-9.-]*$/.test(e),At=e=>typeof e==`object`&&!!e&&!Array.isArray(e),jt=(e,t)=>Reflect.ownKeys(e).every(e=>t.has(String(e)));function Mt(e,t,n){let r=e=>{throw b(`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=/* @__PURE__ */ new Set;for(let e of i){At(e)&&jt(e,Dt)&&Object.hasOwn(e,`options`)||r(`Invalid plugin request`);let{id:n,contractVersion:i,compatibilityKey:s,requiredOpenMode:c,options:l}=e;kt(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:Nt(a)}}function Nt(e){return{version:2,capabilities:[...new Set(Ot)].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 Pt=/* @__PURE__ */ new WeakMap,Ft=/* @__PURE__ */ new Set([`.vault`,`.crypt`,`.crypt.log`]),It=/* @__PURE__ */ new Set([`id`,`contractVersion`,`compatibilityKey`,`requiredOpenMode`,`storage`,`logicalChanges`]),Lt=/* @__PURE__ */ new Set([`factory`,`sidecars`]),Rt=/* @__PURE__ */ new WeakSet,zt=/* @__PURE__ */ new WeakSet,Bt=/* @__PURE__ */ new WeakSet,Vt=(e,t)=>Reflect.ownKeys(e).every(e=>typeof e==`string`&&t.has(e));function Ht(e,t,n){if(e===void 0)return[];let r=e=>{throw b(`EINVAL`,n,e)};Array.isArray(e)||r(`Plugins must be an array`);let i=[],a=/* @__PURE__ */ new Set,o=/* @__PURE__ */ new Set,s=0,c=0;for(let n of e){typeof n==`object`&&n||r(`Invalid configured plugin`);let e=n;Vt(e,It)||r(`Unsupported plugin contribution`);let{id:l,contractVersion:u,compatibilityKey:d,requiredOpenMode:f,storage:p,logicalChanges:m}=e;kt(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)&&Vt(p,Lt)||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=>!Ft.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)&&Vt(m,/* @__PURE__ */ 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 Ut(e,t){for(let n of e){let e=n.storage?n.storage.factory:n.logicalChanges.create,r=n.logicalChanges?.source;if(Rt.has(n.source)||zt.has(e)||r&&Bt.has(r))throw b(`EINVAL`,t,`Configured plugin already mounted: ${n.id}`);Rt.add(n.source),zt.add(e),r&&Bt.add(r)}}function Wt(e,t){for(let n of e){let e=n.storage?n.storage.factory:n.logicalChanges.create,r=n.logicalChanges?.source;if(Rt.has(n.source)||zt.has(e)||r&&Bt.has(r))throw b(`EINVAL`,t,`Configured plugin already mounted: ${n.id}`)}}function Gt(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 Kt=[`.bin`,`.meta.a`,`.meta.b`,`.bitmap`,`.meta.log`,`.data.log`,`.bootstrap`,`.vault`,`.crypt`,`.crypt.log`,`.meta`,`.importing`],qt=class extends Error{code=`VOLUME_IMPORTING`;constructor(e){super(`Volume ${e} has an incomplete import`),this.name=`VolumeImportingError`}};function Jt(e){if(typeof e!=`string`||!e.endsWith(`.bin`)||e.length<=4||/[/\\\\]/.test(e))throw b(`EINVAL`,e,`Volume name must be a basename ending in .bin`);return Kt.map(t=>e.slice(0,-4)+t)}function Yt(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`NotFoundError`}async function Xt(e,t){for(let n of t)try{return await e.getFileHandle(n,{create:!1}),n}catch(e){if(!Yt(e))throw e}}var Zt=/* @__PURE__ */ new Map;async function Qt(e){return await Zt.get(e),new Promise((t,n)=>{let r=navigator.locks.request(`opfs-vfs-volume-${e}`,{ifAvailable:!0},async n=>{if(!n)throw b(`EBUSY`,e,`Volume is in use`);await new Promise(n=>{let i=!1;t(()=>{if(!i){i=!0,Zt.set(e,r);let t=()=>{Zt.get(e)===r&&Zt.delete(e)};r.then(t,t),n()}return r})})});r.catch(n)})}async function $t(e){try{await e.closeVfs()}catch(t){try{await e.closeVfs()}catch{}throw t}}var en=e=>{try{return new DataView(e),!0}catch{return!1}},z=4096,tn=16384,nn=new Uint8Array(z),rn=new TextEncoder,an=1<<20;function on(e,t){return 256+_t(e,t-256)}var sn=(e,t)=>e===`/`||t===e||t.startsWith(`${e}/`),cn=e=>{let t=0;for(let n=0;n<e.length;n++)e.charCodeAt(n)===47&&t++;return e===`/`?0:t},ln=(e,t)=>e<t?-1:+(e>t),un=(e,t)=>e.record.deletePhase-t.record.deletePhase||t.depth-e.depth||ln(e.record.path,t.record.path),dn=(e,t)=>e.depth-t.depth||ln(e.record.path,t.record.path),fn=(e,t)=>ln(e.path,t.path),pn=e=>e instanceof Error&&v(e.code),mn=4294967295,hn=255,gn=864e5,_n=4194304;function vn(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.name===`QuotaExceededError`||t.code===22}var yn=1112950355,bn=1,xn=1,Sn=2,Cn=32,wn=12;function Tn(e){let t=2166136261;for(let n=0;n<e.length;n++)t=Math.imul(t^e.charCodeAt(n),16777619);return t>>>0}var En=33188,Dn=16877,On=41471,kn=3,An=292,jn=146,Mn=73,Nn=32768,Pn=16384,Fn=40960,In=40,Ln=/* @__PURE__ */ 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}({}),Rn=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)r<0||r>=this.totalBlocks?n?.(r):(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 zn(e,t=En){let n=Date.now();return{ino:e,kind:`file`,isDir:!1,size:0,blocks:[],children:[],mode:Nn|t&4095,nlink:1,atimeMs:n,mtimeMs:n,ctimeMs:n,timestampMs:n}}function Bn(e,t=Dn){let n=Date.now();return{ino:e,kind:`dir`,isDir:!0,size:0,blocks:[],children:[],mode:Pn|t&4095,nlink:2,atimeMs:n,mtimeMs:n,ctimeMs:n,timestampMs:n}}function Vn(e,t,n=On){let r=Date.now();return{ino:e,kind:`symlink`,isDir:!1,size:rn.encode(t).byteLength,blocks:[],children:[],symlinkTarget:t,mode:Fn|n&4095,nlink:1,atimeMs:r,mtimeMs:r,ctimeMs:r,timestampMs:r}}function B(e){return e.kind===`symlink`||(e.mode&61440)==40960&&!e.isDir}function Hn(e){let t=e&kn;return t===0||t===2}function Un(e){let t=e&kn;return t===1||t===2}var Wn=/* @__PURE__ */ new WeakMap;async function Gn(e,t,n){let r=t.replace(/\\.bin$/,`.importing`),i;try{i=await e.getFileHandle(r,{create:!1})}catch(e){if(!Yt(e))throw e;if(n)throw new qt(t);return}if(!n||n.length!==16)throw new qt(t);try{await e.getFileHandle(t,{create:!1})}catch(e){throw Yt(e)?new qt(t):e}let a=await i.getFile();if(a.size!==16||!new Uint8Array(await a.arrayBuffer()).every((e,t)=>e===n[t]))throw new qt(t)}var Kn=class{dataHandle;logHandle;dataLogHandle;bootstrapHandle;flushedDataSize=0;flushedLogicalExtent=0;committedLogicalExtent=0;metaHandleA;metaHandleB;activeMetaSlot=0;metaSnapshotSequence=0;logOffset=0;lastSnapshotSize=0;metaLogFlushPending=!1;metaLogWriteFailed=!1;dataLogOffset=0;dataWalTruncatePending=!1;dataWalCycleSealer;dirtyInodes=/* @__PURE__ */ new Set;attrDirtyInodes=/* @__PURE__ */ new Set;deletedInodes=/* @__PURE__ */ new Set;inodes;inodeTable=/* @__PURE__ */ new Map;dirEntries=/* @__PURE__ */ new Map;pathIndex=/* @__PURE__ */ new Map;inoToPaths=/* @__PURE__ */ new Map;bitmap;pendingFree=/* @__PURE__ */ new Set;zeroBuffer=null;sortedPaths=[];fileData=/* @__PURE__ */ new Map;openFiles=/* @__PURE__ */ new Map;nextFd=10+(crypto.getRandomValues(/* @__PURE__ */ new Uint32Array(1))[0]>>>2);totalBlocks=tn;dirtyPages=/* @__PURE__ */ new Map;persistedSize=/* @__PURE__ */ new WeakMap;pendingDeletedInodes=/* @__PURE__ */ 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;mountCorruption;reportMountCorruption(e){this.mountCorruption?this.mountCorruption.message+=`; ${e.message}`:this.mountCorruption=e}failureRevision=0;retainedFailure;persistenceListener;wrapSyncAccessHandle;volumeIdentity;firstMountAncillarySidecarsWereEmpty=!1;storageFactory;storageSidecars;logicalChanges;logicalSession;logicalSessionClosed=!1;logicalChangesPoisoned=!1;logicalCaptureToken;logicalCaptureBuffers=/* @__PURE__ */ new WeakSet;logicalDeliveryBuffers=/* @__PURE__ */ new WeakSet;logicalSequence=0;logicalOperation;changeGeneration;directChangeClientId=crypto.randomUUID();changeChannels=/* @__PURE__ */ new Map;changeChannelCounts=/* @__PURE__ */ new Map;pendingChangeChannels=/* @__PURE__ */ new Set;changeSubscriptionIds=/* @__PURE__ */ new Map;changeSubscriptionCount=0;changeTerminalIds=/* @__PURE__ */ new Set;get recordingLogicalChanges(){return!!this.logicalSession&&!this.logicalChangesPoisoned&&this.changeSubscriptionCount>0}constructor(e,t){if(t&&`encryption`in t)throw b(`EINVAL`,e,`Use the premium package for encryption options`);if(t&&`storageFactory`in t)throw b(`EINVAL`,e,`Use plugins instead of storageFactory`);this.openMode=t?.openMode??`open-or-create`;let n=(t&&Pt.get(t))??Ht(t?.plugins,this.openMode,e);t&&Pt.delete(t),Ut(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&&xt.get(t))??crypto.randomUUID(),St.set(this,{open:(e,t,n,r,i,a)=>this.openFileChangeChannelForClient(e,t,n,r,i,a)}),Ct.set(this,{read:()=>({state:this.localPersistenceState,failure:this.retainedFailure,failureRevision:this.failureRevision,salvage:this.lastSalvage}),watch:e=>{this.persistenceListener=e}}),this.volumeIdentity=Tn(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,mn):mn;let o=e=>e!==void 0&&Number.isSafeInteger(e)&&e>=0?e:void 0;this.maxNameLength=o(t?.maxNameLength)??hn,this.maxPathDepth=o(t?.maxPathDepth),this.maxFiles=o(t?.maxFiles),this.maxTotalBytes=o(t?.maxTotalBytes);let s=t&&Wn.get(t);t&&Wn.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:this.mountCorruption}}initializing=!0;closeRequested=!1;closing;releaseVolumeLock;async init(e,t){let n=[];try{let r=Jt(e);if(![`open-or-create`,`create-new`,`open-existing`].includes(this.openMode))throw b(`EINVAL`,e,`Unknown volume open mode`);if(this.releaseVolumeLock=await Qt(e),this.closeRequested)throw b(`EBADF`,e,`Volume closed during initialization`);let i=await navigator.storage.getDirectory();if(await Gn(i,e,t),this.openMode===`create-new`&&await Xt(i,r))throw b(`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 h(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 Gt(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 Xt(i,r.slice(1))))throw b(`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 m=e.replace(/\\.bin$/,`.data.log`),g=await i.getFileHandle(m,{create:!0});if(this.dataLogHandle=await o(g,`dataLog`),this.bufferMode===`disk`&&this.dataLogHandle.getSize()>0)throw b(`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 y=this.hasFirstMountMarker(),x=this.loadMetaSnapshotPayload(a),S=x===null&&this.logHandle.getSize()===0;if(x){let e=Ue(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()).sort(),this.bitmap=new Rn(this.totalBlocks)}else this.bitmap=new Rn(tn),this.inodes=/* @__PURE__ */ new Map,this.inodes.set(`/`,Bn(1)),this.nextInodeNumber=2,this.sortedPaths=[`/`],S&&(this.beginFirstMount(),this.storage?.beforeDataCommit?.(),this.writeMeta(!0),this.finishFirstMount());let C=x!==null&&y;this.logOffset=0;let w=0,T=this.logHandle.getSize();if(T>0){let e=new Uint8Array(T);this.logHandle.read(e,{at:0});let t=tt(e.buffer,this.inodes,this.sortedPaths,this.totalBlocks,this.metaSnapshotSequence,this.sealer);if(t.generationMismatch===`newer`){let e=new rt(`Meta log generation is newer than the readable snapshot ${this.metaSnapshotSequence}`);if(this.recoveryMode===`fail-stop`)throw e;e.message+=`; mounted that older snapshot and dropped the newer log`,this.reportMountCorruption(e)}w=t.count;let n=t.validEnd;n<T&&(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)}w>0&&this.reattachDetachedPaths(),this.normalizeLoadedInodes(),this.rebuildIndexesFromPathMap(),this.storage?.validateAfterMetadata?.([...new Set(this.inodes.values())].some(e=>!e.isDir&&!B(e)&&e.blocks.some(e=>e!==0))),this.hydrateMemoryFileData(),this.replayDataWal();let E=this.bufferMode===`disk`&&this.reconcileDiskState();if(this.rebuildBitmapFromMetadata(),E)try{this.flushVfs()}catch(e){this.logWalDebug(`reconcileDiskState repair flush failed`,e)}if(this.mountCorruption&&this.setLocalPersistenceState(`error`,this.mountCorruption),C&&this.finishFirstMount(),this.closeRequested)throw b(`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(/* @__PURE__ */ TypeError(`Storage setup has finished`));if(!this.storageSidecars.includes(r))return Promise.reject(/* @__PURE__ */ 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 b(`EINVAL`,e,`Record codecs require both WAL cycle hooks`);this.dataHandle=Gt(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(Cn),n=new DataView(t.buffer);return n.setUint32(0,yn,!0),n.setUint32(4,bn,!0),n.setUint32(8,e,!0),n.setUint32(12,this.volumeIdentity,!0),t.set(crypto.getRandomValues(new Uint8Array(wn)),16),n.setUint32(28,k(t.subarray(0,28)),!0),t}firstMountMarkerState(){if(this.bootstrapHandle.getSize()!==Cn)return null;let e=new Uint8Array(Cn);if(this.bootstrapHandle.read(e,{at:0})!==e.byteLength)return null;let t=new DataView(e.buffer);if(t.getUint32(0,!0)!==yn||t.getUint32(4,!0)!==bn||t.getUint32(12,!0)!==this.volumeIdentity||t.getUint32(28,!0)!==k(e.subarray(0,28)))return null;let n=t.getUint32(8,!0);return n===xn||n===Sn?n:null}hasFirstMountMarker(){return this.firstMountMarkerState()===xn}beginFirstMount(){let e=this.firstMountMarker(xn);this.bootstrapHandle.truncate(0),this.writeAll(this.bootstrapHandle,e,0,`first-mount intent`),this.bootstrapHandle.flush()}finishFirstMount(){let e=this.firstMountMarker(Sn);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:ct(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 rt(`Meta snapshot present but unreadable (slotA=${n.size}B, slotB=${r.size}B); no valid checksum and no usable fallback.`)}if(e)throw new x(`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 rt(`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/z),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||B(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*z,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}reattachDetachedPaths(){let e=!1,t=[];for(;;){let n=/* @__PURE__ */ new Set;for(let t of this.sortedPaths){if(t===`/`)continue;let r=j(t);for(;r!==`/`&&!this.inodes.has(r);)r=j(r),e=!0;(n.has(r)||this.inodes.get(r)?.isDir===!1)&&n.add(t)}if(n.size===0)break;let r=e=>this.inodes.has(e)||this.sortedPaths.some(t=>t.startsWith(`${e}/`)),i=`/lost+found`;for(let e=2;r(i);e++)i=`/lost+found-${e}`;for(let e of n)this.inodes.set(i+e,this.inodes.get(e)),this.inodes.delete(e);this.sortedPaths=Array.from(this.inodes.keys()).sort();let a=[...n];t.push(`Moved ${a.length} entr${a.length===1?`y`:`ies`} that sat under a non-directory to ${i}: `+a.slice(0,8).join(`, `)+(a.length>8?`, …`:``))}if(!e&&t.length===0)return;let n=/* @__PURE__ */ new Set;for(let e of this.inodes.keys())for(let t=j(e);t!==`/`&&!this.inodes.has(t);t=j(t))n.add(t);let r=this.nextInodeNumber;for(let e of this.inodes.values())r=Math.max(r,e.ino+1);for(let e of n)this.inodes.set(e,Bn(r++));if(this.nextInodeNumber=r,n.size>0){let e=[...n].sort();t.push(`Recreated ${e.length} missing parent director${e.length===1?`y`:`ies`}: `+e.slice(0,8).join(`, `)+(e.length>8?`, …`:``))}this.sortedPaths=Array.from(this.inodes.keys()).sort(),this.dirtyStructure=!0,this.reportMountCorruption(new x(`meta-log`,`Repaired entries an earlier release left detached. ${t.join(`. `)}`)),this.logWalDebug(`reattached detached paths`,{findings:t})}rebuildBitmapFromMetadata(){let e=/* @__PURE__ */ new Set,t=[],n=-1;for(let r of this.inodes.values())if(!(r.isDir||B(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.reportMountCorruption(new x(`meta-snapshot`,`${r} data block(s) are claimed by more than one file; their contents may belong to another file`)),this.logWalDebug(`rebuildBitmapFromMetadata detected double-claimed blocks`,{doubleClaims:r,totalBlocks:this.totalBlocks}))}hydrateMemoryFileData(){if(this.bufferMode!==`memory`)return;this.fileData.clear();let e=/* @__PURE__ */ new Map;for(let[t,n]of this.inodes){if(n.isDir||B(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*z);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),this.persistedSize.set(n,n.size)}}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);if(this.dataLogHandle.read(t,{at:0}),t.every(e=>e===0)){this.dataLogHandle.truncate(0),this.dataLogHandle.flush(),this.dataLogOffset=0,this.setLocalPersistenceState(`clean`);return}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=fe({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 w(`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/z>>>0,i=(t+n-1)/z>>>0,a=this.dirtyPages.get(e);a||(a=/* @__PURE__ */ 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=/* @__PURE__ */ new Set,this.dirtyPages.set(e,r));for(let e=Math.floor(t/z);e<Math.ceil(n/z);e++)r.add(e)}applyReplayWrite(e,t,n){this.ensureDerivedIndexes();let r=this.inodeTable.get(e);if(!r||r.isDir||B(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)??/* @__PURE__ */ 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||B(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)??/* @__PURE__ */ 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=On){return this.recordingLogicalChanges?this.withLogicalOperation(()=>this.symlinkSyncImpl(e,t,n)):this.symlinkSyncImpl(e,t,n)}symlinkSyncImpl(e,t,n){if(e.length===0)throw b(`ENOENT`,t,`Empty symlink target`);if(e.includes(`\\0`))throw b(`EINVAL`,t,`Symlink target contains NUL byte`);if(rn.encode(e).byteLength>=4096)throw b(`ENAMETOOLONG`,t);let r=A(t),i=this.resolveInodePath(r.path,!1);if(this.hasPathEntry(i))throw b(`EEXIST`,i);let a=this.resolveInodePath(j(i),!0),o=M(i),s=this.getInodeByPath(a);if(!s)throw b(`ENOENT`,a);if(!s.isDir)throw b(`ENOTDIR`,a);this.assertSearchablePath(a,!0),this.assertDirectoryWritable(a,s),this.assertNameWithinQuota(i),this.assertFileCountWithinQuota(i),this.impact(i,!1);let c=Vn(this.nextInodeNumber++,e,n);this.addDirEntry(s,o,c),this.linkInodePath(i,c),Jn(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=A(e),n=this.resolveInodePath(t.path,!1),r=this.getInodeByPath(n);if(!r)throw b(`ENOENT`,n);if(!B(r))throw b(`EINVAL`,n,`Path is not a symbolic link`);return this.assertSearchablePath(n,!1),this.touchInodeAccess(n,r),r.symlinkTarget??``}realpathSync(e){let t=A(e),n=this.resolveInodePath(t.path,!0),r=this.getInodeByPath(n);if(!r)throw b(`ENOENT`,n);return this.assertSearchablePath(n,r.isDir),n}resolveInodePath(e,t){if(this.closed)throw b(`EBADF`,e,`Volume is closed`);let n=e.split(`/`).filter(Boolean).reverse(),r=`/`,i=this.getInodeByPath(`/`),a=0;for(;n.length>0;){let e=n.pop();if(!i){if(e===`.`||e===`..`)throw b(`ENOENT`,r);r=r===`/`?`/${e}`:`${r}/${e}`;continue}if(!i.isDir)throw b(`ENOTDIR`,r);if(this.assertDirectoryExecutable(r,i),e===`.`)continue;if(e===`..`){r=j(r),i=this.getInodeByPath(r);continue}let o=this.lookupChild(r,i,e);if(o.inode&&B(o.inode)&&(t||n.length>0)){if(++a>In)throw b(`ELOOP`,o.path);let e=o.inode.symlinkTarget??``;e.startsWith(`/`)&&(r=`/`,i=this.getInodeByPath(`/`));let t=e.split(`/`).filter(Boolean);for(let e=t.length-1;e>=0;e--)n.push(t[e])}else r=o.path,i=o.inode}return r}mkdirSync(e,t=Dn){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=A(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(B(a)){let n=this.resolveInodePath(t,!0),a=this.getInodeByPath(n);if(!a)throw b(e===r.length-1?`EEXIST`:`ENOENT`,i);if(!a.isDir)throw b(e===r.length-1?`EEXIST`:`ENOTDIR`,i);e<r.length-1&&this.assertSearchablePath(n,!0);continue}if(!a.isDir)throw b(e===r.length-1?`EEXIST`:`ENOTDIR`,i);e<r.length-1&&this.assertSearchablePath(i,!0)}else this.mkdirSingleSync(i,n.mode)}}else this.mkdirSingleSync(e,n.mode)}mkdirSingleSync(e,t=Dn){let n=A(e),r=this.resolveInodePath(n.path,!1);if(this.hasPathEntry(r))throw b(`EEXIST`,r);let i=j(r),a=M(r),o=this.getInodeByPath(i);if(!o)throw b(`ENOENT`,i);if(!o.isDir)throw b(`ENOTDIR`,i);this.assertSearchablePath(i,!0),this.assertDirectoryWritable(i,o),this.assertNameWithinQuota(r),this.assertFileCountWithinQuota(r),this.impact(r,!1);let s=Bn(this.nextInodeNumber++,t);this.addDirEntry(o,a,s),o.nlink=(o.nlink??2)+1,this.linkInodePath(r,s),Jn(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=En){return!(t&576)||!this.recordingLogicalChanges?this.openSyncImpl(e,t,n):this.withLogicalOperation(()=>this.openSyncImpl(e,t,n))}openSyncImpl(e,t,n){let r=A(e);if(t&512&&!Un(t))throw b(`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 b(`EEXIST`,r.path);let a=this.resolveInodePath(r.path,!0),o=this.getInodeByPath(a);if(r.requiresDirectory&&!o?.isDir)throw b(`ENOTDIR`,a);if(o){if(this.assertSearchablePath(a,r.requiresDirectory||o.isDir),o.isDir)throw b(`EISDIR`,a);if(Hn(t)&&this.assertFilePermission(a,o,An),Un(t)&&this.assertFilePermission(a,o,jn),i)throw b(`EEXIST`,a)}else{if(!(t&64))throw b(`ENOENT`,a);let e=j(a),r=M(a),i=this.getInodeByPath(e);if(!i)throw b(`ENOENT`,e);if(!i.isDir)throw b(`ENOTDIR`,e);this.assertSearchablePath(e,!0),this.assertDirectoryWritable(e,i),this.assertNameWithinQuota(a),this.assertFileCountWithinQuota(a),this.impact(a,!1);let s=zn(this.nextInodeNumber++,n);this.addDirEntry(i,r,s),this.linkInodePath(a,s),Jn(this.sortedPaths,a),this.bufferMode===`memory`&&this.fileData.set(a,/* @__PURE__ */ 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)??/* @__PURE__ */ new Uint8Array:void 0,flags:t,readable:Hn(t),writable:Un(t),append:!!(t&1024)}),s}assertValidOffset(e,t,n){if(!Number.isSafeInteger(e)||e<0)throw b(`EINVAL`,t,`Invalid ${n}`)}assertWithinMaxFileSize(e,t){if(e>this.maxFileSize)throw b(`EFBIG`,t,`File size ${e} exceeds maximum ${this.maxFileSize}`)}assertNameWithinQuota(e){if(M(e).length>this.maxNameLength)throw b(`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 b(`ENOSPC`,e,`Path depth ${t} exceeds maximum ${this.maxPathDepth}`)}}assertFileCountWithinQuota(e){if(this.maxFiles!==void 0&&this.inodes.size>=this.maxFiles)throw b(`ENOSPC`,e,`File count ${this.inodes.size} would exceed maximum ${this.maxFiles}`)}computeLiveDataBytes(){let e=0,t=/* @__PURE__ */ new Set;for(let n of this.inodes.values())n.isDir||B(n)||t.has(n.ino)||(t.add(n.ino),e+=n.size);for(let n of this.pendingDeletedInodes)n.isDir||B(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 b(`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)*z;if(n>this.maxTotalBytes)throw b(`ENOSPC`,t,`Total bytes ${n} would exceed maximum ${this.maxTotalBytes}`)}assertWholeFileQuota(e,t,n,r){this.maxTotalBytes!==void 0&&(this.bufferMode===`memory`?this.assertTotalBytesWithinQuota(e,t,r):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/z);i<Math.ceil(t/z);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 b(`EBADF`);if(!r.writable)throw b(`EBADF`,r.path,`Descriptor is not open for writing`);if(!(t instanceof Uint8Array))throw b(`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)??/* @__PURE__ */ 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 b(`EINVAL`);if(!n||typeof n!=`object`||Array.isArray(n))throw b(`EINVAL`,e);for(let t of Object.keys(n))if(t!==`exclusive`&&t!==`expected`&&t!==`append`)throw b(`EINVAL`,e);if(!(t instanceof Uint8Array))throw b(`EINVAL`,e);if(t.byteLength>16777216)throw b(`EFBIG`,e);if(n.expected!==void 0&&!(n.expected instanceof Uint8Array))throw b(`EINVAL`,e);if(n.expected&&n.expected.byteLength>16777216)throw b(`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 b(`EINVAL`,e);let r=A(e),i=this.resolveInodePath(r.path,!0),a=this.getInodeByPath(i);if(a&&n.exclusive)throw b(`EEXIST`,i);let o=(n.append?a?.size??0:0)+t.byteLength;if(o>16777216)throw b(`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 b(`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 b(`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 b(`EBADF`);if(!r.readable)throw b(`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:/* @__PURE__ */ 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)??/* @__PURE__ */ 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 b(`EBADF`);if(!r.readable)throw b(`EBADF`,r.path,`Descriptor is not open for reading`);if(!(t instanceof Uint8Array))throw b(`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)??/* @__PURE__ */ 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/z>>>0,o=a%z,s=e.blocks[t];if(s===void 0)throw b(`EINVAL`,void 0,`Corrupted inode block table`);let c=Math.min(z-o,n-i),l=t+1,u=s;for(;i+c<n;){let t=e.blocks[l];if(t===void 0)throw b(`EINVAL`,void 0,`Corrupted inode block table`);if(s===0?t!==0:t!==u+1)break;let r=Math.min(z,n-i-c);c+=r,u=t,l++}r(s===0?0:s*z+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 b(`EBADF`);if(!Number.isSafeInteger(t))throw b(`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 b(`EINVAL`,r.path,`Invalid whence`)}if(!Number.isSafeInteger(a)||a<0)throw b(`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 b(`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:z,blocks:this.bufferMode===`disk`?e.blocks.reduce((e,t)=>e+(t===0?0:z/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&&!B(e)}}fstatSync(e){let t=this.openFiles.get(e);if(!t)throw b(`EBADF`);return this.toStat(t.inode)}fsyncSync(e){if(!this.openFiles.has(e))throw b(`EBADF`);this.syncSync()}chmodSync(e,t){return this.recordingLogicalChanges?this.withLogicalOperation(()=>this.chmodSyncImpl(e,t)):this.chmodSyncImpl(e,t)}chmodSyncImpl(e,t){let n=A(e),r=this.resolveInodePath(n.path,!0),{requiresDirectory:i}=n,a=this.getInodeByPath(r);if(!a)throw b(`ENOENT`,r);if(i&&!a.isDir)throw b(`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){for(let r of[t,n])if(!(r>=0&&r<2**32*1e3))throw b(`EINVAL`,e,`Invalid time`);let r=A(e),i=this.resolveInodePath(r.path,!0),{requiresDirectory:a}=r,o=this.getInodeByPath(i);if(!o)throw b(`ENOENT`,i);if(a&&!o.isDir)throw b(`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=A(e),r=A(t),i=this.resolveInodePath(n.path,!1),a=this.getInodeByPath(i);if(!a)throw b(`ENOENT`,i);if(n.requiresDirectory&&!a.isDir)throw b(`ENOTDIR`,i);if(a.isDir)throw b(`EPERM`,i,`Hard links to directories are not supported`);let o=this.resolveInodePath(r.path,!1);if(this.hasPathEntry(o))throw b(`EEXIST`,o);if(r.requiresDirectory&&!a.isDir)throw b(`ENOTDIR`,o);let s=j(o),c=M(o),l=this.getInodeByPath(s);if(!l)throw b(`ENOENT`,s);if(!l.isDir)throw b(`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),Jn(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=A(e),n=this.resolveInodePath(t.path,!1),{requiresDirectory:r}=t,i=this.getInodeByPath(n);if(!i)throw b(`ENOENT`,n);if(r&&!i.isDir)throw b(`ENOTDIR`,n);if(i.isDir)throw b(`EISDIR`,n);let a=j(n),o=this.getInodeByPath(a);this.assertSearchablePath(a,!0),o&&this.assertDirectoryWritable(a,o),this.impact(n,!1),o&&this.removeDirEntry(o,M(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)}assertNotDotEntry(e){let t=M(e);if(t===`.`||t===`..`)throw b(`EINVAL`,e)}rmdirSyncImpl(e){let t=A(e);this.assertNotDotEntry(t.path);let n=this.resolveInodePath(t.path,!1),{requiresDirectory:r}=t;if(n===`/`)throw b(`EPERM`,n);let i=this.getInodeByPath(n);if(!i)throw b(`ENOENT`,n);if(r&&!i.isDir||!i.isDir)throw b(`ENOTDIR`,n);if(this.assertSearchablePath(n,!0),this.listDirNames(i).length>0)throw b(`ENOTEMPTY`,n);if(this.hasOpenFilesInSubtree(n))throw b(`EBUSY`,n);let a=j(n),o=this.getInodeByPath(a);o&&this.assertDirectoryWritable(a,o),this.impact(n,!0),o&&(this.removeDirEntry(o,M(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=A(e);this.assertNotDotEntry(t.path);let n=this.resolveInodePath(t.path,!1),r=this.getInodeByPath(n);if(!r)throw b(`ENOENT`,n);if(t.requiresDirectory&&!r.isDir)throw b(`ENOTDIR`,n);if(r.isDir){if(n===`/`)throw b(`EPERM`,n);if(this.hasOpenFilesInSubtree(n))throw b(`EBUSY`,n);this.assertSearchablePath(n,!0);let e=j(n),t=this.getInodeByPath(e);t&&this.assertDirectoryWritable(e,t),this.impact(n,!0),t&&(this.removeDirEntry(t,M(n)),t.nlink=Math.max(2,(t.nlink??2)-1)),this.deleteSubtree(n),this.commitNamespaceChange(),this.touchInode(e),this.dirtyInodes.add(e),this.flushMemoryNamespaceLog()}else this.unlinkSync(n)}renameSync(e,t){return this.recordingLogicalChanges?this.withLogicalOperation(()=>this.renameSyncImpl(e,t)):this.renameSyncImpl(e,t)}renameSyncImpl(e,t){let n=A(e),r=A(t);this.assertNotDotEntry(n.path),this.assertNotDotEntry(r.path);let i=this.resolveInodePath(n.path,!1),a=this.resolveInodePath(r.path,!1),o=this.getInodeByPath(i);if(!o)throw b(`ENOENT`,i);if(n.requiresDirectory&&!o.isDir)throw b(`ENOTDIR`,i);if(r.requiresDirectory&&!o.isDir)throw b(`ENOTDIR`,a);if(this.getInodeByPath(a)===o)return;if(i===`/`)throw b(`EPERM`,i);if(this.assertSearchablePath(i,n.requiresDirectory||o.isDir),o.isDir&&a.startsWith(`${i}/`))throw b(`EINVAL`,a,`Cannot move directory into its own subtree`);let s=j(i),c=M(i),l=this.getInodeByPath(s),u=j(a),d=M(a),f=this.getInodeByPath(u);if(!f)throw b(`ENOENT`,u);if(!f.isDir)throw b(`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 b(`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 b(p.isDir?`EISDIR`:`ENOTDIR`,a);if(p.isDir){if(this.listDirNames(p).length>0)throw b(`ENOTEMPTY`,a);if(this.hasOpenFilesInSubtree(a))throw b(`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=/* @__PURE__ */ 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 b(`EBADF`);if(!n.writable)throw b(`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 b(`EISDIR`,e);let r;if(this.bufferMode===`memory`){let e=this.lookupFileDataForInode(this.pathForInode(t),t),i=Array.from(this.openFiles.values()).find(e=>e.inode===t)?.data,a=e??i??/* @__PURE__ */ new Uint8Array;n<=a.length?r=a.slice(0,n):(r=new Uint8Array(n),r.set(a))}let i=t.size!==n;i&&this.impactInode(t),this.invalidateFlush();let a=t.size;if(this.bufferMode===`memory`&&this.appendDataWal({version:1,op:`truncate`,inodeId:t.ino,path:e,size:n}),this.bufferMode===`disk`){if(n>a){let r=Math.min(n,Math.ceil(a/z)*z);r>a&&this.withQuotaMapped(()=>this.zeroDiskRange(t,a,r),e);let i=Math.ceil(n/z);for(;t.blocks.length<i;)t.blocks.push(0)}let r=n===0?0:Math.ceil(n/z);for(;t.blocks.length>r;){let e=t.blocks.pop();e!==0&&this.releaseBlock(e)}}t.size=n,this.markAllPathsForInode(t),this.touchInode(e,Date.now(),t),i&&this.recordLogicalUpdate(t),r&&(this.syncFileDataForInode(t,r),this.updateOpenFileBuffers(t,r),this.markResized(t,a,n))}truncateSync(e,t){return this.recordingLogicalChanges?this.withLogicalOperation(()=>this.truncateSyncImpl(e,t)):this.truncateSyncImpl(e,t)}truncateSyncImpl(e,t){let n=A(e),r=this.resolveInodePath(n.path,!0),{requiresDirectory:i}=n,a=this.getInodeByPath(r);if(!a)throw b(`ENOENT`,r);if(i&&!a.isDir)throw b(`ENOTDIR`,r);this.assertSearchablePath(r,i||a.isDir),this.assertInodeWritable(r,a),this.truncateInode(r,a,t)}existsSync(e){let t=A(e),n;try{n=this.resolveInodePath(t.path,!0)}catch(e){let t=e.code;if(t===`ENOENT`||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=A(e),n=this.resolveInodePath(t.path,!0),{requiresDirectory:r}=t,i=this.getInodeByPath(n);if(!i)throw b(`ENOENT`,n);if(r&&!i.isDir)throw b(`ENOTDIR`,n);return this.assertSearchablePath(n,r||i.isDir),this.toStat(i)}lstatSync(e){let t=A(e),n=this.resolveInodePath(t.path,!1),r=this.getInodeByPath(n);if(!r)throw b(`ENOENT`,n);if(t.requiresDirectory&&!r.isDir)throw b(`ENOTDIR`,n);return this.assertSearchablePath(n,t.requiresDirectory||r.isDir),this.toStat(r)}readdirSync(e){let t=this.resolveInodePath(A(e).path,!0),n=this.getInodeByPath(t);if(!n)throw b(`ENOENT`,t);if(!n.isDir)throw b(`ENOTDIR`,t);return this.assertSearchablePath(t,!0),this.assertDirectoryReadable(t,n),this.touchInodeAccess(t,n),[`.`,`..`,...this.listDirNames(n)]}readdirNamesSync(e){let t=this.resolveInodePath(A(e).path,!0),n=this.getInodeByPath(t);if(!n)throw b(`ENOENT`,t);if(!n.isDir)throw b(`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(A(e).path,!0),n=this.getInodeByPath(t);if(!n)throw b(`ENOENT`,t);if(!n.isDir)throw b(`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 b(`ENOENT`,t);return{name:e,mode:r.mode,is_dir:r.isDir,is_file:!r.isDir&&!B(r)}})}listPathsSync(){if(this.closed)throw b(`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(()=>{this.storage?.beforeDataCommit?.(),this.flushData()}),this.hasDirtyMeta&&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)*z)}flushVfs(){if(!(this.closed||this.flushed)){this.setLocalPersistenceState(`flushing`);try{let e=()=>{this.storage?.beforeDataCommit?.(),this.flushData(!0)};this.bufferMode===`memory`?(this.flushRecoveryLogs(),this.persistToOpfs(e)):e(),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(Et(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 b(`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 b(`EINVAL`,void 0,`Invalid file change channel`);if(typeof e!=`string`||!e||e.length>128||t!==`local`&&t!==`follower-relay`)throw b(`EINVAL`,void 0,`Invalid file change client`);if(this.changeChannels.size+this.pendingChangeChannels.size>=128||(this.changeChannelCounts.get(e)??0)>=32)throw b(`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 b(`EBADF`,void 0,`Volume is closed`);if(!this.logicalSession||this.logicalChangesPoisoned)throw b(`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 b(`EBADF`,void 0,`File change channel is closed`);let t=vt(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)??/* @__PURE__ */ new Set;if(e.has(n))throw b(`EINVAL`,void 0,`Duplicate file change subscription`);if(e.size>=32||this.changeSubscriptionCount>=128)throw b(`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 b(`ENOTSUP`,void 0,`Logical changes unavailable`);try{let e=i.control(a,t);if(yt(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(),b(`EINVAL`,void 0,`Invalid file change reply`)}catch(e){throw r&&this.releaseChangeSubscription(a,n),t.type===`register`&&pn(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 b(`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(()=>{}),b(`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&&sn(i.path,e)||!t&&i.path===e)return}let i=n.impactCharged;if(t)for(let t=r.length-1;t>=0;t--)sn(e,r[t].path)&&(i-=n.impactCharges[t],r.splice(t,1),n.impactCharges.splice(t,1));let a=on(e,65536-i);r.length>=128||!Number.isFinite(a)?(n.impactAll=!0,r.length=0,n.impactCharges.length=0):(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}/`))||i.path===e){n=!0;break}}if(n)continue;r++;let a=on(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=on(t,4194304-i.charged);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()):(i.charged+=a,i.namespace.push({type:e,path:t,kind:n.isDir?`directory`:B(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;t&&(t.overflow||t.changedInodes.has(e.ino)||(t.namespace.length+t.changedInodes.size>=4096||t.charged+256>4194304?(t.overflow=!0,t.namespace.length=0,t.changedInodes.clear(),t.createdPaths.clear()):(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:/* @__PURE__ */ new Set,createdPaths:/* @__PURE__ */ 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=on(t,4194304-r);if(!Number.isFinite(i)||(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`:B(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:cn(r.path)};r.type===`delete`?t.push(e):n.push(e)}t.sort(un),n.sort(dn);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(fn);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??=/* @__PURE__ */ 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||B(t)||t.size!==e.size||(this.assertSearchablePath(e.path,!1),this.assertFilePermission(e.path,t,An),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):/* @__PURE__ */ 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=bt(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||!en(i.buffer)||this.logicalCaptureBuffers.has(i.buffer)||this.logicalDeliveryBuffers.has(i.buffer)))this.poisonLogicalChanges();else{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 b(`EINVAL`,void 0,`Invalid subscription target`);if(e.path.split(`/`).some(e=>e===`.`||e===`..`))throw b(`EINVAL`,e.path,`Subscription target must not contain . or .. components`);let t=A(e.path);if(t.requiresDirectory&&e.scope!==`directory`)throw b(`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 b(`ENOTDIR`,n);let t=this.lookupChild(n,r,i[e]);if(n=t.path,r=t.inode,!r)return;if(B(r))throw b(`EINVAL`,n,`Subscription target traverses symlink`);if(!r.isDir)throw b(`ENOTDIR`,n);this.assertDirectoryExecutable(n,r)}if(i.length===0){if(e.scope===`file`)throw b(`EINVAL`,t.path,`Root requires directory scope`);return}if(!r?.isDir)throw b(`ENOTDIR`,n);let a=this.lookupChild(n,r,i[i.length-1]).inode;if(a){if(e.scope===`file`&&a.isDir)throw b(`EINVAL`,t.path,`Directory conflicts with file scope`);if(e.scope===`directory`&&!a.isDir)throw b(`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(vn(e)){let e=b(`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 b(`ENOSPC`);return e}ensureDiskBlocks(e,t,n,r,i){let a=Math.ceil(n/z),o=Math.floor(r/z);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]*z,i=Math.min(z,Math.max(0,r-t)),a=Math.min(z,Math.max(0,t+z-n));i>0&&this.dataHandle.write(this.zeroSource(i),{at:c[e]*z}),a>0&&this.dataHandle.write(this.zeroSource(a),{at:(c[e]+1)*z-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+=an){let r=Math.min(an,n-t);this.dataHandle.write(this.zeroSource(r),{at:e+t})}this.markDataDirty()}})}zeroSource(e){return e<=z?nn.subarray(0,e):(this.zeroBuffer||=new Uint8Array(an),this.zeroBuffer.subarray(0,e))}moveSortedSubtree(e,t){let n=this.sortedPaths;Yn(n,e);let r=`${e}/`,i=qn(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));Jn(n,t);let s=qn(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=qn(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=/* @__PURE__ */ 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),Yn(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),Yn(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);else{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=/* @__PURE__ */ new Set,i=/* @__PURE__ */ 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`:B(a)?`symlink`:`file`),a.kind===`symlink`?(a.isDir=!1,a.mode=a.mode&511|40960||On,a.size=rn.encode(a.symlinkTarget??``).byteLength):a.isDir=a.kind===`dir`,a.kind!==`symlink`&&!(a.mode&61440)&&(a.mode|=a.isDir?Pn:Nn);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=/* @__PURE__ */ 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(j(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=/* @__PURE__ */ 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,/* @__PURE__ */ new Map)}for(let[e,t]of this.inodes){if(e===`/`)continue;let n=j(e),r=this.inodes.get(n);if(!r?.isDir)continue;let i=this.dirEntries.get(r.ino);i||(i=/* @__PURE__ */ new Map,this.dirEntries.set(r.ino,i)),i.set(M(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=/* @__PURE__ */ 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,/* @__PURE__ */ 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=/* @__PURE__ */ 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=/* @__PURE__ */ new Map),this.dirEntries instanceof Map||(this.dirEntries=/* @__PURE__ */ new Map),this.pathIndex instanceof Map||(this.pathIndex=/* @__PURE__ */ new Map),this.inoToPaths instanceof Map||(this.inoToPaths=/* @__PURE__ */ 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>=gn))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);else 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 b(`ENOTDIR`,a);let t=this.lookupChild(a,o,r[e]);a=t.path;let n=t.inode;if(!n)throw b(`ENOENT`,a);if(!n.isDir)throw b(`ENOTDIR`,a);this.assertDirectoryExecutable(a,n),o=n}}assertInodeWritable(e,t){t.isDir?this.assertDirectoryWritable(e,t):this.assertFilePermission(e,t,jn)}assertDirectoryReadable(e,t){if((t.mode&An)===0)throw b(`EACCES`,e)}assertDirectoryWritable(e,t){if((t.mode&jn)===0||(t.mode&Mn)===0)throw b(`EACCES`,e)}assertDirectoryExecutable(e,t){if((t.mode&Mn)===0)throw b(`EACCES`,e)}assertFilePermission(e,t,n){if((t.mode&n)===0)throw b(`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??Dn,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(){if(this.bufferMode===`memory`){if(this.localDurabilityMode===`strict`)this.writeMeta(!1,!1);else try{this.writeMeta(!1,!0)}catch(e){let t=e?.code;if(!(e instanceof DOMException||t===`ENOSPC`||t===`EIO`))throw e;this.metaLogWriteFailed=!0}}}flushRecoveryLogs(){this.walPendingBytes>0&&this.localDurabilityMode!==`strict`&&this.dataLogHandle.flush(),this.metaLogWriteFailed&&this.writeMeta(!1,!0),this.flushPendingMetaLog()}flushPendingMetaLog(){this.metaLogFlushPending&&=(this.logHandle.flush(),!1)}persistToOpfs(e){let t=[];try{for(let[e,n]of this.dirtyPages){let r=this.pathForInode(e);if(!r||e.isDir||B(e))continue;let i=this.lookupFileDataForInode(r,e);if(!i)continue;let a={inode:e,blocksBefore:e.blocks.slice(),released:[]};t.push(a),this.persistInodePages(e,n,r,i,a.released)}e()}catch(e){for(let{inode:e,blocksBefore:n}of t){let t=new Set(n);for(let n of e.blocks)n!==0&&!t.has(n)&&this.bitmap.free(n);e.blocks=n}throw e}for(let{inode:e,released:n}of t){for(let e of n)this.releaseBlock(e);(this.persistedSize.get(e)??0)!==e.size&&this.markAllPathsForInode(e),this.persistedSize.set(e,e.size)}this.dirtyPages.clear()}persistInodePages(e,t,n,r,i){let a=e.size===0?0:Math.ceil(e.size/z),o=e.blocks.length,s=a-e.blocks.length;if(s>1){let t=this.bitmap.allocRun(s);if(t>=0)for(let n=0;n<s;n++)e.blocks.push(t+n)}for(;e.blocks.length<a;){let t=this.bitmap.alloc();if(t<0&&(this.growStorage(),t=this.bitmap.alloc(),t<0))throw b(`ENOSPC`);e.blocks.push(t)}for(;e.blocks.length>a;){let t=e.blocks.pop();t!==0&&i.push(t)}for(let i of t){if(i>=Math.min(o,a)||e.blocks[i]!==0||!r.subarray(i*z,Math.min((i+1)*z,e.size)).some(e=>e!==0))continue;let s=this.bitmap.alloc();if(s<0&&(this.growStorage(),s=this.bitmap.alloc(),s<0))throw b(`ENOSPC`);e.blocks[i]=s,t.add(i),this.dirtyInodes.add(n)}e.blocks.length!==o&&this.dirtyInodes.add(n);for(let e=o;e<a;e++)t.add(e);let c=Array.from(t).filter(t=>t<e.blocks.length&&e.blocks[t]!==0).sort((e,t)=>e-t);for(let t=0;t<c.length;){let i=c[t],a=e.blocks[i],o=t,s=i;for(;o+1<c.length&&c[o+1]===s+1&&e.blocks[c[o+1]]===e.blocks[s]+1&&(s+1)*z<=e.size;)o++,s=c[o];let l=i*z,u=Math.min((s+1)*z,e.size),d=u-l;if(d>0){this.withQuotaMapped(()=>this.dataHandle.write(r.subarray(l,l+d),{at:a*z}),n);let e=u%z;e>0&&this.dataHandle.getSize()<(a+s-i+1)*z&&this.withQuotaMapped(()=>this.dataHandle.write(this.zeroSource(z-e),{at:a*z+d}),n),this.markDataDirty()}t=o+1}}writeMeta(e=!1,t=!1){try{this.writeMetaRecords(e,t)}catch(e){throw this.setLocalPersistenceState(`error`,e),e}}atPersistedSize(e,t){if(this.bufferMode!==`memory`||this.dirtyPages.size===0)return t();let n=[];for(let t of e)this.dirtyPages.has(t)&&(n.push([t,t.size]),t.size=this.persistedSize.get(t)??0);try{return t()}finally{for(let[e,t]of n)e.size=t}}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(_n,(this.lastSnapshotSize||0)*2),i=this.logOffset>=r;if(e||this.dirtyStructure||i){let e=new Uint8Array(this.atPersistedSize(this.dirtyPages.keys(),()=>He(this.inodes,this.totalBlocks,z,this.sortedPaths,this.nextInodeNumber)));this.lastSnapshotSize=e.byteLength;let t=this.metaSnapshotSequence+1>>>0,n=st(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=Je([],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(We(t,null));for(let t of this.dirtyInodes){let n=this.inodes.get(t);n&&e.push(this.atPersistedSize([n],()=>We(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(this.atPersistedSize([n],()=>Ge(t,n)))}if(e.length>0){let n=Je(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.metaLogWriteFailed=!1,this.drainPendingFree()}};function qn(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 Jn(e,t){e.splice(qn(e,t),0,t)}function Yn(e,t){let n=qn(e,t);n<e.length&&e[n]===t&&e.splice(n,1)}var Xn=/^[A-Za-z][A-Za-z0-9_]{0,63}$/,Zn=/^[A-Z][A-Z0-9_]{0,63}$/,Qn=/* @__PURE__ */ new Set([`meta-snapshot`,`data-wal`,`bitmap`,`meta-log`,`format-version`]);function $n(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 er(e,t){let n=t?V(t,`message`):void 0;if(typeof n==`string`)return $n(n);try{return $n(String(e))}catch{return`Unknown VFS error`}}function tr(e){let t=typeof e==`object`&&e?e:null,n=er(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`&&Xn.test(r)?{name:r}:{},...typeof i==`string`&&Zn.test(i)?{code:i}:{},...typeof a==`number`&&Number.isSafeInteger(a)?{errno:a}:{},...typeof o==`string`&&Qn.has(o)?{category:o}:{},...typeof s==`number`&&Number.isSafeInteger(s)&&s>=0?{offset:s}:{}})}function nr(e){let{message:t,...n}=tr(e);return{error:t,...n}}function rr(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=/* @__PURE__ */ 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`||!Xn.test(o))||f&&(typeof s!=`string`||!Zn.test(s))||p&&(typeof c!=`number`||!Number.isSafeInteger(c))||m&&(typeof l!=`string`||!Qn.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 ir(e){let{message:t,name:n,...r}=e,i=Object.assign(Error(t),r);return n!==void 0&&(i.name=n),i}var ar=4194304,H=64,U=0,or=1,W=2,sr=3,cr=1e3,lr=5e3,ur=3e4,dr=new TextEncoder,fr=new TextDecoder,pr=/* @__PURE__ */ new WeakSet;function mr(e){return e instanceof Error?e.message:String(e)}function hr(e,t,n=0,r=ar){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 gr=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){hr(e,t,n,this.payloadCapacity)}encodeBoundedErrorHeader(e){let t=this.payloadCapacity,{error:n,...r}=nr(e);for(let e of[r,r.code===void 0?{}:{code:r.code}]){let r=t=>dr.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 dr.encode(`{}`).subarray(0,Math.max(0,t))}makeRemoteError(e){let t=rr(e);if(!t)return/* @__PURE__ */ Error(`Invalid VFS error response`);let n=ir(t);return pr.add(n),n}call(e,t,n,r){try{let i=r?.timeoutMs,a=typeof i==`number`&&Number.isFinite(i)&&i>0?i:ur;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,cr)===`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 o=JSON.stringify({type:e,payload:t}),s=dr.encode(o);this.ensureFits(`SyncMessenger.call(${e}) request`,s.length,n?.length??0),this.callCount=this.callCount+1|0;let c=this.callCount;if(this.int32[sr]=c,this.int32[or]=s.length,new Uint8Array(this.sab,H).set(s),n&&n.length>0?(this.int32[W]=n.length,new Uint8Array(this.sab,H+s.length).set(n)):this.int32[W]=0,Atomics.store(this.int32,U,1),Atomics.notify(this.int32,U),this.waitForStatusChange(1,a)===`timed-out`)throw Error(`VFS worker did not respond within ${a/1e3}s (command: ${e})`);let l=Atomics.load(this.int32,U),u,d,f;try{if(l!==2&&l!==3)throw Error(`SyncMessenger protocol desync: invalid response status ${l}`);f=this.int32[sr];let t=this.int32[or],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)),u=JSON.parse(fr.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))):(d=new Uint8Array(n),d.set(e))}}finally{Atomics.store(this.int32,U,0),Atomics.notify(this.int32,U)}if(f!==c)throw Error(`SyncMessenger protocol desync: expected call ID ${c} but got ${f} (stale response after a timeout?)`);if(l===3)throw this.makeRemoteError(u);return d?u.result&&typeof u.result==`object`?{...u.result,data:d}:{result:u.result,data:d}:u.result}catch(t){throw typeof t==`object`&&t&&(pr.has(t)||`code`in t&&typeof t.code==`string`)?t:Error(`SyncMessenger.call(${e}) failed: ${mr(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[sr]!==e||Atomics.load(this.int32,U)!==1,o=(e,t)=>{if(a(t))return;let n=this.encodeBoundedErrorHeader(e);this.int32[or]=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=dr.encode(JSON.stringify(t));try{this.ensureFits(`SyncMessenger.listen response`,i.length,n?.length??0)}catch(e){throw Object.assign(e,{code:`EOVERFLOW`})}this.int32[or]=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,lr)===`timed-out`&&Atomics.compareExchange(this.int32,U,t,0)===t&&Atomics.notify(this.int32,U);else{let e=await c(t,lr);t!==0&&e===`timed-out`&&(Atomics.compareExchange(this.int32,U,t,0),Atomics.notify(this.int32,U))}continue}let n=this.int32[sr],i=this.int32[or],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(fr.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))}}})()}},_r=`PERSISTENCE_STATUS`,vr=`PERSISTENCE_FRAME`;function yr(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:nr(n.failure??/* @__PURE__ */ Error(`Local persistence failed`)),lastSalvage:r?{reason:r.reason,truncatedAt:r.truncatedAt,discardedBytes:r.discardedBytes,detail:r.detail,at:r.at}:null}}function br(e){return e.code!==`ENOENT`&&e.code!==`ENOTDIR`}var G,K=null,xr=null,Sr=!1,Cr=!1,wr=null,Tr=!1,Er=null,Dr=!1,q=null,J,Or=0,Y=/* @__PURE__ */ new Map,X=/* @__PURE__ */ new Map,kr=(e,t)=>JSON.stringify([e,t]),Ar=e=>typeof e==`string`&&e.length>0&&e.length<=128;function jr(){Y.clear(),X.clear()}function Mr(e){let t=kr(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 Nr(e){return e.state===`open`&&Y.get(kr(e.clientId,e.channelId))===e&&K===e.mount&&q===e.generation}function Pr(e,t=!1){if(e.queued=!1,K!==e.mount||q!==e.generation)return;let n=Ct.get(e.mount)?.read();if(!n||!t&&e.last?.state===n.state&&e.last.failureRevision===n.failureRevision)return;let r=yr(e.generation,++e.sequence,n);return e.last={state:n.state,failureRevision:n.failureRevision},r}function Fr(e){if(Or>0)return;let t=Pr(e);if(t)try{G.postMessage({type:vr,payload:t})}catch{}}function Ir(e,t){let n={mount:e,generation:t,sequence:0,enabled:!1,queued:!1};J=n,Ct.get(e)?.watch(()=>{n.enabled&&!n.queued&&(n.queued=!0,queueMicrotask(()=>Fr(n)))})}function Lr(e){if(typeof e!=`object`||!e||Array.isArray(e))throw b(`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 b(`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 b(`EINVAL`,void 0,`Invalid persistence status request`);return i}catch{throw b(`EINVAL`,void 0,`Invalid persistence status request`)}}function Rr(...e){Sr&&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 b(`EINVAL`,void 0,`Invalid numeric payload field: ${t}`);return r}function zr(e,t){let n=e[t];if(typeof n!=`number`||!(n>=0&&n<2**32*1e3))throw b(`EINVAL`,void 0,`Invalid numeric payload field: ${t}`);return n}function $(e,t){if(e[t]!==void 0)return Q(e,t)}function Br(e,t){let n=e[t];return typeof n==`boolean`?n:void 0}var Vr=/* @__PURE__ */ new Set([`fileName`,`sab`,`debug`,`plugins`,`openMode`,`bufferMode`,`localDurabilityMode`,`debugWal`,`noatime`,`recoveryMode`,`maxFileSize`,`maxNameLength`,`maxPathDepth`,`maxFiles`,`maxTotalBytes`,`generation`]);function Hr(e){if(typeof e!=`object`||!e||Array.isArray(e))throw b(`EINVAL`,void 0,`Invalid INIT payload`);let t=e;for(let e of Reflect.ownKeys(t))if(!Vr.has(String(e)))throw b(`EINVAL`,void 0,`Unsupported INIT field: ${String(e)}`);let n=t.fileName;if(typeof n!=`string`)throw b(`EINVAL`,void 0,`Invalid INIT fileName`);Jt(n);let r=e=>{throw b(`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 Ur(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw b(`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||!Ar(n.generation)||!Ar(n.clientId)||!Ar(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 b(`EINVAL`,void 0,`Invalid file change channel`);return{generation:n.generation,clientId:n.clientId,channelId:n.channelId,route:n.route,command:n.command}}function Wr(e){return e===`FILE_CHANGES_OPEN`||e===`FILE_CHANGES_COMMAND`||e===`FILE_CHANGES_CLOSE`}function Gr(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw b(`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 b(`EINVAL`,void 0,`Invalid file change request`)}function Kr(e){if(Nr(e)){e.state=`closed`,Mr(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 qr(e,t,n={}){if(!Nr(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{Kr(e)}}async function Jr(e,t,n){let r=n=>G.postMessage({id:t,type:e,result:n}),i=Ur(n,e),a=K;if(!a||q!==i.generation)throw b(`EBADF`,void 0,`File change channel is closed`);let o=kr(i.clientId,i.channelId);if(e===`FILE_CHANGES_OPEN`){if(Y.has(o)||(X.get(i.clientId)??0)>=32||Y.size>=128)throw b(`ENOSPC`,void 0,`Too many file change channels`);let e=St.get(a);if(!e)throw b(`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=>qr(t,`FILE_CHANGES_FRAME`,{frame:e}),e=>qr(t,`FILE_CHANGES_INTERRUPTED`,{code:e}),()=>qr(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(),b(`EBADF`,void 0,`File change channel is closed`);t.channel=n,t.state=`open`,r({generation:n.generation})}catch(e){throw Mr(t),e}return}let s=Y.get(o);if(!s||s.generation!==i.generation||s.route!==i.route)throw b(`EBADF`,void 0,`File change channel is closed`);if(e===`FILE_CHANGES_CLOSE`){s.state=`closed`,Mr(s),s.channel?.close(),r(`OK`);return}if(s.state!==`open`||!s.channel)throw b(`EBADF`,void 0,`File change channel is closed`);let c=await s.channel.request(i.command);if(!Nr(s))throw b(`EBADF`,void 0,`File change channel is closed`);r(c)}function Yr({plugins:e=[],endpoint:t=self}={}){if(Cr)throw Error(`VFS worker already started`);if(!Array.isArray(e))throw Error(`Worker plugins must be an array`);let n=/* @__PURE__ */ new Map;for(let t of e){if(typeof t!=`object`&&typeof t!=`function`||t===null||typeof t.id!=`string`||!kt(t.id)||typeof t.configure!=`function`||n.has(t.id))throw Error(`Invalid or duplicate worker plugin registration`);n.set(t.id,t)}Cr=!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(Rr(`VFS Worker message:`,i,r),i===`PING`)G.postMessage({id:r,type:`PONG`});else try{if(Wr(i)){Gr(t,i),await Jr(i,r,a);return}switch(i){case`INIT`:{let{fileName:e,sab:t,debug:i,options:o,plugins:s,generation:c}=Hr(a);if(Dr)throw b(`EBUSY`,e,`VFS initialization already in progress`);if(Tr&&c===Er)throw b(`EINVAL`,e,`VFS owner generation already mounted`);Dr=!0;try{let{requests:a}=Mt(s,o.openMode,e),l=a.map(t=>{let r=n.get(t.id);if(!r)throw b(`EINVAL`,e,`Unknown worker plugin: ${t.id}`);return r}),u=Ht(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=b(`EINVAL`,e,`Invalid worker plugin options: ${t.id}`);throw a.code=i,a}}),o.openMode??`open-or-create`,e);Wt(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 b(`EINVAL`,e,`Worker plugin request mismatch: ${n.id}`)}let d=Nt(u);if(Sr=i,Tr){wr?.abort(),wr=null,xr=null;for(let e of Y.values())e.state===`opening`&&(e.state=`closed`);try{K&&(Tt(K),await $t(K))}catch{}queueMicrotask(jr),K=null,q=null,J=void 0,Tr=!1}try{Pt.set(o,u),xt.set(o,c),K=new Kn(e,o),await K.ready,q=c,Ir(K,c)}catch(e){let t=nr(e),n=`VFS init failed: ${t.error}`,{error:i,...a}=t;console.error(n),G.postMessage({id:r,type:`ERROR`,result:nr({message:n,...a})});return}Tr=!0,Er=c,G.postMessage({id:r,type:`INIT`,result:{profile:d}}),typeof SharedArrayBuffer==`function`&&t instanceof SharedArrayBuffer&&(wr=new AbortController,xr=new gr(t),xr.listen(Xr,{signal:wr.signal}))}finally{Dr=!1}break}case _r:{let e=Lr(a),t=J;if(!K||!t||e!==q)throw b(`EBADF`,void 0,`VFS persistence status is unavailable`);t.enabled=!0,t.queued=!1;let n=Pr(t,!0);if(!n)throw b(`EBADF`,void 0,`VFS persistence status is unavailable`);G.postMessage({id:r,type:i,result:n});break}default:{s=!0,Or++;let{result:e,data:t}=await Xr(i,a,o),n=J?.queued?Pr(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=nr(e),n=Wr(i)?`File change control failed: ${t.code??`EIO`}`:t.error;br({code:t.code,message:n,payload:a,type:i})&&console.error(`VFS Worker error:`,n);let o=i!==`INIT`&&i!==`PERSISTENCE_STATUS`&&!Wr(i)&&J?.queued?Pr(J):void 0;G.postMessage({id:r,type:`ERROR`,result:Wr(i)?{...t,error:n}:t,...o===void 0?{}:{persistence:o}})}finally{let e=J;s&&--Or===0&&e?.queued&&queueMicrotask(()=>Fr(e))}}}async function Xr(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 b(`EFBIG`,e);let n=K.openSync(e,Ln.O_RDONLY);try{let{size:r}=K.fstatSync(n);if(r>t)throw b(`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 b(`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 b(`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 b(`EEXIST`,t)}case`MKDIR`:return K.mkdirSync(Z(r,`path`),Br(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??/* @__PURE__ */ 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`),zr(r,`atimeMs`),zr(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 $t(K),Er=null,{result:`OK`}}finally{queueMicrotask(jr)}default:throw Error(`Unknown command: ${e}`)}}Yr({plugins:[p]});", 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
+ // src/coordinator.ts
34
+ var T = /* @__PURE__ */ new WeakMap(), E = (e) => ({
35
+ ...e,
36
+ gate: m.makeUnsafe(1),
37
+ terminalSignal: c.makeUnsafe(),
38
+ files: /* @__PURE__ */ new Set(),
39
+ subscriptionSetups: /* @__PURE__ */ new Map(),
40
+ subscriptionUnknown: /* @__PURE__ */ new Map(),
41
+ continuity: { _tag: "clean" }
42
+ }), D = (e, t) => {
43
+ T.set(e, t);
44
+ }, O = (e) => T.get(e), k = (e, t) => {
45
+ c.isDoneUnsafe(e.terminalSignal) || l.runSync(c.succeed(e.terminalSignal, t));
46
+ }, A = /* @__PURE__ */ x({
47
+ Volume: () => j,
48
+ errorOf: () => $,
49
+ inspect: () => R,
50
+ layer: () => Y,
51
+ layerDirect: () => H,
52
+ make: () => J,
53
+ makeDirect: () => V,
54
+ unsafeBackend: () => X,
55
+ withSync: () => M
56
+ }), j = class extends s.Service()("@opfs-vfs/effect/Volume") {}, M = (e) => l.gen(function* () {
57
+ let t = yield* j;
58
+ return yield* l.tap(e, () => t.sync);
59
+ }), N = (e) => l.forEach([...e?.files ?? []], (e) => l.exit(e()), { concurrency: 1 }).pipe(l.flatMap((e) => {
60
+ let t;
61
+ for (let n of e) u.isFailure(n) && (t = t ? o.combine(t, n.cause) : n.cause);
62
+ return t ? l.failCause(t) : l.void;
63
+ })), P = (e, t) => {
64
+ let n = u.isFailure(e) ? u.isFailure(t) ? o.combine(e.cause, t.cause) : e.cause : u.isFailure(t) ? t.cause : void 0;
65
+ return n ? l.failCause(n) : l.void;
66
+ }, 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) => {
67
+ try {
68
+ return e(...t);
69
+ } catch {
70
+ throw I();
71
+ }
72
+ }, 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({
73
+ try: () => g(e),
74
+ catch: (t) => a(t, e, "inspect", "filesystem", "not-applied")
75
+ }), z = (e) => l.uninterruptibleMask((t) => l.gen(function* () {
76
+ 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);
77
+ return yield* p.addFinalizerExit(i, x), yield* _(null), yield* l.gen(function* () {
78
+ let n = yield* t(l.isEffect(e) ? l.provideService(e, p.Scope, o) : l.succeed(e));
79
+ yield* _(null);
80
+ let i;
81
+ if (n.plugins) try {
82
+ i = n.plugins();
83
+ } catch {
84
+ return yield* l.fail(a(/* @__PURE__ */ Error("Plugin configuration failed"), n.fileName, "configure plugins", "configuration", "not-applied"));
85
+ }
86
+ g = i?.some((e) => e.logicalChanges?.version === 1) ?? !1;
87
+ let { fileName: u, plugins: d, ...y } = n;
88
+ 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"));
89
+ try {
90
+ c = new h(u, {
91
+ ...y,
92
+ plugins: i
93
+ });
94
+ } catch (e) {
95
+ 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"));
96
+ }
97
+ return yield* p.addFinalizer(o, l.gen(function* () {
98
+ 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({
99
+ try: v,
100
+ catch: (e) => r(e, u, "close", "lifecycle")
101
+ }).pipe(l.orDie)));
102
+ })), yield* _(u), yield* t(l.tryPromise({
103
+ try: () => c.ready,
104
+ catch: (e) => r(e, u, "initialize", "filesystem")
105
+ })), yield* _(u), m = E({
106
+ fileName: u,
107
+ scope: o,
108
+ readinessTimeout: Infinity,
109
+ subscriptionsAvailable: g,
110
+ backend: c,
111
+ isClosed: () => s,
112
+ currentGeneration: () => s ? void 0 : "direct",
113
+ canRecapture: () => !1,
114
+ terminal: () => void 0,
115
+ awaitReady: (e, t) => s ? l.fail(a(/* @__PURE__ */ Error("Volume is closed"), u, t, "lifecycle", "not-applied")) : l.succeed("direct")
116
+ }), f = B(c, u, () => s, m), D(f, m), Z.set(f, c), yield* p.addFinalizer(o, l.sync(() => {
117
+ s = !0, f && Q.add(f);
118
+ })), yield* _(u), f;
119
+ }).pipe(l.onExit((e) => u.isFailure(e) ? l.gen(function* () {
120
+ let t = yield* l.exit(x(e));
121
+ if (yield* l.exit(p.close(i, e)), u.isFailure(t)) return yield* l.failCause(t.cause);
122
+ }) : l.void));
123
+ })), B = (t, o, s, u) => {
124
+ let d = (e) => s() ? a(/* @__PURE__ */ Error("Volume is closed"), o, e, "lifecycle", "not-applied") : void 0;
125
+ return {
126
+ fileName: o,
127
+ sync: l.uninterruptibleMask((i) => l.gen(function* () {
128
+ let s = yield* i(u.awaitReady({ remaining: Infinity }, "sync"));
129
+ yield* l.scoped(l.gen(function* () {
130
+ 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))))));
131
+ let f = d("sync");
132
+ if (f) return yield* l.fail(q(f));
133
+ if (u.continuity._tag === "lost" || u.continuity._tag === "pending" && u.continuity.generation !== s) return u.continuity = {
134
+ _tag: "lost",
135
+ generation: u.continuity.generation
136
+ }, 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"));
137
+ yield* l.try({
138
+ try: () => t.syncSync(),
139
+ catch: (t) => t instanceof e || t instanceof n ? t : r(t, o, "sync", "persistence")
140
+ }), u.continuity._tag === "pending" && (u.continuity = { _tag: "clean" });
141
+ }));
142
+ })),
143
+ persistence: l.try({
144
+ try: () => {
145
+ let e = d("persistence");
146
+ if (e) throw e;
147
+ let n = t.getLocalPersistenceStatusSync();
148
+ return {
149
+ state: n.localPersistenceState,
150
+ error: n.localPersistenceState === "error" && n.lastError !== void 0 ? i(n.lastError) : null
151
+ };
152
+ },
153
+ catch: (e) => e instanceof n ? e : a(e, o, "persistence", "lifecycle")
154
+ }),
155
+ acknowledgeOwnerChange: l.uninterruptibleMask((e) => l.scoped(l.gen(function* () {
156
+ 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))));
157
+ let t = d("acknowledgeOwnerChange");
158
+ if (t) return yield* l.fail(t);
159
+ })))
160
+ };
161
+ };
162
+ function V(e) {
163
+ return z(e);
164
+ }
165
+ function H(e) {
166
+ return d.effect(j, z(e));
167
+ }
168
+ var U = (t) => l.uninterruptibleMask((i) => l.gen(function* () {
169
+ 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 || (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);
170
+ return yield* p.addFinalizerExit(s, z), yield* p.addFinalizer(c, l.tryPromise({
171
+ try: M,
172
+ catch: (e) => r(e, null, "close", "lifecycle")
173
+ }).pipe(l.catch((e) => l.die(e)))), yield* p.addFinalizer(c, l.sync(() => {
174
+ d = !0, T.abort(), C && k(C, a(/* @__PURE__ */ Error("Volume is closed"), null, "close", "lifecycle", "unknown"));
175
+ })), yield* A(null), yield* l.gen(function* () {
176
+ let o = yield* i(l.isEffect(t) ? l.provideService(t, p.Scope, c) : l.succeed(t));
177
+ yield* A(o.fileName);
178
+ let { fileName: s, plugins: u, ...h } = o, g = h.initTimeout || 15e3;
179
+ if (F(s)) return yield* l.fail(a(/* @__PURE__ */ TypeError("Volume name must be a basename ending in .bin"), s, "configure", "configuration", "not-applied"));
180
+ let b;
181
+ try {
182
+ b = [...typeof u == "function" ? u() : u ?? []];
183
+ } catch {
184
+ return yield* l.fail(a(/* @__PURE__ */ Error("Plugin configuration failed"), s, "configure plugins", "configuration", "not-applied"));
185
+ }
186
+ let M = b.some((e) => e.id === "subscriptions" && e.contractVersion === 1 && e.compatibilityKey === y);
187
+ yield* A(s);
188
+ let I = L(h.worker ?? (() => new w())), R = h.sharedWorker ? L(h.sharedWorker) : void 0;
189
+ _ = Promise.resolve().then(() => v(s, {
190
+ ...h,
191
+ worker: I,
192
+ sharedWorker: R,
193
+ plugins: b,
194
+ signal: T.signal
195
+ })), m = yield* i(l.tryPromise({
196
+ try: () => _,
197
+ catch: (e) => typeof e == "object" && e && "code" in e && e.code === "EINVAL" ? a(e, s, "mount", "configuration") : r(e, s, "mount", "filesystem")
198
+ })), yield* A(s), yield* p.addFinalizer(c, l.gen(function* () {
199
+ 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({
200
+ try: () => (x && Q.add(x), j(m)),
201
+ catch: (e) => r(e, s, "close", "lifecycle")
202
+ }).pipe(l.catch((e) => l.die(e)))));
203
+ })), yield* A(s);
204
+ let z = () => {
205
+ let e = m.getStatus();
206
+ if (S || e.state !== "closing" && e.state !== "failed" && e.state !== "closed" || (S = W(e, s, "worker")), S && x) {
207
+ let e = O(x);
208
+ e && k(e, S);
209
+ }
210
+ }, B = m.subscribeStatus(z);
211
+ return yield* p.addFinalizer(c, l.sync(B)), z(), yield* i(l.tryPromise({
212
+ try: () => m.ready,
213
+ 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"))
214
+ })), yield* A(s), z(), S ? f.is(e)(S.cause) ? yield* l.fail(S.cause) : yield* l.fail(S) : (C = E({
215
+ fileName: s,
216
+ scope: c,
217
+ readinessTimeout: g,
218
+ subscriptionsAvailable: M,
219
+ backend: m,
220
+ isClosed: () => d,
221
+ currentGeneration: () => {
222
+ z();
223
+ let e = m.getStatus();
224
+ return e.state === "ready" ? e.ownerGeneration ?? void 0 : void 0;
225
+ },
226
+ canRecapture: () => !d && !S && m.getStatus().transport === "dedicated",
227
+ terminal: () => (z(), S),
228
+ awaitReady: (e, t) => K(m, s, t, e, () => (z(), S)).pipe(l.map((e) => e.ownerGeneration), l.mapError((e) => e))
229
+ }), x = G(m, s, () => d, () => (z(), S), g, C), D(x, C), Z.set(x, m), yield* A(s), x);
230
+ }).pipe(l.onExit((e) => u.isFailure(e) ? l.gen(function* () {
231
+ let t = yield* l.exit(z(e));
232
+ if (yield* l.exit(p.close(s, e)), u.isFailure(t)) return yield* l.failCause(t.cause);
233
+ }) : l.void));
234
+ })), W = (e, t, i) => {
235
+ 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;
236
+ return new n({
237
+ kind: "lifecycle",
238
+ fileName: t,
239
+ operation: i,
240
+ ...s?.code ? { code: s.code } : {},
241
+ outcome: "unknown",
242
+ details: s,
243
+ cause: o
244
+ });
245
+ }, G = (e, t, o, s, u, d) => {
246
+ let f = (e) => o() ? a(/* @__PURE__ */ Error("Volume is closed"), t, e, "lifecycle", "not-applied") : s(), p = l.try({
247
+ try: () => {
248
+ let t = f("persistence");
249
+ if (t) throw t;
250
+ let n = e.getStatus().persistence;
251
+ return n ? {
252
+ state: n.state,
253
+ error: n.state === "error" ? n.lastError : null
254
+ } : {
255
+ state: "unknown",
256
+ error: null
257
+ };
258
+ },
259
+ catch: (e) => e instanceof n ? e : a(e, t, "persistence", "lifecycle")
260
+ });
261
+ return {
262
+ fileName: t,
263
+ sync: l.uninterruptibleMask((n) => l.gen(function* () {
264
+ let o = f("sync");
265
+ if (o) return yield* l.fail(q(o));
266
+ 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)));
267
+ yield* l.scoped(l.gen(function* () {
268
+ 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))))));
269
+ let o = e.getStatus(), s = f("sync");
270
+ if (s) return yield* l.fail(q(s));
271
+ let u = p.ownerGeneration;
272
+ 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"));
273
+ if (o.ownerGeneration !== u) return d.continuity._tag === "pending" ? (d.continuity = {
274
+ _tag: "lost",
275
+ generation: d.continuity.generation
276
+ }, 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"));
277
+ if (d.continuity._tag === "lost" || d.continuity._tag === "pending" && d.continuity.generation !== u) return d.continuity = {
278
+ _tag: "lost",
279
+ generation: d.continuity.generation
280
+ }, 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"));
281
+ yield* l.tryPromise({
282
+ try: () => e.forGeneration(u).sync(),
283
+ catch: (e) => {
284
+ let n = f("sync");
285
+ if (n) return q(n);
286
+ let o = e instanceof _ ? e.dispatch : void 0, s = e instanceof _ ? e.cause : e, c = i(s).code;
287
+ return o === "refused" && c === "VFS_ATTACHMENT_LOST" && d.continuity._tag === "pending" ? (d.continuity = {
288
+ _tag: "lost",
289
+ generation: d.continuity.generation
290
+ }, 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");
291
+ }
292
+ }), d.continuity._tag === "pending" && (d.continuity = { _tag: "clean" });
293
+ }));
294
+ })),
295
+ persistence: p,
296
+ acknowledgeOwnerChange: l.uninterruptibleMask((n) => l.gen(function* () {
297
+ let r = f("acknowledgeOwnerChange");
298
+ if (r) return yield* l.fail(r);
299
+ let i = yield* n(K(e, t, "acknowledgeOwnerChange", { remaining: u }, s));
300
+ yield* l.scoped(l.gen(function* () {
301
+ 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))));
302
+ let r = f("acknowledgeOwnerChange");
303
+ if (r) return yield* l.fail(r);
304
+ let o = e.getStatus();
305
+ 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"));
306
+ (d.continuity._tag === "lost" || d.continuity._tag === "pending" && d.continuity.generation !== i.ownerGeneration) && (d.continuity = {
307
+ _tag: "pending",
308
+ generation: i.ownerGeneration
309
+ });
310
+ }));
311
+ }))
312
+ };
313
+ }, K = (e, t, n, r, i, o = ((e) => e)) => {
314
+ let s = l.callback((r) => {
315
+ let a = !1, s = () => {}, c = (e) => {
316
+ a || (a = !0, s(), r(e));
317
+ }, u = () => {
318
+ let r = e.getStatus();
319
+ 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))));
320
+ };
321
+ return s = e.subscribeStatus(u), u(), l.sync(s);
322
+ });
323
+ return l.gen(function* () {
324
+ let e = a(Object.assign(/* @__PURE__ */ Error("Ready owner wait timed out"), { code: "VFS_OWNER_READY_TIMEOUT" }), t, n, "lifecycle", "not-applied");
325
+ if (r.remaining <= 0) return yield* l.fail(o(e));
326
+ let i = yield* l.clockWith((e) => e.currentTimeMillis), c = l.sleep(r.remaining).pipe(l.andThen(l.fail(o(e))));
327
+ return yield* l.raceFirst(s, c).pipe(l.onExit(() => l.clockWith((e) => e.currentTimeMillis).pipe(l.flatMap((e) => l.sync(() => {
328
+ r.remaining = Math.max(0, r.remaining - Math.max(0, e - i));
329
+ })))));
330
+ });
331
+ }, q = (t) => f.is(e)(t.cause) ? t.cause : t;
332
+ function J(e) {
333
+ return U(e);
334
+ }
335
+ function Y(e) {
336
+ return d.effect(j, U(e));
337
+ }
338
+ var X = (e) => {
339
+ let t = Z.get(e);
340
+ if (!t) throw TypeError("Volume service was not created by this adapter");
341
+ if (Q.has(e)) throw a(/* @__PURE__ */ Error("Volume scope is closed"), e.fileName, "unsafeBackend", "lifecycle", "not-applied");
342
+ return t;
343
+ }, Z = /* @__PURE__ */ new WeakMap(), Q = /* @__PURE__ */ new WeakSet(), $ = (r) => {
344
+ try {
345
+ let i = r.reason?.cause;
346
+ if (f.is(n)(i) && i.kind === "lifecycle" && i.cause !== void 0) {
347
+ let r = i.cause;
348
+ if (f.is(n)(r) || f.is(e)(r) || f.is(t)(r)) return r;
349
+ }
350
+ if (f.is(n)(i) || f.is(e)(i) || f.is(t)(i)) return i;
351
+ } catch {
352
+ return;
353
+ }
354
+ };
355
+ 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 };