UNPKG

@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.

10 lines 468 kB
"use strict";var Is=Object.create;var st=Object.defineProperty;var Fs=Object.getOwnPropertyDescriptor;var Ps=Object.getOwnPropertyNames;var As=Object.getPrototypeOf,ks=Object.prototype.hasOwnProperty;var na=e=>{throw TypeError(e)};var Ts=(e,t,r)=>t in e?st(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var ot=(e,t)=>()=>(e&&(t=e(e=0)),t);var Be=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ie=(e,t)=>{for(var r in t)st(e,r,{get:t[r],enumerable:!0})},ia=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ps(t))!ks.call(e,s)&&s!==r&&st(e,s,{get:()=>t[s],enumerable:!(a=Fs(t,s))||a.enumerable});return e};var K=(e,t,r)=>(r=e!=null?Is(As(e)):{},ia(t||!e||!e.__esModule?st(r,"default",{value:e,enumerable:!0}):r,e)),Us=e=>ia(st({},"__esModule",{value:!0}),e);var ne=(e,t,r)=>Ts(e,typeof t!="symbol"?t+"":t,r),ur=(e,t,r)=>t.has(e)||na("Cannot "+r);var p=(e,t,r)=>(ur(e,t,"read from private field"),r?r.call(e):t.get(e)),E=(e,t,r)=>t.has(e)?na("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),S=(e,t,r,a)=>(ur(e,t,"write to private field"),a?a.call(e,r):t.set(e,r),r),h=(e,t,r)=>(ur(e,t,"access private method"),r);var Fe=(e,t,r,a)=>({set _(s){S(e,t,s,r)},get _(){return p(e,t,a)}});var Rs,C,M=ot(()=>{"use strict";Rs=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href,C=Rs()});var Ct=Be((Wi,Q)=>{"use strict";M();var Oa=9007199254740991,La=function(e){return e}();function _n(e){return e===La}function Ba(e){return typeof e=="string"||Object.prototype.toString.call(e)=="[object String]"}function mn(e){return Object.prototype.toString.call(e)=="[object Date]"}function tr(e){return e!==null&&typeof e=="object"}function rr(e){return typeof e=="function"}function pn(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Oa}function dn(e){return Object.prototype.toString.call(e)=="[object Array]"}function Ga(e){return tr(e)&&!rr(e)&&pn(e.length)}function Hr(e){return Object.prototype.toString.call(e)=="[object ArrayBuffer]"}function un(e,t){return Array.prototype.map.call(e,t)}function cn(e,t){var r=La;return rr(t)&&Array.prototype.every.call(e,function(a,s,o){var n=t(a,s,o);return n&&(r=a),!n}),r}function gn(e){return Object.assign.apply(null,arguments)}function Ha(e){var t,r,a;if(Ba(e)){for(r=e.length,a=new Uint8Array(r),t=0;t<r;t++)a[t]=e.charCodeAt(t)&255;return a}return Hr(e)?new Uint8Array(e):tr(e)&&Hr(e.buffer)?new Uint8Array(e.buffer):Ga(e)?new Uint8Array(e):tr(e)&&rr(e.toString)?Ha(e.toString()):new Uint8Array}Q.exports.MAX_SAFE_INTEGER=Oa;Q.exports.isUndefined=_n;Q.exports.isString=Ba;Q.exports.isObject=tr;Q.exports.isDateTime=mn;Q.exports.isFunction=rr;Q.exports.isArray=dn;Q.exports.isArrayLike=Ga;Q.exports.isArrayBuffer=Hr;Q.exports.map=un;Q.exports.find=cn;Q.exports.extend=gn;Q.exports.toUint8Array=Ha});var It=Be((Ki,Xa)=>{"use strict";M();var Xr="\0";Xa.exports={NULL_CHAR:Xr,TMAGIC:"ustar"+Xr+"00",OLDGNU_MAGIC:"ustar "+Xr,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 Vr=Be((Ji,$)=>{"use strict";M();var ja=Ct(),L=It(),fn=512,jr=L.TPERMALL,Wa=0,Va=0,Wr=[["name",100,0,function(e,t){return Ft(e[t[0]],t[1])},function(e,t,r){return De(e.slice(t,t+r[1]))}],["mode",8,100,function(e,t){var r=e[t[0]]||jr;return r=r&L.TPERMMASK,Ve(r,t[1],jr)},function(e,t,r){var a=fe(e.slice(t,t+r[1]));return a&=L.TPERMMASK,a}],["uid",8,108,function(e,t){return Ve(e[t[0]],t[1],Wa)},function(e,t,r){return fe(e.slice(t,t+r[1]))}],["gid",8,116,function(e,t){return Ve(e[t[0]],t[1],Va)},function(e,t,r){return fe(e.slice(t,t+r[1]))}],["size",12,124,function(e,t){return Ve(e.data.length,t[1])},function(e,t,r){return fe(e.slice(t,t+r[1]))}],["modifyTime",12,136,function(e,t){return ar(e[t[0]],t[1])},function(e,t,r){return sr(e.slice(t,t+r[1]))}],["checksum",8,148,function(e,t){return" "},function(e,t,r){return fe(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 De(e.slice(t,t+r[1]))}],["ustar",8,257,function(e,t){return L.TMAGIC},function(e,t,r){return hn(De(e.slice(t,t+r[1]),!0))},function(e,t){return e[t[0]]==L.TMAGIC||e[t[0]]==L.OLDGNU_MAGIC}],["owner",32,265,function(e,t){return Ft(e[t[0]],t[1])},function(e,t,r){return De(e.slice(t,t+r[1]))}],["group",32,297,function(e,t){return Ft(e[t[0]],t[1])},function(e,t,r){return De(e.slice(t,t+r[1]))}],["majorNumber",8,329,function(e,t){return""},function(e,t,r){return fe(e.slice(t,t+r[1]))}],["minorNumber",8,337,function(e,t){return""},function(e,t,r){return fe(e.slice(t,t+r[1]))}],["prefix",131,345,function(e,t){return Ft(e[t[0]],t[1])},function(e,t,r){return De(e.slice(t,t+r[1]))}],["accessTime",12,476,function(e,t){return ar(e[t[0]],t[1])},function(e,t,r){return sr(e.slice(t,t+r[1]))}],["createTime",12,488,function(e,t){return ar(e[t[0]],t[1])},function(e,t,r){return sr(e.slice(t,t+r[1]))}]],Ka=function(e){var t=e[e.length-1];return t[2]+t[1]}(Wr);function hn(e){if(e.length==8){var t=e.split("");if(t[5]==L.NULL_CHAR)return(t[6]==" "||t[6]==L.NULL_CHAR)&&(t[6]="0"),(t[7]==" "||t[7]==L.NULL_CHAR)&&(t[7]="0"),t=t.join(""),t==L.TMAGIC?t:e;if(t[7]==L.NULL_CHAR)return t[5]==L.NULL_CHAR&&(t[5]=" "),t[6]==L.NULL_CHAR&&(t[6]=" "),t==L.OLDGNU_MAGIC?t:e}return e}function Ft(e,t){return t-=1,ja.isUndefined(e)&&(e=""),e=(""+e).substr(0,t),e+L.NULL_CHAR}function Ve(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+L.NULL_CHAR}function ar(e,t){if(ja.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 Ve(e,t,0)}function De(e,t){var r=String.fromCharCode.apply(null,e);if(t)return r;var a=r.indexOf(L.NULL_CHAR);return a>=0?r.substr(0,a):r}function fe(e){var t=String.fromCharCode.apply(null,e);return parseInt(t.replace(/^0+$/g,""),8)||0}function sr(e){return e.length==0||e[0]==0?null:new Date(1e3*fe(e))}function xn(e,t,r){var a=parseInt(t,10)||0,s=Math.min(a+Ka,e.length),o=0,n=0,l=0;r&&Wr.every(function(u){return u[0]=="checksum"?(n=a+u[2],l=n+u[1],!1):!0});for(var _=32,m=a;m<s;m++){var d=m>=n&&m<l?_:e[m];o=(o+d)%262144}return o}$.exports.recordSize=fn;$.exports.defaultFileMode=jr;$.exports.defaultUid=Wa;$.exports.defaultGid=Va;$.exports.posixHeader=Wr;$.exports.effectiveHeaderSize=Ka;$.exports.calculateChecksum=xn;$.exports.formatTarString=Ft;$.exports.formatTarNumber=Ve;$.exports.formatTarDateTime=ar;$.exports.parseTarString=De;$.exports.parseTarNumber=fe;$.exports.parseTarDateTime=sr});var $a=Be(($i,Qa)=>{"use strict";M();var Mn=It(),or=Ct(),Se=Vr();function Ya(e){return Se.recordSize}function Ja(e){return Math.ceil(e.data.length/Se.recordSize)*Se.recordSize}function Sn(e){var t=0;return e.forEach(function(r){t+=Ya(r)+Ja(r)}),t+=Se.recordSize*2,new Uint8Array(t)}function En(e,t,r){r=parseInt(r)||0;var a=r;Se.posixHeader.forEach(function(_){for(var m=_[3](t,_),d=m.length,u=0;u<d;u+=1)e[a+u]=m.charCodeAt(u)&255;a+=_[1]});var s=or.find(Se.posixHeader,function(_){return _[0]=="checksum"});if(s){var o=Se.calculateChecksum(e,r,!0),n=Se.formatTarNumber(o,s[1]-2)+Mn.NULL_CHAR+" ";a=r+s[2];for(var l=0;l<n.length;l+=1)e[a]=n.charCodeAt(l)&255,a++}return r+Ya(t)}function vn(e,t,r){return r=parseInt(r,10)||0,e.set(t.data,r),r+Ja(t)}function yn(e){e=or.map(e,function(a){return or.extend({},a,{data:or.toUint8Array(a.data)})});var t=Sn(e),r=0;return e.forEach(function(a){r=En(t,a,r),r=vn(t,a,r)}),t}Qa.exports.tar=yn});var es=Be((el,Za)=>{"use strict";M();var wn=It(),Yr=Ct(),_e=Vr(),bn={extractData:!0,checkHeader:!0,checkChecksum:!0,checkFileSize:!0},Cn={size:!0,checksum:!0,ustar:!0},Kr={unexpectedEndOfFile:"Unexpected end of file.",fileCorrupted:"File is corrupted.",checksumCheckFailed:"Checksum check failed."};function In(e){return _e.recordSize}function Fn(e){return Math.ceil(e/_e.recordSize)*_e.recordSize}function Pn(e,t){for(var r=t,a=Math.min(e.length,t+_e.recordSize*2),s=r;s<a;s++)if(e[s]!=0)return!1;return!0}function An(e,t,r){if(e.length-t<_e.recordSize){if(r.checkFileSize)throw new Error(Kr.unexpectedEndOfFile);return null}t=parseInt(t)||0;var a={},s=t;if(_e.posixHeader.forEach(function(l){a[l[0]]=l[4](e,s,l),s+=l[1]}),a.type!=0&&(a.size=0),r.checkHeader&&_e.posixHeader.forEach(function(l){if(Yr.isFunction(l[5])&&!l[5](a,l)){var _=new Error(Kr.fileCorrupted);throw _.data={offset:t+l[2],field:l[0]},_}}),r.checkChecksum){var o=_e.calculateChecksum(e,t,!0);if(o!=a.checksum){var n=new Error(Kr.checksumCheckFailed);throw n.data={offset:t,header:a,checksum:o},n}}return a}function kn(e,t,r,a){return a.extractData?r.size<=0?new Uint8Array:e.slice(t,t+r.size):null}function Tn(e,t){var r={};return _e.posixHeader.forEach(function(a){var s=a[0];Cn[s]||(r[s]=e[s])}),r.isOldGNUFormat=e.ustar==wn.OLDGNU_MAGIC,t&&(r.data=t),r}function Un(e,t){t=Yr.extend({},bn,t);for(var r=[],a=0,s=e.length;s-a>=_e.recordSize;){e=Yr.toUint8Array(e);var o=An(e,a,t);if(!o)break;a+=In(o);var n=kn(e,a,o,t);if(r.push(Tn(o,n)),a+=Fn(o.size),Pn(e,a))break}return r}Za.exports.untar=Un});var Jr=Be((rl,ts)=>{"use strict";M();var Rn=Ct(),Dn=It(),qn=$a(),Nn=es();Rn.extend(ts.exports,qn,Nn,Dn)});async function Zr(e,t,r="pgdata",a="auto"){let s=Gn(e,t),[o,n]=await Hn(s,a),l=r+(n?".tar.gz":".tar"),_=n?"application/x-gzip":"application/x-tar";return typeof File<"u"?new File([o],l,{type:_}):new Blob([o],{type:_})}async function ps(e,t,r){let a=new Uint8Array(await t.arrayBuffer()),s=typeof File<"u"&&t instanceof File?t.name:void 0;(Ln.includes(t.type)||s?.endsWith(".tgz")||s?.endsWith(".tar.gz"))&&(a=await _s(a));let n;try{n=(0,ie.untar)(a)}catch(l){if(l instanceof Error&&l.message.includes("File is corrupted"))a=await _s(a),n=(0,ie.untar)(a);else throw l}for(let l of n){let _=r+l.name,m=_.split("/").slice(0,-1);for(let d=1;d<=m.length;d++){let u=m.slice(0,d).join("/");e.analyzePath(u).exists||e.mkdir(u)}l.type===ie.REGTYPE?(e.writeFile(_,l.data),e.utime(_,ms(l.modifyTime),ms(l.modifyTime))):l.type===ie.DIRTYPE&&e.mkdir(_)}}function Bn(e,t){let r=[],a=s=>{e.readdir(s).forEach(n=>{if(n==="."||n==="..")return;let l=s+"/"+n,_=e.stat(l),m=e.isFile(_.mode)?e.readFile(l,{encoding:"binary"}):new Uint8Array(0);r.push({name:l.substring(t.length),mode:_.mode,size:_.size,type:e.isFile(_.mode)?ie.REGTYPE:ie.DIRTYPE,modifyTime:_.mtime,data:m}),e.isDir(_.mode)&&a(l)})};return a(t),r}function Gn(e,t){let r=Bn(e,t);return(0,ie.tar)(r)}async function Hn(e,t="auto"){if(t==="none")return[e,!1];if(typeof CompressionStream<"u")return[await Xn(e),!0];if(typeof process<"u"&&process.versions&&process.versions.node)return[await jn(e),!0];if(t==="auto")return[e,!1];throw new Error("Compression not supported in this environment")}async function Xn(e){let t=new CompressionStream("gzip"),r=t.writable.getWriter(),a=t.readable.getReader();r.write(e),r.close();let s=[];for(;;){let{value:l,done:_}=await a.read();if(_)break;l&&s.push(l)}let o=new Uint8Array(s.reduce((l,_)=>l+_.length,0)),n=0;return s.forEach(l=>{o.set(l,n),n+=l.length}),o}async function jn(e){let{promisify:t}=await import("util"),{gzip:r}=await import("zlib");return await t(r)(e)}async function _s(e){if(typeof CompressionStream<"u")return await Wn(e);if(typeof process<"u"&&process.versions&&process.versions.node)return await Vn(e);throw new Error("Unsupported environment for decompression")}async function Wn(e){let t=new DecompressionStream("gzip"),r=t.writable.getWriter(),a=t.readable.getReader();r.write(e),r.close();let s=[];for(;;){let{value:l,done:_}=await a.read();if(_)break;l&&s.push(l)}let o=new Uint8Array(s.reduce((l,_)=>l+_.length,0)),n=0;return s.forEach(l=>{o.set(l,n),n+=l.length}),o}async function Vn(e){let{promisify:t}=await import("util"),{gunzip:r}=await import("zlib");return await t(r)(e)}function ms(e){return e?typeof e=="number"?e:Math.floor(e.getTime()/1e3):Math.floor(Date.now()/1e3)}var ie,Ln,ea=ot(()=>{"use strict";M();ie=K(Jr(),1);Ln=["application/x-gtar","application/x-tar+gzip","application/x-gzip","application/gzip"]});var Ut,X,Ee,kt,Tt,Kn,Ye=ot(()=>{"use strict";M();ea();Ut="/tmp/pglite",X=Ut+"/base",Ee=class{constructor(t){this.dataDir=t}async init(t,r){return this.pg=t,{emscriptenOpts:r}}async syncToFs(t){}async initialSyncFs(){}async closeFs(){}async dumpTar(t,r){return Zr(this.pg.Module.FS,X,t,r)}},kt=class{constructor(t,{debug:r=!1}={}){this.dataDir=t,this.debug=r}async syncToFs(t){}async initialSyncFs(){}async closeFs(){}async dumpTar(t,r){return Zr(this.pg.Module.FS,X,t,r)}async init(t,r){return this.pg=t,{emscriptenOpts:{...r,preRun:[...r.preRun||[],s=>{let o=Kn(s,this);s.FS.mkdir(X),s.FS.mount(o,{},X)}]}}}},Tt={EBADF:8,EBADFD:127,EEXIST:20,EINVAL:28,EISDIR:31,ENODEV:43,ENOENT:44,ENOTDIR:54,ENOTEMPTY:55},Kn=(e,t)=>{let r=e.FS,a=t.debug?console.log:null,s={tryFSOperation(o){try{return o()}catch(n){throw n.code?n.code==="UNKNOWN"?new r.ErrnoError(Tt.EINVAL):new r.ErrnoError(n.code):n}},mount(o){return s.createNode(null,"/",16895,0)},syncfs(o,n,l){},createNode(o,n,l,_){if(!r.isDir(l)&&!r.isFile(l))throw new r.ErrnoError(28);let m=r.createNode(o,n,l);return m.node_ops=s.node_ops,m.stream_ops=s.stream_ops,m},getMode:function(o){return a?.("getMode",o),s.tryFSOperation(()=>t.lstat(o).mode)},realPath:function(o){let n=[];for(;o.parent!==o;)n.push(o.name),o=o.parent;return n.push(o.mount.opts.root),n.reverse(),n.join("/")},node_ops:{getattr(o){a?.("getattr",s.realPath(o));let n=s.realPath(o);return s.tryFSOperation(()=>{let l=t.lstat(n);return{...l,dev:0,ino:o.id,nlink:1,rdev:o.rdev,atime:new Date(l.atime),mtime:new Date(l.mtime),ctime:new Date(l.ctime)}})},setattr(o,n){a?.("setattr",s.realPath(o),n);let l=s.realPath(o);s.tryFSOperation(()=>{n.mode!==void 0&&t.chmod(l,n.mode),n.size!==void 0&&t.truncate(l,n.size),n.timestamp!==void 0&&t.utimes(l,n.timestamp,n.timestamp),n.size!==void 0&&t.truncate(l,n.size)})},lookup(o,n){a?.("lookup",s.realPath(o),n);let l=[s.realPath(o),n].join("/"),_=s.getMode(l);return s.createNode(o,n,_)},mknod(o,n,l,_){a?.("mknod",s.realPath(o),n,l,_);let m=s.createNode(o,n,l,_),d=s.realPath(m);return s.tryFSOperation(()=>(r.isDir(m.mode)?t.mkdir(d,{mode:l}):t.writeFile(d,"",{mode:l}),m))},rename(o,n,l){a?.("rename",s.realPath(o),s.realPath(n),l);let _=s.realPath(o),m=[s.realPath(n),l].join("/");s.tryFSOperation(()=>{t.rename(_,m)}),o.name=l},unlink(o,n){a?.("unlink",s.realPath(o),n);let l=[s.realPath(o),n].join("/");try{t.unlink(l)}catch{}},rmdir(o,n){a?.("rmdir",s.realPath(o),n);let l=[s.realPath(o),n].join("/");return s.tryFSOperation(()=>{t.rmdir(l)})},readdir(o){a?.("readdir",s.realPath(o));let n=s.realPath(o);return s.tryFSOperation(()=>t.readdir(n))},symlink(o,n,l){throw a?.("symlink",s.realPath(o),n,l),new r.ErrnoError(63)},readlink(o){throw a?.("readlink",s.realPath(o)),new r.ErrnoError(63)}},stream_ops:{open(o){a?.("open stream",s.realPath(o.node));let n=s.realPath(o.node);return s.tryFSOperation(()=>{r.isFile(o.node.mode)&&(o.shared.refcount=1,o.nfd=t.open(n))})},close(o){return a?.("close stream",s.realPath(o.node)),s.tryFSOperation(()=>{r.isFile(o.node.mode)&&o.nfd&&--o.shared.refcount===0&&t.close(o.nfd)})},dup(o){a?.("dup stream",s.realPath(o.node)),o.shared.refcount++},read(o,n,l,_,m){return a?.("read stream",s.realPath(o.node),l,_,m),_===0?0:s.tryFSOperation(()=>t.read(o.nfd,n,l,_,m))},write(o,n,l,_,m){return a?.("write stream",s.realPath(o.node),l,_,m),s.tryFSOperation(()=>t.write(o.nfd,n.buffer,l,_,m))},llseek(o,n,l){a?.("llseek stream",s.realPath(o.node),n,l);let _=n;if(l===1?_+=o.position:l===2&&r.isFile(o.node.mode)&&s.tryFSOperation(()=>{let m=t.fstat(o.nfd);_+=m.size}),_<0)throw new r.ErrnoError(28);return _},mmap(o,n,l,_,m){if(a?.("mmap stream",s.realPath(o.node),n,l,_,m),!r.isFile(o.node.mode))throw new r.ErrnoError(Tt.ENODEV);let d=e.mmapAlloc(n);return s.stream_ops.read(o,e.HEAP8,d,n,l),{ptr:d,allocated:!0}},msync(o,n,l,_,m){return a?.("msync stream",s.realPath(o.node),l,_,m),s.stream_ops.write(o,n,0,_,l),0}}};return s}});var ds={};Ie(ds,{NodeFS:()=>ta});var nr,ir,ta,us=ot(()=>{"use strict";M();nr=K(require("fs"),1),ir=K(require("path"),1);Ye();ta=class extends Ee{constructor(t){super(t),this.rootDir=ir.resolve(t),nr.existsSync(ir.join(this.rootDir))||nr.mkdirSync(this.rootDir)}async init(t,r){return this.pg=t,{emscriptenOpts:{...r,preRun:[...r.preRun||[],s=>{let o=s.FS.filesystems.NODEFS;s.FS.mkdir(X),s.FS.mount(o,{root:this.rootDir},X)}]}}}async closeFs(){this.pg.Module.FS.quit()}}});var hs={};Ie(hs,{OpfsAhpFS:()=>aa});var Yn,Jn,ra,Dt,Ze,ve,qt,B,he,W,Nt,ye,we,pe,v,cs,qe,$e,me,j,Rt,gs,sa,aa,q,xs=ot(()=>{"use strict";M();Ye();Yn="state.txt",Jn="data",ra={DIR:16384,FILE:32768},aa=class extends kt{constructor(r,{initialPoolSize:a=1e3,maintainedPoolSize:s=100,debug:o=!1}={}){super(r,{debug:o});E(this,v);E(this,Dt);E(this,Ze);E(this,ve);E(this,qt);E(this,B);E(this,he,new Map);E(this,W,new Map);E(this,Nt,0);E(this,ye,new Map);E(this,we,new Map);this.lastCheckpoint=0;this.checkpointInterval=1e3*60;this.poolCounter=0;E(this,pe,new Set);this.initialPoolSize=a,this.maintainedPoolSize=s}async init(r,a){return await h(this,v,cs).call(this),super.init(r,a)}async syncToFs(r=!1){await this.maybeCheckpointState(),await this.maintainPool(),r||this.flush()}async closeFs(){for(let r of p(this,W).values())r.close();p(this,B).flush(),p(this,B).close(),this.pg.Module.FS.quit()}async maintainPool(r){r=r||this.maintainedPoolSize;let a=r-this.state.pool.length,s=[];for(let o=0;o<a;o++)s.push(new Promise(async n=>{++this.poolCounter;let l=`${(Date.now()-1704063600).toString(16).padStart(8,"0")}-${this.poolCounter.toString(16).padStart(8,"0")}`,_=await p(this,ve).getFileHandle(l,{create:!0}),m=await _.createSyncAccessHandle();p(this,he).set(l,_),p(this,W).set(l,m),h(this,v,$e).call(this,{opp:"createPoolFile",args:[l]}),this.state.pool.push(l),n()}));for(let o=0;o>a;o--)s.push(new Promise(async n=>{let l=this.state.pool.pop();h(this,v,$e).call(this,{opp:"deletePoolFile",args:[l]});let _=p(this,he).get(l);p(this,W).get(l)?.close(),await p(this,ve).removeEntry(_.name),p(this,he).delete(l),p(this,W).delete(l),n()}));await Promise.all(s)}_createPoolFileState(r){this.state.pool.push(r)}_deletePoolFileState(r){let a=this.state.pool.indexOf(r);a>-1&&this.state.pool.splice(a,1)}async maybeCheckpointState(){Date.now()-this.lastCheckpoint>this.checkpointInterval&&await this.checkpointState()}async checkpointState(){let r=new TextEncoder().encode(JSON.stringify(this.state));p(this,B).truncate(0),p(this,B).write(r,{at:0}),p(this,B).flush(),this.lastCheckpoint=Date.now()}flush(){for(let r of p(this,pe))try{r.flush()}catch{}p(this,pe).clear()}chmod(r,a){h(this,v,qe).call(this,{opp:"chmod",args:[r,a]},()=>{this._chmodState(r,a)})}_chmodState(r,a){let s=h(this,v,j).call(this,r);s.mode=a}close(r){let a=h(this,v,Rt).call(this,r);p(this,ye).delete(r),p(this,we).delete(a)}fstat(r){let a=h(this,v,Rt).call(this,r);return this.lstat(a)}lstat(r){let a=h(this,v,j).call(this,r),s=a.type==="file"?p(this,W).get(a.backingFilename).getSize():0,o=4096;return{dev:0,ino:0,mode:a.mode,nlink:1,uid:0,gid:0,rdev:0,size:s,blksize:o,blocks:Math.ceil(s/o),atime:a.lastModified,mtime:a.lastModified,ctime:a.lastModified}}mkdir(r,a){h(this,v,qe).call(this,{opp:"mkdir",args:[r,a]},()=>{this._mkdirState(r,a)})}_mkdirState(r,a){let s=h(this,v,me).call(this,r),o=s.pop(),n=[],l=this.state.root;for(let m of s){if(n.push(r),!Object.prototype.hasOwnProperty.call(l.children,m))if(a?.recursive)this.mkdir(n.join("/"));else throw new q("ENOENT","No such file or directory");if(l.children[m].type!=="directory")throw new q("ENOTDIR","Not a directory");l=l.children[m]}if(Object.prototype.hasOwnProperty.call(l.children,o))throw new q("EEXIST","File exists");let _={type:"directory",lastModified:Date.now(),mode:a?.mode||ra.DIR,children:{}};l.children[o]=_}open(r,a,s){if(h(this,v,j).call(this,r).type!=="file")throw new q("EISDIR","Is a directory");let n=h(this,v,gs).call(this);return p(this,ye).set(n,r),p(this,we).set(r,n),n}readdir(r){let a=h(this,v,j).call(this,r);if(a.type!=="directory")throw new q("ENOTDIR","Not a directory");return Object.keys(a.children)}read(r,a,s,o,n){let l=h(this,v,Rt).call(this,r),_=h(this,v,j).call(this,l);if(_.type!=="file")throw new q("EISDIR","Is a directory");return p(this,W).get(_.backingFilename).read(new Uint8Array(a.buffer,s,o),{at:n})}rename(r,a){h(this,v,qe).call(this,{opp:"rename",args:[r,a]},()=>{this._renameState(r,a,!0)})}_renameState(r,a,s=!1){let o=h(this,v,me).call(this,r),n=o.pop(),l=h(this,v,j).call(this,o.join("/"));if(!Object.prototype.hasOwnProperty.call(l.children,n))throw new q("ENOENT","No such file or directory");let _=h(this,v,me).call(this,a),m=_.pop(),d=h(this,v,j).call(this,_.join("/"));if(s&&Object.prototype.hasOwnProperty.call(d.children,m)){let u=d.children[m];p(this,W).get(u.backingFilename).truncate(0),this.state.pool.push(u.backingFilename)}d.children[m]=l.children[n],delete l.children[n]}rmdir(r){h(this,v,qe).call(this,{opp:"rmdir",args:[r]},()=>{this._rmdirState(r)})}_rmdirState(r){let a=h(this,v,me).call(this,r),s=a.pop(),o=h(this,v,j).call(this,a.join("/"));if(!Object.prototype.hasOwnProperty.call(o.children,s))throw new q("ENOENT","No such file or directory");let n=o.children[s];if(n.type!=="directory")throw new q("ENOTDIR","Not a directory");if(Object.keys(n.children).length>0)throw new q("ENOTEMPTY","Directory not empty");delete o.children[s]}truncate(r,a=0){let s=h(this,v,j).call(this,r);if(s.type!=="file")throw new q("EISDIR","Is a directory");let o=p(this,W).get(s.backingFilename);if(!o)throw new q("ENOENT","No such file or directory");o.truncate(a),p(this,pe).add(o)}unlink(r){h(this,v,qe).call(this,{opp:"unlink",args:[r]},()=>{this._unlinkState(r,!0)})}_unlinkState(r,a=!1){let s=h(this,v,me).call(this,r),o=s.pop(),n=h(this,v,j).call(this,s.join("/"));if(!Object.prototype.hasOwnProperty.call(n.children,o))throw new q("ENOENT","No such file or directory");let l=n.children[o];if(l.type!=="file")throw new q("EISDIR","Is a directory");if(delete n.children[o],a){let _=p(this,W).get(l.backingFilename);_?.truncate(0),p(this,pe).add(_),p(this,we).has(r)&&(p(this,ye).delete(p(this,we).get(r)),p(this,we).delete(r))}this.state.pool.push(l.backingFilename)}utimes(r,a,s){h(this,v,qe).call(this,{opp:"utimes",args:[r,a,s]},()=>{this._utimesState(r,a,s)})}_utimesState(r,a,s){let o=h(this,v,j).call(this,r);o.lastModified=s}writeFile(r,a,s){let o=h(this,v,me).call(this,r),n=o.pop(),l=h(this,v,j).call(this,o.join("/"));if(Object.prototype.hasOwnProperty.call(l.children,n)){let d=l.children[n];d.lastModified=Date.now(),h(this,v,$e).call(this,{opp:"setLastModified",args:[r,d.lastModified]})}else{if(this.state.pool.length===0)throw new Error("No more file handles available in the pool");let d={type:"file",lastModified:Date.now(),mode:s?.mode||ra.FILE,backingFilename:this.state.pool.pop()};l.children[n]=d,h(this,v,$e).call(this,{opp:"createFileNode",args:[r,d]})}let _=l.children[n],m=p(this,W).get(_.backingFilename);a.length>0&&(m.write(typeof a=="string"?new TextEncoder().encode(a):new Uint8Array(a),{at:0}),r.startsWith("/pg_wal")&&p(this,pe).add(m))}_createFileNodeState(r,a){let s=h(this,v,me).call(this,r),o=s.pop(),n=h(this,v,j).call(this,s.join("/"));n.children[o]=a;let l=this.state.pool.indexOf(a.backingFilename);return l>-1&&this.state.pool.splice(l,1),a}_setLastModifiedState(r,a){let s=h(this,v,j).call(this,r);s.lastModified=a}write(r,a,s,o,n){let l=h(this,v,Rt).call(this,r),_=h(this,v,j).call(this,l);if(_.type!=="file")throw new q("EISDIR","Is a directory");let m=p(this,W).get(_.backingFilename);if(!m)throw new q("EBADF","Bad file descriptor");let d=m.write(new Uint8Array(a,s,o),{at:n});return l.startsWith("/pg_wal")&&p(this,pe).add(m),d}};Dt=new WeakMap,Ze=new WeakMap,ve=new WeakMap,qt=new WeakMap,B=new WeakMap,he=new WeakMap,W=new WeakMap,Nt=new WeakMap,ye=new WeakMap,we=new WeakMap,pe=new WeakMap,v=new WeakSet,cs=async function(){S(this,Dt,await navigator.storage.getDirectory()),S(this,Ze,await h(this,v,sa).call(this,this.dataDir,{create:!0})),S(this,ve,await h(this,v,sa).call(this,Jn,{from:p(this,Ze),create:!0})),S(this,qt,await p(this,Ze).getFileHandle(Yn,{create:!0})),S(this,B,await p(this,qt).createSyncAccessHandle());let r=new ArrayBuffer(p(this,B).getSize());p(this,B).read(r,{at:0});let a,s=new TextDecoder().decode(r).split(` `),o=!1;try{a=JSON.parse(s[0])}catch{a={root:{type:"directory",lastModified:Date.now(),mode:ra.DIR,children:{}},pool:[]},p(this,B).truncate(0),p(this,B).write(new TextEncoder().encode(JSON.stringify(a)),{at:0}),o=!0}this.state=a;let n=s.slice(1).filter(Boolean).map(d=>JSON.parse(d));for(let d of n){let u=`_${d.opp}State`;if(typeof this[u]=="function")try{this[u].bind(this)(...d.args)}catch(c){console.warn("Error applying OPFS AHP WAL entry",d,c)}}let l=[],_=async d=>{if(d.type==="file")try{let u=await p(this,ve).getFileHandle(d.backingFilename),c=await u.createSyncAccessHandle();p(this,he).set(d.backingFilename,u),p(this,W).set(d.backingFilename,c)}catch(u){console.error("Error opening file handle for node",d,u)}else for(let u of Object.values(d.children))l.push(_(u))};await _(this.state.root);let m=[];for(let d of this.state.pool)m.push(new Promise(async u=>{p(this,he).has(d)&&console.warn("File handle already exists for pool file",d);let c=await p(this,ve).getFileHandle(d),g=await c.createSyncAccessHandle();p(this,he).set(d,c),p(this,W).set(d,g),u()}));await Promise.all([...l,...m]),await this.maintainPool(o?this.initialPoolSize:this.maintainedPoolSize)},qe=function(r,a){let s=h(this,v,$e).call(this,r);try{a()}catch(o){throw p(this,B).truncate(s),o}},$e=function(r){let a=JSON.stringify(r),s=new TextEncoder().encode(` ${a}`),o=p(this,B).getSize();return p(this,B).write(s,{at:o}),p(this,pe).add(p(this,B)),o},me=function(r){return r.split("/").filter(Boolean)},j=function(r,a){let s=h(this,v,me).call(this,r),o=a||this.state.root;for(let n of s){if(o.type!=="directory")throw new q("ENOTDIR","Not a directory");if(!Object.prototype.hasOwnProperty.call(o.children,n))throw new q("ENOENT","No such file or directory");o=o.children[n]}return o},Rt=function(r){let a=p(this,ye).get(r);if(!a)throw new q("EBADF","Bad file descriptor");return a},gs=function(){let r=++Fe(this,Nt)._;for(;p(this,ye).has(r);)Fe(this,Nt)._++;return r},sa=async function(r,a){let s=h(this,v,me).call(this,r),o=a?.from||p(this,Dt);for(let n of s)o=await o.getDirectoryHandle(n,{create:a?.create});return o};q=class extends Error{constructor(t,r){super(r),typeof t=="number"?this.code=t:typeof t=="string"&&(this.code=Tt[t])}}});var $n={};Ie($n,{IdbFs:()=>Je,MemoryFS:()=>Qe,Mutex:()=>ce,PGlite:()=>oa,formatQuery:()=>ns,messages:()=>yt,parse:()=>Ir,protocol:()=>Br,types:()=>Cr,uuid:()=>os});module.exports=Us($n);M();M();M();var ti=new Error("timeout while waiting for mutex to become available"),ri=new Error("mutex already locked"),Ds=new Error("request for lock canceled"),qs=function(e,t,r,a){function s(o){return o instanceof r?o:new r(function(n){n(o)})}return new(r||(r=Promise))(function(o,n){function l(d){try{m(a.next(d))}catch(u){n(u)}}function _(d){try{m(a.throw(d))}catch(u){n(u)}}function m(d){d.done?o(d.value):s(d.value).then(l,_)}m((a=a.apply(e,t||[])).next())})},cr=class{constructor(t,r=Ds){this._value=t,this._cancelError=r,this._weightedQueues=[],this._weightedWaiters=[]}acquire(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);return new Promise((r,a)=>{this._weightedQueues[t-1]||(this._weightedQueues[t-1]=[]),this._weightedQueues[t-1].push({resolve:r,reject:a}),this._dispatch()})}runExclusive(t,r=1){return qs(this,void 0,void 0,function*(){let[a,s]=yield this.acquire(r);try{return yield t(a)}finally{s()}})}waitForUnlock(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);return new Promise(r=>{this._weightedWaiters[t-1]||(this._weightedWaiters[t-1]=[]),this._weightedWaiters[t-1].push(r),this._dispatch()})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(t){this._value=t,this._dispatch()}release(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);this._value+=t,this._dispatch()}cancel(){this._weightedQueues.forEach(t=>t.forEach(r=>r.reject(this._cancelError))),this._weightedQueues=[]}_dispatch(){var t;for(let r=this._value;r>0;r--){let a=(t=this._weightedQueues[r-1])===null||t===void 0?void 0:t.shift();if(!a)continue;let s=this._value,o=r;this._value-=r,r=this._value+1,a.resolve([s,this._newReleaser(o)])}this._drainUnlockWaiters()}_newReleaser(t){let r=!1;return()=>{r||(r=!0,this.release(t))}}_drainUnlockWaiters(){for(let t=this._value;t>0;t--)this._weightedWaiters[t-1]&&(this._weightedWaiters[t-1].forEach(r=>r()),this._weightedWaiters[t-1]=[])}},Ns=function(e,t,r,a){function s(o){return o instanceof r?o:new r(function(n){n(o)})}return new(r||(r=Promise))(function(o,n){function l(d){try{m(a.next(d))}catch(u){n(u)}}function _(d){try{m(a.throw(d))}catch(u){n(u)}}function m(d){d.done?o(d.value):s(d.value).then(l,_)}m((a=a.apply(e,t||[])).next())})},ce=class{constructor(t){this._semaphore=new cr(1,t)}acquire(){return Ns(this,void 0,void 0,function*(){let[,t]=yield this._semaphore.acquire();return t})}runExclusive(t){return this._semaphore.runExclusive(()=>t())}isLocked(){return this._semaphore.isLocked()}waitForUnlock(){return this._semaphore.waitForUnlock()}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};M();M();var la={part:"part",container:"container"};function Ht(e,t,...r){let a=e.length-1,s=r.length-1;if(s!==-1){if(s===0){e[a]=e[a]+r[0]+t;return}e[a]=e[a]+r[0],e.push(...r.slice(1,s)),e.push(r[s]+t)}}function zs(e,...t){let r=[e[0]];r.raw=[e.raw[0]];let a=[];for(let s=0;s<t.length;s++){let o=t[s],n=s+1;if(o?._templateType===la.part){Ht(r,e[n],o.str),Ht(r.raw,e.raw[n],o.str);continue}if(o?._templateType===la.container){Ht(r,e[n],...o.strings),Ht(r.raw,e.raw[n],...o.strings.raw),a.push(...o.values);continue}r.push(e[n]),r.raw.push(e.raw[n]),a.push(o)}return{_templateType:"container",strings:r,values:a}}function gr(e,...t){let{strings:r,values:a}=zs(e,...t);return{query:[r[0],...a.flatMap((s,o)=>[`$${o+1}`,r[o+1]])].join(""),params:a}}var Ir={};Ie(Ir,{parseDescribeStatementResults:()=>it,parseResults:()=>Wt});M();var Cr={};Ie(Cr,{ABSTIME:()=>$s,ACLITEM:()=>no,BIT:()=>mo,BOOL:()=>hr,BPCHAR:()=>ca,BYTEA:()=>xr,CHAR:()=>Bs,CID:()=>js,CIDR:()=>Qs,CIRCLE:()=>to,DATE:()=>fa,FLOAT4:()=>da,FLOAT8:()=>ua,GTSVECTOR:()=>Io,INET:()=>oo,INT2:()=>_a,INT4:()=>ma,INT8:()=>Mr,INTERVAL:()=>lo,JSON:()=>Sr,JSONB:()=>xa,MACADDR:()=>so,MACADDR8:()=>ro,MONEY:()=>ao,NUMERIC:()=>uo,OID:()=>pa,PATH:()=>Ys,PG_DEPENDENCIES:()=>wo,PG_LSN:()=>vo,PG_NDISTINCT:()=>yo,PG_NODE_TREE:()=>Vs,POLYGON:()=>Js,REFCURSOR:()=>co,REGCLASS:()=>xo,REGCONFIG:()=>Fo,REGDICTIONARY:()=>Po,REGNAMESPACE:()=>Ao,REGOPER:()=>fo,REGOPERATOR:()=>ho,REGPROC:()=>Gs,REGPROCEDURE:()=>go,REGROLE:()=>ko,REGTYPE:()=>Mo,RELTIME:()=>Zs,SMGR:()=>Ks,TEXT:()=>nt,TID:()=>Hs,TIME:()=>io,TIMESTAMP:()=>ha,TIMESTAMPTZ:()=>Er,TIMETZ:()=>_o,TINTERVAL:()=>eo,TSQUERY:()=>Co,TSVECTOR:()=>bo,TXID_SNAPSHOT:()=>Eo,UUID:()=>So,VARBIT:()=>po,VARCHAR:()=>ga,XID:()=>Xs,XML:()=>Ws,arrayParser:()=>br,arraySerializer:()=>jt,parseType:()=>Xt,parsers:()=>yr,serializers:()=>wr,types:()=>Ma});M();var Os=globalThis.JSON.parse,Ls=globalThis.JSON.stringify,hr=16,xr=17,Bs=18,Mr=20,_a=21,ma=23,Gs=24,nt=25,pa=26,Hs=27,Xs=28,js=29,Sr=114,Ws=142,Vs=194,Ks=210,Ys=602,Js=604,Qs=650,da=700,ua=701,$s=702,Zs=703,eo=704,to=718,ro=774,ao=790,so=829,oo=869,no=1033,ca=1042,ga=1043,fa=1082,io=1083,ha=1114,Er=1184,lo=1186,_o=1266,mo=1560,po=1562,uo=1700,co=1790,go=2202,fo=2203,ho=2204,xo=2205,Mo=2206,So=2950,Eo=2970,vo=3220,yo=3361,wo=3402,bo=3614,Co=3615,Io=3642,Fo=3734,Po=3769,xa=3802,Ao=4089,ko=4096,Ma={string:{to:nt,from:[nt,ga,ca],serialize:e=>{if(typeof e=="string")return e;if(typeof e=="number")return e.toString();throw new Error("Invalid input for string type")},parse:e=>e},number:{to:0,from:[_a,ma,pa,da,ua],serialize:e=>e.toString(),parse:e=>+e},bigint:{to:Mr,from:[Mr],serialize:e=>e.toString(),parse:e=>{let t=BigInt(e);return t<Number.MIN_SAFE_INTEGER||t>Number.MAX_SAFE_INTEGER?t:Number(t)}},json:{to:Sr,from:[Sr,xa],serialize:e=>typeof e=="string"?e:Ls(e),parse:e=>Os(e)},boolean:{to:hr,from:[hr],serialize:e=>{if(typeof e!="boolean")throw new Error("Invalid input for boolean type");return e?"t":"f"},parse:e=>e==="t"},date:{to:Er,from:[fa,ha,Er],serialize:e=>{if(typeof e=="string")return e;if(typeof e=="number")return new Date(e).toISOString();if(e instanceof Date)return e.toISOString();throw new Error("Invalid input for date type")},parse:e=>new Date(e)},bytea:{to:xr,from:[xr],serialize:e=>{if(!(e instanceof Uint8Array))throw new Error("Invalid input for bytea type");return"\\x"+Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")},parse:e=>{let t=e.slice(2);return Uint8Array.from({length:t.length/2},(r,a)=>parseInt(t.substring(a*2,(a+1)*2),16))}}},vr=To(Ma),yr=vr.parsers,wr=vr.serializers;function Xt(e,t,r){if(e===null)return null;let a=r?.[t]??vr.parsers[t];return a?a(e,t):e}function To(e){return Object.keys(e).reduce(({parsers:t,serializers:r},a)=>{let{to:s,from:o,serialize:n,parse:l}=e[a];return r[s]=n,r[a]=n,t[a]=l,Array.isArray(o)?o.forEach(_=>{t[_]=l,r[_]=n}):(t[o]=l,r[o]=n),{parsers:t,serializers:r}},{parsers:{},serializers:{}})}var Uo=/\\/g,Ro=/"/g;function Do(e){return e.replace(Uo,"\\\\").replace(Ro,'\\"')}function jt(e,t,r){if(Array.isArray(e)===!1)return e;if(!e.length)return"{}";let a=e[0],s=r===1020?";":",";return Array.isArray(a)?`{${e.map(o=>jt(o,t,r)).join(s)}}`:`{${e.map(o=>(o===void 0&&(o=null),o===null?"null":'"'+Do(t?t(o):o.toString())+'"')).join(s)}}`}var fr={i:0,char:null,str:"",quoted:!1,last:0,p:null};function br(e,t,r){return fr.i=fr.last=0,Sa(fr,e,t,r)[0]}function Sa(e,t,r,a){let s=[],o=a===1020?";":",";for(;e.i<t.length;e.i++){if(e.char=t[e.i],e.quoted)e.char==="\\"?e.str+=t[++e.i]:e.char==='"'?(s.push(r?r(e.str):e.str),e.str="",e.quoted=t[e.i+1]==='"',e.last=e.i+2):e.str+=e.char;else if(e.char==='"')e.quoted=!0;else if(e.char==="{")e.last=++e.i,s.push(Sa(e,t,r,a));else if(e.char==="}"){e.quoted=!1,e.last<e.i&&s.push(r?r(t.slice(e.last,e.i)):t.slice(e.last,e.i)),e.last=e.i+1;break}else e.char===o&&e.p!=="}"&&e.p!=='"'&&(s.push(r?r(t.slice(e.last,e.i)):t.slice(e.last,e.i)),e.last=e.i+1);e.p=e.char}return e.last<e.i&&s.push(r?r(t.slice(e.last,e.i+1)):t.slice(e.last,e.i+1)),s}function Wt(e,t,r,a){let s=[],o={rows:[],fields:[]},n=0,l={...t,...r?.parsers};return e.forEach(_=>{switch(_.name){case"rowDescription":{let m=_;o.fields=m.fields.map(d=>({name:d.name,dataTypeID:d.dataTypeID}));break}case"dataRow":{if(!o)break;let m=_;r?.rowMode==="array"?o.rows.push(m.fields.map((d,u)=>Xt(d,o.fields[u].dataTypeID,l))):o.rows.push(Object.fromEntries(m.fields.map((d,u)=>[o.fields[u].name,Xt(d,o.fields[u].dataTypeID,l)])));break}case"commandComplete":{n+=qo(_),s.push({...o,affectedRows:n,...a?{blob:a}:{}}),o={rows:[],fields:[]};break}}}),s.length===0&&s.push({affectedRows:0,rows:[],fields:[]}),s}function qo(e){let t=e.text.split(" ");switch(t[0]){case"INSERT":return parseInt(t[2],10);case"UPDATE":case"DELETE":case"COPY":return parseInt(t[1],10);default:return 0}}function it(e){let t=e.find(r=>r.name==="parameterDescription");return t?t.dataTypeIDs:[]}var Br={};Ie(Br,{Parser:()=>Ue,messages:()=>yt,serialize:()=>N});M();M();M();M();function Ge(e){let t=e.length;for(let r=e.length-1;r>=0;r--){let a=e.charCodeAt(r);a>127&&a<=2047?t++:a>2047&&a<=65535&&(t+=2),a>=56320&&a<=57343&&r--}return t}var z,O,Xe,Kt,je,J,Vt,He,Ea,Pe=class{constructor(t=256){this.size=t;E(this,J);E(this,z);E(this,O,5);E(this,Xe,!1);E(this,Kt,new TextEncoder);E(this,je,0);S(this,z,h(this,J,Vt).call(this,t))}addInt32(t){return h(this,J,He).call(this,4),p(this,z).setInt32(p(this,O),t,p(this,Xe)),S(this,O,p(this,O)+4),this}addInt16(t){return h(this,J,He).call(this,2),p(this,z).setInt16(p(this,O),t,p(this,Xe)),S(this,O,p(this,O)+2),this}addCString(t){return t&&this.addString(t),h(this,J,He).call(this,1),p(this,z).setUint8(p(this,O),0),Fe(this,O)._++,this}addString(t=""){let r=Ge(t);return h(this,J,He).call(this,r),p(this,Kt).encodeInto(t,new Uint8Array(p(this,z).buffer,p(this,O))),S(this,O,p(this,O)+r),this}add(t){return h(this,J,He).call(this,t.byteLength),new Uint8Array(p(this,z).buffer).set(new Uint8Array(t),p(this,O)),S(this,O,p(this,O)+t.byteLength),this}flush(t){let r=h(this,J,Ea).call(this,t);return S(this,O,5),S(this,z,h(this,J,Vt).call(this,this.size)),new Uint8Array(r)}};z=new WeakMap,O=new WeakMap,Xe=new WeakMap,Kt=new WeakMap,je=new WeakMap,J=new WeakSet,Vt=function(t){return new DataView(new ArrayBuffer(t))},He=function(t){if(p(this,z).byteLength-p(this,O)<t){let a=p(this,z).buffer,s=a.byteLength+(a.byteLength>>1)+t;S(this,z,h(this,J,Vt).call(this,s)),new Uint8Array(p(this,z).buffer).set(new Uint8Array(a))}},Ea=function(t){if(t){p(this,z).setUint8(p(this,je),t);let r=p(this,O)-(p(this,je)+1);p(this,z).setInt32(p(this,je)+1,r,p(this,Xe))}return p(this,z).buffer.slice(t?0:5,p(this,O))};var D=new Pe,No=e=>{D.addInt16(3).addInt16(0);for(let a of Object.keys(e))D.addCString(a).addCString(e[a]);D.addCString("client_encoding").addCString("UTF8");let t=D.addCString("").flush(),r=t.byteLength+4;return new Pe().addInt32(r).add(t).flush()},zo=()=>{let e=new DataView(new ArrayBuffer(8));return e.setInt32(0,8,!1),e.setInt32(4,80877103,!1),new Uint8Array(e.buffer)},Oo=e=>D.addCString(e).flush(112),Lo=(e,t)=>(D.addCString(e).addInt32(Ge(t)).addString(t),D.flush(112)),Bo=e=>D.addString(e).flush(112),Go=e=>D.addCString(e).flush(81),Ho=[],Xo=e=>{let t=e.name??"";t.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",t,t.length),console.error("This can cause conflicts and silent errors executing queries"));let r=D.addCString(t).addCString(e.text).addInt16(e.types?.length??0);return e.types?.forEach(a=>r.addInt32(a)),D.flush(80)},We=new Pe;var jo=(e,t)=>{for(let r=0;r<e.length;r++){let a=t?t(e[r],r):e[r];if(a===null)D.addInt16(0),We.addInt32(-1);else if(a instanceof ArrayBuffer||ArrayBuffer.isView(a)){let s=ArrayBuffer.isView(a)?a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength):a;D.addInt16(1),We.addInt32(s.byteLength),We.add(s)}else D.addInt16(0),We.addInt32(Ge(a)),We.addString(a)}},Wo=(e={})=>{let t=e.portal??"",r=e.statement??"",a=e.binary??!1,s=e.values??Ho,o=s.length;return D.addCString(t).addCString(r),D.addInt16(o),jo(s,e.valueMapper),D.addInt16(o),D.add(We.flush()),D.addInt16(a?1:0),D.flush(66)},Vo=new Uint8Array([69,0,0,0,9,0,0,0,0,0]),Ko=e=>{if(!e||!e.portal&&!e.rows)return Vo;let t=e.portal??"",r=e.rows??0,a=Ge(t),s=4+a+1+4,o=new DataView(new ArrayBuffer(1+s));return o.setUint8(0,69),o.setInt32(1,s,!1),new TextEncoder().encodeInto(t,new Uint8Array(o.buffer,5)),o.setUint8(a+5,0),o.setUint32(o.byteLength-4,r,!1),new Uint8Array(o.buffer)},Yo=(e,t)=>{let r=new DataView(new ArrayBuffer(16));return r.setInt32(0,16,!1),r.setInt16(4,1234,!1),r.setInt16(6,5678,!1),r.setInt32(8,e,!1),r.setInt32(12,t,!1),new Uint8Array(r.buffer)},Fr=(e,t)=>{let r=new Pe;return r.addCString(t),r.flush(e)},Jo=D.addCString("P").flush(68),Qo=D.addCString("S").flush(68),$o=e=>e.name?Fr(68,`${e.type}${e.name??""}`):e.type==="P"?Jo:Qo,Zo=e=>{let t=`${e.type}${e.name??""}`;return Fr(67,t)},en=e=>D.add(e).flush(100),tn=e=>Fr(102,e),Yt=e=>new Uint8Array([e,0,0,0,4]),rn=Yt(72),an=Yt(83),sn=Yt(88),on=Yt(99),N={startup:No,password:Oo,requestSsl:zo,sendSASLInitialResponseMessage:Lo,sendSCRAMClientFinalMessage:Bo,query:Go,parse:Xo,bind:Wo,execute:Ko,describe:$o,close:Zo,flush:()=>rn,sync:()=>an,end:()=>sn,copyData:en,copyDone:()=>on,copyFail:tn,cancel:Yo};M();var yt={};Ie(yt,{AuthenticationCleartextPassword:()=>_t,AuthenticationMD5Password:()=>mt,AuthenticationOk:()=>lt,AuthenticationSASL:()=>pt,AuthenticationSASLContinue:()=>dt,AuthenticationSASLFinal:()=>ut,BackendKeyDataMessage:()=>St,CommandCompleteMessage:()=>ke,CopyDataMessage:()=>ct,CopyResponse:()=>gt,DataRowMessage:()=>vt,DatabaseError:()=>xe,Field:()=>ft,NoticeMessage:()=>Te,NotificationResponseMessage:()=>Ae,ParameterDescriptionMessage:()=>xt,ParameterStatusMessage:()=>Mt,ReadyForQueryMessage:()=>Et,RowDescriptionMessage:()=>ht,bindComplete:()=>Ar,closeComplete:()=>kr,copyDone:()=>qr,emptyQuery:()=>Dr,noData:()=>Tr,parseComplete:()=>Pr,portalSuspended:()=>Ur,replicationStart:()=>Rr});M();var Pr={name:"parseComplete",length:5},Ar={name:"bindComplete",length:5},kr={name:"closeComplete",length:5},Tr={name:"noData",length:5},Ur={name:"portalSuspended",length:5},Rr={name:"replicationStart",length:4},Dr={name:"emptyQuery",length:4},qr={name:"copyDone",length:4},lt=class{constructor(t){this.length=t;this.name="authenticationOk"}},_t=class{constructor(t){this.length=t;this.name="authenticationCleartextPassword"}},mt=class{constructor(t,r){this.length=t;this.salt=r;this.name="authenticationMD5Password"}},pt=class{constructor(t,r){this.length=t;this.mechanisms=r;this.name="authenticationSASL"}},dt=class{constructor(t,r){this.length=t;this.data=r;this.name="authenticationSASLContinue"}},ut=class{constructor(t,r){this.length=t;this.data=r;this.name="authenticationSASLFinal"}},xe=class extends Error{constructor(r,a,s){super(r);this.length=a;this.name=s}},ct=class{constructor(t,r){this.length=t;this.chunk=r;this.name="copyData"}},gt=class{constructor(t,r,a,s){this.length=t;this.name=r;this.binary=a;this.columnTypes=new Array(s)}},ft=class{constructor(t,r,a,s,o,n,l){this.name=t;this.tableID=r;this.columnID=a;this.dataTypeID=s;this.dataTypeSize=o;this.dataTypeModifier=n;this.format=l}},ht=class{constructor(t,r){this.length=t;this.fieldCount=r;this.name="rowDescription";this.fields=new Array(this.fieldCount)}},xt=class{constructor(t,r){this.length=t;this.parameterCount=r;this.name="parameterDescription";this.dataTypeIDs=new Array(this.parameterCount)}},Mt=class{constructor(t,r,a){this.length=t;this.parameterName=r;this.parameterValue=a;this.name="parameterStatus"}},St=class{constructor(t,r,a){this.length=t;this.processID=r;this.secretKey=a;this.name="backendKeyData"}},Ae=class{constructor(t,r,a,s){this.length=t;this.processId=r;this.channel=a;this.payload=s;this.name="notification"}},Et=class{constructor(t,r){this.length=t;this.status=r;this.name="readyForQuery"}},ke=class{constructor(t,r){this.length=t;this.text=r;this.name="commandComplete"}},vt=class{constructor(t,r){this.length=t;this.fields=r;this.name="dataRow";this.fieldCount=r.length}},Te=class{constructor(t,r){this.length=t;this.message=r;this.name="notice"}};M();var Nr={text:0,binary:1};M();var nn=new ArrayBuffer(0),ge,H,Qt,$t,wt,Jt=class{constructor(t=0){E(this,ge,new DataView(nn));E(this,H);E(this,Qt,"utf-8");E(this,$t,new TextDecoder(p(this,Qt)));E(this,wt,!1);S(this,H,t)}setBuffer(t,r){S(this,H,t),S(this,ge,new DataView(r))}int16(){let t=p(this,ge).getInt16(p(this,H),p(this,wt));return S(this,H,p(this,H)+2),t}byte(){let t=p(this,ge).getUint8(p(this,H));return Fe(this,H)._++,t}int32(){let t=p(this,ge).getInt32(p(this,H),p(this,wt));return S(this,H,p(this,H)+4),t}string(t){return p(this,$t).decode(this.bytes(t))}cstring(){let t=p(this,H),r=t;for(;p(this,ge).getUint8(r++)!==0;);let a=this.string(r-t-1);return S(this,H,r),a}bytes(t){let r=p(this,ge).buffer.slice(p(this,H),p(this,H)+t);return S(this,H,p(this,H)+t),new Uint8Array(r)}};ge=new WeakMap,H=new WeakMap,Qt=new WeakMap,$t=new WeakMap,wt=new WeakMap;var zr=1,ln=4,va=zr+ln,ya=new ArrayBuffer(0);var Y,ee,te,w,k,wa,ba,Ca,Ia,Fa,Pa,Aa,Or,ka,Ta,Ua,Ra,Da,qa,Na,za,Lr,Ue=class{constructor(){E(this,k);E(this,Y,new DataView(ya));E(this,ee,0);E(this,te,0);E(this,w,new Jt)}parse(t,r){h(this,k,wa).call(this,ArrayBuffer.isView(t)?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t);let a=p(this,te)+p(this,ee),s=p(this,te);for(;s+va<=a;){let o=p(this,Y).getUint8(s),n=p(this,Y).getUint32(s+zr,!1),l=zr+n;if(l+s<=a){let _=h(this,k,ba).call(this,s+va,o,n,p(this,Y).buffer);r(_),s+=l}else break}s===a?(S(this,Y,new DataView(ya)),S(this,ee,0),S(this,te,0)):(S(this,ee,a-s),S(this,te,s))}};Y=new WeakMap,ee=new WeakMap,te=new WeakMap,w=new WeakMap,k=new WeakSet,wa=function(t){if(p(this,ee)>0){let r=p(this,ee)+t.byteLength;if(r+p(this,te)>p(this,Y).byteLength){let s;if(r<=p(this,Y).byteLength&&p(this,te)>=p(this,ee))s=p(this,Y).buffer;else{let o=p(this,Y).byteLength*2;for(;r>=o;)o*=2;s=new ArrayBuffer(o)}new Uint8Array(s).set(new Uint8Array(p(this,Y).buffer,p(this,te),p(this,ee))),S(this,Y,new DataView(s)),S(this,te,0)}new Uint8Array(p(this,Y).buffer).set(new Uint8Array(t),p(this,te)+p(this,ee)),S(this,ee,r)}else S(this,Y,new DataView(t)),S(this,te,0),S(this,ee,t.byteLength)},ba=function(t,r,a,s){switch(r){case 50:return Ar;case 49:return Pr;case 51:return kr;case 110:return Tr;case 115:return Ur;case 99:return qr;case 87:return Rr;case 73:return Dr;case 68:return h(this,k,Da).call(this,t,a,s);case 67:return h(this,k,Ia).call(this,t,a,s);case 90:return h(this,k,Ca).call(this,t,a,s);case 65:return h(this,k,ka).call(this,t,a,s);case 82:return h(this,k,za).call(this,t,a,s);case 83:return h(this,k,qa).call(this,t,a,s);case 75:return h(this,k,Na).call(this,t,a,s);case 69:return h(this,k,Lr).call(this,t,a,s,"error");case 78:return h(this,k,Lr).call(this,t,a,s,"notice");case 84:return h(this,k,Ta).call(this,t,a,s);case 116:return h(this,k,Ra).call(this,t,a,s);case 71:return h(this,k,Pa).call(this,t,a,s);case 72:return h(this,k,Aa).call(this,t,a,s);case 100:return h(this,k,Fa).call(this,t,a,s);default:return new xe("received invalid response: "+r.toString(16),a,"error")}},Ca=function(t,r,a){p(this,w).setBuffer(t,a);let s=p(this,w).string(1);return new Et(r,s)},Ia=function(t,r,a){p(this,w).setBuffer(t,a);let s=p(this,w).cstring();return new ke(r,s)},Fa=function(t,r,a){let s=a.slice(t,t+(r-4));return new ct(r,new Uint8Array(s))},Pa=function(t,r,a){return h(this,k,Or).call(this,t,r,a,"copyInResponse")},Aa=function(t,r,a){return h(this,k,Or).call(this,t,r,a,"copyOutResponse")},Or=function(t,r,a,s){p(this,w).setBuffer(t,a);let o=p(this,w).byte()!==0,n=p(this,w).int16(),l=new gt(r,s,o,n);for(let _=0;_<n;_++)l.columnTypes[_]=p(this,w).int16();return l},ka=function(t,r,a){p(this,w).setBuffer(t,a);let s=p(this,w).int32(),o=p(this,w).cstring(),n=p(this,w).cstring();return new Ae(r,s,o,n)},Ta=function(t,r,a){p(this,w).setBuffer(t,a);let s=p(this,w).int16(),o=new ht(r,s);for(let n=0;n<s;n++)o.fields[n]=h(this,k,Ua).call(this);return o},Ua=function(){let t=p(this,w).cstring(),r=p(this,w).int32(),a=p(this,w).int16(),s=p(this,w).int32(),o=p(this,w).int16(),n=p(this,w).int32(),l=p(this,w).int16()===0?Nr.text:Nr.binary;return new ft(t,r,a,s,o,n,l)},Ra=function(t,r,a){p(this,w).setBuffer(t,a);let s=p(this,w).int16(),o=new xt(r,s);for(let n=0;n<s;n++)o.dataTypeIDs[n]=p(this,w).int32();return o},Da=function(t,r,a){p(this,w).setBuffer(t,a);let s=p(this,w).int16(),o=new Array(s);for(let n=0;n<s;n++){let l=p(this,w).int32();o[n]=l===-1?null:p(this,w).string(l)}return new vt(r,o)},qa=function(t,r,a){p(this,w).setBuffer(t,a);let s=p(this,w).cstring(),o=p(this,w).cstring();return new Mt(r,s,o)},Na=function(t,r,a){p(this,w).setBuffer(t,a);let s=p(this,w).int32(),o=p(this,w).int32();return new St(r,s,o)},za=function(t,r,a){p(this,w).setBuffer(t,a);let s=p(this,w).int32();switch(s){case 0:return new lt(r);case 3:return new _t(r);case 5:return new mt(r,p(this,w).bytes(4));case 10:{let o=[];for(;;){let n=p(this,w).cstring();if(n.length===0)return new pt(r,o);o.push(n)}}case 11:return new dt(r,p(this,w).string(r-8));case 12:return new ut(r,p(this,w).string(r-8));default:throw new Error("Unknown authenticationOk message type "+s)}},Lr=function(t,r,a,s){p(this,w).setBuffer(t,a);let o={},n=p(this,w).string(1);for(;n!=="\0";)o[n]=p(this,w).cstring(),n=p(this,w).string(1);let l=o.M,_=s==="notice"?new Te(r,l):new xe(l,r,s);return _.severity=o.S,_.code=o.C,_.detail=o.D,_.hint=o.H,_.position=o.P,_.internalPosition=o.p,_.internalQuery=o.q,_.where=o.W,_.schema=o.s,_.table=o.t,_.column=o.c,_.dataType=o.d,_.constraint=o.n,_.file=o.F,_.line=o.L,_.routine=o.R,_};var bt,Me,R,oe,Zt,Re,Gr,er=class{constructor(){E(this,R);this.serializers={...wr};this.parsers={...yr};E(this,bt,!1);E(this,Me,!1)}async _initArrayTypes({force:t=!1}={}){if(p(this,bt)&&!t)return;S(this,bt,!0);let r=await this.query(` SELECT b.oid, b.typarray FROM pg_catalog.pg_type a LEFT JOIN pg_catalog.pg_type b ON b.oid = a.typelem WHERE a.typcategory = 'A' GROUP BY b.oid, b.typarray ORDER BY b.oid `);for(let a of r.rows)this.serializers[a.typarray]=s=>jt(s,this.serializers[a.oid],a.typarray),this.parsers[a.typarray]=s=>br(s,this.parsers[a.oid],a.typarray)}async refreshArrayTypes(){await this._initArrayTypes({force:!0})}async query(t,r,a){return await this._checkReady(),await this._runExclusiveTransaction(async()=>await h(this,R,Zt).call(this,t,r,a))}async sql(t,...r){let{query:a,params:s}=gr(t,...r);return await this.query(a,s)}async exec(t,r){return await this._checkReady(),await this._runExclusiveTransaction(async()=>await h(this,R,Re).call(this,t,r))}async describeQuery(t,r){try{await h(this,R,oe).call(this,N.parse({text:t,types:r?.paramTypes}),r);let a=await h(this,R,oe).call(this,N.describe({type:"S"}),r),s=a.messages.find(_=>_.name==="parameterDescription"),o=a.messages.find(_=>_.name==="rowDescription"),n=s?.dataTypeIDs.map(_=>({dataTypeID:_,serializer:this.serializers[_]}))??[],l=o?.fields.map(_=>({name:_.name,dataTypeID:_.dataTypeID,parser:this.parsers[_.dataTypeID]}))??[];retur