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 476 kB
"use strict";var Fs=Object.create;var at=Object.defineProperty;var Ps=Object.getOwnPropertyDescriptor;var As=Object.getOwnPropertyNames;var ks=Object.getPrototypeOf,Ts=Object.prototype.hasOwnProperty;var ia=e=>{throw TypeError(e)};var Us=(e,t,r)=>t in e?at(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var st=(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)at(e,r,{get:t[r],enumerable:!0})},la=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of As(t))!Ts.call(e,s)&&s!==r&&at(e,s,{get:()=>t[s],enumerable:!(a=Ps(t,s))||a.enumerable});return e};var K=(e,t,r)=>(r=e!=null?Fs(ks(e)):{},la(t||!e||!e.__esModule?at(r,"default",{value:e,enumerable:!0}):r,e)),Rs=e=>la(at({},"__esModule",{value:!0}),e);var ie=(e,t,r)=>Us(e,typeof t!="symbol"?t+"":t,r),cr=(e,t,r)=>t.has(e)||ia("Cannot "+r);var p=(e,t,r)=>(cr(e,t,"read from private field"),r?r.call(e):t.get(e)),E=(e,t,r)=>t.has(e)?ia("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),S=(e,t,r,a)=>(cr(e,t,"write to private field"),a?a.call(e,r):t.set(e,r),r),h=(e,t,r)=>(cr(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 Ds,C,M=st(()=>{"use strict";Ds=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href,C=Ds()});var bt=Be((Zi,Q)=>{"use strict";M();var La=9007199254740991,Ba=function(e){return e}();function mn(e){return e===Ba}function Ga(e){return typeof e=="string"||Object.prototype.toString.call(e)=="[object String]"}function pn(e){return Object.prototype.toString.call(e)=="[object Date]"}function rr(e){return e!==null&&typeof e=="object"}function ar(e){return typeof e=="function"}function dn(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=La}function un(e){return Object.prototype.toString.call(e)=="[object Array]"}function Ha(e){return rr(e)&&!ar(e)&&dn(e.length)}function Xr(e){return Object.prototype.toString.call(e)=="[object ArrayBuffer]"}function cn(e,t){return Array.prototype.map.call(e,t)}function gn(e,t){var r=Ba;return ar(t)&&Array.prototype.every.call(e,function(a,s,o){var n=t(a,s,o);return n&&(r=a),!n}),r}function fn(e){return Object.assign.apply(null,arguments)}function Xa(e){var t,r,a;if(Ga(e)){for(r=e.length,a=new Uint8Array(r),t=0;t<r;t++)a[t]=e.charCodeAt(t)&255;return a}return Xr(e)?new Uint8Array(e):rr(e)&&Xr(e.buffer)?new Uint8Array(e.buffer):Ha(e)?new Uint8Array(e):rr(e)&&ar(e.toString)?Xa(e.toString()):new Uint8Array}Q.exports.MAX_SAFE_INTEGER=La;Q.exports.isUndefined=mn;Q.exports.isString=Ga;Q.exports.isObject=rr;Q.exports.isDateTime=pn;Q.exports.isFunction=ar;Q.exports.isArray=un;Q.exports.isArrayLike=Ha;Q.exports.isArrayBuffer=Xr;Q.exports.map=cn;Q.exports.find=gn;Q.exports.extend=fn;Q.exports.toUint8Array=Xa});var Ct=Be((tl,ja)=>{"use strict";M();var jr="\0";ja.exports={NULL_CHAR:jr,TMAGIC:"ustar"+jr+"00",OLDGNU_MAGIC:"ustar "+jr,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 Kr=Be((al,$)=>{"use strict";M();var Wa=bt(),L=Ct(),hn=512,Wr=L.TPERMALL,Va=0,Ka=0,Vr=[["name",100,0,function(e,t){return It(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]]||Wr;return r=r&L.TPERMMASK,Ve(r,t[1],Wr)},function(e,t,r){var a=he(e.slice(t,t+r[1]));return a&=L.TPERMMASK,a}],["uid",8,108,function(e,t){return Ve(e[t[0]],t[1],Va)},function(e,t,r){return he(e.slice(t,t+r[1]))}],["gid",8,116,function(e,t){return Ve(e[t[0]],t[1],Ka)},function(e,t,r){return he(e.slice(t,t+r[1]))}],["size",12,124,function(e,t){return Ve(e.data.length,t[1])},function(e,t,r){return he(e.slice(t,t+r[1]))}],["modifyTime",12,136,function(e,t){return sr(e[t[0]],t[1])},function(e,t,r){return or(e.slice(t,t+r[1]))}],["checksum",8,148,function(e,t){return" "},function(e,t,r){return he(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 xn(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 It(e[t[0]],t[1])},function(e,t,r){return De(e.slice(t,t+r[1]))}],["group",32,297,function(e,t){return It(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 he(e.slice(t,t+r[1]))}],["minorNumber",8,337,function(e,t){return""},function(e,t,r){return he(e.slice(t,t+r[1]))}],["prefix",131,345,function(e,t){return It(e[t[0]],t[1])},function(e,t,r){return De(e.slice(t,t+r[1]))}],["accessTime",12,476,function(e,t){return sr(e[t[0]],t[1])},function(e,t,r){return or(e.slice(t,t+r[1]))}],["createTime",12,488,function(e,t){return sr(e[t[0]],t[1])},function(e,t,r){return or(e.slice(t,t+r[1]))}]],Ya=function(e){var t=e[e.length-1];return t[2]+t[1]}(Vr);function xn(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 It(e,t){return t-=1,Wa.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 sr(e,t){if(Wa.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 he(e){var t=String.fromCharCode.apply(null,e);return parseInt(t.replace(/^0+$/g,""),8)||0}function or(e){return e.length==0||e[0]==0?null:new Date(1e3*he(e))}function Mn(e,t,r){var a=parseInt(t,10)||0,s=Math.min(a+Ya,e.length),o=0,n=0,l=0;r&&Vr.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=hn;$.exports.defaultFileMode=Wr;$.exports.defaultUid=Va;$.exports.defaultGid=Ka;$.exports.posixHeader=Vr;$.exports.effectiveHeaderSize=Ya;$.exports.calculateChecksum=Mn;$.exports.formatTarString=It;$.exports.formatTarNumber=Ve;$.exports.formatTarDateTime=sr;$.exports.parseTarString=De;$.exports.parseTarNumber=he;$.exports.parseTarDateTime=or});var Za=Be((ol,$a)=>{"use strict";M();var Sn=Ct(),nr=bt(),Se=Kr();function Ja(e){return Se.recordSize}function Qa(e){return Math.ceil(e.data.length/Se.recordSize)*Se.recordSize}function En(e){var t=0;return e.forEach(function(r){t+=Ja(r)+Qa(r)}),t+=Se.recordSize*2,new Uint8Array(t)}function vn(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=nr.find(Se.posixHeader,function(_){return _[0]=="checksum"});if(s){var o=Se.calculateChecksum(e,r,!0),n=Se.formatTarNumber(o,s[1]-2)+Sn.NULL_CHAR+" ";a=r+s[2];for(var l=0;l<n.length;l+=1)e[a]=n.charCodeAt(l)&255,a++}return r+Ja(t)}function wn(e,t,r){return r=parseInt(r,10)||0,e.set(t.data,r),r+Qa(t)}function yn(e){e=nr.map(e,function(a){return nr.extend({},a,{data:nr.toUint8Array(a.data)})});var t=En(e),r=0;return e.forEach(function(a){r=vn(t,a,r),r=wn(t,a,r)}),t}$a.exports.tar=yn});var ts=Be((il,es)=>{"use strict";M();var bn=Ct(),Jr=bt(),me=Kr(),Cn={extractData:!0,checkHeader:!0,checkChecksum:!0,checkFileSize:!0},In={size:!0,checksum:!0,ustar:!0},Yr={unexpectedEndOfFile:"Unexpected end of file.",fileCorrupted:"File is corrupted.",checksumCheckFailed:"Checksum check failed."};function Fn(e){return me.recordSize}function Pn(e){return Math.ceil(e/me.recordSize)*me.recordSize}function An(e,t){for(var r=t,a=Math.min(e.length,t+me.recordSize*2),s=r;s<a;s++)if(e[s]!=0)return!1;return!0}function kn(e,t,r){if(e.length-t<me.recordSize){if(r.checkFileSize)throw new Error(Yr.unexpectedEndOfFile);return null}t=parseInt(t)||0;var a={},s=t;if(me.posixHeader.forEach(function(l){a[l[0]]=l[4](e,s,l),s+=l[1]}),a.type!=0&&(a.size=0),r.checkHeader&&me.posixHeader.forEach(function(l){if(Jr.isFunction(l[5])&&!l[5](a,l)){var _=new Error(Yr.fileCorrupted);throw _.data={offset:t+l[2],field:l[0]},_}}),r.checkChecksum){var o=me.calculateChecksum(e,t,!0);if(o!=a.checksum){var n=new Error(Yr.checksumCheckFailed);throw n.data={offset:t,header:a,checksum:o},n}}return a}function Tn(e,t,r,a){return a.extractData?r.size<=0?new Uint8Array:e.slice(t,t+r.size):null}function Un(e,t){var r={};return me.posixHeader.forEach(function(a){var s=a[0];In[s]||(r[s]=e[s])}),r.isOldGNUFormat=e.ustar==bn.OLDGNU_MAGIC,t&&(r.data=t),r}function Rn(e,t){t=Jr.extend({},Cn,t);for(var r=[],a=0,s=e.length;s-a>=me.recordSize;){e=Jr.toUint8Array(e);var o=kn(e,a,t);if(!o)break;a+=Fn(o);var n=Tn(e,a,o,t);if(r.push(Un(o,n)),a+=Pn(o.size),An(e,a))break}return r}es.exports.untar=Rn});var Qr=Be((_l,rs)=>{"use strict";M();var Dn=bt(),qn=Ct(),Nn=Za(),zn=ts();Dn.extend(rs.exports,Nn,zn,qn)});async function ea(e,t,r="pgdata",a="auto"){let s=Hn(e,t),[o,n]=await Xn(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 ds(e,t,r){let a=new Uint8Array(await t.arrayBuffer()),s=typeof File<"u"&&t instanceof File?t.name:void 0;(Bn.includes(t.type)||s?.endsWith(".tgz")||s?.endsWith(".tar.gz"))&&(a=await ms(a));let n;try{n=(0,le.untar)(a)}catch(l){if(l instanceof Error&&l.message.includes("File is corrupted"))a=await ms(a),n=(0,le.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===le.REGTYPE?(e.writeFile(_,l.data),e.utime(_,ps(l.modifyTime),ps(l.modifyTime))):l.type===le.DIRTYPE&&e.mkdir(_)}}function Gn(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)?le.REGTYPE:le.DIRTYPE,modifyTime:_.mtime,data:m}),e.isDir(_.mode)&&a(l)})};return a(t),r}function Hn(e,t){let r=Gn(e,t);return(0,le.tar)(r)}async function Xn(e,t="auto"){if(t==="none")return[e,!1];if(typeof CompressionStream<"u")return[await jn(e),!0];if(typeof process<"u"&&process.versions&&process.versions.node)return[await Wn(e),!0];if(t==="auto")return[e,!1];throw new Error("Compression not supported in this environment")}async function jn(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 Wn(e){let{promisify:t}=await import("util"),{gzip:r}=await import("zlib");return await t(r)(e)}async function ms(e){if(typeof CompressionStream<"u")return await Vn(e);if(typeof process<"u"&&process.versions&&process.versions.node)return await Kn(e);throw new Error("Unsupported environment for decompression")}async function Vn(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 Kn(e){let{promisify:t}=await import("util"),{gunzip:r}=await import("zlib");return await t(r)(e)}function ps(e){return e?typeof e=="number"?e:Math.floor(e.getTime()/1e3):Math.floor(Date.now()/1e3)}var le,Bn,ta=st(()=>{"use strict";M();le=K(Qr(),1);Bn=["application/x-gtar","application/x-tar+gzip","application/x-gzip","application/gzip"]});var Ut,X,Ee,kt,Tt,Yn,Ke=st(()=>{"use strict";M();ta();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 ea(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 ea(this.pg.Module.FS,X,t,r)}async init(t,r){return this.pg=t,{emscriptenOpts:{...r,preRun:[...r.preRun||[],s=>{let o=Yn(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},Yn=(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 us={};Ie(us,{NodeFS:()=>ra});var ir,lr,ra,cs=st(()=>{"use strict";M();ir=K(require("fs"),1),lr=K(require("path"),1);Ke();ra=class extends Ee{constructor(t){super(t),this.rootDir=lr.resolve(t),ir.existsSync(lr.join(this.rootDir))||ir.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 xs={};Ie(xs,{OpfsAhpFS:()=>sa});var Jn,Qn,aa,Dt,$e,ve,qt,B,xe,W,Nt,we,ye,de,v,gs,qe,Qe,pe,j,Rt,hs,oa,sa,q,Ms=st(()=>{"use strict";M();Ke();Jn="state.txt",Qn="data",aa={DIR:16384,FILE:32768},sa=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,$e);E(this,ve);E(this,qt);E(this,B);E(this,xe,new Map);E(this,W,new Map);E(this,Nt,0);E(this,we,new Map);E(this,ye,new Map);this.lastCheckpoint=0;this.checkpointInterval=1e3*60;this.poolCounter=0;E(this,de,new Set);this.initialPoolSize=a,this.maintainedPoolSize=s}async init(r,a){return await h(this,v,gs).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,xe).set(l,_),p(this,W).set(l,m),h(this,v,Qe).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,Qe).call(this,{opp:"deletePoolFile",args:[l]});let _=p(this,xe).get(l);p(this,W).get(l)?.close(),await p(this,ve).removeEntry(_.name),p(this,xe).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,de))try{r.flush()}catch{}p(this,de).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,we).delete(r),p(this,ye).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,pe).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||aa.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,hs).call(this);return p(this,we).set(n,r),p(this,ye).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,pe).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,pe).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,pe).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,de).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,pe).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,de).add(_),p(this,ye).has(r)&&(p(this,we).delete(p(this,ye).get(r)),p(this,ye).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,pe).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,Qe).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||aa.FILE,backingFilename:this.state.pool.pop()};l.children[n]=d,h(this,v,Qe).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,de).add(m))}_createFileNodeState(r,a){let s=h(this,v,pe).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,de).add(m),d}};Dt=new WeakMap,$e=new WeakMap,ve=new WeakMap,qt=new WeakMap,B=new WeakMap,xe=new WeakMap,W=new WeakMap,Nt=new WeakMap,we=new WeakMap,ye=new WeakMap,de=new WeakMap,v=new WeakSet,gs=async function(){S(this,Dt,await navigator.storage.getDirectory()),S(this,$e,await h(this,v,oa).call(this,this.dataDir,{create:!0})),S(this,ve,await h(this,v,oa).call(this,Qn,{from:p(this,$e),create:!0})),S(this,qt,await p(this,$e).getFileHandle(Jn,{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:aa.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,xe).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,xe).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,xe).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,Qe).call(this,r);try{a()}catch(o){throw p(this,B).truncate(s),o}},Qe=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,de).add(p(this,B)),o},pe=function(r){return r.split("/").filter(Boolean)},j=function(r,a){let s=h(this,v,pe).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,we).get(r);if(!a)throw new q("EBADF","Bad file descriptor");return a},hs=function(){let r=++Fe(this,Nt)._;for(;p(this,we).has(r);)Fe(this,Nt)._++;return r},oa=async function(r,a){let s=h(this,v,pe).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 Zn={};Ie(Zn,{IdbFs:()=>Ye,MemoryFS:()=>Je,Mutex:()=>ge,PGlite:()=>na,formatQuery:()=>is,messages:()=>vt,parse:()=>Fr,protocol:()=>Gr,types:()=>Ir,uuid:()=>ns});module.exports=Rs(Zn);M();M();M();var ri=new Error("timeout while waiting for mutex to become available"),ai=new Error("mutex already locked"),qs=new Error("request for lock canceled"),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())})},gr=class{constructor(t,r=qs){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 Ns(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]=[])}},zs=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())})},ge=class{constructor(t){this._semaphore=new gr(1,t)}acquire(){return zs(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 _a={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 Os(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===_a.part){Ht(r,e[n],o.str),Ht(r.raw,e.raw[n],o.str);continue}if(o?._templateType===_a.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 fr(e,...t){let{strings:r,values:a}=Os(e,...t);return{query:[r[0],...a.flatMap((s,o)=>[`$${o+1}`,r[o+1]])].join(""),params:a}}var Fr={};Ie(Fr,{parseDescribeStatementResults:()=>nt,parseResults:()=>Wt});M();var Ir={};Ie(Ir,{ABSTIME:()=>Zs,ACLITEM:()=>io,BIT:()=>po,BOOL:()=>xr,BPCHAR:()=>ga,BYTEA:()=>Mr,CHAR:()=>Gs,CID:()=>Ws,CIDR:()=>$s,CIRCLE:()=>ro,DATE:()=>ha,FLOAT4:()=>ua,FLOAT8:()=>ca,GTSVECTOR:()=>Fo,INET:()=>no,INT2:()=>ma,INT4:()=>pa,INT8:()=>Sr,INTERVAL:()=>_o,JSON:()=>Er,JSONB:()=>Ma,MACADDR:()=>oo,MACADDR8:()=>ao,MONEY:()=>so,NUMERIC:()=>co,OID:()=>da,PATH:()=>Js,PG_DEPENDENCIES:()=>bo,PG_LSN:()=>wo,PG_NDISTINCT:()=>yo,PG_NODE_TREE:()=>Ks,POLYGON:()=>Qs,REFCURSOR:()=>go,REGCLASS:()=>Mo,REGCONFIG:()=>Po,REGDICTIONARY:()=>Ao,REGNAMESPACE:()=>ko,REGOPER:()=>ho,REGOPERATOR:()=>xo,REGPROC:()=>Hs,REGPROCEDURE:()=>fo,REGROLE:()=>To,REGTYPE:()=>So,RELTIME:()=>eo,SMGR:()=>Ys,TEXT:()=>ot,TID:()=>Xs,TIME:()=>lo,TIMESTAMP:()=>xa,TIMESTAMPTZ:()=>vr,TIMETZ:()=>mo,TINTERVAL:()=>to,TSQUERY:()=>Io,TSVECTOR:()=>Co,TXID_SNAPSHOT:()=>vo,UUID:()=>Eo,VARBIT:()=>uo,VARCHAR:()=>fa,XID:()=>js,XML:()=>Vs,arrayParser:()=>Cr,arraySerializer:()=>jt,parseType:()=>Xt,parsers:()=>yr,serializers:()=>br,types:()=>Sa});M();var Ls=globalThis.JSON.parse,Bs=globalThis.JSON.stringify,xr=16,Mr=17,Gs=18,Sr=20,ma=21,pa=23,Hs=24,ot=25,da=26,Xs=27,js=28,Ws=29,Er=114,Vs=142,Ks=194,Ys=210,Js=602,Qs=604,$s=650,ua=700,ca=701,Zs=702,eo=703,to=704,ro=718,ao=774,so=790,oo=829,no=869,io=1033,ga=1042,fa=1043,ha=1082,lo=1083,xa=1114,vr=1184,_o=1186,mo=1266,po=1560,uo=1562,co=1700,go=1790,fo=2202,ho=2203,xo=2204,Mo=2205,So=2206,Eo=2950,vo=2970,wo=3220,yo=3361,bo=3402,Co=3614,Io=3615,Fo=3642,Po=3734,Ao=3769,Ma=3802,ko=4089,To=4096,Sa={string:{to:ot,from:[ot,fa,ga],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:[ma,pa,da,ua,ca],serialize:e=>e.toString(),parse:e=>+e},bigint:{to:Sr,from:[Sr],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:Er,from:[Er,Ma],serialize:e=>typeof e=="string"?e:Bs(e),parse:e=>Ls(e)},boolean:{to:xr,from:[xr],serialize:e=>{if(typeof e!="boolean")throw new Error("Invalid input for boolean type");return e?"t":"f"},parse:e=>e==="t"},date:{to:vr,from:[ha,xa,vr],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:Mr,from:[Mr],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))}}},wr=Uo(Sa),yr=wr.parsers,br=wr.serializers;function Xt(e,t,r){if(e===null)return null;let a=r?.[t]??wr.parsers[t];return a?a(e,t):e}function Uo(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 Ro=/\\/g,Do=/"/g;function qo(e){return e.replace(Ro,"\\\\").replace(Do,'\\"')}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":'"'+qo(t?t(o):o.toString())+'"')).join(s)}}`}var hr={i:0,char:null,str:"",quoted:!1,last:0,p:null};function Cr(e,t,r){return hr.i=hr.last=0,Ea(hr,e,t,r)[0]}function Ea(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(Ea(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+=No(_),s.push({...o,affectedRows:n,...a?{blob:a}:{}}),o={rows:[],fields:[]};break}}}),s.length===0&&s.push({affectedRows:0,rows:[],fields:[]}),s}function No(e){let t=e.text.split(" ");switch(t[0]){case"INSERT":return parseInt(t[2],10);case"UPDATE":case"DELETE":case"COPY":case"MERGE":return parseInt(t[1],10);default:return 0}}function nt(e){let t=e.find(r=>r.name==="parameterDescription");return t?t.dataTypeIDs:[]}var Gr={};Ie(Gr,{Parser:()=>Ue,messages:()=>vt,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,va,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,va).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))}},va=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,zo=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()},Oo=()=>{let e=new DataView(new ArrayBuffer(8));return e.setInt32(0,8,!1),e.setInt32(4,80877103,!1),new Uint8Array(e.buffer)},Lo=e=>D.addCString(e).flush(112),Bo=(e,t)=>(D.addCString(e).addInt32(Ge(t)).addString(t),D.flush(112)),Go=e=>D.addString(e).flush(112),Ho=e=>D.addCString(e).flush(81),Xo=[],jo=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 Wo=(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)}},Vo=(e={})=>{let t=e.portal??"",r=e.statement??"",a=e.binary??!1,s=e.values??Xo,o=s.length;return D.addCString(t).addCString(r),D.addInt16(o),Wo(s,e.valueMapper),D.addInt16(o),D.add(We.flush()),D.addInt16(a?1:0),D.flush(66)},Ko=new Uint8Array([69,0,0,0,9,0,0,0,0,0]),Yo=e=>{if(!e||!e.portal&&!e.rows)return Ko;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)},Jo=(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)},Pr=(e,t)=>{let r=new Pe;return r.addCString(t),r.flush(e)},Qo=D.addCString("P").flush(68),$o=D.addCString("S").flush(68),Zo=e=>e.name?Pr(68,`${e.type}${e.name??""}`):e.type==="P"?Qo:$o,en=e=>{let t=`${e.type}${e.name??""}`;return Pr(67,t)},tn=e=>D.add(e).flush(100),rn=e=>Pr(102,e),Yt=e=>new Uint8Array([e,0,0,0,4]),an=Yt(72),sn=Yt(83),on=Yt(88),nn=Yt(99),N={startup:zo,password:Lo,requestSsl:Oo,sendSASLInitialResponseMessage:Bo,sendSCRAMClientFinalMessage:Go,query:Ho,parse:jo,bind:Vo,execute:Yo,describe:Zo,close:en,flush:()=>an,sync:()=>sn,end:()=>on,copyData:tn,copyDone:()=>nn,copyFail:rn,cancel:Jo};M();var vt={};Ie(vt,{AuthenticationCleartextPassword:()=>lt,AuthenticationMD5Password:()=>_t,AuthenticationOk:()=>it,AuthenticationSASL:()=>mt,AuthenticationSASLContinue:()=>pt,AuthenticationSASLFinal:()=>dt,BackendKeyDataMessage:()=>Mt,CommandCompleteMessage:()=>ke,CopyDataMessage:()=>ut,CopyResponse:()=>ct,DataRowMessage:()=>Et,DatabaseError:()=>oe,Field:()=>gt,NoticeMessage:()=>Te,NotificationResponseMessage:()=>Ae,ParameterDescriptionMessage:()=>ht,ParameterStatusMessage:()=>xt,ReadyForQueryMessage:()=>St,RowDescriptionMessage:()=>ft,bindComplete:()=>kr,closeComplete:()=>Tr,copyDone:()=>Nr,emptyQuery:()=>qr,noData:()=>Ur,parseComplete:()=>Ar,portalSuspended:()=>Rr,replicationStart:()=>Dr});M();var Ar={name:"parseComplete",length:5},kr={name:"bindComplete",length:5},Tr={name:"closeComplete",length:5},Ur={name:"noData",length:5},Rr={name:"portalSuspended",length:5},Dr={name:"replicationStart",length:4},qr={name:"emptyQuery",length:4},Nr={name:"copyDone",length:4},it=class{constructor(t){this.length=t;this.name="authenticationOk"}},lt=class{constructor(t){this.length=t;this.name="authenticationCleartextPassword"}},_t=class{constructor(t,r){this.length=t;this.salt=r;this.name="authenticationMD5Password"}},mt=class{constructor(t,r){this.length=t;this.mechanisms=r;this.name="authenticationSASL"}},pt=class{constructor(t,r){this.length=t;this.data=r;this.name="authenticationSASLContinue"}},dt=class{constructor(t,r){this.length=t;this.data=r;this.name="authenticationSASLFinal"}},oe=class extends Error{constructor(r,a,s){super(r);this.length=a;this.name=s}},ut=class{constructor(t,r){this.length=t;this.chunk=r;this.name="copyData"}},ct=class{constructor(t,r,a,s){this.length=t;this.name=r;this.binary=a;this.columnTypes=new Array(s)}},gt=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}},ft=class{constructor(t,r){this.length=t;this.fieldCount=r;this.name="rowDescription";this.fields=new Array(this.fieldCount)}},ht=class{constructor(t,r){this.length=t;this.parameterCount=r;this.name="parameterDescription";this.dataTypeIDs=new Array(this.parameterCount)}},xt=class{constructor(t,r,a){this.length=t;this.parameterName=r;this.parameterValue=a;this.name="parameterStatus"}},Mt=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"}},St=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"}},Et=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 zr={text:0,binary:1};M();var ln=new ArrayBuffer(0),fe,H,Qt,$t,wt,Jt=class{constructor(t=0){E(this,fe,new DataView(ln));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,fe,new DataView(r))}int16(){let t=p(this,fe).getInt16(p(this,H),p(this,wt));return S(this,H,p(this,H)+2),t}byte(){let t=p(this,fe).getUint8(p(this,H));return Fe(this,H)._++,t}int32(){let t=p(this,fe).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,fe).getUint8(r++)!==0;);let a=this.string(r-t-1);return S(this,H,r),a}bytes(t){let r=p(this,fe).buffer.slice(p(this,H),p(this,H)+t);return S(this,H,p(this,H)+t),new Uint8Array(r)}};fe=new WeakMap,H=new WeakMap,Qt=new WeakMap,$t=new WeakMap,wt=new WeakMap;var Or=1,_n=4,wa=Or+_n,ya=new ArrayBuffer(0);var Y,ee,te,y,k,ba,Ca,Ia,Fa,Pa,Aa,ka,Lr,Ta,Ua,Ra,Da,qa,Na,za,Oa,Br,Ue=class{constructor(){E(this,k);E(this,Y,new DataView(ya));E(this,ee,0);E(this,te,0);E(this,y,new Jt)}parse(t,r){h(this,k,ba).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+wa<=a;){let o=p(this,Y).getUint8(s),n=p(this,Y).getUint32(s+Or,!1),l=Or+n;if(l+s<=a){let _=h(this,k,Ca).call(this,s+wa,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,y=new WeakMap,k=new WeakSet,ba=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)},Ca=function(t,r,a,s){switch(r){case 50:return kr;case 49:return Ar;case 51:return Tr;case 110:return Ur;case 115:return Rr;case 99:return Nr;case 87:return Dr;case 73:return qr;case 68:return h(this,k,qa).call(this,t,a,s);case 67:return h(this,k,Fa).call(this,t,a,s);case 90:return h(this,k,Ia).call(this,t,a,s);case 65:return h(this,k,Ta).call(this,t,a,s);case 82:return h(this,k,Oa).call(this,t,a,s);case 83:return h(this,k,Na).call(this,t,a,s);case 75:return h(this,k,za).call(this,t,a,s);case 69:return h(this,k,Br).call(this,t,a,s,"error");case 78:return h(this,k,Br).call(this,t,a,s,"notice");case 84:return h(this,k,Ua).call(this,t,a,s);case 116:return h(this,k,Da).call(this,t,a,s);case 71:return h(this,k,Aa).call(this,t,a,s);case 72:return h(this,k,ka).call(this,t,a,s);case 100:return h(this,k,Pa).call(this,t,a,s);default:return new oe("received invalid response: "+r.toString(16),a,"error")}},Ia=function(t,r,a){p(this,y).setBuffer(t,a);let s=p(this,y).string(1);return new St(r,s)},Fa=function(t,r,a){p(this,y).setBuffer(t,a);let s=p(this,y).cstring();return new ke(r,s)},Pa=function(t,r,a){let s=a.slice(t,t+(r-4));return new ut(r,new Uint8Array(s))},Aa=function(t,r,a){return h(this,k,Lr).call(this,t,r,a,"copyInResponse")},ka=function(t,r,a){return h(this,k,Lr).call(this,t,r,a,"copyOutResponse")},Lr=function(t,r,a,s){p(this,y).setBuffer(t,a);let o=p(this,y).byte()!==0,n=p(this,y).int16(),l=new ct(r,s,o,n);for(let _=0;_<n;_++)l.columnTypes[_]=p(this,y).int16();return l},Ta=function(t,r,a){p(this,y).setBuffer(t,a);let s=p(this,y).int32(),o=p(this,y).cstring(),n=p(this,y).cstring();return new Ae(r,s,o,n)},Ua=function(t,r,a){p(this,y).setBuffer(t,a);let s=p(this,y).int16(),o=new ft(r,s);for(let n=0;n<s;n++)o.fields[n]=h(this,k,Ra).call(this);return o},Ra=function(){let t=p(this,y).cstring(),r=p(this,y).int32(),a=p(this,y).int16(),s=p(this,y).int32(),o=p(this,y).int16(),n=p(this,y).int32(),l=p(this,y).int16()===0?zr.text:zr.binary;return new gt(t,r,a,s,o,n,l)},Da=function(t,r,a){p(this,y).setBuffer(t,a);let s=p(this,y).int16(),o=new ht(r,s);for(let n=0;n<s;n++)o.dataTypeIDs[n]=p(this,y).int32();return o},qa=function(t,r,a){p(this,y).setBuffer(t,a);let s=p(this,y).int16(),o=new Array(s);for(let n=0;n<s;n++){let l=p(this,y).int32();o[n]=l===-1?null:p(this,y).string(l)}return new Et(r,o)},Na=function(t,r,a){p(this,y).setBuffer(t,a);let s=p(this,y).cstring(),o=p(this,y).cstring();return new xt(r,s,o)},za=function(t,r,a){p(this,y).setBuffer(t,a);let s=p(this,y).int32(),o=p(this,y).int32();return new Mt(r,s,o)},Oa=function(t,r,a){p(this,y).setBuffer(t,a);let s=p(this,y).int32();switch(s){case 0:return new it(r);case 3:return new lt(r);case 5:return new _t(r,p(this,y).bytes(4));case 10:{let o=[];for(;;){let n=p(this,y).cstring();if(n.length===0)return new mt(r,o);o.push(n)}}case 11:return new pt(r,p(this,y).string(r-8));case 12:return new dt(r,p(this,y).string(r-8));default:throw new Error("Unknown authenticationOk message type "+s)}},Br=function(t,r,a,s){p(this,y).setBuffer(t,a);let o={},n=p(this,y).string(1);for(;n!=="\0";)o[n]=p(this,y).cstring(),n=p(this,y).string(1);let l=o.M,_=s==="notice"?new Te(r,l):new oe(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,_};M();function Zt(e){let t=e.e;return t.query=e.query,t.params=e.params,t.queryOptions=e.options,t}var yt,Me,R,ne,er,Re,Hr,tr=class{constructor(){E(this,R);this.serializers={...br};this.parsers={...yr};E(this,yt,!1);E(this,Me,!1)}async _initArrayTypes({force:t=!1}={}){if(p(this,yt)&&!t)return;S(this,yt,!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=>Cr(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,er).call(this,t,r,a))}async sql(t,...r){let{query:a,params:s}=fr(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,ne).call(this,N.parse({text:t,types:r?.paramTypes}),r);let a=await h(this,R,ne).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[_]})