@electric-sql/pglite
Version:
PGlite is a WASM Postgres build packaged into a TypeScript client library that enables you to run Postgres in the browser, Node.js and Bun, with no need to install any other dependencies. It is only 3.7mb gzipped.
4 lines • 24.4 kB
JavaScript
"use strict";var Ge=Object.create;var $=Object.defineProperty;var Be=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var qe=Object.getPrototypeOf,Ye=Object.prototype.hasOwnProperty;var Se=e=>{throw TypeError(e)};var Xe=(e,t)=>()=>(e&&(t=e(e=0)),t);var H=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Je=(e,t)=>{for(var r in t)$(e,r,{get:t[r],enumerable:!0})},we=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of We(t))!Ye.call(e,o)&&o!==r&&$(e,o,{get:()=>t[o],enumerable:!(n=Be(t,o))||n.enumerable});return e};var ie=(e,t,r)=>(r=e!=null?Ge(qe(e)):{},we(t||!e||!e.__esModule?$(r,"default",{value:e,enumerable:!0}):r,e)),Ke=e=>we($({},"__esModule",{value:!0}),e);var oe=(e,t,r)=>t.has(e)||Se("Cannot "+r);var d=(e,t,r)=>(oe(e,t,"read from private field"),r?r.call(e):t.get(e)),N=(e,t,r)=>t.has(e)?Se("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),z=(e,t,r,n)=>(oe(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r),p=(e,t,r)=>(oe(e,t,"access private method"),r);var se=(e,t,r,n)=>({set _(o){z(e,t,o,r)},get _(){return d(e,t,n)}});var y=Xe(()=>{"use strict"});var B=H((Ct,F)=>{"use strict";y();var be=9007199254740991,Fe=function(e){return e}();function $e(e){return e===Fe}function Pe(e){return typeof e=="string"||Object.prototype.toString.call(e)=="[object String]"}function Ve(e){return Object.prototype.toString.call(e)=="[object Date]"}function V(e){return e!==null&&typeof e=="object"}function Z(e){return typeof e=="function"}function Ze(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=be}function Qe(e){return Object.prototype.toString.call(e)=="[object Array]"}function Ne(e){return V(e)&&!Z(e)&&Ze(e.length)}function ae(e){return Object.prototype.toString.call(e)=="[object ArrayBuffer]"}function et(e,t){return Array.prototype.map.call(e,t)}function tt(e,t){var r=Fe;return Z(t)&&Array.prototype.every.call(e,function(n,o,i){var s=t(n,o,i);return s&&(r=n),!s}),r}function rt(e){return Object.assign.apply(null,arguments)}function Ee(e){var t,r,n;if(Pe(e)){for(r=e.length,n=new Uint8Array(r),t=0;t<r;t++)n[t]=e.charCodeAt(t)&255;return n}return ae(e)?new Uint8Array(e):V(e)&&ae(e.buffer)?new Uint8Array(e.buffer):Ne(e)?new Uint8Array(e):V(e)&&Z(e.toString)?Ee(e.toString()):new Uint8Array}F.exports.MAX_SAFE_INTEGER=be;F.exports.isUndefined=$e;F.exports.isString=Pe;F.exports.isObject=V;F.exports.isDateTime=Ve;F.exports.isFunction=Z;F.exports.isArray=Qe;F.exports.isArrayLike=Ne;F.exports.isArrayBuffer=ae;F.exports.map=et;F.exports.find=tt;F.exports.extend=rt;F.exports.toUint8Array=Ee});var W=H((Ht,Ae)=>{"use strict";y();var ce="\0";Ae.exports={NULL_CHAR:ce,TMAGIC:"ustar"+ce+"00",OLDGNU_MAGIC:"ustar "+ce,REGTYPE:0,LNKTYPE:1,SYMTYPE:2,CHRTYPE:3,BLKTYPE:4,DIRTYPE:5,FIFOTYPE:6,CONTTYPE:7,TSUID:parseInt("4000",8),TSGID:parseInt("2000",8),TSVTX:parseInt("1000",8),TUREAD:parseInt("0400",8),TUWRITE:parseInt("0200",8),TUEXEC:parseInt("0100",8),TGREAD:parseInt("0040",8),TGWRITE:parseInt("0020",8),TGEXEC:parseInt("0010",8),TOREAD:parseInt("0004",8),TOWRITE:parseInt("0002",8),TOEXEC:parseInt("0001",8),TPERMALL:parseInt("0777",8),TPERMMASK:parseInt("0777",8)}});var le=H((jt,P)=>{"use strict";y();var Te=B(),g=W(),nt=512,de=g.TPERMALL,ve=0,xe=0,ue=[["name",100,0,function(e,t){return q(e[t[0]],t[1])},function(e,t,r){return _(e.slice(t,t+r[1]))}],["mode",8,100,function(e,t){var r=e[t[0]]||de;return r=r&g.TPERMMASK,L(r,t[1],de)},function(e,t,r){var n=v(e.slice(t,t+r[1]));return n&=g.TPERMMASK,n}],["uid",8,108,function(e,t){return L(e[t[0]],t[1],ve)},function(e,t,r){return v(e.slice(t,t+r[1]))}],["gid",8,116,function(e,t){return L(e[t[0]],t[1],xe)},function(e,t,r){return v(e.slice(t,t+r[1]))}],["size",12,124,function(e,t){return L(e.data.length,t[1])},function(e,t,r){return v(e.slice(t,t+r[1]))}],["modifyTime",12,136,function(e,t){return Q(e[t[0]],t[1])},function(e,t,r){return ee(e.slice(t,t+r[1]))}],["checksum",8,148,function(e,t){return" "},function(e,t,r){return v(e.slice(t,t+r[1]))}],["type",1,156,function(e,t){return""+(parseInt(e[t[0]],10)||0)%8},function(e,t,r){return(parseInt(String.fromCharCode(e[t]),10)||0)%8}],["linkName",100,157,function(e,t){return""},function(e,t,r){return _(e.slice(t,t+r[1]))}],["ustar",8,257,function(e,t){return g.TMAGIC},function(e,t,r){return it(_(e.slice(t,t+r[1]),!0))},function(e,t){return e[t[0]]==g.TMAGIC||e[t[0]]==g.OLDGNU_MAGIC}],["owner",32,265,function(e,t){return q(e[t[0]],t[1])},function(e,t,r){return _(e.slice(t,t+r[1]))}],["group",32,297,function(e,t){return q(e[t[0]],t[1])},function(e,t,r){return _(e.slice(t,t+r[1]))}],["majorNumber",8,329,function(e,t){return""},function(e,t,r){return v(e.slice(t,t+r[1]))}],["minorNumber",8,337,function(e,t){return""},function(e,t,r){return v(e.slice(t,t+r[1]))}],["prefix",131,345,function(e,t){return q(e[t[0]],t[1])},function(e,t,r){return _(e.slice(t,t+r[1]))}],["accessTime",12,476,function(e,t){return Q(e[t[0]],t[1])},function(e,t,r){return ee(e.slice(t,t+r[1]))}],["createTime",12,488,function(e,t){return Q(e[t[0]],t[1])},function(e,t,r){return ee(e.slice(t,t+r[1]))}]],De=function(e){var t=e[e.length-1];return t[2]+t[1]}(ue);function it(e){if(e.length==8){var t=e.split("");if(t[5]==g.NULL_CHAR)return(t[6]==" "||t[6]==g.NULL_CHAR)&&(t[6]="0"),(t[7]==" "||t[7]==g.NULL_CHAR)&&(t[7]="0"),t=t.join(""),t==g.TMAGIC?t:e;if(t[7]==g.NULL_CHAR)return t[5]==g.NULL_CHAR&&(t[5]=" "),t[6]==g.NULL_CHAR&&(t[6]=" "),t==g.OLDGNU_MAGIC?t:e}return e}function q(e,t){return t-=1,Te.isUndefined(e)&&(e=""),e=(""+e).substr(0,t),e+g.NULL_CHAR}function L(e,t,r){for(r=parseInt(r)||0,t-=1,e=(parseInt(e)||r).toString(8).substr(-t,t);e.length<t;)e="0"+e;return e+g.NULL_CHAR}function Q(e,t){if(Te.isDateTime(e))e=Math.floor(1*e/1e3);else if(e=parseInt(e,10),isFinite(e)){if(e<=0)return""}else e=Math.floor(1*new Date/1e3);return L(e,t,0)}function _(e,t){var r=String.fromCharCode.apply(null,e);if(t)return r;var n=r.indexOf(g.NULL_CHAR);return n>=0?r.substr(0,n):r}function v(e){var t=String.fromCharCode.apply(null,e);return parseInt(t.replace(/^0+$/g,""),8)||0}function ee(e){return e.length==0||e[0]==0?null:new Date(1e3*v(e))}function ot(e,t,r){var n=parseInt(t,10)||0,o=Math.min(n+De,e.length),i=0,s=0,a=0;r&&ue.every(function(h){return h[0]=="checksum"?(s=n+h[2],a=s+h[1],!1):!0});for(var c=32,u=n;u<o;u++){var m=u>=s&&u<a?c:e[u];i=(i+m)%262144}return i}P.exports.recordSize=nt;P.exports.defaultFileMode=de;P.exports.defaultUid=ve;P.exports.defaultGid=xe;P.exports.posixHeader=ue;P.exports.effectiveHeaderSize=De;P.exports.calculateChecksum=ot;P.exports.formatTarString=q;P.exports.formatTarNumber=L;P.exports.formatTarDateTime=Q;P.exports.parseTarString=_;P.exports.parseTarNumber=v;P.exports.parseTarDateTime=ee});var Me=H((Bt,Ie)=>{"use strict";y();var st=W(),te=B(),k=le();function Oe(e){return k.recordSize}function ke(e){return Math.ceil(e.data.length/k.recordSize)*k.recordSize}function at(e){var t=0;return e.forEach(function(r){t+=Oe(r)+ke(r)}),t+=k.recordSize*2,new Uint8Array(t)}function ct(e,t,r){r=parseInt(r)||0;var n=r;k.posixHeader.forEach(function(c){for(var u=c[3](t,c),m=u.length,h=0;h<m;h+=1)e[n+h]=u.charCodeAt(h)&255;n+=c[1]});var o=te.find(k.posixHeader,function(c){return c[0]=="checksum"});if(o){var i=k.calculateChecksum(e,r,!0),s=k.formatTarNumber(i,o[1]-2)+st.NULL_CHAR+" ";n=r+o[2];for(var a=0;a<s.length;a+=1)e[n]=s.charCodeAt(a)&255,n++}return r+Oe(t)}function dt(e,t,r){return r=parseInt(r,10)||0,e.set(t.data,r),r+ke(t)}function ut(e){e=te.map(e,function(n){return te.extend({},n,{data:te.toUint8Array(n.data)})});var t=at(e),r=0;return e.forEach(function(n){r=ct(t,n,r),r=dt(t,n,r)}),t}Ie.exports.tar=ut});var ze=H((qt,Ue)=>{"use strict";y();var lt=W(),me=B(),E=le(),pt={extractData:!0,checkHeader:!0,checkChecksum:!0,checkFileSize:!0},mt={size:!0,checksum:!0,ustar:!0},pe={unexpectedEndOfFile:"Unexpected end of file.",fileCorrupted:"File is corrupted.",checksumCheckFailed:"Checksum check failed."};function ht(e){return E.recordSize}function ft(e){return Math.ceil(e/E.recordSize)*E.recordSize}function yt(e,t){for(var r=t,n=Math.min(e.length,t+E.recordSize*2),o=r;o<n;o++)if(e[o]!=0)return!1;return!0}function gt(e,t,r){if(e.length-t<E.recordSize){if(r.checkFileSize)throw new Error(pe.unexpectedEndOfFile);return null}t=parseInt(t)||0;var n={},o=t;if(E.posixHeader.forEach(function(a){n[a[0]]=a[4](e,o,a),o+=a[1]}),n.type!=0&&(n.size=0),r.checkHeader&&E.posixHeader.forEach(function(a){if(me.isFunction(a[5])&&!a[5](n,a)){var c=new Error(pe.fileCorrupted);throw c.data={offset:t+a[2],field:a[0]},c}}),r.checkChecksum){var i=E.calculateChecksum(e,t,!0);if(i!=n.checksum){var s=new Error(pe.checksumCheckFailed);throw s.data={offset:t,header:n,checksum:i},s}}return n}function St(e,t,r,n){return n.extractData?r.size<=0?new Uint8Array:e.slice(t,t+r.size):null}function wt(e,t){var r={};return E.posixHeader.forEach(function(n){var o=n[0];mt[o]||(r[o]=e[o])}),r.isOldGNUFormat=e.ustar==lt.OLDGNU_MAGIC,t&&(r.data=t),r}function bt(e,t){t=me.extend({},pt,t);for(var r=[],n=0,o=e.length;o-n>=E.recordSize;){e=me.toUint8Array(e);var i=gt(e,n,t);if(!i)break;n+=ht(i);var s=St(e,n,i,t);if(r.push(wt(i,s)),n+=ft(i.size),yt(e,n))break}return r}Ue.exports.untar=bt});var Ce=H((Xt,_e)=>{"use strict";y();var Ft=B(),Pt=W(),Nt=Me(),Et=ze();Ft.extend(_e.exports,Nt,Et,Pt)});var Ut={};Je(Ut,{OpfsAhpFS:()=>ye});module.exports=Ke(Ut);y();y();y();var C=ie(Ce(),1);async function Re(e,t,r="pgdata",n="auto"){let o=Tt(e,t),[i,s]=await vt(o,n),a=r+(s?".tar.gz":".tar"),c=s?"application/x-gzip":"application/x-tar";return typeof File<"u"?new File([i],a,{type:c}):new Blob([i],{type:c})}function At(e,t){let r=[],n=o=>{e.readdir(o).forEach(s=>{if(s==="."||s==="..")return;let a=o+"/"+s,c=e.stat(a),u=e.isFile(c.mode)?e.readFile(a,{encoding:"binary"}):new Uint8Array(0);r.push({name:a.substring(t.length),mode:c.mode,size:c.size,type:e.isFile(c.mode)?C.REGTYPE:C.DIRTYPE,modifyTime:c.mtime,data:u}),e.isDir(c.mode)&&n(a)})};return n(t),r}function Tt(e,t){let r=At(e,t);return(0,C.tar)(r)}async function vt(e,t="auto"){if(t==="none")return[e,!1];if(typeof CompressionStream<"u")return[await xt(e),!0];if(typeof process<"u"&&process.versions&&process.versions.node)return[await Dt(e),!0];if(t==="auto")return[e,!1];throw new Error("Compression not supported in this environment")}async function xt(e){let t=new CompressionStream("gzip"),r=t.writable.getWriter(),n=t.readable.getReader();r.write(e),r.close();let o=[];for(;;){let{value:a,done:c}=await n.read();if(c)break;a&&o.push(a)}let i=new Uint8Array(o.reduce((a,c)=>a+c.length,0)),s=0;return o.forEach(a=>{i.set(a,s),s+=a.length}),i}async function Dt(e){let{promisify:t}=await import("util"),{gzip:r}=await import("zlib");return await t(r)(e)}var Ot="/tmp/pglite",he=Ot+"/base";var re=class{constructor(t,{debug:r=!1}={}){this.dataDir=t,this.debug=r}async syncToFs(t){}async initialSyncFs(){}async closeFs(){}async dumpTar(t,r){return Re(this.pg.Module.FS,he,t,r)}async init(t,r){return this.pg=t,{emscriptenOpts:{...r,preRun:[...r.preRun||[],o=>{let i=kt(o,this);o.FS.mkdir(he),o.FS.mount(i,{},he)}]}}}},ne={EBADF:8,EBADFD:127,EEXIST:20,EINVAL:28,EISDIR:31,ENODEV:43,ENOENT:44,ENOTDIR:54,ENOTEMPTY:55},kt=(e,t)=>{let r=e.FS,n=t.debug?console.log:null,o={tryFSOperation(i){try{return i()}catch(s){throw s.code?s.code==="UNKNOWN"?new r.ErrnoError(ne.EINVAL):new r.ErrnoError(s.code):s}},mount(i){return o.createNode(null,"/",16895,0)},syncfs(i,s,a){},createNode(i,s,a,c){if(!r.isDir(a)&&!r.isFile(a))throw new r.ErrnoError(28);let u=r.createNode(i,s,a);return u.node_ops=o.node_ops,u.stream_ops=o.stream_ops,u},getMode:function(i){return n?.("getMode",i),o.tryFSOperation(()=>t.lstat(i).mode)},realPath:function(i){let s=[];for(;i.parent!==i;)s.push(i.name),i=i.parent;return s.push(i.mount.opts.root),s.reverse(),s.join("/")},node_ops:{getattr(i){n?.("getattr",o.realPath(i));let s=o.realPath(i);return o.tryFSOperation(()=>{let a=t.lstat(s);return{...a,dev:0,ino:i.id,nlink:1,rdev:i.rdev,atime:new Date(a.atime),mtime:new Date(a.mtime),ctime:new Date(a.ctime)}})},setattr(i,s){n?.("setattr",o.realPath(i),s);let a=o.realPath(i);o.tryFSOperation(()=>{s.mode!==void 0&&t.chmod(a,s.mode),s.size!==void 0&&t.truncate(a,s.size),s.timestamp!==void 0&&t.utimes(a,s.timestamp,s.timestamp),s.size!==void 0&&t.truncate(a,s.size)})},lookup(i,s){n?.("lookup",o.realPath(i),s);let a=[o.realPath(i),s].join("/"),c=o.getMode(a);return o.createNode(i,s,c)},mknod(i,s,a,c){n?.("mknod",o.realPath(i),s,a,c);let u=o.createNode(i,s,a,c),m=o.realPath(u);return o.tryFSOperation(()=>(r.isDir(u.mode)?t.mkdir(m,{mode:a}):t.writeFile(m,"",{mode:a}),u))},rename(i,s,a){n?.("rename",o.realPath(i),o.realPath(s),a);let c=o.realPath(i),u=[o.realPath(s),a].join("/");o.tryFSOperation(()=>{t.rename(c,u)}),i.name=a},unlink(i,s){n?.("unlink",o.realPath(i),s);let a=[o.realPath(i),s].join("/");try{t.unlink(a)}catch{}},rmdir(i,s){n?.("rmdir",o.realPath(i),s);let a=[o.realPath(i),s].join("/");return o.tryFSOperation(()=>{t.rmdir(a)})},readdir(i){n?.("readdir",o.realPath(i));let s=o.realPath(i);return o.tryFSOperation(()=>t.readdir(s))},symlink(i,s,a){throw n?.("symlink",o.realPath(i),s,a),new r.ErrnoError(63)},readlink(i){throw n?.("readlink",o.realPath(i)),new r.ErrnoError(63)}},stream_ops:{open(i){n?.("open stream",o.realPath(i.node));let s=o.realPath(i.node);return o.tryFSOperation(()=>{r.isFile(i.node.mode)&&(i.shared.refcount=1,i.nfd=t.open(s))})},close(i){return n?.("close stream",o.realPath(i.node)),o.tryFSOperation(()=>{r.isFile(i.node.mode)&&i.nfd&&--i.shared.refcount===0&&t.close(i.nfd)})},dup(i){n?.("dup stream",o.realPath(i.node)),i.shared.refcount++},read(i,s,a,c,u){return n?.("read stream",o.realPath(i.node),a,c,u),c===0?0:o.tryFSOperation(()=>t.read(i.nfd,s,a,c,u))},write(i,s,a,c,u){return n?.("write stream",o.realPath(i.node),a,c,u),o.tryFSOperation(()=>t.write(i.nfd,s.buffer,a,c,u))},llseek(i,s,a){n?.("llseek stream",o.realPath(i.node),s,a);let c=s;if(a===1?c+=i.position:a===2&&r.isFile(i.node.mode)&&o.tryFSOperation(()=>{let u=t.fstat(i.nfd);c+=u.size}),c<0)throw new r.ErrnoError(28);return c},mmap(i,s,a,c,u){if(n?.("mmap stream",o.realPath(i.node),s,a,c,u),!r.isFile(i.node.mode))throw new r.ErrnoError(ne.ENODEV);let m=e.mmapAlloc(s);return o.stream_ops.read(i,e.HEAP8,m,s,a),{ptr:m,allocated:!0}},msync(i,s,a,c,u){return n?.("msync stream",o.realPath(i.node),a,c,u),o.stream_ops.write(i,s,0,c,a),0}}};return o};var It="state.txt",Mt="data",fe={DIR:16384,FILE:32768},X,G,I,J,S,x,b,K,M,U,T,l,He,R,j,A,w,Y,Le,ge,ye=class extends re{constructor(r,{initialPoolSize:n=1e3,maintainedPoolSize:o=100,debug:i=!1}={}){super(r,{debug:i});N(this,l);N(this,X);N(this,G);N(this,I);N(this,J);N(this,S);N(this,x,new Map);N(this,b,new Map);N(this,K,0);N(this,M,new Map);N(this,U,new Map);this.lastCheckpoint=0;this.checkpointInterval=1e3*60;this.poolCounter=0;N(this,T,new Set);this.initialPoolSize=n,this.maintainedPoolSize=o}async init(r,n){return await p(this,l,He).call(this),super.init(r,n)}async syncToFs(r=!1){await this.maybeCheckpointState(),await this.maintainPool(),r||this.flush()}async closeFs(){for(let r of d(this,b).values())r.close();d(this,S).flush(),d(this,S).close(),this.pg.Module.FS.quit()}async maintainPool(r){r=r||this.maintainedPoolSize;let n=r-this.state.pool.length,o=[];for(let i=0;i<n;i++)o.push(new Promise(async s=>{++this.poolCounter;let a=`${(Date.now()-1704063600).toString(16).padStart(8,"0")}-${this.poolCounter.toString(16).padStart(8,"0")}`,c=await d(this,I).getFileHandle(a,{create:!0}),u=await c.createSyncAccessHandle();d(this,x).set(a,c),d(this,b).set(a,u),p(this,l,j).call(this,{opp:"createPoolFile",args:[a]}),this.state.pool.push(a),s()}));for(let i=0;i>n;i--)o.push(new Promise(async s=>{let a=this.state.pool.pop();p(this,l,j).call(this,{opp:"deletePoolFile",args:[a]});let c=d(this,x).get(a);d(this,b).get(a)?.close(),await d(this,I).removeEntry(c.name),d(this,x).delete(a),d(this,b).delete(a),s()}));await Promise.all(o)}_createPoolFileState(r){this.state.pool.push(r)}_deletePoolFileState(r){let n=this.state.pool.indexOf(r);n>-1&&this.state.pool.splice(n,1)}async maybeCheckpointState(){Date.now()-this.lastCheckpoint>this.checkpointInterval&&await this.checkpointState()}async checkpointState(){let r=new TextEncoder().encode(JSON.stringify(this.state));d(this,S).truncate(0),d(this,S).write(r,{at:0}),d(this,S).flush(),this.lastCheckpoint=Date.now()}flush(){for(let r of d(this,T))try{r.flush()}catch{}d(this,T).clear()}chmod(r,n){p(this,l,R).call(this,{opp:"chmod",args:[r,n]},()=>{this._chmodState(r,n)})}_chmodState(r,n){let o=p(this,l,w).call(this,r);o.mode=n}close(r){let n=p(this,l,Y).call(this,r);d(this,M).delete(r),d(this,U).delete(n)}fstat(r){let n=p(this,l,Y).call(this,r);return this.lstat(n)}lstat(r){let n=p(this,l,w).call(this,r),o=n.type==="file"?d(this,b).get(n.backingFilename).getSize():0,i=4096;return{dev:0,ino:0,mode:n.mode,nlink:1,uid:0,gid:0,rdev:0,size:o,blksize:i,blocks:Math.ceil(o/i),atime:n.lastModified,mtime:n.lastModified,ctime:n.lastModified}}mkdir(r,n){p(this,l,R).call(this,{opp:"mkdir",args:[r,n]},()=>{this._mkdirState(r,n)})}_mkdirState(r,n){let o=p(this,l,A).call(this,r),i=o.pop(),s=[],a=this.state.root;for(let u of o){if(s.push(r),!Object.prototype.hasOwnProperty.call(a.children,u))if(n?.recursive)this.mkdir(s.join("/"));else throw new f("ENOENT","No such file or directory");if(a.children[u].type!=="directory")throw new f("ENOTDIR","Not a directory");a=a.children[u]}if(Object.prototype.hasOwnProperty.call(a.children,i))throw new f("EEXIST","File exists");let c={type:"directory",lastModified:Date.now(),mode:n?.mode||fe.DIR,children:{}};a.children[i]=c}open(r,n,o){if(p(this,l,w).call(this,r).type!=="file")throw new f("EISDIR","Is a directory");let s=p(this,l,Le).call(this);return d(this,M).set(s,r),d(this,U).set(r,s),s}readdir(r){let n=p(this,l,w).call(this,r);if(n.type!=="directory")throw new f("ENOTDIR","Not a directory");return Object.keys(n.children)}read(r,n,o,i,s){let a=p(this,l,Y).call(this,r),c=p(this,l,w).call(this,a);if(c.type!=="file")throw new f("EISDIR","Is a directory");return d(this,b).get(c.backingFilename).read(new Uint8Array(n.buffer,o,i),{at:s})}rename(r,n){p(this,l,R).call(this,{opp:"rename",args:[r,n]},()=>{this._renameState(r,n,!0)})}_renameState(r,n,o=!1){let i=p(this,l,A).call(this,r),s=i.pop(),a=p(this,l,w).call(this,i.join("/"));if(!Object.prototype.hasOwnProperty.call(a.children,s))throw new f("ENOENT","No such file or directory");let c=p(this,l,A).call(this,n),u=c.pop(),m=p(this,l,w).call(this,c.join("/"));if(o&&Object.prototype.hasOwnProperty.call(m.children,u)){let h=m.children[u];d(this,b).get(h.backingFilename).truncate(0),this.state.pool.push(h.backingFilename)}m.children[u]=a.children[s],delete a.children[s]}rmdir(r){p(this,l,R).call(this,{opp:"rmdir",args:[r]},()=>{this._rmdirState(r)})}_rmdirState(r){let n=p(this,l,A).call(this,r),o=n.pop(),i=p(this,l,w).call(this,n.join("/"));if(!Object.prototype.hasOwnProperty.call(i.children,o))throw new f("ENOENT","No such file or directory");let s=i.children[o];if(s.type!=="directory")throw new f("ENOTDIR","Not a directory");if(Object.keys(s.children).length>0)throw new f("ENOTEMPTY","Directory not empty");delete i.children[o]}truncate(r,n=0){let o=p(this,l,w).call(this,r);if(o.type!=="file")throw new f("EISDIR","Is a directory");let i=d(this,b).get(o.backingFilename);if(!i)throw new f("ENOENT","No such file or directory");i.truncate(n),d(this,T).add(i)}unlink(r){p(this,l,R).call(this,{opp:"unlink",args:[r]},()=>{this._unlinkState(r,!0)})}_unlinkState(r,n=!1){let o=p(this,l,A).call(this,r),i=o.pop(),s=p(this,l,w).call(this,o.join("/"));if(!Object.prototype.hasOwnProperty.call(s.children,i))throw new f("ENOENT","No such file or directory");let a=s.children[i];if(a.type!=="file")throw new f("EISDIR","Is a directory");if(delete s.children[i],n){let c=d(this,b).get(a.backingFilename);c?.truncate(0),d(this,T).add(c),d(this,U).has(r)&&(d(this,M).delete(d(this,U).get(r)),d(this,U).delete(r))}this.state.pool.push(a.backingFilename)}utimes(r,n,o){p(this,l,R).call(this,{opp:"utimes",args:[r,n,o]},()=>{this._utimesState(r,n,o)})}_utimesState(r,n,o){let i=p(this,l,w).call(this,r);i.lastModified=o}writeFile(r,n,o){let i=p(this,l,A).call(this,r),s=i.pop(),a=p(this,l,w).call(this,i.join("/"));if(Object.prototype.hasOwnProperty.call(a.children,s)){let m=a.children[s];m.lastModified=Date.now(),p(this,l,j).call(this,{opp:"setLastModified",args:[r,m.lastModified]})}else{if(this.state.pool.length===0)throw new Error("No more file handles available in the pool");let m={type:"file",lastModified:Date.now(),mode:o?.mode||fe.FILE,backingFilename:this.state.pool.pop()};a.children[s]=m,p(this,l,j).call(this,{opp:"createFileNode",args:[r,m]})}let c=a.children[s],u=d(this,b).get(c.backingFilename);n.length>0&&(u.write(typeof n=="string"?new TextEncoder().encode(n):new Uint8Array(n),{at:0}),r.startsWith("/pg_wal")&&d(this,T).add(u))}_createFileNodeState(r,n){let o=p(this,l,A).call(this,r),i=o.pop(),s=p(this,l,w).call(this,o.join("/"));s.children[i]=n;let a=this.state.pool.indexOf(n.backingFilename);return a>-1&&this.state.pool.splice(a,1),n}_setLastModifiedState(r,n){let o=p(this,l,w).call(this,r);o.lastModified=n}write(r,n,o,i,s){let a=p(this,l,Y).call(this,r),c=p(this,l,w).call(this,a);if(c.type!=="file")throw new f("EISDIR","Is a directory");let u=d(this,b).get(c.backingFilename);if(!u)throw new f("EBADF","Bad file descriptor");let m=u.write(new Uint8Array(n,o,i),{at:s});return a.startsWith("/pg_wal")&&d(this,T).add(u),m}};X=new WeakMap,G=new WeakMap,I=new WeakMap,J=new WeakMap,S=new WeakMap,x=new WeakMap,b=new WeakMap,K=new WeakMap,M=new WeakMap,U=new WeakMap,T=new WeakMap,l=new WeakSet,He=async function(){z(this,X,await navigator.storage.getDirectory()),z(this,G,await p(this,l,ge).call(this,this.dataDir,{create:!0})),z(this,I,await p(this,l,ge).call(this,Mt,{from:d(this,G),create:!0})),z(this,J,await d(this,G).getFileHandle(It,{create:!0})),z(this,S,await d(this,J).createSyncAccessHandle());let r=new ArrayBuffer(d(this,S).getSize());d(this,S).read(r,{at:0});let n,o=new TextDecoder().decode(r).split(`
`),i=!1;try{n=JSON.parse(o[0])}catch{n={root:{type:"directory",lastModified:Date.now(),mode:fe.DIR,children:{}},pool:[]},d(this,S).truncate(0),d(this,S).write(new TextEncoder().encode(JSON.stringify(n)),{at:0}),i=!0}this.state=n;let s=o.slice(1).filter(Boolean).map(m=>JSON.parse(m));for(let m of s){let h=`_${m.opp}State`;if(typeof this[h]=="function")try{this[h].bind(this)(...m.args)}catch(D){console.warn("Error applying OPFS AHP WAL entry",m,D)}}let a=[],c=async m=>{if(m.type==="file")try{let h=await d(this,I).getFileHandle(m.backingFilename),D=await h.createSyncAccessHandle();d(this,x).set(m.backingFilename,h),d(this,b).set(m.backingFilename,D)}catch(h){console.error("Error opening file handle for node",m,h)}else for(let h of Object.values(m.children))a.push(c(h))};await c(this.state.root);let u=[];for(let m of this.state.pool)u.push(new Promise(async h=>{d(this,x).has(m)&&console.warn("File handle already exists for pool file",m);let D=await d(this,I).getFileHandle(m),je=await D.createSyncAccessHandle();d(this,x).set(m,D),d(this,b).set(m,je),h()}));await Promise.all([...a,...u]),await this.maintainPool(i?this.initialPoolSize:this.maintainedPoolSize)},R=function(r,n){let o=p(this,l,j).call(this,r);try{n()}catch(i){throw d(this,S).truncate(o),i}},j=function(r){let n=JSON.stringify(r),o=new TextEncoder().encode(`
${n}`),i=d(this,S).getSize();return d(this,S).write(o,{at:i}),d(this,T).add(d(this,S)),i},A=function(r){return r.split("/").filter(Boolean)},w=function(r,n){let o=p(this,l,A).call(this,r),i=n||this.state.root;for(let s of o){if(i.type!=="directory")throw new f("ENOTDIR","Not a directory");if(!Object.prototype.hasOwnProperty.call(i.children,s))throw new f("ENOENT","No such file or directory");i=i.children[s]}return i},Y=function(r){let n=d(this,M).get(r);if(!n)throw new f("EBADF","Bad file descriptor");return n},Le=function(){let r=++se(this,K)._;for(;d(this,M).has(r);)se(this,K)._++;return r},ge=async function(r,n){let o=p(this,l,A).call(this,r),i=n?.from||d(this,X);for(let s of o)i=await i.getDirectoryHandle(s,{create:n?.create});return i};var f=class extends Error{constructor(t,r){super(r),typeof t=="number"?this.code=t:typeof t=="string"&&(this.code=ne[t])}};0&&(module.exports={OpfsAhpFS});
//# sourceMappingURL=opfs-ahp.cjs.map