New:Socket for Asana Is Now Available.Learn more
Sign In

@electric-sql/pglite

Package Overview
Dependencies
Maintainers
4
Versions
78
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@electric-sql/pglite - npm Package Compare versions

Comparing version
0.5.4
to
0.5.5
+2
dist/chunk-2BOC2OMW.js
import{b as ne,e as r,f as h,g as d,h as p,i as re,j as y}from"./chunk-QY3QWFKW.js";var yn={};ne(yn,{ABSTIME:()=>Et,ACLITEM:()=>Ut,BIT:()=>Qt,BOOL:()=>ye,BPCHAR:()=>ve,BYTEA:()=>he,CHAR:()=>bt,CID:()=>St,CIDR:()=>Rt,CIRCLE:()=>Nt,DATE:()=>ze,FLOAT4:()=>Qe,FLOAT8:()=>_e,GTSVECTOR:()=>nn,INET:()=>Ot,INT2:()=>Ve,INT4:()=>Fe,INT8:()=>be,INTERVAL:()=>Ft,JSON:()=>we,JSONB:()=>Ye,MACADDR:()=>kt,MACADDR8:()=>Pt,MONEY:()=>Lt,NUMERIC:()=>vt,OID:()=>Ge,PATH:()=>xt,PG_DEPENDENCIES:()=>Zt,PG_LSN:()=>$t,PG_NDISTINCT:()=>Xt,PG_NODE_TREE:()=>Dt,POLYGON:()=>Mt,REFCURSOR:()=>Ht,REGCLASS:()=>jt,REGCONFIG:()=>rn,REGDICTIONARY:()=>sn,REGNAMESPACE:()=>an,REGOPER:()=>qt,REGOPERATOR:()=>Yt,REGPROC:()=>gt,REGPROCEDURE:()=>zt,REGROLE:()=>on,REGTYPE:()=>Wt,RELTIME:()=>Ct,SMGR:()=>It,TEXT:()=>ge,TID:()=>wt,TIME:()=>Vt,TIMESTAMP:()=>qe,TIMESTAMPTZ:()=>Ae,TIMETZ:()=>Gt,TINTERVAL:()=>Tt,TSQUERY:()=>tn,TSVECTOR:()=>en,TXID_SNAPSHOT:()=>Jt,UUID:()=>Kt,VARBIT:()=>_t,VARCHAR:()=>He,XID:()=>At,XML:()=>Bt,arrayParser:()=>mn,arraySerializer:()=>We,parseType:()=>se,parsers:()=>un,serializers:()=>cn,types:()=>je});y();var yt=globalThis.JSON.parse,ht=globalThis.JSON.stringify,ye=16,he=17,bt=18,be=20,Ve=21,Fe=23,gt=24,ge=25,Ge=26,wt=27,At=28,St=29,we=114,Bt=142,Dt=194,It=210,xt=602,Mt=604,Rt=650,Qe=700,_e=701,Et=702,Ct=703,Tt=704,Nt=718,Pt=774,Lt=790,kt=829,Ot=869,Ut=1033,ve=1042,He=1043,ze=1082,Vt=1083,qe=1114,Ae=1184,Ft=1186,Gt=1266,Qt=1560,_t=1562,vt=1700,Ht=1790,zt=2202,qt=2203,Yt=2204,jt=2205,Wt=2206,Kt=2950,Jt=2970,$t=3220,Xt=3361,Zt=3402,en=3614,tn=3615,nn=3642,rn=3734,sn=3769,Ye=3802,an=4089,on=4096,je={string:{to:ge,from:[ge,He,ve],serialize:e=>e instanceof Date?e.toISOString():e.toString(),parse:e=>e},number:{to:0,from:[Ve,Fe,Ge,Qe,_e],serialize:e=>e.toString(),parse:e=>+e},bigint:{to:be,from:[be],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:we,from:[we,Ye],serialize:e=>typeof e=="string"?e:ht(e,(t,n)=>typeof n=="bigint"?n.toString():n),parse:e=>yt(e)},boolean:{to:ye,from:[ye],serialize:e=>{if(typeof e=="boolean")return e?"t":"f";if(typeof e=="number"){if(e===1)return"t";if(e===0)return"f"}else if(typeof e=="string"){let t=e.trim().toLowerCase();if(["true","t","yes","y","on","1"].includes(t))return"t";if(["false","f","no","n","off","0"].includes(t))return"f"}throw new Error("Invalid input for boolean type")},parse:e=>e==="t"},date:{to:Ae,from:[ze,qe,Ae],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:he,from:[he],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},(n,s)=>parseInt(t.substring(s*2,(s+1)*2),16))}}},Se=ln(je),un=Se.parsers,cn=Se.serializers;function se(e,t,n){if(e===null)return null;let s=n?.[t]??Se.parsers[t];return s?s(e,t):e}function ln(e){return Object.keys(e).reduce(({parsers:t,serializers:n},s)=>{let{to:i,from:a,serialize:u,parse:m}=e[s];return n[i]=u,n[s]=u,t[s]=m,Array.isArray(a)?a.forEach(l=>{t[l]=m,n[l]=u}):(t[a]=m,n[a]=u),{parsers:t,serializers:n}},{parsers:{},serializers:{}})}var pn=/\\/g,dn=/"/g;function fn(e){return e.replace(pn,"\\\\").replace(dn,'\\"')}function We(e,t,n){if(Array.isArray(e)===!1)return e;if(!e.length)return"{}";let s=e[0],i=n===1020?";":",";return Array.isArray(s)?`{${e.map(a=>We(a,t,n)).join(i)}}`:`{${e.map(a=>(a===void 0&&(a=null),a===null?"null":'"'+fn(t?t(a):a.toString())+'"')).join(i)}}`}var me={i:0,char:null,str:"",quoted:!1,last:0,p:null};function mn(e,t,n){return me.i=me.last=0,Ke(me,e,t,n)[0]}function Ke(e,t,n,s){let i=[],a=s===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==='"'?(i.push(n?n(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,i.push(Ke(e,t,n,s));else if(e.char==="}"){if(e.last<e.i){let u=t.slice(e.last,e.i);u==="NULL"&&!e.quoted?i.push(null):i.push(n?n(u):u)}e.quoted=!1,e.last=e.i+1;break}else if(e.char===a&&e.p!=="}"&&e.p!=='"'){let u=t.slice(e.last,e.i);u==="NULL"&&!e.quoted?i.push(null):i.push(n?n(u):u),e.last=e.i+1}e.p=e.char}return e.last<e.i&&i.push(n?n(t.slice(e.last,e.i+1)):t.slice(e.last,e.i+1)),i}var gn={};ne(gn,{parseDescribeStatementResults:()=>bn,parseResults:()=>hn});y();function hn(e,t,n,s){let i=[],a={rows:[],fields:[]},u=0,m={...t,...n?.parsers};return e.forEach(l=>{switch(l.name){case"rowDescription":{let E=l;a.fields=E.fields.map(I=>({name:I.name,dataTypeID:I.dataTypeID}));break}case"dataRow":{if(!a)break;let E=l;n?.rowMode==="array"?a.rows.push(E.fields.map((I,C)=>se(I,a.fields[C].dataTypeID,m))):a.rows.push(Object.fromEntries(E.fields.map((I,C)=>[a.fields[C].name,se(I,a.fields[C].dataTypeID,m)])));break}case"commandComplete":{let I=l.text.split(" "),C=I[0],de=parseInt(I[I.length-1],10);switch(C){case"INSERT":case"UPDATE":case"DELETE":case"COPY":case"MERGE":u+=de;break}let fe={...a,command:C,affectedRows:u};Number.isNaN(de)||(fe.rowCount=de),s&&(fe.blob=s),i.push(fe),a={rows:[],fields:[]};break}}}),i.length===0&&i.push({affectedRows:0,rows:[],fields:[]}),i}function bn(e){let t=e.find(n=>n.name==="parameterDescription");return t?t.dataTypeIDs:[]}var Te={};ne(Te,{AuthenticationCleartextPassword:()=>F,AuthenticationMD5Password:()=>G,AuthenticationOk:()=>V,AuthenticationSASL:()=>Q,AuthenticationSASLContinue:()=>_,AuthenticationSASLFinal:()=>v,BackendKeyDataMessage:()=>K,CommandCompleteMessage:()=>X,CopyDataMessage:()=>H,CopyResponse:()=>z,DataRowMessage:()=>Z,DatabaseError:()=>N,Field:()=>q,NoticeMessage:()=>ee,NotificationResponseMessage:()=>J,ParameterDescriptionMessage:()=>j,ParameterStatusMessage:()=>W,ReadyForQueryMessage:()=>$,RowDescriptionMessage:()=>Y,bindComplete:()=>De,closeComplete:()=>Ie,copyDone:()=>Ce,emptyQuery:()=>Ee,noData:()=>xe,parseComplete:()=>Be,portalSuspended:()=>Me,replicationStart:()=>Re});y();var Be={name:"parseComplete",length:5},De={name:"bindComplete",length:5},Ie={name:"closeComplete",length:5},xe={name:"noData",length:5},Me={name:"portalSuspended",length:5},Re={name:"replicationStart",length:4},Ee={name:"emptyQuery",length:4},Ce={name:"copyDone",length:4},V=class{constructor(t){this.length=t;this.name="authenticationOk"}},F=class{constructor(t){this.length=t;this.name="authenticationCleartextPassword"}},G=class{constructor(t,n){this.length=t;this.salt=n;this.name="authenticationMD5Password"}},Q=class{constructor(t,n){this.length=t;this.mechanisms=n;this.name="authenticationSASL"}},_=class{constructor(t,n){this.length=t;this.data=n;this.name="authenticationSASLContinue"}},v=class{constructor(t,n){this.length=t;this.data=n;this.name="authenticationSASLFinal"}},N=class extends Error{constructor(n,s,i){super(n);this.length=s;this.name=i}},H=class{constructor(t,n){this.length=t;this.chunk=n;this.name="copyData"}},z=class{constructor(t,n,s,i){this.length=t;this.name=n;this.binary=s;this.columnTypes=new Array(i)}},q=class{constructor(t,n,s,i,a,u,m){this.name=t;this.tableID=n;this.columnID=s;this.dataTypeID=i;this.dataTypeSize=a;this.dataTypeModifier=u;this.format=m}},Y=class{constructor(t,n){this.length=t;this.fieldCount=n;this.name="rowDescription";this.fields=new Array(this.fieldCount)}},j=class{constructor(t,n){this.length=t;this.parameterCount=n;this.name="parameterDescription";this.dataTypeIDs=new Array(this.parameterCount)}},W=class{constructor(t,n,s){this.length=t;this.parameterName=n;this.parameterValue=s;this.name="parameterStatus"}},K=class{constructor(t,n,s){this.length=t;this.processID=n;this.secretKey=s;this.name="backendKeyData"}},J=class{constructor(t,n,s,i){this.length=t;this.processId=n;this.channel=s;this.payload=i;this.name="notification"}},$=class{constructor(t,n){this.length=t;this.status=n;this.name="readyForQuery"}},X=class{constructor(t,n){this.length=t;this.text=n;this.name="commandComplete"}},Z=class{constructor(t,n){this.length=t;this.fields=n;this.name="dataRow";this.fieldCount=n.length}},ee=class{constructor(t,n){this.length=t;this.message=n;this.name="notice"}};var zn={};ne(zn,{Parser:()=>pe,messages:()=>Te,serialize:()=>$e});y();y();y();y();function P(e){let t=e.length;for(let n=e.length-1;n>=0;n--){let s=e.charCodeAt(n);s>127&&s<=2047?t++:s>2047&&s<=65535&&(t+=2),s>=56320&&s<=57343&&n--}return t}var b,g,k,ae,O,S,ie,L,Je,T=class{constructor(t=256){this.size=t;h(this,S);h(this,b);h(this,g,5);h(this,k,!1);h(this,ae,new TextEncoder);h(this,O,0);d(this,b,p(this,S,ie).call(this,t))}addInt32(t){return p(this,S,L).call(this,4),r(this,b).setInt32(r(this,g),t,r(this,k)),d(this,g,r(this,g)+4),this}addInt16(t){return p(this,S,L).call(this,2),r(this,b).setInt16(r(this,g),t,r(this,k)),d(this,g,r(this,g)+2),this}addCString(t){return t&&this.addString(t),p(this,S,L).call(this,1),r(this,b).setUint8(r(this,g),0),re(this,g)._++,this}addString(t=""){let n=P(t);return p(this,S,L).call(this,n),r(this,ae).encodeInto(t,new Uint8Array(r(this,b).buffer,r(this,g))),d(this,g,r(this,g)+n),this}add(t){return p(this,S,L).call(this,t.byteLength),new Uint8Array(r(this,b).buffer).set(new Uint8Array(t),r(this,g)),d(this,g,r(this,g)+t.byteLength),this}flush(t){let n=p(this,S,Je).call(this,t);return d(this,g,5),d(this,b,p(this,S,ie).call(this,this.size)),new Uint8Array(n)}};b=new WeakMap,g=new WeakMap,k=new WeakMap,ae=new WeakMap,O=new WeakMap,S=new WeakSet,ie=function(t){return new DataView(new ArrayBuffer(t))},L=function(t){if(r(this,b).byteLength-r(this,g)<t){let s=r(this,b).buffer,i=s.byteLength+(s.byteLength>>1)+t;d(this,b,p(this,S,ie).call(this,i)),new Uint8Array(r(this,b).buffer).set(new Uint8Array(s))}},Je=function(t){if(t){r(this,b).setUint8(r(this,O),t);let n=r(this,g)-(r(this,O)+1);r(this,b).setInt32(r(this,O)+1,n,r(this,k))}return r(this,b).buffer.slice(t?0:5,r(this,g))};var f=new T,wn=e=>{f.addInt16(3).addInt16(0);for(let s of Object.keys(e))f.addCString(s).addCString(e[s]);f.addCString("client_encoding").addCString("UTF8");let t=f.addCString("").flush(),n=t.byteLength+4;return new T().addInt32(n).add(t).flush()},An=()=>{let e=new DataView(new ArrayBuffer(8));return e.setInt32(0,8,!1),e.setInt32(4,80877103,!1),new Uint8Array(e.buffer)},Sn=e=>f.addCString(e).flush(112),Bn=(e,t)=>(f.addCString(e).addInt32(P(t)).addString(t),f.flush(112)),Dn=e=>f.addString(e).flush(112),In=e=>f.addCString(e).flush(81),xn=[],Mn=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 n=f.addCString(t).addCString(e.text).addInt16(e.types?.length??0);return e.types?.forEach(s=>n.addInt32(s)),f.flush(80)},U=new T;var Rn=(e,t)=>{for(let n=0;n<e.length;n++){let s=t?t(e[n],n):e[n];if(s===null)f.addInt16(0),U.addInt32(-1);else if(s instanceof ArrayBuffer||ArrayBuffer.isView(s)){let i=ArrayBuffer.isView(s)?s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength):s;f.addInt16(1),U.addInt32(i.byteLength),U.add(i)}else f.addInt16(0),U.addInt32(P(s)),U.addString(s)}},En=(e={})=>{let t=e.portal??"",n=e.statement??"",s=e.binary??!1,i=e.values??xn,a=i.length;return f.addCString(t).addCString(n),f.addInt16(a),Rn(i,e.valueMapper),f.addInt16(a),f.add(U.flush()),f.addInt16(s?1:0),f.flush(66)},Cn=new Uint8Array([69,0,0,0,9,0,0,0,0,0]),Tn=e=>{if(!e||!e.portal&&!e.rows)return Cn;let t=e.portal??"",n=e.rows??0,s=P(t),i=4+s+1+4,a=new DataView(new ArrayBuffer(1+i));return a.setUint8(0,69),a.setInt32(1,i,!1),new TextEncoder().encodeInto(t,new Uint8Array(a.buffer,5)),a.setUint8(s+5,0),a.setUint32(a.byteLength-4,n,!1),new Uint8Array(a.buffer)},Nn=(e,t)=>{let n=new DataView(new ArrayBuffer(16));return n.setInt32(0,16,!1),n.setInt16(4,1234,!1),n.setInt16(6,5678,!1),n.setInt32(8,e,!1),n.setInt32(12,t,!1),new Uint8Array(n.buffer)},Ne=(e,t)=>{let n=new T;return n.addCString(t),n.flush(e)},Pn=f.addCString("P").flush(68),Ln=f.addCString("S").flush(68),kn=e=>e.name?Ne(68,`${e.type}${e.name??""}`):e.type==="P"?Pn:Ln,On=e=>{let t=`${e.type}${e.name??""}`;return Ne(67,t)},Un=e=>f.add(e).flush(100),Vn=e=>Ne(102,e),oe=e=>new Uint8Array([e,0,0,0,4]),Fn=oe(72),Gn=oe(83),Qn=oe(88),_n=oe(99),$e={startup:wn,password:Sn,requestSsl:An,sendSASLInitialResponseMessage:Bn,sendSCRAMClientFinalMessage:Dn,query:In,parse:Mn,bind:En,execute:Tn,describe:kn,close:On,flush:()=>Fn,sync:()=>Gn,end:()=>Qn,copyData:Un,copyDone:()=>_n,copyFail:Vn,cancel:Nn};y();y();var Pe={text:0,binary:1};y();var vn=new ArrayBuffer(0),R,w,ce,le,te,ue=class{constructor(t=0){h(this,R,new DataView(vn));h(this,w);h(this,ce,"utf-8");h(this,le,new TextDecoder(r(this,ce)));h(this,te,!1);d(this,w,t)}setBuffer(t,n){d(this,w,t),d(this,R,new DataView(n))}int16(){let t=r(this,R).getInt16(r(this,w),r(this,te));return d(this,w,r(this,w)+2),t}byte(){let t=r(this,R).getUint8(r(this,w));return re(this,w)._++,t}int32(){let t=r(this,R).getInt32(r(this,w),r(this,te));return d(this,w,r(this,w)+4),t}string(t){return r(this,le).decode(this.bytes(t))}cstring(){let t=r(this,w),n=t;for(;r(this,R).getUint8(n++)!==0;);let s=this.string(n-t-1);return d(this,w,n),s}bytes(t){let n=r(this,R).buffer.slice(r(this,w),r(this,w)+t);return d(this,w,r(this,w)+t),new Uint8Array(n)}};R=new WeakMap,w=new WeakMap,ce=new WeakMap,le=new WeakMap,te=new WeakMap;var Le=1,Hn=4,Xe=Le+Hn,Ze=new ArrayBuffer(0);var A,B,D,o,c,ke,et,tt,nt,rt,st,it,at,Oe,ot,ut,ct,lt,pt,dt,ft,mt,Ue,pe=class{constructor(){h(this,c);h(this,A,new DataView(Ze));h(this,B,0);h(this,D,0);h(this,o,new ue)}parse(t,n){p(this,c,et).call(this,ArrayBuffer.isView(t)?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength):t);let s=r(this,D)+r(this,B),i=r(this,D);for(;i+Xe<=s;){let a=r(this,A).getUint8(i),u=r(this,A).getUint32(i+Le,!1),m=Le+u;if(m+i<=s&&u>0){let l;try{l=p(this,c,tt).call(this,i+Xe,a,u,r(this,A).buffer)}catch(E){throw p(this,c,ke).call(this),E}n(l),i+=m}else break}i===s?p(this,c,ke).call(this):(d(this,B,s-i),d(this,D,i))}};A=new WeakMap,B=new WeakMap,D=new WeakMap,o=new WeakMap,c=new WeakSet,ke=function(){d(this,A,new DataView(Ze)),d(this,B,0),d(this,D,0)},et=function(t){if(r(this,B)>0){let n=r(this,B)+t.byteLength;if(n+r(this,D)>r(this,A).byteLength){let i;if(n<=r(this,A).byteLength&&r(this,D)>=r(this,B))i=r(this,A).buffer;else{let a=r(this,A).byteLength*2;for(;n>=a;)a*=2;i=new ArrayBuffer(a)}new Uint8Array(i).set(new Uint8Array(r(this,A).buffer,r(this,D),r(this,B))),d(this,A,new DataView(i)),d(this,D,0)}new Uint8Array(r(this,A).buffer).set(new Uint8Array(t),r(this,D)+r(this,B)),d(this,B,n)}else d(this,A,new DataView(t)),d(this,D,0),d(this,B,t.byteLength)},tt=function(t,n,s,i){switch(n){case 50:return De;case 49:return Be;case 51:return Ie;case 110:return xe;case 115:return Me;case 99:return Ce;case 87:return Re;case 73:return Ee;case 68:return p(this,c,pt).call(this,t,s,i);case 67:return p(this,c,rt).call(this,t,s,i);case 90:return p(this,c,nt).call(this,t,s,i);case 65:return p(this,c,ot).call(this,t,s,i);case 82:return p(this,c,mt).call(this,t,s,i);case 83:return p(this,c,dt).call(this,t,s,i);case 75:return p(this,c,ft).call(this,t,s,i);case 69:return p(this,c,Ue).call(this,t,s,i,"error");case 78:return p(this,c,Ue).call(this,t,s,i,"notice");case 84:return p(this,c,ut).call(this,t,s,i);case 116:return p(this,c,lt).call(this,t,s,i);case 71:return p(this,c,it).call(this,t,s,i);case 72:return p(this,c,at).call(this,t,s,i);case 100:return p(this,c,st).call(this,t,s,i);default:return new N("received invalid response: "+n.toString(16),s,"error")}},nt=function(t,n,s){r(this,o).setBuffer(t,s);let i=r(this,o).string(1);return new $(n,i)},rt=function(t,n,s){r(this,o).setBuffer(t,s);let i=r(this,o).cstring();return new X(n,i)},st=function(t,n,s){let i=s.slice(t,t+(n-4));return new H(n,new Uint8Array(i))},it=function(t,n,s){return p(this,c,Oe).call(this,t,n,s,"copyInResponse")},at=function(t,n,s){return p(this,c,Oe).call(this,t,n,s,"copyOutResponse")},Oe=function(t,n,s,i){r(this,o).setBuffer(t,s);let a=r(this,o).byte()!==0,u=r(this,o).int16(),m=new z(n,i,a,u);for(let l=0;l<u;l++)m.columnTypes[l]=r(this,o).int16();return m},ot=function(t,n,s){r(this,o).setBuffer(t,s);let i=r(this,o).int32(),a=r(this,o).cstring(),u=r(this,o).cstring();return new J(n,i,a,u)},ut=function(t,n,s){r(this,o).setBuffer(t,s);let i=r(this,o).int16(),a=new Y(n,i);for(let u=0;u<i;u++)a.fields[u]=p(this,c,ct).call(this);return a},ct=function(){let t=r(this,o).cstring(),n=r(this,o).int32(),s=r(this,o).int16(),i=r(this,o).int32(),a=r(this,o).int16(),u=r(this,o).int32(),m=r(this,o).int16()===0?Pe.text:Pe.binary;return new q(t,n,s,i,a,u,m)},lt=function(t,n,s){r(this,o).setBuffer(t,s);let i=r(this,o).int16(),a=new j(n,i);for(let u=0;u<i;u++)a.dataTypeIDs[u]=r(this,o).int32();return a},pt=function(t,n,s){r(this,o).setBuffer(t,s);let i=r(this,o).int16(),a=new Array(i);for(let u=0;u<i;u++){let m=r(this,o).int32();a[u]=m===-1?null:r(this,o).string(m)}return new Z(n,a)},dt=function(t,n,s){r(this,o).setBuffer(t,s);let i=r(this,o).cstring(),a=r(this,o).cstring();return new W(n,i,a)},ft=function(t,n,s){r(this,o).setBuffer(t,s);let i=r(this,o).int32(),a=r(this,o).int32();return new K(n,i,a)},mt=function(t,n,s){r(this,o).setBuffer(t,s);let i=r(this,o).int32();switch(i){case 0:return new V(n);case 3:return new F(n);case 5:return new G(n,r(this,o).bytes(4));case 10:{let a=[];for(;;){let u=r(this,o).cstring();if(u.length===0)return new Q(n,a);a.push(u)}}case 11:return new _(n,r(this,o).string(n-8));case 12:return new v(n,r(this,o).string(n-8));default:throw new Error("Unknown authenticationOk message type "+i)}},Ue=function(t,n,s,i){r(this,o).setBuffer(t,s);let a={},u=r(this,o).string(1);for(;u!=="\0";)a[u]=r(this,o).cstring(),u=r(this,o).string(1);let m=a.M,l=i==="notice"?new ee(n,m):new N(m,n,i);return l.severity=a.S,l.code=a.C,l.detail=a.D,l.hint=a.H,l.position=a.P,l.internalPosition=a.p,l.internalQuery=a.q,l.where=a.W,l.schema=a.s,l.table=a.t,l.column=a.c,l.dataType=a.d,l.constraint=a.n,l.file=a.F,l.line=a.L,l.routine=a.R,l};export{ge as a,un as b,cn as c,We as d,mn as e,yn as f,hn as g,bn as h,gn as i,$e as j,N as k,J as l,ee as m,Te as n,pe as o,zn as p};
//# sourceMappingURL=chunk-2BOC2OMW.js.map

Sorry, the diff of this file is too big to display

import{b as Q,c as A,d as B,e as S,g as O,h as q,j as l,k as f}from"./chunk-2BOC2OMW.js";import{d as R}from"./chunk-F4GETNPB.js";import{e as T,f as w,g as d,h as a,j as g}from"./chunk-QY3QWFKW.js";g();g();function E(h){let s=h.e;return s.query=h.query,s.params=h.params,s.queryOptions=h.options,s}var P,p,t,y,x,m,_,z=class{constructor(){w(this,t);this.serializers={...A};this.parsers={...Q};w(this,P,!1);w(this,p,!1)}async _initArrayTypes({force:s=!1}={}){if(T(this,P)&&!s)return;d(this,P,!0);let e=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 r of e.rows)this.serializers[r.typarray]=o=>B(o,this.serializers[r.oid],r.typarray),this.parsers[r.typarray]=o=>S(o,this.parsers[r.oid],r.typarray)}async refreshArrayTypes(){await this._initArrayTypes({force:!0})}async query(s,e,r){return await this._checkReady(),await this._runExclusiveTransaction(async()=>await a(this,t,x).call(this,s,e,r))}async sql(s,...e){let{query:r,params:o}=R(s,...e);return await this.query(r,o)}async exec(s,e){return await this._checkReady(),await this._runExclusiveTransaction(async()=>await a(this,t,m).call(this,s,e))}async describeQuery(s,e){let r=[];try{await a(this,t,y).call(this,l.parse({text:s,types:e?.paramTypes}),e),r=await a(this,t,y).call(this,l.describe({type:"S"}),e)}catch(n){throw n instanceof f?E({e:n,options:e,params:void 0,query:s}):n}finally{r.push(...await a(this,t,y).call(this,l.sync(),e))}let o=r.find(n=>n.name==="parameterDescription"),i=r.find(n=>n.name==="rowDescription"),c=o?.dataTypeIDs.map(n=>({dataTypeID:n,serializer:this.serializers[n]}))??[],u=i?.fields.map(n=>({name:n.name,dataTypeID:n.dataTypeID,parser:this.parsers[n.dataTypeID]}))??[];return{queryParams:c,resultFields:u}}async transaction(s){return await this._checkReady(),await this._runExclusiveTransaction(async()=>{await a(this,t,m).call(this,"BEGIN"),d(this,p,!0);let e=!1,r=()=>{if(e)throw new Error("Transaction is closed")},o={query:async(i,c,u)=>(r(),await a(this,t,x).call(this,i,c,u)),sql:async(i,...c)=>{r();let{query:u,params:n}=R(i,...c);return await a(this,t,x).call(this,u,n)},exec:async(i,c)=>(r(),await a(this,t,m).call(this,i,c)),rollback:async()=>{r(),await a(this,t,m).call(this,"ROLLBACK"),e=!0},listen:async(i,c)=>(r(),await this.listen(i,c,o)),get closed(){return e}};try{let i=await s(o);return e||(e=!0,await a(this,t,m).call(this,"COMMIT")),d(this,p,!1),i}catch(i){throw e||(e=!0,await a(this,t,m).call(this,"ROLLBACK")),d(this,p,!1),i}})}async runExclusive(s){return await this._runExclusiveQuery(s)}};P=new WeakMap,p=new WeakMap,t=new WeakSet,y=async function(s,e={}){return await this.execProtocolStream(s,{...e,syncToFs:!1})},x=async function(s,e=[],r){return await this._runExclusiveQuery(async()=>{a(this,t,_).call(this,"runQuery",s,e,r),await this._handleBlob(r?.blob);let o=[];try{let c=await a(this,t,y).call(this,l.parse({text:s,types:r?.paramTypes}),r),u=q(await a(this,t,y).call(this,l.describe({type:"S"}),r)),n=e.map((b,k)=>{let D=u[k];if(b==null)return null;let v=r?.serializers?.[D]??this.serializers[D];return v?v(b):b.toString()});o=[...c,...await a(this,t,y).call(this,l.bind({values:n}),r),...await a(this,t,y).call(this,l.describe({type:"P"}),r),...await a(this,t,y).call(this,l.execute({}),r)]}catch(c){throw c instanceof f?E({e:c,options:r,params:e,query:s}):c}finally{o.push(...await a(this,t,y).call(this,l.sync(),r))}await this._cleanupBlob(),T(this,p)||await this.syncToFs();let i=await this._getWrittenBlob();return O(o,this.parsers,r,i)[0]})},m=async function(s,e){return await this._runExclusiveQuery(async()=>{a(this,t,_).call(this,"runExec",s,e),await this._handleBlob(e?.blob);let r=[];try{r=await a(this,t,y).call(this,l.query(s),e)}catch(i){throw i instanceof f?E({e:i,options:e,params:void 0,query:s}):i}finally{r.push(...await a(this,t,y).call(this,l.sync(),e))}this._cleanupBlob(),T(this,p)||await this.syncToFs();let o=await this._getWrittenBlob();return O(r,this.parsers,e,o)})},_=function(...s){this.debug>0&&console.log(...s)};export{z as a};
//# sourceMappingURL=chunk-JDT7TZ73.js.map
{"version":3,"sources":["../src/base.ts","../src/errors.ts"],"sourcesContent":["import { query as queryTemplate } from './templating.js'\nimport { parseDescribeStatementResults, parseResults } from './parse.js'\nimport {\n type Serializer,\n type Parser,\n serializers,\n parsers,\n arraySerializer,\n arrayParser,\n} from './types.js'\nimport type {\n DebugLevel,\n PGliteInterface,\n Results,\n Transaction,\n QueryOptions,\n ExecProtocolOptions,\n ExecProtocolResult,\n DescribeQueryResult,\n ExecProtocolOptionsStream,\n} from './interface.js'\n\nimport { serialize as serializeProtocol } from '@electric-sql/pg-protocol'\nimport {\n RowDescriptionMessage,\n ParameterDescriptionMessage,\n DatabaseError,\n BackendMessage,\n} from '@electric-sql/pg-protocol/messages'\nimport { makePGliteError } from './errors.js'\n\nexport abstract class BasePGlite\n implements Pick<PGliteInterface, 'query' | 'sql' | 'exec' | 'transaction'>\n{\n serializers: Record<number | string, Serializer> = { ...serializers }\n parsers: Record<number | string, Parser> = { ...parsers }\n #arrayTypesInitialized = false\n\n // # Abstract properties:\n abstract debug: DebugLevel\n\n // # Private properties:\n #inTransaction = false\n\n // # Abstract methods:\n\n /**\n * Execute a postgres wire protocol message\n * @param message The postgres wire protocol message to execute\n * @returns The result of the query\n */\n abstract execProtocol(\n message: Uint8Array,\n { syncToFs, onNotice }: ExecProtocolOptions,\n ): Promise<ExecProtocolResult>\n\n /**\n * Execute a postgres wire protocol message\n * @param message The postgres wire protocol message to execute\n * @returns The parsed results of the query\n */\n abstract execProtocolStream(\n message: Uint8Array,\n { syncToFs, onNotice }: ExecProtocolOptions,\n ): Promise<BackendMessage[]>\n\n /**\n * Execute a postgres wire protocol message directly without wrapping the response.\n * Only use if `execProtocol()` doesn't suite your needs.\n *\n * **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,\n * transactions, and notification listeners. Only use if you need to bypass these wrappers and\n * don't intend to use the above features.\n *\n * @param message The postgres wire protocol message to execute\n * @returns The direct message data response produced by Postgres\n */\n abstract execProtocolRaw(\n message: Uint8Array,\n { syncToFs }: ExecProtocolOptions,\n ): Promise<Uint8Array>\n\n /**\n * Execute a postgres wire protocol message directly without wrapping the response.\n * Only use if `execProtocol()` doesn't suite your needs.\n *\n * **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,\n * transactions, and notification listeners. Only use if you need to bypass these wrappers and\n * don't intend to use the above features.\n *\n * @param message The postgres wire protocol message to execute\n * @param options.onRawData Callback to receive streaming data\n */\n abstract execProtocolRawStream(\n message: Uint8Array,\n { syncToFs, onRawData }: ExecProtocolOptionsStream,\n ): Promise<void>\n\n /**\n * Sync the database to the filesystem\n * @returns Promise that resolves when the database is synced to the filesystem\n */\n abstract syncToFs(): Promise<void>\n\n /**\n * Handle a file attached to the current query\n * @param file The file to handle\n */\n abstract _handleBlob(blob?: File | Blob): Promise<void>\n\n /**\n * Get the written file\n */\n abstract _getWrittenBlob(): Promise<File | Blob | undefined>\n\n /**\n * Cleanup the current file\n */\n abstract _cleanupBlob(): Promise<void>\n\n abstract _checkReady(): Promise<void>\n abstract _runExclusiveQuery<T>(fn: () => Promise<T>): Promise<T>\n abstract _runExclusiveTransaction<T>(fn: () => Promise<T>): Promise<T>\n\n /**\n * Listen for notifications on a channel\n */\n abstract listen(\n channel: string,\n callback: (payload: string) => void,\n tx?: Transaction,\n ): Promise<(tx?: Transaction) => Promise<void>>\n\n // # Concrete implementations:\n\n /**\n * Initialize the array types\n * The oid if the type of an element and the typarray is the oid of the type of the\n * array.\n * We extract these from the database then create the serializers/parsers for\n * each type.\n * This should be called at the end of #init() in the implementing class.\n */\n async _initArrayTypes({ force = false } = {}) {\n if (this.#arrayTypesInitialized && !force) return\n this.#arrayTypesInitialized = true\n\n const types = await this.query<{ oid: number; typarray: number }>(`\n SELECT b.oid, b.typarray\n FROM pg_catalog.pg_type a\n LEFT JOIN pg_catalog.pg_type b ON b.oid = a.typelem\n WHERE a.typcategory = 'A'\n GROUP BY b.oid, b.typarray\n ORDER BY b.oid\n `)\n\n for (const type of types.rows) {\n this.serializers[type.typarray] = (x) =>\n arraySerializer(x, this.serializers[type.oid], type.typarray)\n this.parsers[type.typarray] = (x) =>\n arrayParser(x, this.parsers[type.oid], type.typarray)\n }\n }\n\n async #execProtocolNoSync(\n message: Uint8Array,\n options: ExecProtocolOptions = {},\n ): Promise<BackendMessage[]> {\n const results = await this.execProtocolStream(message, {\n ...options,\n syncToFs: false,\n })\n\n return results\n }\n\n /**\n * Re-syncs the array types from the database\n * This is useful if you add a new type to the database and want to use it, otherwise pglite won't recognize it.\n */\n async refreshArrayTypes() {\n await this._initArrayTypes({ force: true })\n }\n\n /**\n * Execute a single SQL statement\n * This uses the \"Extended Query\" postgres wire protocol message.\n * @param query The query to execute\n * @param params Optional parameters for the query\n * @returns The result of the query\n */\n async query<T>(\n query: string,\n params?: any[],\n options?: QueryOptions,\n ): Promise<Results<T>> {\n await this._checkReady()\n // We wrap the public query method in the transaction mutex to ensure that\n // only one query can be executed at a time and not concurrently with a\n // transaction.\n return await this._runExclusiveTransaction(async () => {\n return await this.#runQuery<T>(query, params, options)\n })\n }\n\n /**\n * Execute a single SQL statement like with {@link PGlite.query}, but with a\n * templated statement where template values will be treated as parameters.\n *\n * You can use helpers from `/template` to further format the query with\n * identifiers, raw SQL, and nested statements.\n *\n * This uses the \"Extended Query\" postgres wire protocol message.\n *\n * @param query The query to execute with parameters as template values\n * @returns The result of the query\n *\n * @example\n * ```ts\n * const results = await db.sql`SELECT * FROM ${identifier`foo`} WHERE id = ${id}`\n * ```\n */\n async sql<T>(\n sqlStrings: TemplateStringsArray,\n ...params: any[]\n ): Promise<Results<T>> {\n const { query, params: actualParams } = queryTemplate(sqlStrings, ...params)\n return await this.query(query, actualParams)\n }\n\n /**\n * Execute a SQL query, this can have multiple statements.\n * This uses the \"Simple Query\" postgres wire protocol message.\n * @param query The query to execute\n * @returns The result of the query\n */\n async exec(query: string, options?: QueryOptions): Promise<Array<Results>> {\n await this._checkReady()\n // We wrap the public exec method in the transaction mutex to ensure that\n // only one query can be executed at a time and not concurrently with a\n // transaction.\n return await this._runExclusiveTransaction(async () => {\n return await this.#runExec(query, options)\n })\n }\n\n /**\n * Internal method to execute a query\n * Not protected by the transaction mutex, so it can be used inside a transaction\n * @param query The query to execute\n * @param params Optional parameters for the query\n * @returns The result of the query\n */\n async #runQuery<T>(\n query: string,\n params: any[] = [],\n options?: QueryOptions,\n ): Promise<Results<T>> {\n return await this._runExclusiveQuery(async () => {\n // We need to parse, bind and execute a query with parameters\n this.#log('runQuery', query, params, options)\n await this._handleBlob(options?.blob)\n\n let results = []\n\n try {\n const parseResults = await this.#execProtocolNoSync(\n serializeProtocol.parse({ text: query, types: options?.paramTypes }),\n options,\n )\n\n const dataTypeIDs = parseDescribeStatementResults(\n await this.#execProtocolNoSync(\n serializeProtocol.describe({ type: 'S' }),\n options,\n ),\n )\n\n const values = params.map((param, i) => {\n const oid = dataTypeIDs[i]\n if (param === null || param === undefined) {\n return null\n }\n const serialize = options?.serializers?.[oid] ?? this.serializers[oid]\n if (serialize) {\n return serialize(param)\n } else {\n return param.toString()\n }\n })\n\n results = [\n ...parseResults,\n ...(await this.#execProtocolNoSync(\n serializeProtocol.bind({\n values,\n }),\n options,\n )),\n ...(await this.#execProtocolNoSync(\n serializeProtocol.describe({ type: 'P' }),\n options,\n )),\n ...(await this.#execProtocolNoSync(\n serializeProtocol.execute({}),\n options,\n )),\n ]\n } catch (e) {\n if (e instanceof DatabaseError) {\n const pgError = makePGliteError({ e, options, params, query })\n throw pgError\n }\n throw e\n } finally {\n results.push(\n ...(await this.#execProtocolNoSync(\n serializeProtocol.sync(),\n options,\n )),\n )\n }\n\n await this._cleanupBlob()\n if (!this.#inTransaction) {\n await this.syncToFs()\n }\n const blob = await this._getWrittenBlob()\n return parseResults(results, this.parsers, options, blob)[0] as Results<T>\n })\n }\n\n /**\n * Internal method to execute a query\n * Not protected by the transaction mutex, so it can be used inside a transaction\n * @param query The query to execute\n * @param params Optional parameters for the query\n * @returns The result of the query\n */\n async #runExec(\n query: string,\n options?: QueryOptions,\n ): Promise<Array<Results>> {\n return await this._runExclusiveQuery(async () => {\n // No params so we can just send the query\n this.#log('runExec', query, options)\n await this._handleBlob(options?.blob)\n let results = []\n try {\n results = await this.#execProtocolNoSync(\n serializeProtocol.query(query),\n options,\n )\n } catch (e) {\n if (e instanceof DatabaseError) {\n const pgError = makePGliteError({\n e,\n options,\n params: undefined,\n query,\n })\n throw pgError\n }\n throw e\n } finally {\n results.push(\n ...(await this.#execProtocolNoSync(\n serializeProtocol.sync(),\n options,\n )),\n )\n }\n this._cleanupBlob()\n if (!this.#inTransaction) {\n await this.syncToFs()\n }\n const blob = await this._getWrittenBlob()\n return parseResults(\n results,\n this.parsers,\n options,\n blob,\n ) as Array<Results>\n })\n }\n\n /**\n * Describe a query\n * @param query The query to describe\n * @returns A description of the result types for the query\n */\n async describeQuery(\n query: string,\n options?: QueryOptions,\n ): Promise<DescribeQueryResult> {\n let messages = []\n try {\n await this.#execProtocolNoSync(\n serializeProtocol.parse({ text: query, types: options?.paramTypes }),\n options,\n )\n\n messages = await this.#execProtocolNoSync(\n serializeProtocol.describe({ type: 'S' }),\n options,\n )\n } catch (e) {\n if (e instanceof DatabaseError) {\n const pgError = makePGliteError({\n e,\n options,\n params: undefined,\n query,\n })\n throw pgError\n }\n throw e\n } finally {\n messages.push(\n ...(await this.#execProtocolNoSync(serializeProtocol.sync(), options)),\n )\n }\n\n const paramDescription = messages.find(\n (msg): msg is ParameterDescriptionMessage =>\n msg.name === 'parameterDescription',\n )\n const resultDescription = messages.find(\n (msg): msg is RowDescriptionMessage => msg.name === 'rowDescription',\n )\n\n const queryParams =\n paramDescription?.dataTypeIDs.map((dataTypeID) => ({\n dataTypeID,\n serializer: this.serializers[dataTypeID],\n })) ?? []\n\n const resultFields =\n resultDescription?.fields.map((field) => ({\n name: field.name,\n dataTypeID: field.dataTypeID,\n parser: this.parsers[field.dataTypeID],\n })) ?? []\n\n return { queryParams, resultFields }\n }\n\n /**\n * Execute a transaction\n * @param callback A callback function that takes a transaction object\n * @returns The result of the transaction\n */\n async transaction<T>(callback: (tx: Transaction) => Promise<T>): Promise<T> {\n await this._checkReady()\n return await this._runExclusiveTransaction(async () => {\n await this.#runExec('BEGIN')\n this.#inTransaction = true\n\n // Once a transaction is closed, we throw an error if it's used again\n let closed = false\n const checkClosed = () => {\n if (closed) {\n throw new Error('Transaction is closed')\n }\n }\n\n const tx: Transaction = {\n query: async <T>(\n query: string,\n params?: any[],\n options?: QueryOptions,\n ): Promise<Results<T>> => {\n checkClosed()\n return await this.#runQuery(query, params, options)\n },\n sql: async <T>(\n sqlStrings: TemplateStringsArray,\n ...params: any[]\n ): Promise<Results<T>> => {\n checkClosed()\n const { query, params: actualParams } = queryTemplate(\n sqlStrings,\n ...params,\n )\n return await this.#runQuery(query, actualParams)\n },\n exec: async (\n query: string,\n options?: QueryOptions,\n ): Promise<Array<Results>> => {\n checkClosed()\n return await this.#runExec(query, options)\n },\n rollback: async () => {\n checkClosed()\n // Rollback and set the closed flag to prevent further use of this\n // transaction\n await this.#runExec('ROLLBACK')\n closed = true\n },\n listen: async (\n channel: string,\n callback: (payload: string) => void,\n ) => {\n checkClosed()\n return await this.listen(channel, callback, tx)\n },\n get closed() {\n return closed\n },\n }\n\n try {\n const result = await callback(tx)\n if (!closed) {\n closed = true\n await this.#runExec('COMMIT')\n }\n this.#inTransaction = false\n return result\n } catch (e) {\n if (!closed) {\n closed = true\n await this.#runExec('ROLLBACK')\n }\n this.#inTransaction = false\n throw e\n }\n })\n }\n\n /**\n * Run a function exclusively, no other transactions or queries will be allowed\n * while the function is running.\n * This is useful when working with the execProtocol methods as they are not blocked,\n * and do not block the locks used by transactions and queries.\n * @param fn The function to run\n * @returns The result of the function\n */\n async runExclusive<T>(fn: () => Promise<T>): Promise<T> {\n return await this._runExclusiveQuery(fn)\n }\n\n /**\n * Internal log function\n */\n #log(...args: any[]) {\n if (this.debug > 0) {\n console.log(...args)\n }\n }\n}\n","import { DatabaseError } from '@electric-sql/pg-protocol/messages'\nimport { QueryOptions } from './interface'\n\nexport interface PGliteError extends DatabaseError {\n query: string | undefined\n params: any[] | undefined\n queryOptions: QueryOptions | undefined\n}\n\nexport function makePGliteError(data: {\n e: DatabaseError\n query: string\n params: any[] | undefined\n options: QueryOptions | undefined\n}) {\n const pgError = data.e as PGliteError\n pgError.query =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","_inTransaction","_BasePGlite_instances","execProtocolNoSync_fn","runQuery_fn","runExec_fn","log_fn","BasePGlite","__privateAdd","serializers","parsers","force","__privateGet","__privateSet","types","type","x","arraySerializer","arrayParser","query","params","options","__privateMethod","sqlStrings","actualParams","messages","serialize","e","DatabaseError","makePGliteError","paramDescription","msg","resultDescription","queryParams","dataTypeID","resultFields","field","callback","closed","checkClosed","tx","channel","result","fn","message","results","parseResults","dataTypeIDs","parseDescribeStatementResults","values","param","i","oid","blob","args"]}
import{a as u,h as y,j as c}from"./chunk-2BOC2OMW.js";import{j as f}from"./chunk-QY3QWFKW.js";f();async function v(s,e,r,n){if(!r||r.length===0)return e;n=n??s;let t=[];try{await s.execProtocol(c.parse({text:e}),{syncToFs:!1}),t.push(...(await s.execProtocol(c.describe({type:"S"}),{syncToFs:!1})).messages)}finally{t.push(...(await s.execProtocol(c.sync(),{syncToFs:!1})).messages)}let a=y(t),i=e.replace(/\$([0-9]+)/g,(d,l)=>"%"+l+"$L");return(await n.query(`SELECT format($1, ${r.map((d,l)=>`$${l+2}`).join(", ")}) as query`,[i,...r],{paramTypes:[u,...a]})).rows[0].query}function x(s){let e,r=!1,n=async()=>{if(!e){r=!1;return}r=!0;let{args:t,resolve:a,reject:i}=e;e=void 0;try{let o=await s(...t);a(o)}catch(o){i(o)}finally{n()}};return async(...t)=>{e&&e.resolve(void 0);let a=new Promise((i,o)=>{e={args:t,resolve:i,reject:o}});return r||n(),a}}export{v as a,x as b};
//# sourceMappingURL=chunk-RYDTTX3G.js.map
{"version":3,"sources":["../src/utils.ts"],"sourcesContent":["import type { PGliteInterface, Transaction } from './interface.js'\nimport { serialize as serializeProtocol } from '@electric-sql/pg-protocol'\nimport { parseDescribeStatementResults } from './parse.js'\nimport { TEXT } from './types.js'\n\n/**\n * Formats a query with parameters\n * Expects that any tables/relations referenced in the query exist in the database\n * due to requiring them to be present to describe the parameters types.\n * `tx` is optional, and to be used when formatQuery is called during a transaction.\n * @param pg - The PGlite instance\n * @param query - The query to format\n * @param params - The parameters to format the query with\n * @param tx - The transaction to use, defaults to the PGlite instance\n * @returns The formatted query\n */\nexport async function formatQuery(\n pg: PGliteInterface,\n query: string,\n params?: any[] | null,\n tx?: Transaction | PGliteInterface,\n) {\n if (!params || params.length === 0) {\n // no params so no formatting needed\n return query\n }\n\n tx = tx ?? pg\n\n // Get the types of the parameters\n const messages = []\n try {\n await pg.execProtocol(serializeProtocol.parse({ text: query }), {\n syncToFs: false,\n })\n\n messages.push(\n ...(\n await pg.execProtocol(serializeProtocol.describe({ type: 'S' }), {\n syncToFs: false,\n })\n ).messages,\n )\n } finally {\n messages.push(\n ...(await pg.execProtocol(serializeProtocol.sync(), { syncToFs: false }))\n .messages,\n )\n }\n\n const dataTypeIDs = parseDescribeStatementResults(messages)\n\n // replace $1, $2, etc with %1$L, %2$L, etc\n // The `$` in `%n$L` is required for positional arguments; a bare `%nL` is\n // \"min width n\" and makes format() consume arguments sequentially, binding\n // the wrong values when placeholders are out of order or repeated.\n const subbedQuery = query.replace(/\\$([0-9]+)/g, (_, num) => {\n return '%' + num + '$L'\n })\n\n const ret = await tx.query<{\n query: string\n }>(\n `SELECT format($1, ${params.map((_, i) => `$${i + 2}`).join(', ')}) as query`,\n [subbedQuery, ...params],\n { paramTypes: [TEXT, ...dataTypeIDs] },\n )\n return ret.rows[0].query\n}\n\n/**\n * Debounce a function to ensure that only one instance of the function is running at\n * a time.\n * - If the function is called while an instance is already running, the new\n * call is scheduled to run after the current instance completes.\n * - If there is already a scheduled call, it is replaced with the new call.\n * @param fn - The function to debounce\n * @returns A debounced version of the function\n */\nexport function debounceMutex<A extends any[], R>(\n fn: (...args: A) => Promise<R>,\n): (...args: A) => Promise<R | void> {\n let next:\n | {\n args: A\n resolve: (value: R | void) => void\n reject: (reason?: any) => void\n }\n | undefined = undefined\n\n let isRunning = false\n const processNext = async () => {\n if (!next) {\n isRunning = false\n return\n }\n isRunning = true\n const { args, resolve, reject } = next\n next = undefined\n try {\n const ret = await fn(...args)\n resolve(ret)\n } catch (e) {\n reject(e)\n } finally {\n processNext()\n }\n }\n return async (...args: A) => {\n if (next) {\n next.resolve(undefined)\n }\n const promise = new Promise<R | void>((resolve, reject) => {\n next = { args, resolve, reject }\n })\n if (!isRunning) {\n processNext()\n }\n return promise\n }\n}\n"],"mappings":"8FAAAA,IAgBA,eAAsBC,EACpBC,EACAC,EACAC,EACAC,EACA,CACA,GAAI,CAACD,GAAUA,EAAO,SAAW,EAE/B,OAAOD,EAGTE,EAAKA,GAAMH,EAGX,IAAMI,EAAW,CAAC,EAClB,GAAI,CACF,MAAMJ,EAAG,aAAaK,EAAkB,MAAM,CAAE,KAAMJ,CAAM,CAAC,EAAG,CAC9D,SAAU,EACZ,CAAC,EAEDG,EAAS,KACP,IACE,MAAMJ,EAAG,aAAaK,EAAkB,SAAS,CAAE,KAAM,GAAI,CAAC,EAAG,CAC/D,SAAU,EACZ,CAAC,GACD,QACJ,CACF,QAAE,CACAD,EAAS,KACP,IAAI,MAAMJ,EAAG,aAAaK,EAAkB,KAAK,EAAG,CAAE,SAAU,EAAM,CAAC,GACpE,QACL,CACF,CAEA,IAAMC,EAAcC,EAA8BH,CAAQ,EAMpDI,EAAcP,EAAM,QAAQ,cAAe,CAACQ,EAAGC,IAC5C,IAAMA,EAAM,IACpB,EASD,OAPY,MAAMP,EAAG,MAGnB,qBAAqBD,EAAO,IAAI,CAACO,EAAGE,IAAM,IAAIA,EAAI,CAAC,EAAE,EAAE,KAAK,IAAI,CAAC,aACjE,CAACH,EAAa,GAAGN,CAAM,EACvB,CAAE,WAAY,CAACU,EAAM,GAAGN,CAAW,CAAE,CACvC,GACW,KAAK,CAAC,EAAE,KACrB,CAWO,SAASO,EACdC,EACmC,CACnC,IAAIC,EAQAC,EAAY,GACVC,EAAc,SAAY,CAC9B,GAAI,CAACF,EAAM,CACTC,EAAY,GACZ,MACF,CACAA,EAAY,GACZ,GAAM,CAAE,KAAAE,EAAM,QAAAC,EAAS,OAAAC,CAAO,EAAIL,EAClCA,EAAO,OACP,GAAI,CACF,IAAMM,EAAM,MAAMP,EAAG,GAAGI,CAAI,EAC5BC,EAAQE,CAAG,CACb,OAASC,EAAG,CACVF,EAAOE,CAAC,CACV,QAAE,CACAL,EAAY,CACd,CACF,EACA,MAAO,UAAUC,IAAY,CACvBH,GACFA,EAAK,QAAQ,MAAS,EAExB,IAAMQ,EAAU,IAAI,QAAkB,CAACJ,EAASC,IAAW,CACzDL,EAAO,CAAE,KAAAG,EAAM,QAAAC,EAAS,OAAAC,CAAO,CACjC,CAAC,EACD,OAAKJ,GACHC,EAAY,EAEPM,CACT,CACF","names":["init_esm_shims","formatQuery","pg","query","params","tx","messages","serialize","dataTypeIDs","parseDescribeStatementResults","subbedQuery","_","num","i","TEXT","debounceMutex","fn","next","isRunning","processNext","args","resolve","reject","ret","e","promise"]}
"use strict";var s=Object.defineProperty;var a=Object.getOwnPropertyDescriptor;var c=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var p=(t,e)=>{for(var r in e)s(t,r,{get:e[r],enumerable:!0})},u=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of c(e))!m.call(t,n)&&n!==r&&s(t,n,{get:()=>e[n],enumerable:!(i=a(e,n))||i.enumerable});return t};var f=t=>u(s({},"__esModule",{value:!0}),t);var R={};p(R,{moddatetime:()=>x});module.exports=f(R);var d=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href,o=d();var l=async(t,e)=>({bundlePath:new URL("../spi.tar.gz",o)}),x={name:"moddatetime",setup:l};0&&(module.exports={moddatetime});
//# sourceMappingURL=moddatetime.cjs.map
{"version":3,"sources":["../../src/contrib/moddatetime.ts","../../../../node_modules/.pnpm/tsup@8.3.0_@microsoft+api-extractor@7.47.7_@types+node@20.16.11__postcss@8.4.47_tsx@4.19.2_typescript@5.6.3/node_modules/tsup/assets/cjs_shims.js"],"sourcesContent":["import type {\n Extension,\n ExtensionSetupResult,\n PGliteInterface,\n} from '../interface'\n\nconst setup = async (_pg: PGliteInterface, _emscriptenOpts: any) => {\n return {\n bundlePath: new URL('../../release/spi.tar.gz', import.meta.url),\n } satisfies ExtensionSetupResult\n}\n\nexport const moddatetime = {\n name: 'moddatetime',\n setup,\n} satisfies Extension\n","// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () =>\n typeof document === 'undefined'\n ? new URL(`file:${__filename}`).href\n : (document.currentScript && document.currentScript.src) ||\n new URL('main.js', document.baseURI).href\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iBAAAE,IAAA,eAAAC,EAAAH,GCKA,IAAMI,EAAmB,IACvB,OAAO,SAAa,IAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,KAC7B,SAAS,eAAiB,SAAS,cAAc,KAClD,IAAI,IAAI,UAAW,SAAS,OAAO,EAAE,KAE9BC,EAAgCD,EAAiB,EDL9D,IAAME,EAAQ,MAAOC,EAAsBC,KAClC,CACL,WAAY,IAAI,IAAI,2BAA4BC,CAAe,CACjE,GAGWC,EAAc,CACzB,KAAM,cACN,MAAAJ,CACF","names":["moddatetime_exports","__export","moddatetime","__toCommonJS","getImportMetaUrl","importMetaUrl","setup","_pg","_emscriptenOpts","importMetaUrl","moddatetime"]}
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';
declare const moddatetime: {
name: string;
setup: (_pg: PGliteInterface, _emscriptenOpts: any) => Promise<{
bundlePath: URL;
}>;
};
export { moddatetime };
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';
declare const moddatetime: {
name: string;
setup: (_pg: PGliteInterface, _emscriptenOpts: any) => Promise<{
bundlePath: URL;
}>;
};
export { moddatetime };
import{j as e}from"../chunk-QY3QWFKW.js";e();var t=async(n,s)=>({bundlePath:new URL("../spi.tar.gz",import.meta.url)}),r={name:"moddatetime",setup:t};export{r as moddatetime};
//# sourceMappingURL=moddatetime.js.map
{"version":3,"sources":["../../src/contrib/moddatetime.ts"],"sourcesContent":["import type {\n Extension,\n ExtensionSetupResult,\n PGliteInterface,\n} from '../interface'\n\nconst setup = async (_pg: PGliteInterface, _emscriptenOpts: any) => {\n return {\n bundlePath: new URL('../../release/spi.tar.gz', import.meta.url),\n } satisfies ExtensionSetupResult\n}\n\nexport const moddatetime = {\n name: 'moddatetime',\n setup,\n} satisfies Extension\n"],"mappings":"yCAAAA,IAMA,IAAMC,EAAQ,MAAOC,EAAsBC,KAClC,CACL,WAAY,IAAI,IAAI,2BAA4B,YAAY,GAAG,CACjE,GAGWC,EAAc,CACzB,KAAM,cACN,MAAAH,CACF","names":["init_esm_shims","setup","_pg","_emscriptenOpts","moddatetime"]}
declare const Modes: {
readonly text: 0;
readonly binary: 1;
};
type Mode = (typeof Modes)[keyof typeof Modes];
type BufferParameter = ArrayBuffer | ArrayBufferView;
type MessageName = 'parseComplete' | 'bindComplete' | 'closeComplete' | 'noData' | 'portalSuspended' | 'replicationStart' | 'emptyQuery' | 'copyDone' | 'copyData' | 'rowDescription' | 'parameterDescription' | 'parameterStatus' | 'backendKeyData' | 'notification' | 'readyForQuery' | 'commandComplete' | 'dataRow' | 'copyInResponse' | 'copyOutResponse' | 'authenticationOk' | 'authenticationMD5Password' | 'authenticationCleartextPassword' | 'authenticationSASL' | 'authenticationSASLContinue' | 'authenticationSASLFinal' | 'error' | 'notice';
type BackendMessage = {
name: MessageName;
length: number;
};
declare const parseComplete: BackendMessage;
declare const bindComplete: BackendMessage;
declare const closeComplete: BackendMessage;
declare const noData: BackendMessage;
declare const portalSuspended: BackendMessage;
declare const replicationStart: BackendMessage;
declare const emptyQuery: BackendMessage;
declare const copyDone: BackendMessage;
declare class AuthenticationOk implements BackendMessage {
readonly length: number;
readonly name = "authenticationOk";
constructor(length: number);
}
declare class AuthenticationCleartextPassword implements BackendMessage {
readonly length: number;
readonly name = "authenticationCleartextPassword";
constructor(length: number);
}
declare class AuthenticationMD5Password implements BackendMessage {
readonly length: number;
readonly salt: Uint8Array;
readonly name = "authenticationMD5Password";
constructor(length: number, salt: Uint8Array);
}
declare class AuthenticationSASL implements BackendMessage {
readonly length: number;
readonly mechanisms: string[];
readonly name = "authenticationSASL";
constructor(length: number, mechanisms: string[]);
}
declare class AuthenticationSASLContinue implements BackendMessage {
readonly length: number;
readonly data: string;
readonly name = "authenticationSASLContinue";
constructor(length: number, data: string);
}
declare class AuthenticationSASLFinal implements BackendMessage {
readonly length: number;
readonly data: string;
readonly name = "authenticationSASLFinal";
constructor(length: number, data: string);
}
type AuthenticationMessage = AuthenticationOk | AuthenticationCleartextPassword | AuthenticationMD5Password | AuthenticationSASL | AuthenticationSASLContinue | AuthenticationSASLFinal;
interface NoticeOrError {
message: string | undefined;
severity: string | undefined;
code: string | undefined;
detail: string | undefined;
hint: string | undefined;
position: string | undefined;
internalPosition: string | undefined;
internalQuery: string | undefined;
where: string | undefined;
schema: string | undefined;
table: string | undefined;
column: string | undefined;
dataType: string | undefined;
constraint: string | undefined;
file: string | undefined;
line: string | undefined;
routine: string | undefined;
}
declare class DatabaseError extends Error implements NoticeOrError {
readonly length: number;
readonly name: MessageName;
severity: string | undefined;
code: string | undefined;
detail: string | undefined;
hint: string | undefined;
position: string | undefined;
internalPosition: string | undefined;
internalQuery: string | undefined;
where: string | undefined;
schema: string | undefined;
table: string | undefined;
column: string | undefined;
dataType: string | undefined;
constraint: string | undefined;
file: string | undefined;
line: string | undefined;
routine: string | undefined;
constructor(message: string, length: number, name: MessageName);
}
declare class CopyDataMessage implements BackendMessage {
readonly length: number;
readonly chunk: Uint8Array;
readonly name = "copyData";
constructor(length: number, chunk: Uint8Array);
}
declare class CopyResponse implements BackendMessage {
readonly length: number;
readonly name: MessageName;
readonly binary: boolean;
readonly columnTypes: number[];
constructor(length: number, name: MessageName, binary: boolean, columnCount: number);
}
declare class Field {
readonly name: string;
readonly tableID: number;
readonly columnID: number;
readonly dataTypeID: number;
readonly dataTypeSize: number;
readonly dataTypeModifier: number;
readonly format: Mode;
constructor(name: string, tableID: number, columnID: number, dataTypeID: number, dataTypeSize: number, dataTypeModifier: number, format: Mode);
}
declare class RowDescriptionMessage implements BackendMessage {
readonly length: number;
readonly fieldCount: number;
readonly name: MessageName;
readonly fields: Field[];
constructor(length: number, fieldCount: number);
}
declare class ParameterDescriptionMessage implements BackendMessage {
readonly length: number;
readonly parameterCount: number;
readonly name: MessageName;
readonly dataTypeIDs: number[];
constructor(length: number, parameterCount: number);
}
declare class ParameterStatusMessage implements BackendMessage {
readonly length: number;
readonly parameterName: string;
readonly parameterValue: string;
readonly name: MessageName;
constructor(length: number, parameterName: string, parameterValue: string);
}
declare class BackendKeyDataMessage implements BackendMessage {
readonly length: number;
readonly processID: number;
readonly secretKey: number;
readonly name: MessageName;
constructor(length: number, processID: number, secretKey: number);
}
declare class NotificationResponseMessage implements BackendMessage {
readonly length: number;
readonly processId: number;
readonly channel: string;
readonly payload: string;
readonly name: MessageName;
constructor(length: number, processId: number, channel: string, payload: string);
}
declare class ReadyForQueryMessage implements BackendMessage {
readonly length: number;
readonly status: string;
readonly name: MessageName;
constructor(length: number, status: string);
}
declare class CommandCompleteMessage implements BackendMessage {
readonly length: number;
readonly text: string;
readonly name: MessageName;
constructor(length: number, text: string);
}
declare class DataRowMessage implements BackendMessage {
length: number;
fields: (string | null)[];
readonly fieldCount: number;
readonly name: MessageName;
constructor(length: number, fields: (string | null)[]);
}
declare class NoticeMessage implements BackendMessage, NoticeOrError {
readonly length: number;
readonly message: string | undefined;
constructor(length: number, message: string | undefined);
readonly name = "notice";
severity: string | undefined;
code: string | undefined;
detail: string | undefined;
hint: string | undefined;
position: string | undefined;
internalPosition: string | undefined;
internalQuery: string | undefined;
where: string | undefined;
schema: string | undefined;
table: string | undefined;
column: string | undefined;
dataType: string | undefined;
constraint: string | undefined;
file: string | undefined;
line: string | undefined;
routine: string | undefined;
}
type messages_AuthenticationCleartextPassword = AuthenticationCleartextPassword;
declare const messages_AuthenticationCleartextPassword: typeof AuthenticationCleartextPassword;
type messages_AuthenticationMD5Password = AuthenticationMD5Password;
declare const messages_AuthenticationMD5Password: typeof AuthenticationMD5Password;
type messages_AuthenticationMessage = AuthenticationMessage;
type messages_AuthenticationOk = AuthenticationOk;
declare const messages_AuthenticationOk: typeof AuthenticationOk;
type messages_AuthenticationSASL = AuthenticationSASL;
declare const messages_AuthenticationSASL: typeof AuthenticationSASL;
type messages_AuthenticationSASLContinue = AuthenticationSASLContinue;
declare const messages_AuthenticationSASLContinue: typeof AuthenticationSASLContinue;
type messages_AuthenticationSASLFinal = AuthenticationSASLFinal;
declare const messages_AuthenticationSASLFinal: typeof AuthenticationSASLFinal;
type messages_BackendKeyDataMessage = BackendKeyDataMessage;
declare const messages_BackendKeyDataMessage: typeof BackendKeyDataMessage;
type messages_BackendMessage = BackendMessage;
type messages_CommandCompleteMessage = CommandCompleteMessage;
declare const messages_CommandCompleteMessage: typeof CommandCompleteMessage;
type messages_CopyDataMessage = CopyDataMessage;
declare const messages_CopyDataMessage: typeof CopyDataMessage;
type messages_CopyResponse = CopyResponse;
declare const messages_CopyResponse: typeof CopyResponse;
type messages_DataRowMessage = DataRowMessage;
declare const messages_DataRowMessage: typeof DataRowMessage;
type messages_DatabaseError = DatabaseError;
declare const messages_DatabaseError: typeof DatabaseError;
type messages_Field = Field;
declare const messages_Field: typeof Field;
type messages_MessageName = MessageName;
type messages_NoticeMessage = NoticeMessage;
declare const messages_NoticeMessage: typeof NoticeMessage;
type messages_NotificationResponseMessage = NotificationResponseMessage;
declare const messages_NotificationResponseMessage: typeof NotificationResponseMessage;
type messages_ParameterDescriptionMessage = ParameterDescriptionMessage;
declare const messages_ParameterDescriptionMessage: typeof ParameterDescriptionMessage;
type messages_ParameterStatusMessage = ParameterStatusMessage;
declare const messages_ParameterStatusMessage: typeof ParameterStatusMessage;
type messages_ReadyForQueryMessage = ReadyForQueryMessage;
declare const messages_ReadyForQueryMessage: typeof ReadyForQueryMessage;
type messages_RowDescriptionMessage = RowDescriptionMessage;
declare const messages_RowDescriptionMessage: typeof RowDescriptionMessage;
declare const messages_bindComplete: typeof bindComplete;
declare const messages_closeComplete: typeof closeComplete;
declare const messages_copyDone: typeof copyDone;
declare const messages_emptyQuery: typeof emptyQuery;
declare const messages_noData: typeof noData;
declare const messages_parseComplete: typeof parseComplete;
declare const messages_portalSuspended: typeof portalSuspended;
declare const messages_replicationStart: typeof replicationStart;
declare namespace messages {
export { messages_AuthenticationCleartextPassword as AuthenticationCleartextPassword, messages_AuthenticationMD5Password as AuthenticationMD5Password, type messages_AuthenticationMessage as AuthenticationMessage, messages_AuthenticationOk as AuthenticationOk, messages_AuthenticationSASL as AuthenticationSASL, messages_AuthenticationSASLContinue as AuthenticationSASLContinue, messages_AuthenticationSASLFinal as AuthenticationSASLFinal, messages_BackendKeyDataMessage as BackendKeyDataMessage, type messages_BackendMessage as BackendMessage, messages_CommandCompleteMessage as CommandCompleteMessage, messages_CopyDataMessage as CopyDataMessage, messages_CopyResponse as CopyResponse, messages_DataRowMessage as DataRowMessage, messages_DatabaseError as DatabaseError, messages_Field as Field, type messages_MessageName as MessageName, messages_NoticeMessage as NoticeMessage, messages_NotificationResponseMessage as NotificationResponseMessage, messages_ParameterDescriptionMessage as ParameterDescriptionMessage, messages_ParameterStatusMessage as ParameterStatusMessage, messages_ReadyForQueryMessage as ReadyForQueryMessage, messages_RowDescriptionMessage as RowDescriptionMessage, messages_bindComplete as bindComplete, messages_closeComplete as closeComplete, messages_copyDone as copyDone, messages_emptyQuery as emptyQuery, messages_noData as noData, messages_parseComplete as parseComplete, messages_portalSuspended as portalSuspended, messages_replicationStart as replicationStart };
}
type IDBFS = Emscripten.FileSystemType & {
quit: () => void;
dbs: Record<string, IDBDatabase>;
};
type FS = typeof FS & {
filesystems: {
MEMFS: Emscripten.FileSystemType;
NODEFS: Emscripten.FileSystemType;
IDBFS: IDBFS;
};
quit: () => void;
};
interface PostgresMod extends Omit<EmscriptenModule, 'preInit' | 'preRun' | 'postRun'> {
preInit: Array<{
(mod: PostgresMod): void;
}>;
preRun: Array<{
(mod: PostgresMod): void;
}>;
postRun: Array<{
(mod: PostgresMod): void;
}>;
thisProgram: string;
stdin: (() => number | null) | null;
FS: FS;
wasmMemory: WebAssembly.Memory;
PROXYFS: Emscripten.FileSystemType;
WASM_PREFIX: string;
pg_extensions: Record<string, Promise<Blob | null>>;
UTF8ToString: (ptr: number, maxBytesToRead?: number) => string;
stringToUTF8OnStack: (s: string) => number;
_pgl_set_system_fn: (system_fn: number) => void;
_pgl_set_popen_fn: (popen_fn: number) => void;
_pgl_set_pclose_fn: (pclose_fn: number) => void;
_pgl_set_rw_cbs: (read_cb: number, write_cb: number) => void;
_pgl_set_pipe_fn: (pipe_fn: number) => number;
_pgl_freopen: (filepath: number, mode: number, stream: number) => number;
_pgl_pq_flush: () => void;
_fopen: (path: number, mode: number) => number;
_fclose: (stream: number) => number;
_fflush: (stream: number) => void;
_pgl_proc_exit: (code: number) => number;
addFunction: (cb: (ptr: any, length: number) => void, signature: string) => number;
removeFunction: (f: number) => void;
callMain: (args?: string[]) => number;
_PostgresMainLoopOnce: () => void;
_PostgresMainLongJmp: () => void;
_PostgresSendReadyForQueryIfNecessary: () => void;
_ProcessStartupPacket: (Port: number, ssl_done: boolean, gss_done: boolean) => number;
_IsTransactionBlock: () => number;
_pgl_setPGliteActive: (newValue: number) => number;
_pgl_startPGlite: () => void;
_pgl_getMyProcPort: () => number;
_pgl_sendConnData: () => void;
ENV: any;
PGLITE_ENV: any;
_emscripten_force_exit: (status: number) => void;
_pgl_run_atexit_funcs: () => void;
_pq_buffer_remaining_data: () => number;
}
type PostgresFactory<T extends PostgresMod = PostgresMod> = (moduleOverrides?: Partial<T>) => Promise<T>;
declare const _default: PostgresFactory<PostgresMod>;
type postgresMod_FS = FS;
type postgresMod_PostgresMod = PostgresMod;
declare namespace postgresMod {
export { type postgresMod_FS as FS, type postgresMod_PostgresMod as PostgresMod, _default as default };
}
type DumpTarCompressionOptions = 'none' | 'gzip' | 'auto';
type FsType = 'nodefs' | 'idbfs' | 'memoryfs' | 'opfs-ahp';
/**
* Filesystem interface.
* All virtual filesystems that are compatible with PGlite must implement
* this interface.
*/
interface Filesystem {
/**
* Initiate the filesystem and return the options to pass to the emscripten module.
*/
init(pg: PGlite, emscriptenOptions: Partial<PostgresMod>): Promise<{
emscriptenOpts: Partial<PostgresMod>;
}>;
/**
* Sync the filesystem to any underlying storage.
*/
syncToFs(relaxedDurability?: boolean): Promise<void>;
/**
* Sync the filesystem from any underlying storage.
*/
initialSyncFs(): Promise<void>;
/**
* Dump the PGDATA dir from the filesystem to a gzipped tarball.
*/
dumpTar(dbname: string, compression?: DumpTarCompressionOptions): Promise<File | Blob>;
/**
* Close the filesystem.
*/
closeFs(): Promise<void>;
}
/**
* Base class for all emscripten built-in filesystems.
*/
declare class EmscriptenBuiltinFilesystem implements Filesystem {
protected dataDir?: string;
protected pg?: PGlite;
constructor(dataDir?: string);
init(pg: PGlite, emscriptenOptions: Partial<PostgresMod>): Promise<{
emscriptenOpts: Partial<PostgresMod>;
}>;
syncToFs(_relaxedDurability?: boolean): Promise<void>;
initialSyncFs(): Promise<void>;
closeFs(): Promise<void>;
dumpTar(dbname: string, compression?: DumpTarCompressionOptions): Promise<Blob | File>;
}
/**
* Abstract base class for all custom virtual filesystems.
* Each custom filesystem needs to implement an interface similar to the NodeJS FS API.
*/
declare abstract class BaseFilesystem implements Filesystem {
protected dataDir?: string;
protected pg?: PGlite;
readonly debug: boolean;
constructor(dataDir?: string, { debug }?: {
debug?: boolean;
});
syncToFs(_relaxedDurability?: boolean): Promise<void>;
initialSyncFs(): Promise<void>;
closeFs(): Promise<void>;
dumpTar(dbname: string, compression?: DumpTarCompressionOptions): Promise<Blob | File>;
init(pg: PGlite, emscriptenOptions: Partial<PostgresMod>): Promise<{
emscriptenOpts: Partial<PostgresMod>;
}>;
abstract chmod(path: string, mode: number): void;
abstract close(fd: number): void;
abstract fstat(fd: number): FsStats;
abstract lstat(path: string): FsStats;
abstract mkdir(path: string, options?: {
recursive?: boolean;
mode?: number;
}): void;
abstract open(path: string, flags?: string, mode?: number): number;
abstract readdir(path: string): string[];
abstract read(fd: number, buffer: Uint8Array, // Buffer to read into
offset: number, // Offset in buffer to start writing to
length: number, // Number of bytes to read
position: number): number;
abstract rename(oldPath: string, newPath: string): void;
abstract rmdir(path: string): void;
abstract truncate(path: string, len: number): void;
abstract unlink(path: string): void;
abstract utimes(path: string, atime: number, mtime: number): void;
abstract writeFile(path: string, data: string | Uint8Array, options?: {
encoding?: string;
mode?: number;
flag?: string;
}): void;
abstract write(fd: number, buffer: Uint8Array, // Buffer to read from
offset: number, // Offset in buffer to start reading from
length: number, // Number of bytes to write
position: number): number;
}
type FsStats = {
dev: number;
ino: number;
mode: number;
nlink: number;
uid: number;
gid: number;
rdev: number;
size: number;
blksize: number;
blocks: number;
atime: number;
mtime: number;
ctime: number;
};
declare const ERRNO_CODES: {
readonly EBADF: 8;
readonly EBADFD: 127;
readonly EEXIST: 20;
readonly EINVAL: 28;
readonly EISDIR: 31;
readonly ENODEV: 43;
readonly ENOENT: 44;
readonly ENOTDIR: 54;
readonly ENOTEMPTY: 55;
};
type FilesystemType = 'nodefs' | 'idbfs' | 'memoryfs';
type DebugLevel = 0 | 1 | 2 | 3 | 4 | 5;
type RowMode = 'array' | 'object';
interface ParserOptions {
[pgType: number]: (value: string) => any;
}
interface SerializerOptions {
[pgType: number]: (value: any) => string;
}
interface QueryOptions {
rowMode?: RowMode;
parsers?: ParserOptions;
serializers?: SerializerOptions;
blob?: Blob | File;
onNotice?: (notice: NoticeMessage) => void;
paramTypes?: number[];
}
interface ExecProtocolOptions {
syncToFs?: boolean;
throwOnError?: boolean;
onNotice?: (notice: NoticeMessage) => void;
}
interface ExecProtocolOptionsStream {
syncToFs?: boolean;
onRawData: (data: Uint8Array) => void;
}
interface ExtensionSetupResult<TNamespace = any> {
emscriptenOpts?: any;
namespaceObj?: TNamespace;
bundlePath?: URL;
sharedPreloadLibraries?: string[];
init?: () => Promise<void>;
close?: () => Promise<void>;
}
type ExtensionSetup<TNamespace = any> = (pg: PGliteInterface, emscriptenOpts: any, clientOnly?: boolean) => Promise<ExtensionSetupResult<TNamespace>>;
interface Extension<TNamespace = any> {
name: string;
setup: ExtensionSetup<TNamespace>;
}
type ExtensionNamespace<T> = T extends Extension<infer TNamespace> ? TNamespace : any;
type Extensions = {
[namespace: string]: Extension | URL;
};
type InitializedExtensions<TExtensions extends Extensions = Extensions> = {
[K in keyof TExtensions]: ExtensionNamespace<TExtensions[K]>;
};
interface ExecProtocolResult {
messages: BackendMessage[];
data: Uint8Array;
}
interface DumpDataDirResult {
tarball: Uint8Array;
extension: '.tar' | '.tgz';
filename: string;
}
interface PGliteOptions<TExtensions extends Extensions = Extensions> {
noInitDb?: boolean;
dataDir?: string;
username?: string;
database?: string;
fs?: Filesystem;
debug?: DebugLevel;
relaxedDurability?: boolean;
extensions?: TExtensions;
loadDataDir?: Blob | File;
icuDataDir?: Blob | File;
initialMemory?: number;
pgliteWasmModule?: WebAssembly.Module;
initdbWasmModule?: WebAssembly.Module;
fsBundle?: Blob | File;
parsers?: ParserOptions;
serializers?: SerializerOptions;
startParams?: string[];
initDbStartParams?: string[];
postgresqlconf?: string[] | string;
}
type PGliteInterface<T extends Extensions = Extensions> = InitializedExtensions<T> & {
readonly waitReady: Promise<void>;
readonly debug: DebugLevel;
readonly ready: boolean;
readonly closed: boolean;
close(): Promise<void>;
query<T>(query: string, params?: any[], options?: QueryOptions): Promise<Results<T>>;
sql<T>(sqlStrings: TemplateStringsArray, ...params: any[]): Promise<Results<T>>;
exec(query: string, options?: QueryOptions): Promise<Array<Results>>;
describeQuery(query: string): Promise<DescribeQueryResult>;
transaction<T>(callback: (tx: Transaction) => Promise<T>): Promise<T>;
execProtocolRaw(message: Uint8Array, options?: ExecProtocolOptions): Promise<Uint8Array>;
execProtocolRawStream(message: Uint8Array, options?: ExecProtocolOptionsStream): Promise<void>;
execProtocol(message: Uint8Array, options?: ExecProtocolOptions): Promise<ExecProtocolResult>;
runExclusive<T>(fn: () => Promise<T>): Promise<T>;
listen(channel: string, callback: (payload: string) => void, tx?: Transaction): Promise<(tx?: Transaction) => Promise<void>>;
unlisten(channel: string, callback?: (payload: string) => void, tx?: Transaction): Promise<void>;
onNotification(callback: (channel: string, payload: string) => void): () => void;
offNotification(callback: (channel: string, payload: string) => void): void;
dumpDataDir(compression?: DumpTarCompressionOptions): Promise<File | Blob>;
refreshArrayTypes(): Promise<void>;
};
type PGliteInterfaceExtensions<E> = E extends Extensions ? {
[K in keyof E]: E[K] extends Extension ? Awaited<ReturnType<E[K]['setup']>>['namespaceObj'] extends infer N ? N extends undefined | null | void ? never : N : never : never;
} : Record<string, never>;
type Row<T = {
[key: string]: any;
}> = T;
type Results<T = {
[key: string]: any;
}> = {
rows: Row<T>[];
affectedRows?: number;
/**
* The command of the query that was run, e.g. "SELECT", "INSERT", "CREATE".
*/
command?: string;
/**
* The number of rows reported by the command tag, e.g. the rows returned
* by a SELECT or changed by an UPDATE. Unlike `affectedRows` this is per statement
* and not cumulative across a multi-statement query.
*/
rowCount?: number;
fields: {
name: string;
dataTypeID: number;
}[];
blob?: Blob;
};
interface Transaction {
query<T>(query: string, params?: any[], options?: QueryOptions): Promise<Results<T>>;
sql<T>(sqlStrings: TemplateStringsArray, ...params: any[]): Promise<Results<T>>;
exec(query: string, options?: QueryOptions): Promise<Array<Results>>;
rollback(): Promise<void>;
listen(channel: string, callback: (payload: string) => void): Promise<(tx?: Transaction) => Promise<void>>;
get closed(): boolean;
}
type DescribeQueryResult = {
queryParams: {
dataTypeID: number;
serializer: Serializer;
}[];
resultFields: {
name: string;
dataTypeID: number;
parser: Parser;
}[];
};
declare const BOOL = 16;
declare const BYTEA = 17;
declare const CHAR = 18;
declare const INT8 = 20;
declare const INT2 = 21;
declare const INT4 = 23;
declare const REGPROC = 24;
declare const TEXT = 25;
declare const OID = 26;
declare const TID = 27;
declare const XID = 28;
declare const CID = 29;
declare const JSON = 114;
declare const XML = 142;
declare const PG_NODE_TREE = 194;
declare const SMGR = 210;
declare const PATH = 602;
declare const POLYGON = 604;
declare const CIDR = 650;
declare const FLOAT4 = 700;
declare const FLOAT8 = 701;
declare const ABSTIME = 702;
declare const RELTIME = 703;
declare const TINTERVAL = 704;
declare const CIRCLE = 718;
declare const MACADDR8 = 774;
declare const MONEY = 790;
declare const MACADDR = 829;
declare const INET = 869;
declare const ACLITEM = 1033;
declare const BPCHAR = 1042;
declare const VARCHAR = 1043;
declare const DATE = 1082;
declare const TIME = 1083;
declare const TIMESTAMP = 1114;
declare const TIMESTAMPTZ = 1184;
declare const INTERVAL = 1186;
declare const TIMETZ = 1266;
declare const BIT = 1560;
declare const VARBIT = 1562;
declare const NUMERIC = 1700;
declare const REFCURSOR = 1790;
declare const REGPROCEDURE = 2202;
declare const REGOPER = 2203;
declare const REGOPERATOR = 2204;
declare const REGCLASS = 2205;
declare const REGTYPE = 2206;
declare const UUID = 2950;
declare const TXID_SNAPSHOT = 2970;
declare const PG_LSN = 3220;
declare const PG_NDISTINCT = 3361;
declare const PG_DEPENDENCIES = 3402;
declare const TSVECTOR = 3614;
declare const TSQUERY = 3615;
declare const GTSVECTOR = 3642;
declare const REGCONFIG = 3734;
declare const REGDICTIONARY = 3769;
declare const JSONB = 3802;
declare const REGNAMESPACE = 4089;
declare const REGROLE = 4096;
declare const types: {
string: {
to: number;
from: number[];
serialize: (x: string | number | Date) => string;
parse: (x: string) => string;
};
number: {
to: number;
from: number[];
serialize: (x: number) => string;
parse: (x: string) => number;
};
bigint: {
to: number;
from: number[];
serialize: (x: bigint) => string;
parse: (x: string) => number | bigint;
};
json: {
to: number;
from: number[];
serialize: (x: any) => string;
parse: (x: string) => any;
};
boolean: {
to: number;
from: number[];
serialize: (x: boolean | number | string) => "t" | "f";
parse: (x: string) => x is "t";
};
date: {
to: number;
from: number[];
serialize: (x: Date | string | number) => string;
parse: (x: string | number) => Date;
};
bytea: {
to: number;
from: number[];
serialize: (x: Uint8Array) => string;
parse: (x: string) => Uint8Array;
};
};
type Parser = (x: string, typeId?: number) => any;
type Serializer = (x: any) => string;
type TypeHandler = {
to: number;
from: number | number[];
serialize: Serializer;
parse: Parser;
};
type TypeHandlers = {
[key: string]: TypeHandler;
};
declare const parsers: {
[key: string]: (x: string, typeId?: number) => any;
[key: number]: (x: string, typeId?: number) => any;
};
declare const serializers: {
[key: string]: Serializer;
[key: number]: Serializer;
};
declare function parseType(x: string | null, type: number, parsers?: ParserOptions): any;
declare function arraySerializer(xs: any, serializer: Serializer | undefined, typarray: number): string;
declare function arrayParser(x: string, parser: Parser, typarray: number): any;
declare const types$1_ABSTIME: typeof ABSTIME;
declare const types$1_ACLITEM: typeof ACLITEM;
declare const types$1_BIT: typeof BIT;
declare const types$1_BOOL: typeof BOOL;
declare const types$1_BPCHAR: typeof BPCHAR;
declare const types$1_BYTEA: typeof BYTEA;
declare const types$1_CHAR: typeof CHAR;
declare const types$1_CID: typeof CID;
declare const types$1_CIDR: typeof CIDR;
declare const types$1_CIRCLE: typeof CIRCLE;
declare const types$1_DATE: typeof DATE;
declare const types$1_FLOAT4: typeof FLOAT4;
declare const types$1_FLOAT8: typeof FLOAT8;
declare const types$1_GTSVECTOR: typeof GTSVECTOR;
declare const types$1_INET: typeof INET;
declare const types$1_INT2: typeof INT2;
declare const types$1_INT4: typeof INT4;
declare const types$1_INT8: typeof INT8;
declare const types$1_INTERVAL: typeof INTERVAL;
declare const types$1_JSON: typeof JSON;
declare const types$1_JSONB: typeof JSONB;
declare const types$1_MACADDR: typeof MACADDR;
declare const types$1_MACADDR8: typeof MACADDR8;
declare const types$1_MONEY: typeof MONEY;
declare const types$1_NUMERIC: typeof NUMERIC;
declare const types$1_OID: typeof OID;
declare const types$1_PATH: typeof PATH;
declare const types$1_PG_DEPENDENCIES: typeof PG_DEPENDENCIES;
declare const types$1_PG_LSN: typeof PG_LSN;
declare const types$1_PG_NDISTINCT: typeof PG_NDISTINCT;
declare const types$1_PG_NODE_TREE: typeof PG_NODE_TREE;
declare const types$1_POLYGON: typeof POLYGON;
type types$1_Parser = Parser;
declare const types$1_REFCURSOR: typeof REFCURSOR;
declare const types$1_REGCLASS: typeof REGCLASS;
declare const types$1_REGCONFIG: typeof REGCONFIG;
declare const types$1_REGDICTIONARY: typeof REGDICTIONARY;
declare const types$1_REGNAMESPACE: typeof REGNAMESPACE;
declare const types$1_REGOPER: typeof REGOPER;
declare const types$1_REGOPERATOR: typeof REGOPERATOR;
declare const types$1_REGPROC: typeof REGPROC;
declare const types$1_REGPROCEDURE: typeof REGPROCEDURE;
declare const types$1_REGROLE: typeof REGROLE;
declare const types$1_REGTYPE: typeof REGTYPE;
declare const types$1_RELTIME: typeof RELTIME;
declare const types$1_SMGR: typeof SMGR;
type types$1_Serializer = Serializer;
declare const types$1_TEXT: typeof TEXT;
declare const types$1_TID: typeof TID;
declare const types$1_TIME: typeof TIME;
declare const types$1_TIMESTAMP: typeof TIMESTAMP;
declare const types$1_TIMESTAMPTZ: typeof TIMESTAMPTZ;
declare const types$1_TIMETZ: typeof TIMETZ;
declare const types$1_TINTERVAL: typeof TINTERVAL;
declare const types$1_TSQUERY: typeof TSQUERY;
declare const types$1_TSVECTOR: typeof TSVECTOR;
declare const types$1_TXID_SNAPSHOT: typeof TXID_SNAPSHOT;
type types$1_TypeHandler = TypeHandler;
type types$1_TypeHandlers = TypeHandlers;
declare const types$1_UUID: typeof UUID;
declare const types$1_VARBIT: typeof VARBIT;
declare const types$1_VARCHAR: typeof VARCHAR;
declare const types$1_XID: typeof XID;
declare const types$1_XML: typeof XML;
declare const types$1_arrayParser: typeof arrayParser;
declare const types$1_arraySerializer: typeof arraySerializer;
declare const types$1_parseType: typeof parseType;
declare const types$1_parsers: typeof parsers;
declare const types$1_serializers: typeof serializers;
declare const types$1_types: typeof types;
declare namespace types$1 {
export { types$1_ABSTIME as ABSTIME, types$1_ACLITEM as ACLITEM, types$1_BIT as BIT, types$1_BOOL as BOOL, types$1_BPCHAR as BPCHAR, types$1_BYTEA as BYTEA, types$1_CHAR as CHAR, types$1_CID as CID, types$1_CIDR as CIDR, types$1_CIRCLE as CIRCLE, types$1_DATE as DATE, types$1_FLOAT4 as FLOAT4, types$1_FLOAT8 as FLOAT8, types$1_GTSVECTOR as GTSVECTOR, types$1_INET as INET, types$1_INT2 as INT2, types$1_INT4 as INT4, types$1_INT8 as INT8, types$1_INTERVAL as INTERVAL, types$1_JSON as JSON, types$1_JSONB as JSONB, types$1_MACADDR as MACADDR, types$1_MACADDR8 as MACADDR8, types$1_MONEY as MONEY, types$1_NUMERIC as NUMERIC, types$1_OID as OID, types$1_PATH as PATH, types$1_PG_DEPENDENCIES as PG_DEPENDENCIES, types$1_PG_LSN as PG_LSN, types$1_PG_NDISTINCT as PG_NDISTINCT, types$1_PG_NODE_TREE as PG_NODE_TREE, types$1_POLYGON as POLYGON, type types$1_Parser as Parser, types$1_REFCURSOR as REFCURSOR, types$1_REGCLASS as REGCLASS, types$1_REGCONFIG as REGCONFIG, types$1_REGDICTIONARY as REGDICTIONARY, types$1_REGNAMESPACE as REGNAMESPACE, types$1_REGOPER as REGOPER, types$1_REGOPERATOR as REGOPERATOR, types$1_REGPROC as REGPROC, types$1_REGPROCEDURE as REGPROCEDURE, types$1_REGROLE as REGROLE, types$1_REGTYPE as REGTYPE, types$1_RELTIME as RELTIME, types$1_SMGR as SMGR, type types$1_Serializer as Serializer, types$1_TEXT as TEXT, types$1_TID as TID, types$1_TIME as TIME, types$1_TIMESTAMP as TIMESTAMP, types$1_TIMESTAMPTZ as TIMESTAMPTZ, types$1_TIMETZ as TIMETZ, types$1_TINTERVAL as TINTERVAL, types$1_TSQUERY as TSQUERY, types$1_TSVECTOR as TSVECTOR, types$1_TXID_SNAPSHOT as TXID_SNAPSHOT, type types$1_TypeHandler as TypeHandler, type types$1_TypeHandlers as TypeHandlers, types$1_UUID as UUID, types$1_VARBIT as VARBIT, types$1_VARCHAR as VARCHAR, types$1_XID as XID, types$1_XML as XML, types$1_arrayParser as arrayParser, types$1_arraySerializer as arraySerializer, types$1_parseType as parseType, types$1_parsers as parsers, types$1_serializers as serializers, types$1_types as types };
}
declare abstract class BasePGlite implements Pick<PGliteInterface, 'query' | 'sql' | 'exec' | 'transaction'> {
#private;
serializers: Record<number | string, Serializer>;
parsers: Record<number | string, Parser>;
abstract debug: DebugLevel;
/**
* Execute a postgres wire protocol message
* @param message The postgres wire protocol message to execute
* @returns The result of the query
*/
abstract execProtocol(message: Uint8Array, { syncToFs, onNotice }: ExecProtocolOptions): Promise<ExecProtocolResult>;
/**
* Execute a postgres wire protocol message
* @param message The postgres wire protocol message to execute
* @returns The parsed results of the query
*/
abstract execProtocolStream(message: Uint8Array, { syncToFs, onNotice }: ExecProtocolOptions): Promise<BackendMessage[]>;
/**
* Execute a postgres wire protocol message directly without wrapping the response.
* Only use if `execProtocol()` doesn't suite your needs.
*
* **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,
* transactions, and notification listeners. Only use if you need to bypass these wrappers and
* don't intend to use the above features.
*
* @param message The postgres wire protocol message to execute
* @returns The direct message data response produced by Postgres
*/
abstract execProtocolRaw(message: Uint8Array, { syncToFs }: ExecProtocolOptions): Promise<Uint8Array>;
/**
* Execute a postgres wire protocol message directly without wrapping the response.
* Only use if `execProtocol()` doesn't suite your needs.
*
* **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,
* transactions, and notification listeners. Only use if you need to bypass these wrappers and
* don't intend to use the above features.
*
* @param message The postgres wire protocol message to execute
* @param options.onRawData Callback to receive streaming data
*/
abstract execProtocolRawStream(message: Uint8Array, { syncToFs, onRawData }: ExecProtocolOptionsStream): Promise<void>;
/**
* Sync the database to the filesystem
* @returns Promise that resolves when the database is synced to the filesystem
*/
abstract syncToFs(): Promise<void>;
/**
* Handle a file attached to the current query
* @param file The file to handle
*/
abstract _handleBlob(blob?: File | Blob): Promise<void>;
/**
* Get the written file
*/
abstract _getWrittenBlob(): Promise<File | Blob | undefined>;
/**
* Cleanup the current file
*/
abstract _cleanupBlob(): Promise<void>;
abstract _checkReady(): Promise<void>;
abstract _runExclusiveQuery<T>(fn: () => Promise<T>): Promise<T>;
abstract _runExclusiveTransaction<T>(fn: () => Promise<T>): Promise<T>;
/**
* Listen for notifications on a channel
*/
abstract listen(channel: string, callback: (payload: string) => void, tx?: Transaction): Promise<(tx?: Transaction) => Promise<void>>;
/**
* Initialize the array types
* The oid if the type of an element and the typarray is the oid of the type of the
* array.
* We extract these from the database then create the serializers/parsers for
* each type.
* This should be called at the end of #init() in the implementing class.
*/
_initArrayTypes({ force }?: {
force?: boolean | undefined;
}): Promise<void>;
/**
* Re-syncs the array types from the database
* This is useful if you add a new type to the database and want to use it, otherwise pglite won't recognize it.
*/
refreshArrayTypes(): Promise<void>;
/**
* Execute a single SQL statement
* This uses the "Extended Query" postgres wire protocol message.
* @param query The query to execute
* @param params Optional parameters for the query
* @returns The result of the query
*/
query<T>(query: string, params?: any[], options?: QueryOptions): Promise<Results<T>>;
/**
* Execute a single SQL statement like with {@link PGlite.query}, but with a
* templated statement where template values will be treated as parameters.
*
* You can use helpers from `/template` to further format the query with
* identifiers, raw SQL, and nested statements.
*
* This uses the "Extended Query" postgres wire protocol message.
*
* @param query The query to execute with parameters as template values
* @returns The result of the query
*
* @example
* ```ts
* const results = await db.sql`SELECT * FROM ${identifier`foo`} WHERE id = ${id}`
* ```
*/
sql<T>(sqlStrings: TemplateStringsArray, ...params: any[]): Promise<Results<T>>;
/**
* Execute a SQL query, this can have multiple statements.
* This uses the "Simple Query" postgres wire protocol message.
* @param query The query to execute
* @returns The result of the query
*/
exec(query: string, options?: QueryOptions): Promise<Array<Results>>;
/**
* Describe a query
* @param query The query to describe
* @returns A description of the result types for the query
*/
describeQuery(query: string, options?: QueryOptions): Promise<DescribeQueryResult>;
/**
* Execute a transaction
* @param callback A callback function that takes a transaction object
* @returns The result of the transaction
*/
transaction<T>(callback: (tx: Transaction) => Promise<T>): Promise<T>;
/**
* Run a function exclusively, no other transactions or queries will be allowed
* while the function is running.
* This is useful when working with the execProtocol methods as they are not blocked,
* and do not block the locks used by transactions and queries.
* @param fn The function to run
* @returns The result of the function
*/
runExclusive<T>(fn: () => Promise<T>): Promise<T>;
}
declare class PGlite extends BasePGlite implements PGliteInterface, AsyncDisposable {
#private;
fs?: Filesystem;
protected mod?: PostgresMod;
private readonly POSTGRES_MAIN_LONGJMP;
get ENV(): any;
readonly dataDir?: string;
readonly waitReady: Promise<void>;
readonly debug: DebugLevel;
static readonly paths: {
readonly PG_ROOT: "/pglite";
readonly PGDATA: string;
readonly ICU_DATA_PATH: string;
readonly INITDB_EXE_PATH: string;
readonly POSTGRES_EXE_PATH: string;
};
static readonly DEFAULT_RECV_BUF_SIZE: number;
static readonly MAX_BUFFER_SIZE: number;
externalCommandStreamFd: number | null;
static readonly defaultStartParams: string[];
/**
* Create a new PGlite instance
* @param dataDir The directory to store the database files
* Prefix with idb:// to use indexeddb filesystem in the browser
* Use memory:// to use in-memory filesystem
* @param options PGlite options
*/
constructor(dataDir?: string, options?: PGliteOptions);
/**
* Create a new PGlite instance
* @param options PGlite options including the data directory
*/
constructor(options?: PGliteOptions);
/**
* Create a new PGlite instance with extensions on the Typescript interface
* (The main constructor does enable extensions, however due to the limitations
* of Typescript, the extensions are not available on the instance interface)
* @param options PGlite options including the data directory
* @returns A promise that resolves to the PGlite instance when it's ready.
*/
static create<O extends PGliteOptions>(options?: O): Promise<PGlite & PGliteInterfaceExtensions<O['extensions']>>;
/**
* Create a new PGlite instance with extensions on the Typescript interface
* (The main constructor does enable extensions, however due to the limitations
* of Typescript, the extensions are not available on the instance interface)
* @param dataDir The directory to store the database files
* Prefix with idb:// to use indexeddb filesystem in the browser
* Use memory:// to use in-memory filesystem
* @param options PGlite options
* @returns A promise that resolves to the PGlite instance when it's ready.
*/
static create<O extends PGliteOptions>(dataDir?: string, options?: O): Promise<PGlite & PGliteInterfaceExtensions<O['extensions']>>;
handleExternalCmd(cmd: string, mode: string): number;
/**
* The Postgres Emscripten Module
*/
get Module(): PostgresMod;
/**
* The ready state of the database
*/
get ready(): boolean;
/**
* The closed state of the database
*/
get closed(): boolean;
/**
* Close the database
* @returns A promise that resolves when the database is closed
*/
close(): Promise<void>;
/**
* Close the database when the object exits scope
* Stage 3 ECMAScript Explicit Resource Management
* https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management
*/
[Symbol.asyncDispose](): Promise<void>;
/**
* Handle a file attached to the current query
* @param file The file to handle
*/
_handleBlob(blob?: File | Blob): Promise<void>;
/**
* Cleanup the current file
*/
_cleanupBlob(): Promise<void>;
/**
* Get the written blob from the current query
* @returns The written blob
*/
_getWrittenBlob(): Promise<Blob | undefined>;
/**
* Wait for the database to be ready
*/
_checkReady(): Promise<void>;
/**
* Execute a postgres wire protocol synchronously
* @param message The postgres wire protocol message to execute
* @returns The direct message data response produced by Postgres
*/
execProtocolRawSync(message: Uint8Array): Uint8Array;
/**
* Execute a postgres wire protocol message directly without wrapping the response.
* Only use if `execProtocol()` doesn't suite your needs.
*
* **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,
* transactions, and notification listeners. Only use if you need to bypass these wrappers and
* don't intend to use the above features.
*
* @param message The postgres wire protocol message to execute
* @returns The direct message data response produced by Postgres
*/
execProtocolRaw(message: Uint8Array, { syncToFs }?: ExecProtocolOptions): Promise<Uint8Array>;
/**
* Execute a postgres wire protocol message directly without wrapping the response.
* Only use if `execProtocol()` doesn't suite your needs.
*
* **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,
* transactions, and notification listeners. Only use if you need to bypass these wrappers and
* don't intend to use the above features.
*
* @param message The postgres wire protocol message to execute
* @param options.onRawData Callback to receive results as streaming data
*/
execProtocolRawStream(message: Uint8Array, { syncToFs, onRawData }: ExecProtocolOptionsStream): Promise<void>;
/**
* Execute a postgres wire protocol message
* @param message The postgres wire protocol message to execute
* @returns The result of the query
*/
execProtocol(message: Uint8Array, { syncToFs, throwOnError, onNotice, }?: ExecProtocolOptions): Promise<ExecProtocolResult>;
/**
* Execute a postgres wire protocol message
* @param message The postgres wire protocol message to execute
* @returns The parsed results of the query
*/
execProtocolStream(message: Uint8Array, { syncToFs, throwOnError, onNotice }?: ExecProtocolOptions): Promise<BackendMessage[]>;
/**
* Check if the database is in a transaction
* @returns True if the database is in a transaction, false otherwise
*/
isInTransaction(): boolean;
/**
* Perform any sync operations implemented by the filesystem, this is
* run after every query to ensure that the filesystem is synced.
*/
syncToFs(): Promise<void>;
/**
* Listen for a notification
* @param channel The channel to listen on
* @param callback The callback to call when a notification is received
*/
listen(channel: string, callback: (payload: string) => void, tx?: Transaction): Promise<(tx?: Transaction) => Promise<void>>;
/**
* Stop listening for a notification
* @param channel The channel to stop listening on
* @param callback The callback to remove
*/
unlisten(channel: string, callback?: (payload: string) => void, tx?: Transaction): Promise<void>;
/**
* Listen to notifications
* @param callback The callback to call when a notification is received
*/
onNotification(callback: (channel: string, payload: string) => void): () => void;
/**
* Stop listening to notifications
* @param callback The callback to remove
*/
offNotification(callback: (channel: string, payload: string) => void): void;
/**
* Dump the PGDATA dir from the filesystem to a gzipped tarball.
* @param compression The compression options to use - 'gzip', 'auto', 'none'
* @returns The tarball as a File object where available, and fallback to a Blob
*/
dumpDataDir(compression?: DumpTarCompressionOptions): Promise<File | Blob>;
/**
* Run a function in a mutex that's exclusive to queries
* @param fn The query to run
* @returns The result of the query
*/
_runExclusiveQuery<T>(fn: () => Promise<T>): Promise<T>;
/**
* Run a function in a mutex that's exclusive to transactions
* @param fn The function to run
* @returns The result of the function
*/
_runExclusiveTransaction<T>(fn: () => Promise<T>): Promise<T>;
clone(): Promise<PGliteInterface>;
_runExclusiveListen<T>(fn: () => Promise<T>): Promise<T>;
callMain(args: string[]): number;
copyToFS(filePath: string, data: Uint8Array, mode?: number): void;
}
export { type FsType as A, type BackendMessage as B, type Filesystem as C, type DebugLevel as D, EmscriptenBuiltinFilesystem as E, type FilesystemType as F, ERRNO_CODES as G, type InitializedExtensions as I, type Mode as M, type Parser as P, type QueryOptions as Q, type Results as R, type SerializerOptions as S, type Transaction as T, type BufferParameter as a, PGlite as b, type PostgresMod as c, type PGliteInterface as d, type RowMode as e, type ParserOptions as f, type ExecProtocolOptions as g, type ExecProtocolOptionsStream as h, type ExtensionSetupResult as i, type ExtensionSetup as j, type Extension as k, type ExtensionNamespace as l, messages as m, type Extensions as n, type ExecProtocolResult as o, postgresMod as p, type DumpDataDirResult as q, type PGliteOptions as r, type PGliteInterfaceExtensions as s, types$1 as t, type Row as u, type DescribeQueryResult as v, BaseFilesystem as w, type FsStats as x, BasePGlite as y, type DumpTarCompressionOptions as z };
declare const Modes: {
readonly text: 0;
readonly binary: 1;
};
type Mode = (typeof Modes)[keyof typeof Modes];
type BufferParameter = ArrayBuffer | ArrayBufferView;
type MessageName = 'parseComplete' | 'bindComplete' | 'closeComplete' | 'noData' | 'portalSuspended' | 'replicationStart' | 'emptyQuery' | 'copyDone' | 'copyData' | 'rowDescription' | 'parameterDescription' | 'parameterStatus' | 'backendKeyData' | 'notification' | 'readyForQuery' | 'commandComplete' | 'dataRow' | 'copyInResponse' | 'copyOutResponse' | 'authenticationOk' | 'authenticationMD5Password' | 'authenticationCleartextPassword' | 'authenticationSASL' | 'authenticationSASLContinue' | 'authenticationSASLFinal' | 'error' | 'notice';
type BackendMessage = {
name: MessageName;
length: number;
};
declare const parseComplete: BackendMessage;
declare const bindComplete: BackendMessage;
declare const closeComplete: BackendMessage;
declare const noData: BackendMessage;
declare const portalSuspended: BackendMessage;
declare const replicationStart: BackendMessage;
declare const emptyQuery: BackendMessage;
declare const copyDone: BackendMessage;
declare class AuthenticationOk implements BackendMessage {
readonly length: number;
readonly name = "authenticationOk";
constructor(length: number);
}
declare class AuthenticationCleartextPassword implements BackendMessage {
readonly length: number;
readonly name = "authenticationCleartextPassword";
constructor(length: number);
}
declare class AuthenticationMD5Password implements BackendMessage {
readonly length: number;
readonly salt: Uint8Array;
readonly name = "authenticationMD5Password";
constructor(length: number, salt: Uint8Array);
}
declare class AuthenticationSASL implements BackendMessage {
readonly length: number;
readonly mechanisms: string[];
readonly name = "authenticationSASL";
constructor(length: number, mechanisms: string[]);
}
declare class AuthenticationSASLContinue implements BackendMessage {
readonly length: number;
readonly data: string;
readonly name = "authenticationSASLContinue";
constructor(length: number, data: string);
}
declare class AuthenticationSASLFinal implements BackendMessage {
readonly length: number;
readonly data: string;
readonly name = "authenticationSASLFinal";
constructor(length: number, data: string);
}
type AuthenticationMessage = AuthenticationOk | AuthenticationCleartextPassword | AuthenticationMD5Password | AuthenticationSASL | AuthenticationSASLContinue | AuthenticationSASLFinal;
interface NoticeOrError {
message: string | undefined;
severity: string | undefined;
code: string | undefined;
detail: string | undefined;
hint: string | undefined;
position: string | undefined;
internalPosition: string | undefined;
internalQuery: string | undefined;
where: string | undefined;
schema: string | undefined;
table: string | undefined;
column: string | undefined;
dataType: string | undefined;
constraint: string | undefined;
file: string | undefined;
line: string | undefined;
routine: string | undefined;
}
declare class DatabaseError extends Error implements NoticeOrError {
readonly length: number;
readonly name: MessageName;
severity: string | undefined;
code: string | undefined;
detail: string | undefined;
hint: string | undefined;
position: string | undefined;
internalPosition: string | undefined;
internalQuery: string | undefined;
where: string | undefined;
schema: string | undefined;
table: string | undefined;
column: string | undefined;
dataType: string | undefined;
constraint: string | undefined;
file: string | undefined;
line: string | undefined;
routine: string | undefined;
constructor(message: string, length: number, name: MessageName);
}
declare class CopyDataMessage implements BackendMessage {
readonly length: number;
readonly chunk: Uint8Array;
readonly name = "copyData";
constructor(length: number, chunk: Uint8Array);
}
declare class CopyResponse implements BackendMessage {
readonly length: number;
readonly name: MessageName;
readonly binary: boolean;
readonly columnTypes: number[];
constructor(length: number, name: MessageName, binary: boolean, columnCount: number);
}
declare class Field {
readonly name: string;
readonly tableID: number;
readonly columnID: number;
readonly dataTypeID: number;
readonly dataTypeSize: number;
readonly dataTypeModifier: number;
readonly format: Mode;
constructor(name: string, tableID: number, columnID: number, dataTypeID: number, dataTypeSize: number, dataTypeModifier: number, format: Mode);
}
declare class RowDescriptionMessage implements BackendMessage {
readonly length: number;
readonly fieldCount: number;
readonly name: MessageName;
readonly fields: Field[];
constructor(length: number, fieldCount: number);
}
declare class ParameterDescriptionMessage implements BackendMessage {
readonly length: number;
readonly parameterCount: number;
readonly name: MessageName;
readonly dataTypeIDs: number[];
constructor(length: number, parameterCount: number);
}
declare class ParameterStatusMessage implements BackendMessage {
readonly length: number;
readonly parameterName: string;
readonly parameterValue: string;
readonly name: MessageName;
constructor(length: number, parameterName: string, parameterValue: string);
}
declare class BackendKeyDataMessage implements BackendMessage {
readonly length: number;
readonly processID: number;
readonly secretKey: number;
readonly name: MessageName;
constructor(length: number, processID: number, secretKey: number);
}
declare class NotificationResponseMessage implements BackendMessage {
readonly length: number;
readonly processId: number;
readonly channel: string;
readonly payload: string;
readonly name: MessageName;
constructor(length: number, processId: number, channel: string, payload: string);
}
declare class ReadyForQueryMessage implements BackendMessage {
readonly length: number;
readonly status: string;
readonly name: MessageName;
constructor(length: number, status: string);
}
declare class CommandCompleteMessage implements BackendMessage {
readonly length: number;
readonly text: string;
readonly name: MessageName;
constructor(length: number, text: string);
}
declare class DataRowMessage implements BackendMessage {
length: number;
fields: (string | null)[];
readonly fieldCount: number;
readonly name: MessageName;
constructor(length: number, fields: (string | null)[]);
}
declare class NoticeMessage implements BackendMessage, NoticeOrError {
readonly length: number;
readonly message: string | undefined;
constructor(length: number, message: string | undefined);
readonly name = "notice";
severity: string | undefined;
code: string | undefined;
detail: string | undefined;
hint: string | undefined;
position: string | undefined;
internalPosition: string | undefined;
internalQuery: string | undefined;
where: string | undefined;
schema: string | undefined;
table: string | undefined;
column: string | undefined;
dataType: string | undefined;
constraint: string | undefined;
file: string | undefined;
line: string | undefined;
routine: string | undefined;
}
type messages_AuthenticationCleartextPassword = AuthenticationCleartextPassword;
declare const messages_AuthenticationCleartextPassword: typeof AuthenticationCleartextPassword;
type messages_AuthenticationMD5Password = AuthenticationMD5Password;
declare const messages_AuthenticationMD5Password: typeof AuthenticationMD5Password;
type messages_AuthenticationMessage = AuthenticationMessage;
type messages_AuthenticationOk = AuthenticationOk;
declare const messages_AuthenticationOk: typeof AuthenticationOk;
type messages_AuthenticationSASL = AuthenticationSASL;
declare const messages_AuthenticationSASL: typeof AuthenticationSASL;
type messages_AuthenticationSASLContinue = AuthenticationSASLContinue;
declare const messages_AuthenticationSASLContinue: typeof AuthenticationSASLContinue;
type messages_AuthenticationSASLFinal = AuthenticationSASLFinal;
declare const messages_AuthenticationSASLFinal: typeof AuthenticationSASLFinal;
type messages_BackendKeyDataMessage = BackendKeyDataMessage;
declare const messages_BackendKeyDataMessage: typeof BackendKeyDataMessage;
type messages_BackendMessage = BackendMessage;
type messages_CommandCompleteMessage = CommandCompleteMessage;
declare const messages_CommandCompleteMessage: typeof CommandCompleteMessage;
type messages_CopyDataMessage = CopyDataMessage;
declare const messages_CopyDataMessage: typeof CopyDataMessage;
type messages_CopyResponse = CopyResponse;
declare const messages_CopyResponse: typeof CopyResponse;
type messages_DataRowMessage = DataRowMessage;
declare const messages_DataRowMessage: typeof DataRowMessage;
type messages_DatabaseError = DatabaseError;
declare const messages_DatabaseError: typeof DatabaseError;
type messages_Field = Field;
declare const messages_Field: typeof Field;
type messages_MessageName = MessageName;
type messages_NoticeMessage = NoticeMessage;
declare const messages_NoticeMessage: typeof NoticeMessage;
type messages_NotificationResponseMessage = NotificationResponseMessage;
declare const messages_NotificationResponseMessage: typeof NotificationResponseMessage;
type messages_ParameterDescriptionMessage = ParameterDescriptionMessage;
declare const messages_ParameterDescriptionMessage: typeof ParameterDescriptionMessage;
type messages_ParameterStatusMessage = ParameterStatusMessage;
declare const messages_ParameterStatusMessage: typeof ParameterStatusMessage;
type messages_ReadyForQueryMessage = ReadyForQueryMessage;
declare const messages_ReadyForQueryMessage: typeof ReadyForQueryMessage;
type messages_RowDescriptionMessage = RowDescriptionMessage;
declare const messages_RowDescriptionMessage: typeof RowDescriptionMessage;
declare const messages_bindComplete: typeof bindComplete;
declare const messages_closeComplete: typeof closeComplete;
declare const messages_copyDone: typeof copyDone;
declare const messages_emptyQuery: typeof emptyQuery;
declare const messages_noData: typeof noData;
declare const messages_parseComplete: typeof parseComplete;
declare const messages_portalSuspended: typeof portalSuspended;
declare const messages_replicationStart: typeof replicationStart;
declare namespace messages {
export { messages_AuthenticationCleartextPassword as AuthenticationCleartextPassword, messages_AuthenticationMD5Password as AuthenticationMD5Password, type messages_AuthenticationMessage as AuthenticationMessage, messages_AuthenticationOk as AuthenticationOk, messages_AuthenticationSASL as AuthenticationSASL, messages_AuthenticationSASLContinue as AuthenticationSASLContinue, messages_AuthenticationSASLFinal as AuthenticationSASLFinal, messages_BackendKeyDataMessage as BackendKeyDataMessage, type messages_BackendMessage as BackendMessage, messages_CommandCompleteMessage as CommandCompleteMessage, messages_CopyDataMessage as CopyDataMessage, messages_CopyResponse as CopyResponse, messages_DataRowMessage as DataRowMessage, messages_DatabaseError as DatabaseError, messages_Field as Field, type messages_MessageName as MessageName, messages_NoticeMessage as NoticeMessage, messages_NotificationResponseMessage as NotificationResponseMessage, messages_ParameterDescriptionMessage as ParameterDescriptionMessage, messages_ParameterStatusMessage as ParameterStatusMessage, messages_ReadyForQueryMessage as ReadyForQueryMessage, messages_RowDescriptionMessage as RowDescriptionMessage, messages_bindComplete as bindComplete, messages_closeComplete as closeComplete, messages_copyDone as copyDone, messages_emptyQuery as emptyQuery, messages_noData as noData, messages_parseComplete as parseComplete, messages_portalSuspended as portalSuspended, messages_replicationStart as replicationStart };
}
type IDBFS = Emscripten.FileSystemType & {
quit: () => void;
dbs: Record<string, IDBDatabase>;
};
type FS = typeof FS & {
filesystems: {
MEMFS: Emscripten.FileSystemType;
NODEFS: Emscripten.FileSystemType;
IDBFS: IDBFS;
};
quit: () => void;
};
interface PostgresMod extends Omit<EmscriptenModule, 'preInit' | 'preRun' | 'postRun'> {
preInit: Array<{
(mod: PostgresMod): void;
}>;
preRun: Array<{
(mod: PostgresMod): void;
}>;
postRun: Array<{
(mod: PostgresMod): void;
}>;
thisProgram: string;
stdin: (() => number | null) | null;
FS: FS;
wasmMemory: WebAssembly.Memory;
PROXYFS: Emscripten.FileSystemType;
WASM_PREFIX: string;
pg_extensions: Record<string, Promise<Blob | null>>;
UTF8ToString: (ptr: number, maxBytesToRead?: number) => string;
stringToUTF8OnStack: (s: string) => number;
_pgl_set_system_fn: (system_fn: number) => void;
_pgl_set_popen_fn: (popen_fn: number) => void;
_pgl_set_pclose_fn: (pclose_fn: number) => void;
_pgl_set_rw_cbs: (read_cb: number, write_cb: number) => void;
_pgl_set_pipe_fn: (pipe_fn: number) => number;
_pgl_freopen: (filepath: number, mode: number, stream: number) => number;
_pgl_pq_flush: () => void;
_fopen: (path: number, mode: number) => number;
_fclose: (stream: number) => number;
_fflush: (stream: number) => void;
_pgl_proc_exit: (code: number) => number;
addFunction: (cb: (ptr: any, length: number) => void, signature: string) => number;
removeFunction: (f: number) => void;
callMain: (args?: string[]) => number;
_PostgresMainLoopOnce: () => void;
_PostgresMainLongJmp: () => void;
_PostgresSendReadyForQueryIfNecessary: () => void;
_ProcessStartupPacket: (Port: number, ssl_done: boolean, gss_done: boolean) => number;
_IsTransactionBlock: () => number;
_pgl_setPGliteActive: (newValue: number) => number;
_pgl_startPGlite: () => void;
_pgl_getMyProcPort: () => number;
_pgl_sendConnData: () => void;
ENV: any;
PGLITE_ENV: any;
_emscripten_force_exit: (status: number) => void;
_pgl_run_atexit_funcs: () => void;
_pq_buffer_remaining_data: () => number;
}
type PostgresFactory<T extends PostgresMod = PostgresMod> = (moduleOverrides?: Partial<T>) => Promise<T>;
declare const _default: PostgresFactory<PostgresMod>;
type postgresMod_FS = FS;
type postgresMod_PostgresMod = PostgresMod;
declare namespace postgresMod {
export { type postgresMod_FS as FS, type postgresMod_PostgresMod as PostgresMod, _default as default };
}
type DumpTarCompressionOptions = 'none' | 'gzip' | 'auto';
type FsType = 'nodefs' | 'idbfs' | 'memoryfs' | 'opfs-ahp';
/**
* Filesystem interface.
* All virtual filesystems that are compatible with PGlite must implement
* this interface.
*/
interface Filesystem {
/**
* Initiate the filesystem and return the options to pass to the emscripten module.
*/
init(pg: PGlite, emscriptenOptions: Partial<PostgresMod>): Promise<{
emscriptenOpts: Partial<PostgresMod>;
}>;
/**
* Sync the filesystem to any underlying storage.
*/
syncToFs(relaxedDurability?: boolean): Promise<void>;
/**
* Sync the filesystem from any underlying storage.
*/
initialSyncFs(): Promise<void>;
/**
* Dump the PGDATA dir from the filesystem to a gzipped tarball.
*/
dumpTar(dbname: string, compression?: DumpTarCompressionOptions): Promise<File | Blob>;
/**
* Close the filesystem.
*/
closeFs(): Promise<void>;
}
/**
* Base class for all emscripten built-in filesystems.
*/
declare class EmscriptenBuiltinFilesystem implements Filesystem {
protected dataDir?: string;
protected pg?: PGlite;
constructor(dataDir?: string);
init(pg: PGlite, emscriptenOptions: Partial<PostgresMod>): Promise<{
emscriptenOpts: Partial<PostgresMod>;
}>;
syncToFs(_relaxedDurability?: boolean): Promise<void>;
initialSyncFs(): Promise<void>;
closeFs(): Promise<void>;
dumpTar(dbname: string, compression?: DumpTarCompressionOptions): Promise<Blob | File>;
}
/**
* Abstract base class for all custom virtual filesystems.
* Each custom filesystem needs to implement an interface similar to the NodeJS FS API.
*/
declare abstract class BaseFilesystem implements Filesystem {
protected dataDir?: string;
protected pg?: PGlite;
readonly debug: boolean;
constructor(dataDir?: string, { debug }?: {
debug?: boolean;
});
syncToFs(_relaxedDurability?: boolean): Promise<void>;
initialSyncFs(): Promise<void>;
closeFs(): Promise<void>;
dumpTar(dbname: string, compression?: DumpTarCompressionOptions): Promise<Blob | File>;
init(pg: PGlite, emscriptenOptions: Partial<PostgresMod>): Promise<{
emscriptenOpts: Partial<PostgresMod>;
}>;
abstract chmod(path: string, mode: number): void;
abstract close(fd: number): void;
abstract fstat(fd: number): FsStats;
abstract lstat(path: string): FsStats;
abstract mkdir(path: string, options?: {
recursive?: boolean;
mode?: number;
}): void;
abstract open(path: string, flags?: string, mode?: number): number;
abstract readdir(path: string): string[];
abstract read(fd: number, buffer: Uint8Array, // Buffer to read into
offset: number, // Offset in buffer to start writing to
length: number, // Number of bytes to read
position: number): number;
abstract rename(oldPath: string, newPath: string): void;
abstract rmdir(path: string): void;
abstract truncate(path: string, len: number): void;
abstract unlink(path: string): void;
abstract utimes(path: string, atime: number, mtime: number): void;
abstract writeFile(path: string, data: string | Uint8Array, options?: {
encoding?: string;
mode?: number;
flag?: string;
}): void;
abstract write(fd: number, buffer: Uint8Array, // Buffer to read from
offset: number, // Offset in buffer to start reading from
length: number, // Number of bytes to write
position: number): number;
}
type FsStats = {
dev: number;
ino: number;
mode: number;
nlink: number;
uid: number;
gid: number;
rdev: number;
size: number;
blksize: number;
blocks: number;
atime: number;
mtime: number;
ctime: number;
};
declare const ERRNO_CODES: {
readonly EBADF: 8;
readonly EBADFD: 127;
readonly EEXIST: 20;
readonly EINVAL: 28;
readonly EISDIR: 31;
readonly ENODEV: 43;
readonly ENOENT: 44;
readonly ENOTDIR: 54;
readonly ENOTEMPTY: 55;
};
type FilesystemType = 'nodefs' | 'idbfs' | 'memoryfs';
type DebugLevel = 0 | 1 | 2 | 3 | 4 | 5;
type RowMode = 'array' | 'object';
interface ParserOptions {
[pgType: number]: (value: string) => any;
}
interface SerializerOptions {
[pgType: number]: (value: any) => string;
}
interface QueryOptions {
rowMode?: RowMode;
parsers?: ParserOptions;
serializers?: SerializerOptions;
blob?: Blob | File;
onNotice?: (notice: NoticeMessage) => void;
paramTypes?: number[];
}
interface ExecProtocolOptions {
syncToFs?: boolean;
throwOnError?: boolean;
onNotice?: (notice: NoticeMessage) => void;
}
interface ExecProtocolOptionsStream {
syncToFs?: boolean;
onRawData: (data: Uint8Array) => void;
}
interface ExtensionSetupResult<TNamespace = any> {
emscriptenOpts?: any;
namespaceObj?: TNamespace;
bundlePath?: URL;
sharedPreloadLibraries?: string[];
init?: () => Promise<void>;
close?: () => Promise<void>;
}
type ExtensionSetup<TNamespace = any> = (pg: PGliteInterface, emscriptenOpts: any, clientOnly?: boolean) => Promise<ExtensionSetupResult<TNamespace>>;
interface Extension<TNamespace = any> {
name: string;
setup: ExtensionSetup<TNamespace>;
}
type ExtensionNamespace<T> = T extends Extension<infer TNamespace> ? TNamespace : any;
type Extensions = {
[namespace: string]: Extension | URL;
};
type InitializedExtensions<TExtensions extends Extensions = Extensions> = {
[K in keyof TExtensions]: ExtensionNamespace<TExtensions[K]>;
};
interface ExecProtocolResult {
messages: BackendMessage[];
data: Uint8Array;
}
interface DumpDataDirResult {
tarball: Uint8Array;
extension: '.tar' | '.tgz';
filename: string;
}
interface PGliteOptions<TExtensions extends Extensions = Extensions> {
noInitDb?: boolean;
dataDir?: string;
username?: string;
database?: string;
fs?: Filesystem;
debug?: DebugLevel;
relaxedDurability?: boolean;
extensions?: TExtensions;
loadDataDir?: Blob | File;
icuDataDir?: Blob | File;
initialMemory?: number;
pgliteWasmModule?: WebAssembly.Module;
initdbWasmModule?: WebAssembly.Module;
fsBundle?: Blob | File;
parsers?: ParserOptions;
serializers?: SerializerOptions;
startParams?: string[];
initDbStartParams?: string[];
postgresqlconf?: string[] | string;
}
type PGliteInterface<T extends Extensions = Extensions> = InitializedExtensions<T> & {
readonly waitReady: Promise<void>;
readonly debug: DebugLevel;
readonly ready: boolean;
readonly closed: boolean;
close(): Promise<void>;
query<T>(query: string, params?: any[], options?: QueryOptions): Promise<Results<T>>;
sql<T>(sqlStrings: TemplateStringsArray, ...params: any[]): Promise<Results<T>>;
exec(query: string, options?: QueryOptions): Promise<Array<Results>>;
describeQuery(query: string): Promise<DescribeQueryResult>;
transaction<T>(callback: (tx: Transaction) => Promise<T>): Promise<T>;
execProtocolRaw(message: Uint8Array, options?: ExecProtocolOptions): Promise<Uint8Array>;
execProtocolRawStream(message: Uint8Array, options?: ExecProtocolOptionsStream): Promise<void>;
execProtocol(message: Uint8Array, options?: ExecProtocolOptions): Promise<ExecProtocolResult>;
runExclusive<T>(fn: () => Promise<T>): Promise<T>;
listen(channel: string, callback: (payload: string) => void, tx?: Transaction): Promise<(tx?: Transaction) => Promise<void>>;
unlisten(channel: string, callback?: (payload: string) => void, tx?: Transaction): Promise<void>;
onNotification(callback: (channel: string, payload: string) => void): () => void;
offNotification(callback: (channel: string, payload: string) => void): void;
dumpDataDir(compression?: DumpTarCompressionOptions): Promise<File | Blob>;
refreshArrayTypes(): Promise<void>;
};
type PGliteInterfaceExtensions<E> = E extends Extensions ? {
[K in keyof E]: E[K] extends Extension ? Awaited<ReturnType<E[K]['setup']>>['namespaceObj'] extends infer N ? N extends undefined | null | void ? never : N : never : never;
} : Record<string, never>;
type Row<T = {
[key: string]: any;
}> = T;
type Results<T = {
[key: string]: any;
}> = {
rows: Row<T>[];
affectedRows?: number;
/**
* The command of the query that was run, e.g. "SELECT", "INSERT", "CREATE".
*/
command?: string;
/**
* The number of rows reported by the command tag, e.g. the rows returned
* by a SELECT or changed by an UPDATE. Unlike `affectedRows` this is per statement
* and not cumulative across a multi-statement query.
*/
rowCount?: number;
fields: {
name: string;
dataTypeID: number;
}[];
blob?: Blob;
};
interface Transaction {
query<T>(query: string, params?: any[], options?: QueryOptions): Promise<Results<T>>;
sql<T>(sqlStrings: TemplateStringsArray, ...params: any[]): Promise<Results<T>>;
exec(query: string, options?: QueryOptions): Promise<Array<Results>>;
rollback(): Promise<void>;
listen(channel: string, callback: (payload: string) => void): Promise<(tx?: Transaction) => Promise<void>>;
get closed(): boolean;
}
type DescribeQueryResult = {
queryParams: {
dataTypeID: number;
serializer: Serializer;
}[];
resultFields: {
name: string;
dataTypeID: number;
parser: Parser;
}[];
};
declare const BOOL = 16;
declare const BYTEA = 17;
declare const CHAR = 18;
declare const INT8 = 20;
declare const INT2 = 21;
declare const INT4 = 23;
declare const REGPROC = 24;
declare const TEXT = 25;
declare const OID = 26;
declare const TID = 27;
declare const XID = 28;
declare const CID = 29;
declare const JSON = 114;
declare const XML = 142;
declare const PG_NODE_TREE = 194;
declare const SMGR = 210;
declare const PATH = 602;
declare const POLYGON = 604;
declare const CIDR = 650;
declare const FLOAT4 = 700;
declare const FLOAT8 = 701;
declare const ABSTIME = 702;
declare const RELTIME = 703;
declare const TINTERVAL = 704;
declare const CIRCLE = 718;
declare const MACADDR8 = 774;
declare const MONEY = 790;
declare const MACADDR = 829;
declare const INET = 869;
declare const ACLITEM = 1033;
declare const BPCHAR = 1042;
declare const VARCHAR = 1043;
declare const DATE = 1082;
declare const TIME = 1083;
declare const TIMESTAMP = 1114;
declare const TIMESTAMPTZ = 1184;
declare const INTERVAL = 1186;
declare const TIMETZ = 1266;
declare const BIT = 1560;
declare const VARBIT = 1562;
declare const NUMERIC = 1700;
declare const REFCURSOR = 1790;
declare const REGPROCEDURE = 2202;
declare const REGOPER = 2203;
declare const REGOPERATOR = 2204;
declare const REGCLASS = 2205;
declare const REGTYPE = 2206;
declare const UUID = 2950;
declare const TXID_SNAPSHOT = 2970;
declare const PG_LSN = 3220;
declare const PG_NDISTINCT = 3361;
declare const PG_DEPENDENCIES = 3402;
declare const TSVECTOR = 3614;
declare const TSQUERY = 3615;
declare const GTSVECTOR = 3642;
declare const REGCONFIG = 3734;
declare const REGDICTIONARY = 3769;
declare const JSONB = 3802;
declare const REGNAMESPACE = 4089;
declare const REGROLE = 4096;
declare const types: {
string: {
to: number;
from: number[];
serialize: (x: string | number | Date) => string;
parse: (x: string) => string;
};
number: {
to: number;
from: number[];
serialize: (x: number) => string;
parse: (x: string) => number;
};
bigint: {
to: number;
from: number[];
serialize: (x: bigint) => string;
parse: (x: string) => number | bigint;
};
json: {
to: number;
from: number[];
serialize: (x: any) => string;
parse: (x: string) => any;
};
boolean: {
to: number;
from: number[];
serialize: (x: boolean | number | string) => "t" | "f";
parse: (x: string) => x is "t";
};
date: {
to: number;
from: number[];
serialize: (x: Date | string | number) => string;
parse: (x: string | number) => Date;
};
bytea: {
to: number;
from: number[];
serialize: (x: Uint8Array) => string;
parse: (x: string) => Uint8Array;
};
};
type Parser = (x: string, typeId?: number) => any;
type Serializer = (x: any) => string;
type TypeHandler = {
to: number;
from: number | number[];
serialize: Serializer;
parse: Parser;
};
type TypeHandlers = {
[key: string]: TypeHandler;
};
declare const parsers: {
[key: string]: (x: string, typeId?: number) => any;
[key: number]: (x: string, typeId?: number) => any;
};
declare const serializers: {
[key: string]: Serializer;
[key: number]: Serializer;
};
declare function parseType(x: string | null, type: number, parsers?: ParserOptions): any;
declare function arraySerializer(xs: any, serializer: Serializer | undefined, typarray: number): string;
declare function arrayParser(x: string, parser: Parser, typarray: number): any;
declare const types$1_ABSTIME: typeof ABSTIME;
declare const types$1_ACLITEM: typeof ACLITEM;
declare const types$1_BIT: typeof BIT;
declare const types$1_BOOL: typeof BOOL;
declare const types$1_BPCHAR: typeof BPCHAR;
declare const types$1_BYTEA: typeof BYTEA;
declare const types$1_CHAR: typeof CHAR;
declare const types$1_CID: typeof CID;
declare const types$1_CIDR: typeof CIDR;
declare const types$1_CIRCLE: typeof CIRCLE;
declare const types$1_DATE: typeof DATE;
declare const types$1_FLOAT4: typeof FLOAT4;
declare const types$1_FLOAT8: typeof FLOAT8;
declare const types$1_GTSVECTOR: typeof GTSVECTOR;
declare const types$1_INET: typeof INET;
declare const types$1_INT2: typeof INT2;
declare const types$1_INT4: typeof INT4;
declare const types$1_INT8: typeof INT8;
declare const types$1_INTERVAL: typeof INTERVAL;
declare const types$1_JSON: typeof JSON;
declare const types$1_JSONB: typeof JSONB;
declare const types$1_MACADDR: typeof MACADDR;
declare const types$1_MACADDR8: typeof MACADDR8;
declare const types$1_MONEY: typeof MONEY;
declare const types$1_NUMERIC: typeof NUMERIC;
declare const types$1_OID: typeof OID;
declare const types$1_PATH: typeof PATH;
declare const types$1_PG_DEPENDENCIES: typeof PG_DEPENDENCIES;
declare const types$1_PG_LSN: typeof PG_LSN;
declare const types$1_PG_NDISTINCT: typeof PG_NDISTINCT;
declare const types$1_PG_NODE_TREE: typeof PG_NODE_TREE;
declare const types$1_POLYGON: typeof POLYGON;
type types$1_Parser = Parser;
declare const types$1_REFCURSOR: typeof REFCURSOR;
declare const types$1_REGCLASS: typeof REGCLASS;
declare const types$1_REGCONFIG: typeof REGCONFIG;
declare const types$1_REGDICTIONARY: typeof REGDICTIONARY;
declare const types$1_REGNAMESPACE: typeof REGNAMESPACE;
declare const types$1_REGOPER: typeof REGOPER;
declare const types$1_REGOPERATOR: typeof REGOPERATOR;
declare const types$1_REGPROC: typeof REGPROC;
declare const types$1_REGPROCEDURE: typeof REGPROCEDURE;
declare const types$1_REGROLE: typeof REGROLE;
declare const types$1_REGTYPE: typeof REGTYPE;
declare const types$1_RELTIME: typeof RELTIME;
declare const types$1_SMGR: typeof SMGR;
type types$1_Serializer = Serializer;
declare const types$1_TEXT: typeof TEXT;
declare const types$1_TID: typeof TID;
declare const types$1_TIME: typeof TIME;
declare const types$1_TIMESTAMP: typeof TIMESTAMP;
declare const types$1_TIMESTAMPTZ: typeof TIMESTAMPTZ;
declare const types$1_TIMETZ: typeof TIMETZ;
declare const types$1_TINTERVAL: typeof TINTERVAL;
declare const types$1_TSQUERY: typeof TSQUERY;
declare const types$1_TSVECTOR: typeof TSVECTOR;
declare const types$1_TXID_SNAPSHOT: typeof TXID_SNAPSHOT;
type types$1_TypeHandler = TypeHandler;
type types$1_TypeHandlers = TypeHandlers;
declare const types$1_UUID: typeof UUID;
declare const types$1_VARBIT: typeof VARBIT;
declare const types$1_VARCHAR: typeof VARCHAR;
declare const types$1_XID: typeof XID;
declare const types$1_XML: typeof XML;
declare const types$1_arrayParser: typeof arrayParser;
declare const types$1_arraySerializer: typeof arraySerializer;
declare const types$1_parseType: typeof parseType;
declare const types$1_parsers: typeof parsers;
declare const types$1_serializers: typeof serializers;
declare const types$1_types: typeof types;
declare namespace types$1 {
export { types$1_ABSTIME as ABSTIME, types$1_ACLITEM as ACLITEM, types$1_BIT as BIT, types$1_BOOL as BOOL, types$1_BPCHAR as BPCHAR, types$1_BYTEA as BYTEA, types$1_CHAR as CHAR, types$1_CID as CID, types$1_CIDR as CIDR, types$1_CIRCLE as CIRCLE, types$1_DATE as DATE, types$1_FLOAT4 as FLOAT4, types$1_FLOAT8 as FLOAT8, types$1_GTSVECTOR as GTSVECTOR, types$1_INET as INET, types$1_INT2 as INT2, types$1_INT4 as INT4, types$1_INT8 as INT8, types$1_INTERVAL as INTERVAL, types$1_JSON as JSON, types$1_JSONB as JSONB, types$1_MACADDR as MACADDR, types$1_MACADDR8 as MACADDR8, types$1_MONEY as MONEY, types$1_NUMERIC as NUMERIC, types$1_OID as OID, types$1_PATH as PATH, types$1_PG_DEPENDENCIES as PG_DEPENDENCIES, types$1_PG_LSN as PG_LSN, types$1_PG_NDISTINCT as PG_NDISTINCT, types$1_PG_NODE_TREE as PG_NODE_TREE, types$1_POLYGON as POLYGON, type types$1_Parser as Parser, types$1_REFCURSOR as REFCURSOR, types$1_REGCLASS as REGCLASS, types$1_REGCONFIG as REGCONFIG, types$1_REGDICTIONARY as REGDICTIONARY, types$1_REGNAMESPACE as REGNAMESPACE, types$1_REGOPER as REGOPER, types$1_REGOPERATOR as REGOPERATOR, types$1_REGPROC as REGPROC, types$1_REGPROCEDURE as REGPROCEDURE, types$1_REGROLE as REGROLE, types$1_REGTYPE as REGTYPE, types$1_RELTIME as RELTIME, types$1_SMGR as SMGR, type types$1_Serializer as Serializer, types$1_TEXT as TEXT, types$1_TID as TID, types$1_TIME as TIME, types$1_TIMESTAMP as TIMESTAMP, types$1_TIMESTAMPTZ as TIMESTAMPTZ, types$1_TIMETZ as TIMETZ, types$1_TINTERVAL as TINTERVAL, types$1_TSQUERY as TSQUERY, types$1_TSVECTOR as TSVECTOR, types$1_TXID_SNAPSHOT as TXID_SNAPSHOT, type types$1_TypeHandler as TypeHandler, type types$1_TypeHandlers as TypeHandlers, types$1_UUID as UUID, types$1_VARBIT as VARBIT, types$1_VARCHAR as VARCHAR, types$1_XID as XID, types$1_XML as XML, types$1_arrayParser as arrayParser, types$1_arraySerializer as arraySerializer, types$1_parseType as parseType, types$1_parsers as parsers, types$1_serializers as serializers, types$1_types as types };
}
declare abstract class BasePGlite implements Pick<PGliteInterface, 'query' | 'sql' | 'exec' | 'transaction'> {
#private;
serializers: Record<number | string, Serializer>;
parsers: Record<number | string, Parser>;
abstract debug: DebugLevel;
/**
* Execute a postgres wire protocol message
* @param message The postgres wire protocol message to execute
* @returns The result of the query
*/
abstract execProtocol(message: Uint8Array, { syncToFs, onNotice }: ExecProtocolOptions): Promise<ExecProtocolResult>;
/**
* Execute a postgres wire protocol message
* @param message The postgres wire protocol message to execute
* @returns The parsed results of the query
*/
abstract execProtocolStream(message: Uint8Array, { syncToFs, onNotice }: ExecProtocolOptions): Promise<BackendMessage[]>;
/**
* Execute a postgres wire protocol message directly without wrapping the response.
* Only use if `execProtocol()` doesn't suite your needs.
*
* **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,
* transactions, and notification listeners. Only use if you need to bypass these wrappers and
* don't intend to use the above features.
*
* @param message The postgres wire protocol message to execute
* @returns The direct message data response produced by Postgres
*/
abstract execProtocolRaw(message: Uint8Array, { syncToFs }: ExecProtocolOptions): Promise<Uint8Array>;
/**
* Execute a postgres wire protocol message directly without wrapping the response.
* Only use if `execProtocol()` doesn't suite your needs.
*
* **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,
* transactions, and notification listeners. Only use if you need to bypass these wrappers and
* don't intend to use the above features.
*
* @param message The postgres wire protocol message to execute
* @param options.onRawData Callback to receive streaming data
*/
abstract execProtocolRawStream(message: Uint8Array, { syncToFs, onRawData }: ExecProtocolOptionsStream): Promise<void>;
/**
* Sync the database to the filesystem
* @returns Promise that resolves when the database is synced to the filesystem
*/
abstract syncToFs(): Promise<void>;
/**
* Handle a file attached to the current query
* @param file The file to handle
*/
abstract _handleBlob(blob?: File | Blob): Promise<void>;
/**
* Get the written file
*/
abstract _getWrittenBlob(): Promise<File | Blob | undefined>;
/**
* Cleanup the current file
*/
abstract _cleanupBlob(): Promise<void>;
abstract _checkReady(): Promise<void>;
abstract _runExclusiveQuery<T>(fn: () => Promise<T>): Promise<T>;
abstract _runExclusiveTransaction<T>(fn: () => Promise<T>): Promise<T>;
/**
* Listen for notifications on a channel
*/
abstract listen(channel: string, callback: (payload: string) => void, tx?: Transaction): Promise<(tx?: Transaction) => Promise<void>>;
/**
* Initialize the array types
* The oid if the type of an element and the typarray is the oid of the type of the
* array.
* We extract these from the database then create the serializers/parsers for
* each type.
* This should be called at the end of #init() in the implementing class.
*/
_initArrayTypes({ force }?: {
force?: boolean | undefined;
}): Promise<void>;
/**
* Re-syncs the array types from the database
* This is useful if you add a new type to the database and want to use it, otherwise pglite won't recognize it.
*/
refreshArrayTypes(): Promise<void>;
/**
* Execute a single SQL statement
* This uses the "Extended Query" postgres wire protocol message.
* @param query The query to execute
* @param params Optional parameters for the query
* @returns The result of the query
*/
query<T>(query: string, params?: any[], options?: QueryOptions): Promise<Results<T>>;
/**
* Execute a single SQL statement like with {@link PGlite.query}, but with a
* templated statement where template values will be treated as parameters.
*
* You can use helpers from `/template` to further format the query with
* identifiers, raw SQL, and nested statements.
*
* This uses the "Extended Query" postgres wire protocol message.
*
* @param query The query to execute with parameters as template values
* @returns The result of the query
*
* @example
* ```ts
* const results = await db.sql`SELECT * FROM ${identifier`foo`} WHERE id = ${id}`
* ```
*/
sql<T>(sqlStrings: TemplateStringsArray, ...params: any[]): Promise<Results<T>>;
/**
* Execute a SQL query, this can have multiple statements.
* This uses the "Simple Query" postgres wire protocol message.
* @param query The query to execute
* @returns The result of the query
*/
exec(query: string, options?: QueryOptions): Promise<Array<Results>>;
/**
* Describe a query
* @param query The query to describe
* @returns A description of the result types for the query
*/
describeQuery(query: string, options?: QueryOptions): Promise<DescribeQueryResult>;
/**
* Execute a transaction
* @param callback A callback function that takes a transaction object
* @returns The result of the transaction
*/
transaction<T>(callback: (tx: Transaction) => Promise<T>): Promise<T>;
/**
* Run a function exclusively, no other transactions or queries will be allowed
* while the function is running.
* This is useful when working with the execProtocol methods as they are not blocked,
* and do not block the locks used by transactions and queries.
* @param fn The function to run
* @returns The result of the function
*/
runExclusive<T>(fn: () => Promise<T>): Promise<T>;
}
declare class PGlite extends BasePGlite implements PGliteInterface, AsyncDisposable {
#private;
fs?: Filesystem;
protected mod?: PostgresMod;
private readonly POSTGRES_MAIN_LONGJMP;
get ENV(): any;
readonly dataDir?: string;
readonly waitReady: Promise<void>;
readonly debug: DebugLevel;
static readonly paths: {
readonly PG_ROOT: "/pglite";
readonly PGDATA: string;
readonly ICU_DATA_PATH: string;
readonly INITDB_EXE_PATH: string;
readonly POSTGRES_EXE_PATH: string;
};
static readonly DEFAULT_RECV_BUF_SIZE: number;
static readonly MAX_BUFFER_SIZE: number;
externalCommandStreamFd: number | null;
static readonly defaultStartParams: string[];
/**
* Create a new PGlite instance
* @param dataDir The directory to store the database files
* Prefix with idb:// to use indexeddb filesystem in the browser
* Use memory:// to use in-memory filesystem
* @param options PGlite options
*/
constructor(dataDir?: string, options?: PGliteOptions);
/**
* Create a new PGlite instance
* @param options PGlite options including the data directory
*/
constructor(options?: PGliteOptions);
/**
* Create a new PGlite instance with extensions on the Typescript interface
* (The main constructor does enable extensions, however due to the limitations
* of Typescript, the extensions are not available on the instance interface)
* @param options PGlite options including the data directory
* @returns A promise that resolves to the PGlite instance when it's ready.
*/
static create<O extends PGliteOptions>(options?: O): Promise<PGlite & PGliteInterfaceExtensions<O['extensions']>>;
/**
* Create a new PGlite instance with extensions on the Typescript interface
* (The main constructor does enable extensions, however due to the limitations
* of Typescript, the extensions are not available on the instance interface)
* @param dataDir The directory to store the database files
* Prefix with idb:// to use indexeddb filesystem in the browser
* Use memory:// to use in-memory filesystem
* @param options PGlite options
* @returns A promise that resolves to the PGlite instance when it's ready.
*/
static create<O extends PGliteOptions>(dataDir?: string, options?: O): Promise<PGlite & PGliteInterfaceExtensions<O['extensions']>>;
handleExternalCmd(cmd: string, mode: string): number;
/**
* The Postgres Emscripten Module
*/
get Module(): PostgresMod;
/**
* The ready state of the database
*/
get ready(): boolean;
/**
* The closed state of the database
*/
get closed(): boolean;
/**
* Close the database
* @returns A promise that resolves when the database is closed
*/
close(): Promise<void>;
/**
* Close the database when the object exits scope
* Stage 3 ECMAScript Explicit Resource Management
* https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management
*/
[Symbol.asyncDispose](): Promise<void>;
/**
* Handle a file attached to the current query
* @param file The file to handle
*/
_handleBlob(blob?: File | Blob): Promise<void>;
/**
* Cleanup the current file
*/
_cleanupBlob(): Promise<void>;
/**
* Get the written blob from the current query
* @returns The written blob
*/
_getWrittenBlob(): Promise<Blob | undefined>;
/**
* Wait for the database to be ready
*/
_checkReady(): Promise<void>;
/**
* Execute a postgres wire protocol synchronously
* @param message The postgres wire protocol message to execute
* @returns The direct message data response produced by Postgres
*/
execProtocolRawSync(message: Uint8Array): Uint8Array;
/**
* Execute a postgres wire protocol message directly without wrapping the response.
* Only use if `execProtocol()` doesn't suite your needs.
*
* **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,
* transactions, and notification listeners. Only use if you need to bypass these wrappers and
* don't intend to use the above features.
*
* @param message The postgres wire protocol message to execute
* @returns The direct message data response produced by Postgres
*/
execProtocolRaw(message: Uint8Array, { syncToFs }?: ExecProtocolOptions): Promise<Uint8Array>;
/**
* Execute a postgres wire protocol message directly without wrapping the response.
* Only use if `execProtocol()` doesn't suite your needs.
*
* **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,
* transactions, and notification listeners. Only use if you need to bypass these wrappers and
* don't intend to use the above features.
*
* @param message The postgres wire protocol message to execute
* @param options.onRawData Callback to receive results as streaming data
*/
execProtocolRawStream(message: Uint8Array, { syncToFs, onRawData }: ExecProtocolOptionsStream): Promise<void>;
/**
* Execute a postgres wire protocol message
* @param message The postgres wire protocol message to execute
* @returns The result of the query
*/
execProtocol(message: Uint8Array, { syncToFs, throwOnError, onNotice, }?: ExecProtocolOptions): Promise<ExecProtocolResult>;
/**
* Execute a postgres wire protocol message
* @param message The postgres wire protocol message to execute
* @returns The parsed results of the query
*/
execProtocolStream(message: Uint8Array, { syncToFs, throwOnError, onNotice }?: ExecProtocolOptions): Promise<BackendMessage[]>;
/**
* Check if the database is in a transaction
* @returns True if the database is in a transaction, false otherwise
*/
isInTransaction(): boolean;
/**
* Perform any sync operations implemented by the filesystem, this is
* run after every query to ensure that the filesystem is synced.
*/
syncToFs(): Promise<void>;
/**
* Listen for a notification
* @param channel The channel to listen on
* @param callback The callback to call when a notification is received
*/
listen(channel: string, callback: (payload: string) => void, tx?: Transaction): Promise<(tx?: Transaction) => Promise<void>>;
/**
* Stop listening for a notification
* @param channel The channel to stop listening on
* @param callback The callback to remove
*/
unlisten(channel: string, callback?: (payload: string) => void, tx?: Transaction): Promise<void>;
/**
* Listen to notifications
* @param callback The callback to call when a notification is received
*/
onNotification(callback: (channel: string, payload: string) => void): () => void;
/**
* Stop listening to notifications
* @param callback The callback to remove
*/
offNotification(callback: (channel: string, payload: string) => void): void;
/**
* Dump the PGDATA dir from the filesystem to a gzipped tarball.
* @param compression The compression options to use - 'gzip', 'auto', 'none'
* @returns The tarball as a File object where available, and fallback to a Blob
*/
dumpDataDir(compression?: DumpTarCompressionOptions): Promise<File | Blob>;
/**
* Run a function in a mutex that's exclusive to queries
* @param fn The query to run
* @returns The result of the query
*/
_runExclusiveQuery<T>(fn: () => Promise<T>): Promise<T>;
/**
* Run a function in a mutex that's exclusive to transactions
* @param fn The function to run
* @returns The result of the function
*/
_runExclusiveTransaction<T>(fn: () => Promise<T>): Promise<T>;
clone(): Promise<PGliteInterface>;
_runExclusiveListen<T>(fn: () => Promise<T>): Promise<T>;
callMain(args: string[]): number;
copyToFS(filePath: string, data: Uint8Array, mode?: number): void;
}
export { type FsType as A, type BackendMessage as B, type Filesystem as C, type DebugLevel as D, EmscriptenBuiltinFilesystem as E, type FilesystemType as F, ERRNO_CODES as G, type InitializedExtensions as I, type Mode as M, type Parser as P, type QueryOptions as Q, type Results as R, type SerializerOptions as S, type Transaction as T, type BufferParameter as a, PGlite as b, type PostgresMod as c, type PGliteInterface as d, type RowMode as e, type ParserOptions as f, type ExecProtocolOptions as g, type ExecProtocolOptionsStream as h, type ExtensionSetupResult as i, type ExtensionSetup as j, type Extension as k, type ExtensionNamespace as l, messages as m, type Extensions as n, type ExecProtocolResult as o, postgresMod as p, type DumpDataDirResult as q, type PGliteOptions as r, type PGliteInterfaceExtensions as s, types$1 as t, type Row as u, type DescribeQueryResult as v, BaseFilesystem as w, type FsStats as x, BasePGlite as y, type DumpTarCompressionOptions as z };

Sorry, the diff of this file is not supported yet

+1
-1

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const amcheck: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const amcheck: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const auto_explain: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const auto_explain: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const bloom: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const bloom: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const btree_gin: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const btree_gin: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const btree_gist: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const btree_gist: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const citext: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const citext: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const cube: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const cube: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const dict_int: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const dict_int: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const dict_xsyn: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const dict_xsyn: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const earthdistance: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const earthdistance: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const file_fdw: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const file_fdw: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const fuzzystrmatch: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const fuzzystrmatch: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const hstore: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const hstore: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const intarray: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const intarray: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const isn: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const isn: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const lo: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const lo: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const ltree: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const ltree: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const pageinspect: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const pageinspect: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const pg_buffercache: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const pg_buffercache: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const pg_freespacemap: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const pg_freespacemap: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const pg_stat_statements: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const pg_stat_statements: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const pg_surgery: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const pg_surgery: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const pg_trgm: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const pg_trgm: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const pg_visibility: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const pg_visibility: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const pg_walinspect: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const pg_walinspect: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const pgcrypto: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const pgcrypto: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const seg: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const seg: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const tablefunc: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const tablefunc: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const tcn: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const tcn: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const tsm_system_rows: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const tsm_system_rows: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const tsm_system_time: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const tsm_system_time: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const unaccent: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const unaccent: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare const uuid_ossp: {

@@ -1,2 +0,2 @@

import { d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare const uuid_ossp: {

@@ -1,1 +0,1 @@

export { w as BaseFilesystem, G as ERRNO_CODES, E as EmscriptenBuiltinFilesystem, C as Filesystem, x as FsStats, A as FsType } from '../pglite-CpaPhfpC.cjs';
export { w as BaseFilesystem, G as ERRNO_CODES, E as EmscriptenBuiltinFilesystem, C as Filesystem, x as FsStats, A as FsType } from '../pglite-DIqDo27J.cjs';

@@ -1,1 +0,1 @@

export { w as BaseFilesystem, G as ERRNO_CODES, E as EmscriptenBuiltinFilesystem, C as Filesystem, x as FsStats, A as FsType } from '../pglite-CpaPhfpC.js';
export { w as BaseFilesystem, G as ERRNO_CODES, E as EmscriptenBuiltinFilesystem, C as Filesystem, x as FsStats, A as FsType } from '../pglite-DIqDo27J.js';

@@ -1,2 +0,2 @@

import { E as EmscriptenBuiltinFilesystem, b as PGlite, c as PostgresMod } from '../pglite-CpaPhfpC.cjs';
import { E as EmscriptenBuiltinFilesystem, b as PGlite, c as PostgresMod } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ declare class NodeFS extends EmscriptenBuiltinFilesystem {

@@ -1,2 +0,2 @@

import { E as EmscriptenBuiltinFilesystem, b as PGlite, c as PostgresMod } from '../pglite-CpaPhfpC.js';
import { E as EmscriptenBuiltinFilesystem, b as PGlite, c as PostgresMod } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ declare class NodeFS extends EmscriptenBuiltinFilesystem {

@@ -1,2 +0,2 @@

import { w as BaseFilesystem, b as PGlite, c as PostgresMod, x as FsStats } from '../pglite-CpaPhfpC.cjs';
import { w as BaseFilesystem, b as PGlite, c as PostgresMod, x as FsStats } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ interface OpfsAhpOptions {

@@ -1,2 +0,2 @@

import { w as BaseFilesystem, b as PGlite, c as PostgresMod, x as FsStats } from '../pglite-CpaPhfpC.js';
import { w as BaseFilesystem, b as PGlite, c as PostgresMod, x as FsStats } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ interface OpfsAhpOptions {

@@ -1,3 +0,3 @@

import { B as BackendMessage$1, P as Parser$1, Q as QueryOptions, R as Results, M as Mode, a as BufferParameter, E as EmscriptenBuiltinFilesystem, b as PGlite, c as PostgresMod, d as PGliteInterface, T as Transaction } from './pglite-CpaPhfpC.cjs';
export { D as DebugLevel, v as DescribeQueryResult, q as DumpDataDirResult, g as ExecProtocolOptions, h as ExecProtocolOptionsStream, o as ExecProtocolResult, k as Extension, l as ExtensionNamespace, j as ExtensionSetup, i as ExtensionSetupResult, n as Extensions, F as FilesystemType, I as InitializedExtensions, s as PGliteInterfaceExtensions, r as PGliteOptions, f as ParserOptions, u as Row, e as RowMode, S as SerializerOptions, m as messages, p as postgresMod, t as types } from './pglite-CpaPhfpC.cjs';
import { B as BackendMessage$1, P as Parser$1, Q as QueryOptions, R as Results, M as Mode, a as BufferParameter, E as EmscriptenBuiltinFilesystem, b as PGlite, c as PostgresMod, d as PGliteInterface, T as Transaction } from './pglite-DIqDo27J.cjs';
export { D as DebugLevel, v as DescribeQueryResult, q as DumpDataDirResult, g as ExecProtocolOptions, h as ExecProtocolOptionsStream, o as ExecProtocolResult, k as Extension, l as ExtensionNamespace, j as ExtensionSetup, i as ExtensionSetupResult, n as Extensions, F as FilesystemType, I as InitializedExtensions, s as PGliteInterfaceExtensions, r as PGliteOptions, f as ParserOptions, u as Row, e as RowMode, S as SerializerOptions, m as messages, p as postgresMod, t as types } from './pglite-DIqDo27J.cjs';

@@ -4,0 +4,0 @@ /**

@@ -1,3 +0,3 @@

import { B as BackendMessage$1, P as Parser$1, Q as QueryOptions, R as Results, M as Mode, a as BufferParameter, E as EmscriptenBuiltinFilesystem, b as PGlite, c as PostgresMod, d as PGliteInterface, T as Transaction } from './pglite-CpaPhfpC.js';
export { D as DebugLevel, v as DescribeQueryResult, q as DumpDataDirResult, g as ExecProtocolOptions, h as ExecProtocolOptionsStream, o as ExecProtocolResult, k as Extension, l as ExtensionNamespace, j as ExtensionSetup, i as ExtensionSetupResult, n as Extensions, F as FilesystemType, I as InitializedExtensions, s as PGliteInterfaceExtensions, r as PGliteOptions, f as ParserOptions, u as Row, e as RowMode, S as SerializerOptions, m as messages, p as postgresMod, t as types } from './pglite-CpaPhfpC.js';
import { B as BackendMessage$1, P as Parser$1, Q as QueryOptions, R as Results, M as Mode, a as BufferParameter, E as EmscriptenBuiltinFilesystem, b as PGlite, c as PostgresMod, d as PGliteInterface, T as Transaction } from './pglite-DIqDo27J.js';
export { D as DebugLevel, v as DescribeQueryResult, q as DumpDataDirResult, g as ExecProtocolOptions, h as ExecProtocolOptionsStream, o as ExecProtocolResult, k as Extension, l as ExtensionNamespace, j as ExtensionSetup, i as ExtensionSetupResult, n as Extensions, F as FilesystemType, I as InitializedExtensions, s as PGliteInterfaceExtensions, r as PGliteOptions, f as ParserOptions, u as Row, e as RowMode, S as SerializerOptions, m as messages, p as postgresMod, t as types } from './pglite-DIqDo27J.js';

@@ -4,0 +4,0 @@ /**

@@ -1,2 +0,2 @@

"use strict";var we=Object.create;var Q=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var Se=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var oe=e=>{throw TypeError(e)};var Ie=(e,t)=>{for(var n in t)Q(e,n,{get:t[n],enumerable:!0})},ue=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Te(t))!Re.call(e,r)&&r!==n&&Q(e,r,{get:()=>t[r],enumerable:!(s=Ae(t,r))||s.enumerable});return e};var ce=(e,t,n)=>(n=e!=null?we(Se(e)):{},ue(t||!e||!e.__esModule?Q(n,"default",{value:e,enumerable:!0}):n,e)),Ce=e=>ue(Q({},"__esModule",{value:!0}),e);var te=(e,t,n)=>t.has(e)||oe("Cannot "+n);var c=(e,t,n)=>(te(e,t,"read from private field"),n?n.call(e):t.get(e)),O=(e,t,n)=>t.has(e)?oe("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),C=(e,t,n,s)=>(te(e,t,"write to private field"),s?s.call(e,n):t.set(e,n),n),L=(e,t,n)=>(te(e,t,"access private method"),n);var ne=(e,t,n,s)=>({set _(r){C(e,t,r,n)},get _(){return c(e,t,s)}});var Ct={};Ie(Ct,{live:()=>Rt});module.exports=Ce(Ct);function U(e){let t=e.length;for(let n=e.length-1;n>=0;n--){let s=e.charCodeAt(n);s>127&&s<=2047?t++:s>2047&&s<=65535&&(t+=2),s>=56320&&s<=57343&&n--}return t}var A,T,k,H,V,R,W,F,le,x=class{constructor(t=256){this.size=t;O(this,R);O(this,A);O(this,T,5);O(this,k,!1);O(this,H,new TextEncoder);O(this,V,0);C(this,A,L(this,R,W).call(this,t))}addInt32(t){return L(this,R,F).call(this,4),c(this,A).setInt32(c(this,T),t,c(this,k)),C(this,T,c(this,T)+4),this}addInt16(t){return L(this,R,F).call(this,2),c(this,A).setInt16(c(this,T),t,c(this,k)),C(this,T,c(this,T)+2),this}addCString(t){return t&&this.addString(t),L(this,R,F).call(this,1),c(this,A).setUint8(c(this,T),0),ne(this,T)._++,this}addString(t=""){let n=U(t);return L(this,R,F).call(this,n),c(this,H).encodeInto(t,new Uint8Array(c(this,A).buffer,c(this,T))),C(this,T,c(this,T)+n),this}add(t){return L(this,R,F).call(this,t.byteLength),new Uint8Array(c(this,A).buffer).set(new Uint8Array(t),c(this,T)),C(this,T,c(this,T)+t.byteLength),this}flush(t){let n=L(this,R,le).call(this,t);return C(this,T,5),C(this,A,L(this,R,W).call(this,this.size)),new Uint8Array(n)}};A=new WeakMap,T=new WeakMap,k=new WeakMap,H=new WeakMap,V=new WeakMap,R=new WeakSet,W=function(t){return new DataView(new ArrayBuffer(t))},F=function(t){if(c(this,A).byteLength-c(this,T)<t){let s=c(this,A).buffer,r=s.byteLength+(s.byteLength>>1)+t;C(this,A,L(this,R,W).call(this,r)),new Uint8Array(c(this,A).buffer).set(new Uint8Array(s))}},le=function(t){if(t){c(this,A).setUint8(c(this,V),t);let n=c(this,T)-(c(this,V)+1);c(this,A).setInt32(c(this,V)+1,n,c(this,k))}return c(this,A).buffer.slice(t?0:5,c(this,T))};var g=new x,ve=e=>{g.addInt16(3).addInt16(0);for(let s of Object.keys(e))g.addCString(s).addCString(e[s]);g.addCString("client_encoding").addCString("UTF8");let t=g.addCString("").flush(),n=t.byteLength+4;return new x().addInt32(n).add(t).flush()},Ne=()=>{let e=new DataView(new ArrayBuffer(8));return e.setInt32(0,8,!1),e.setInt32(4,80877103,!1),new Uint8Array(e.buffer)},Le=e=>g.addCString(e).flush(112),De=(e,t)=>(g.addCString(e).addInt32(U(t)).addString(t),g.flush(112)),Oe=e=>g.addString(e).flush(112),Me=e=>g.addCString(e).flush(81),Be=[],Pe=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 n=g.addCString(t).addCString(e.text).addInt16(e.types?.length??0);return e.types?.forEach(s=>n.addInt32(s)),g.flush(80)},q=new x;var xe=(e,t)=>{for(let n=0;n<e.length;n++){let s=t?t(e[n],n):e[n];if(s===null)g.addInt16(0),q.addInt32(-1);else if(s instanceof ArrayBuffer||ArrayBuffer.isView(s)){let r=ArrayBuffer.isView(s)?s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength):s;g.addInt16(1),q.addInt32(r.byteLength),q.add(r)}else g.addInt16(0),q.addInt32(U(s)),q.addString(s)}},$e=(e={})=>{let t=e.portal??"",n=e.statement??"",s=e.binary??!1,r=e.values??Be,a=r.length;return g.addCString(t).addCString(n),g.addInt16(a),xe(r,e.valueMapper),g.addInt16(a),g.add(q.flush()),g.addInt16(s?1:0),g.flush(66)},Ue=new Uint8Array([69,0,0,0,9,0,0,0,0,0]),Fe=e=>{if(!e||!e.portal&&!e.rows)return Ue;let t=e.portal??"",n=e.rows??0,s=U(t),r=4+s+1+4,a=new DataView(new ArrayBuffer(1+r));return a.setUint8(0,69),a.setInt32(1,r,!1),new TextEncoder().encodeInto(t,new Uint8Array(a.buffer,5)),a.setUint8(s+5,0),a.setUint32(a.byteLength-4,n,!1),new Uint8Array(a.buffer)},ke=(e,t)=>{let n=new DataView(new ArrayBuffer(16));return n.setInt32(0,16,!1),n.setInt16(4,1234,!1),n.setInt16(6,5678,!1),n.setInt32(8,e,!1),n.setInt32(12,t,!1),new Uint8Array(n.buffer)},re=(e,t)=>{let n=new x;return n.addCString(t),n.flush(e)},Ve=g.addCString("P").flush(68),qe=g.addCString("S").flush(68),Ge=e=>e.name?re(68,`${e.type}${e.name??""}`):e.type==="P"?Ve:qe,je=e=>{let t=`${e.type}${e.name??""}`;return re(67,t)},Qe=e=>g.add(e).flush(100),We=e=>re(102,e),X=e=>new Uint8Array([e,0,0,0,4]),He=X(72),Xe=X(83),ze=X(88),Je=X(99),G={startup:ve,password:Le,requestSsl:Ne,sendSASLInitialResponseMessage:De,sendSCRAMClientFinalMessage:Oe,query:Me,parse:Pe,bind:$e,execute:Fe,describe:Ge,close:je,flush:()=>He,sync:()=>Xe,end:()=>ze,copyData:Qe,copyDone:()=>Je,copyFail:We,cancel:ke};var qt=new ArrayBuffer(0);var Ke=1,Ze=4,Nn=Ke+Ze,Ln=new ArrayBuffer(0);var et=globalThis.JSON.parse,tt=globalThis.JSON.stringify,de=16,pe=17;var fe=20,nt=21,rt=23;var z=25,st=26;var me=114;var it=700,at=701;var ot=1042,ut=1043,ct=1082;var lt=1114,ye=1184;var dt=3802;var pt={string:{to:z,from:[z,ut,ot],serialize:e=>e instanceof Date?e.toISOString():e.toString(),parse:e=>e},number:{to:0,from:[nt,rt,st,it,at],serialize:e=>e.toString(),parse:e=>+e},bigint:{to:fe,from:[fe],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:me,from:[me,dt],serialize:e=>typeof e=="string"?e:tt(e,(t,n)=>typeof n=="bigint"?n.toString():n),parse:e=>et(e)},boolean:{to:de,from:[de],serialize:e=>{if(typeof e=="boolean")return e?"t":"f";if(typeof e=="number"){if(e===1)return"t";if(e===0)return"f"}else if(typeof e=="string"){let t=e.trim().toLowerCase();if(["true","t","yes","y","on","1"].includes(t))return"t";if(["false","f","no","n","off","0"].includes(t))return"f"}throw new Error("Invalid input for boolean type")},parse:e=>e==="t"},date:{to:ye,from:[ct,lt,ye],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:pe,from:[pe],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},(n,s)=>parseInt(t.substring(s*2,(s+1)*2),16))}}},he=ft(pt),Fn=he.parsers,kn=he.serializers;function ft(e){return Object.keys(e).reduce(({parsers:t,serializers:n},s)=>{let{to:r,from:a,serialize:i,parse:b}=e[s];return n[r]=i,n[s]=i,t[s]=b,Array.isArray(a)?a.forEach(y=>{t[y]=b,n[y]=i}):(t[a]=b,n[a]=i),{parsers:t,serializers:n}},{parsers:{},serializers:{}})}function ge(e){let t=e.find(n=>n.name==="parameterDescription");return t?t.dataTypeIDs:[]}async function se(e,t,n,s){if(!n||n.length===0)return t;s=s??e;let r=[];try{await e.execProtocol(G.parse({text:t}),{syncToFs:!1}),r.push(...(await e.execProtocol(G.describe({type:"S"}),{syncToFs:!1})).messages)}finally{r.push(...(await e.execProtocol(G.sync(),{syncToFs:!1})).messages)}let a=ge(r),i=t.replace(/\$([0-9]+)/g,(y,l)=>"%"+l+"L");return(await s.query(`SELECT format($1, ${n.map((y,l)=>`$${l+2}`).join(", ")}) as query`,[i,...n],{paramTypes:[z,...a]})).rows[0].query}function ie(e){let t,n=!1,s=async()=>{if(!t){n=!1;return}n=!0;let{args:r,resolve:a,reject:i}=t;t=void 0;try{let b=await e(...r);a(b)}catch(b){i(b)}finally{s()}};return async(...r)=>{t&&t.resolve(void 0);let a=new Promise((i,b)=>{t={args:r,resolve:i,reject:b}});return n||s(),a}}var mt=Object.defineProperty,yt=(e,t)=>{for(var n in t)mt(e,n,{get:t[n],enumerable:!0})},Y={};yt(Y,{IN_NODE:()=>K,WASM_PREFIX:()=>gt,getFsBundle:()=>Et,instantiateWasm:()=>_t,pgliteProc:()=>bt,rmdirRecursive:()=>be,startArtifactDownload:()=>ae,toPostgresName:()=>At,uuid:()=>wt});function ht(){let e=process.type;return e==="renderer"||e==="worker"||e==="service-worker"}var K=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&!ht(),gt="/pglite",j=new Map;async function ae(e){K||j.has(e.toString())||j.set(e.toString(),fetch(e))}var J=new Map,bt=globalThis&&typeof globalThis.process<"u"?globalThis.process:{exitCode:void 0};async function _t(e,t,n){if(n||J.has(t.toString())){let s=n||J.get(t.toString());return{instance:await WebAssembly.instantiate(s,e),module:s}}if(K){let s=await(await import("fs/promises")).readFile(t),{module:r,instance:a}=await WebAssembly.instantiate(s,e);return J.set(t.toString(),r),{instance:a,module:r}}else{j.has(t.toString())||ae(t);let s=await j.get(t.toString()),{module:r,instance:a}=await WebAssembly.instantiateStreaming(s.clone(),e);return J.set(t.toString(),r),{instance:a,module:r}}}async function Et(e){return K?(await(await import("fs/promises")).readFile(e)).buffer:(ae(e),(await j.get(e.toString())).clone().arrayBuffer())}var wt=()=>{if(globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e=new Uint8Array(16);if(globalThis.crypto?.getRandomValues)globalThis.crypto.getRandomValues(e);else for(let n=0;n<e.length;n++)e[n]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[];return e.forEach(n=>{t.push(n.toString(16).padStart(2,"0"))}),t.slice(0,4).join("")+"-"+t.slice(4,6).join("")+"-"+t.slice(6,8).join("")+"-"+t.slice(8,10).join("")+"-"+t.slice(10).join("")};function At(e){let t;return e.startsWith('"')&&e.endsWith('"')?t=e.substring(1,e.length-1):t=e.toLowerCase(),t}function be(e,t){try{let n=e.readdir(t).filter(s=>s!=="."&&s!=="..");for(let s of n){let r=t+"/"+s;try{e.readdir(r),be(e,r)}catch{e.unlink(r)}}e.rmdir(t)}catch{try{e.unlink(t)}catch{}}}var Tt=5,St=async(e,t)=>{let n=new Set,s={async query(r,a,i){let b,y,l;if(typeof r!="string"&&(b=r.signal,a=r.params,i=r.callback,y=r.offset,l=r.limit,r=r.query),y===void 0!=(l===void 0))throw new Error("offset and limit must be provided together");let o=y!==void 0&&l!==void 0,S;if(o&&(typeof y!="number"||isNaN(y)||typeof l!="number"||isNaN(l)))throw new Error("offset and limit must be numbers");let _=i?[i]:[],m=Y.uuid().replace(/-/g,""),D=!1,I,M,$=async()=>{await e.transaction(async u=>{let d=a&&a.length>0?await se(e,r,a,u):r;await u.exec(`CREATE OR REPLACE TEMP VIEW live_query_${m}_view AS ${d}`);let E=await _e(u,`live_query_${m}_view`);await Ee(u,E,n),o?(await u.exec(`
"use strict";var we=Object.create;var Q=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var Se=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var oe=e=>{throw TypeError(e)};var Ie=(e,t)=>{for(var n in t)Q(e,n,{get:t[n],enumerable:!0})},ue=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Te(t))!Re.call(e,r)&&r!==n&&Q(e,r,{get:()=>t[r],enumerable:!(s=Ae(t,r))||s.enumerable});return e};var ce=(e,t,n)=>(n=e!=null?we(Se(e)):{},ue(t||!e||!e.__esModule?Q(n,"default",{value:e,enumerable:!0}):n,e)),Ne=e=>ue(Q({},"__esModule",{value:!0}),e);var te=(e,t,n)=>t.has(e)||oe("Cannot "+n);var c=(e,t,n)=>(te(e,t,"read from private field"),n?n.call(e):t.get(e)),M=(e,t,n)=>t.has(e)?oe("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),N=(e,t,n,s)=>(te(e,t,"write to private field"),s?s.call(e,n):t.set(e,n),n),L=(e,t,n)=>(te(e,t,"access private method"),n);var ne=(e,t,n,s)=>({set _(r){N(e,t,r,n)},get _(){return c(e,t,s)}});var Nt={};Ie(Nt,{live:()=>Rt});module.exports=Ne(Nt);function U(e){let t=e.length;for(let n=e.length-1;n>=0;n--){let s=e.charCodeAt(n);s>127&&s<=2047?t++:s>2047&&s<=65535&&(t+=2),s>=56320&&s<=57343&&n--}return t}var A,T,k,H,V,R,W,F,le,x=class{constructor(t=256){this.size=t;M(this,R);M(this,A);M(this,T,5);M(this,k,!1);M(this,H,new TextEncoder);M(this,V,0);N(this,A,L(this,R,W).call(this,t))}addInt32(t){return L(this,R,F).call(this,4),c(this,A).setInt32(c(this,T),t,c(this,k)),N(this,T,c(this,T)+4),this}addInt16(t){return L(this,R,F).call(this,2),c(this,A).setInt16(c(this,T),t,c(this,k)),N(this,T,c(this,T)+2),this}addCString(t){return t&&this.addString(t),L(this,R,F).call(this,1),c(this,A).setUint8(c(this,T),0),ne(this,T)._++,this}addString(t=""){let n=U(t);return L(this,R,F).call(this,n),c(this,H).encodeInto(t,new Uint8Array(c(this,A).buffer,c(this,T))),N(this,T,c(this,T)+n),this}add(t){return L(this,R,F).call(this,t.byteLength),new Uint8Array(c(this,A).buffer).set(new Uint8Array(t),c(this,T)),N(this,T,c(this,T)+t.byteLength),this}flush(t){let n=L(this,R,le).call(this,t);return N(this,T,5),N(this,A,L(this,R,W).call(this,this.size)),new Uint8Array(n)}};A=new WeakMap,T=new WeakMap,k=new WeakMap,H=new WeakMap,V=new WeakMap,R=new WeakSet,W=function(t){return new DataView(new ArrayBuffer(t))},F=function(t){if(c(this,A).byteLength-c(this,T)<t){let s=c(this,A).buffer,r=s.byteLength+(s.byteLength>>1)+t;N(this,A,L(this,R,W).call(this,r)),new Uint8Array(c(this,A).buffer).set(new Uint8Array(s))}},le=function(t){if(t){c(this,A).setUint8(c(this,V),t);let n=c(this,T)-(c(this,V)+1);c(this,A).setInt32(c(this,V)+1,n,c(this,k))}return c(this,A).buffer.slice(t?0:5,c(this,T))};var g=new x,ve=e=>{g.addInt16(3).addInt16(0);for(let s of Object.keys(e))g.addCString(s).addCString(e[s]);g.addCString("client_encoding").addCString("UTF8");let t=g.addCString("").flush(),n=t.byteLength+4;return new x().addInt32(n).add(t).flush()},Ce=()=>{let e=new DataView(new ArrayBuffer(8));return e.setInt32(0,8,!1),e.setInt32(4,80877103,!1),new Uint8Array(e.buffer)},Le=e=>g.addCString(e).flush(112),De=(e,t)=>(g.addCString(e).addInt32(U(t)).addString(t),g.flush(112)),Oe=e=>g.addString(e).flush(112),Me=e=>g.addCString(e).flush(81),Be=[],Pe=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 n=g.addCString(t).addCString(e.text).addInt16(e.types?.length??0);return e.types?.forEach(s=>n.addInt32(s)),g.flush(80)},q=new x;var xe=(e,t)=>{for(let n=0;n<e.length;n++){let s=t?t(e[n],n):e[n];if(s===null)g.addInt16(0),q.addInt32(-1);else if(s instanceof ArrayBuffer||ArrayBuffer.isView(s)){let r=ArrayBuffer.isView(s)?s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength):s;g.addInt16(1),q.addInt32(r.byteLength),q.add(r)}else g.addInt16(0),q.addInt32(U(s)),q.addString(s)}},$e=(e={})=>{let t=e.portal??"",n=e.statement??"",s=e.binary??!1,r=e.values??Be,a=r.length;return g.addCString(t).addCString(n),g.addInt16(a),xe(r,e.valueMapper),g.addInt16(a),g.add(q.flush()),g.addInt16(s?1:0),g.flush(66)},Ue=new Uint8Array([69,0,0,0,9,0,0,0,0,0]),Fe=e=>{if(!e||!e.portal&&!e.rows)return Ue;let t=e.portal??"",n=e.rows??0,s=U(t),r=4+s+1+4,a=new DataView(new ArrayBuffer(1+r));return a.setUint8(0,69),a.setInt32(1,r,!1),new TextEncoder().encodeInto(t,new Uint8Array(a.buffer,5)),a.setUint8(s+5,0),a.setUint32(a.byteLength-4,n,!1),new Uint8Array(a.buffer)},ke=(e,t)=>{let n=new DataView(new ArrayBuffer(16));return n.setInt32(0,16,!1),n.setInt16(4,1234,!1),n.setInt16(6,5678,!1),n.setInt32(8,e,!1),n.setInt32(12,t,!1),new Uint8Array(n.buffer)},re=(e,t)=>{let n=new x;return n.addCString(t),n.flush(e)},Ve=g.addCString("P").flush(68),qe=g.addCString("S").flush(68),Ge=e=>e.name?re(68,`${e.type}${e.name??""}`):e.type==="P"?Ve:qe,je=e=>{let t=`${e.type}${e.name??""}`;return re(67,t)},Qe=e=>g.add(e).flush(100),We=e=>re(102,e),X=e=>new Uint8Array([e,0,0,0,4]),He=X(72),Xe=X(83),ze=X(88),Je=X(99),G={startup:ve,password:Le,requestSsl:Ce,sendSASLInitialResponseMessage:De,sendSCRAMClientFinalMessage:Oe,query:Me,parse:Pe,bind:$e,execute:Fe,describe:Ge,close:je,flush:()=>He,sync:()=>Xe,end:()=>ze,copyData:Qe,copyDone:()=>Je,copyFail:We,cancel:ke};var qt=new ArrayBuffer(0);var Ke=1,Ze=4,Cn=Ke+Ze,Ln=new ArrayBuffer(0);var et=globalThis.JSON.parse,tt=globalThis.JSON.stringify,de=16,pe=17;var fe=20,nt=21,rt=23;var z=25,st=26;var me=114;var it=700,at=701;var ot=1042,ut=1043,ct=1082;var lt=1114,ye=1184;var dt=3802;var pt={string:{to:z,from:[z,ut,ot],serialize:e=>e instanceof Date?e.toISOString():e.toString(),parse:e=>e},number:{to:0,from:[nt,rt,st,it,at],serialize:e=>e.toString(),parse:e=>+e},bigint:{to:fe,from:[fe],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:me,from:[me,dt],serialize:e=>typeof e=="string"?e:tt(e,(t,n)=>typeof n=="bigint"?n.toString():n),parse:e=>et(e)},boolean:{to:de,from:[de],serialize:e=>{if(typeof e=="boolean")return e?"t":"f";if(typeof e=="number"){if(e===1)return"t";if(e===0)return"f"}else if(typeof e=="string"){let t=e.trim().toLowerCase();if(["true","t","yes","y","on","1"].includes(t))return"t";if(["false","f","no","n","off","0"].includes(t))return"f"}throw new Error("Invalid input for boolean type")},parse:e=>e==="t"},date:{to:ye,from:[ct,lt,ye],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:pe,from:[pe],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},(n,s)=>parseInt(t.substring(s*2,(s+1)*2),16))}}},he=ft(pt),Fn=he.parsers,kn=he.serializers;function ft(e){return Object.keys(e).reduce(({parsers:t,serializers:n},s)=>{let{to:r,from:a,serialize:i,parse:b}=e[s];return n[r]=i,n[s]=i,t[s]=b,Array.isArray(a)?a.forEach(y=>{t[y]=b,n[y]=i}):(t[a]=b,n[a]=i),{parsers:t,serializers:n}},{parsers:{},serializers:{}})}function ge(e){let t=e.find(n=>n.name==="parameterDescription");return t?t.dataTypeIDs:[]}async function se(e,t,n,s){if(!n||n.length===0)return t;s=s??e;let r=[];try{await e.execProtocol(G.parse({text:t}),{syncToFs:!1}),r.push(...(await e.execProtocol(G.describe({type:"S"}),{syncToFs:!1})).messages)}finally{r.push(...(await e.execProtocol(G.sync(),{syncToFs:!1})).messages)}let a=ge(r),i=t.replace(/\$([0-9]+)/g,(y,l)=>"%"+l+"$L");return(await s.query(`SELECT format($1, ${n.map((y,l)=>`$${l+2}`).join(", ")}) as query`,[i,...n],{paramTypes:[z,...a]})).rows[0].query}function ie(e){let t,n=!1,s=async()=>{if(!t){n=!1;return}n=!0;let{args:r,resolve:a,reject:i}=t;t=void 0;try{let b=await e(...r);a(b)}catch(b){i(b)}finally{s()}};return async(...r)=>{t&&t.resolve(void 0);let a=new Promise((i,b)=>{t={args:r,resolve:i,reject:b}});return n||s(),a}}var mt=Object.defineProperty,yt=(e,t)=>{for(var n in t)mt(e,n,{get:t[n],enumerable:!0})},Y={};yt(Y,{IN_NODE:()=>K,WASM_PREFIX:()=>gt,getFsBundle:()=>Et,instantiateWasm:()=>_t,pgliteProc:()=>bt,rmdirRecursive:()=>be,startArtifactDownload:()=>ae,toPostgresName:()=>At,uuid:()=>wt});function ht(){let e=process.type;return e==="renderer"||e==="worker"||e==="service-worker"}var K=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&!ht(),gt="/pglite",j=new Map;async function ae(e){K||j.has(e.toString())||j.set(e.toString(),fetch(e))}var J=new Map,bt=globalThis&&typeof globalThis.process<"u"?globalThis.process:{exitCode:void 0};async function _t(e,t,n){if(n||J.has(t.toString())){let s=n||J.get(t.toString());return{instance:await WebAssembly.instantiate(s,e),module:s}}if(K){let s=await(await import("fs/promises")).readFile(t),{module:r,instance:a}=await WebAssembly.instantiate(s,e);return J.set(t.toString(),r),{instance:a,module:r}}else{j.has(t.toString())||ae(t);let s=await j.get(t.toString()),{module:r,instance:a}=await WebAssembly.instantiateStreaming(s.clone(),e);return J.set(t.toString(),r),{instance:a,module:r}}}async function Et(e){return K?(await(await import("fs/promises")).readFile(e)).buffer:(ae(e),(await j.get(e.toString())).clone().arrayBuffer())}var wt=()=>{if(globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e=new Uint8Array(16);if(globalThis.crypto?.getRandomValues)globalThis.crypto.getRandomValues(e);else for(let n=0;n<e.length;n++)e[n]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[];return e.forEach(n=>{t.push(n.toString(16).padStart(2,"0"))}),t.slice(0,4).join("")+"-"+t.slice(4,6).join("")+"-"+t.slice(6,8).join("")+"-"+t.slice(8,10).join("")+"-"+t.slice(10).join("")};function At(e){let t;return e.startsWith('"')&&e.endsWith('"')?t=e.substring(1,e.length-1):t=e.toLowerCase(),t}function be(e,t){try{let n=e.readdir(t).filter(s=>s!=="."&&s!=="..");for(let s of n){let r=t+"/"+s;try{e.readdir(r),be(e,r)}catch{e.unlink(r)}}e.rmdir(t)}catch{try{e.unlink(t)}catch{}}}var Tt=5,St=async(e,t)=>{let n=new Set,s={async query(r,a,i){let b,y,l;if(typeof r!="string"&&(b=r.signal,a=r.params,i=r.callback,y=r.offset,l=r.limit,r=r.query),y===void 0!=(l===void 0))throw new Error("offset and limit must be provided together");let o=y!==void 0&&l!==void 0,S;if(o&&(typeof y!="number"||isNaN(y)||typeof l!="number"||isNaN(l)))throw new Error("offset and limit must be numbers");let _=i?[i]:[],m=Y.uuid().replace(/-/g,""),D=!1,I,B,$=async()=>{await e.transaction(async u=>{let p=a&&a.length>0?await se(e,r,a,u):r;await u.exec(`CREATE OR REPLACE TEMP VIEW live_query_${m}_view AS ${p}`);let E=await _e(u,`live_query_${m}_view`);await Ee(u,E,n),o?(await u.exec(`
PREPARE live_query_${m}_get(int, int) AS

@@ -11,6 +11,6 @@ SELECT * FROM live_query_${m}_view

SELECT * FROM live_query_${m}_view;
`),I=await u.query(`EXECUTE live_query_${m}_get;`)),M=await Promise.all(E.map(w=>u.listen(`"table_change__${w.schema_oid}__${w.table_oid}"`,async()=>{N()})))})};await $();let N=ie(async({offset:u,limit:d}={})=>{if(!o&&(u!==void 0||d!==void 0))throw new Error("offset and limit cannot be provided for non-windowed queries");if(u&&(typeof u!="number"||isNaN(u))||d&&(typeof d!="number"||isNaN(d)))throw new Error("offset and limit must be numbers");y=u??y,l=d??l;let E=async(w=0)=>{if(_.length!==0){try{o?I={...await e.query(`EXECUTE live_query_${m}_get(${l}, ${y});`),offset:y,limit:l,totalCount:S}:I=await e.query(`EXECUTE live_query_${m}_get;`)}catch(h){let p=h.message;if(p.startsWith(`prepared statement "live_query_${m}`)&&p.endsWith("does not exist")){if(w>Tt)throw h;await $(),E(w+1)}else throw h}if(Z(_,I),o){let h=(await e.query(`EXECUTE live_query_${m}_get_total_count;`)).rows[0].count;h!==S&&(S=h,N())}}};await E()}),B=u=>{if(D)throw new Error("Live query is no longer active and cannot be subscribed to");_.push(u)},f=async u=>{u?_=_.filter(d=>d!==d):_=[],_.length===0&&!D&&(D=!0,await e.transaction(async d=>{await Promise.all(M.map(E=>E(d))),await d.exec(`
`),I=await u.query(`EXECUTE live_query_${m}_get;`)),B=await Promise.all(E.map(w=>u.listen(`"table_change__${w.schema_oid}__${w.table_oid}"`,async()=>{C()})))})};await $();let C=ie(async({offset:u,limit:p}={})=>{if(!o&&(u!==void 0||p!==void 0))throw new Error("offset and limit cannot be provided for non-windowed queries");if(u&&(typeof u!="number"||isNaN(u))||p&&(typeof p!="number"||isNaN(p)))throw new Error("offset and limit must be numbers");y=u??y,l=p??l;let E=async(w=0)=>{if(_.length!==0){try{o?I={...await e.query(`EXECUTE live_query_${m}_get(${l}, ${y});`),offset:y,limit:l,totalCount:S}:I=await e.query(`EXECUTE live_query_${m}_get;`)}catch(h){let d=h.message;if(d.startsWith(`prepared statement "live_query_${m}`)&&d.endsWith("does not exist")){if(w>Tt)throw h;await $(),E(w+1)}else throw h}if(Z(_,I),o){let h=(await e.query(`EXECUTE live_query_${m}_get_total_count;`)).rows[0].count;h!==S&&(S=h,C())}}};await E()}),O=u=>{if(D)throw new Error("Live query is no longer active and cannot be subscribed to");_.push(u)},f=async u=>{u?_=_.filter(p=>p!==u):_=[],_.length===0&&!D&&(D=!0,await e.transaction(async p=>{await Promise.all(B.map(E=>E(p))),await p.exec(`
DROP VIEW IF EXISTS live_query_${m}_view;
DEALLOCATE live_query_${m}_get;
`)}))};return b?.aborted?await f():b?.addEventListener("abort",()=>{f()},{once:!0}),Z(_,I),{initialResults:I,subscribe:B,unsubscribe:f,refresh:N}},async changes(r,a,i,b){let y;if(typeof r!="string"&&(y=r.signal,a=r.params,i=r.key,b=r.callback,r=r.query),!i)throw new Error("key is required for changes queries");let l=b?[b]:[],o=Y.uuid().replace(/-/g,""),S=!1,_=1,m,D,I=async()=>{await e.transaction(async f=>{let u=await se(e,r,a,f);await f.query(`CREATE OR REPLACE TEMP VIEW live_query_${o}_view AS ${u}`);let d=await _e(f,`live_query_${o}_view`);await Ee(f,d,n);let E=[...(await f.query(`
`)}))};return b?.aborted?await f():b?.addEventListener("abort",()=>{f()},{once:!0}),Z(_,I),{initialResults:I,subscribe:O,unsubscribe:f,refresh:C}},async changes(r,a,i,b){let y;if(typeof r!="string"&&(y=r.signal,a=r.params,i=r.key,b=r.callback,r=r.query),!i)throw new Error("key is required for changes queries");let l=b?[b]:[],o=Y.uuid().replace(/-/g,""),S=!1,_=1,m,D,I=async()=>{await e.transaction(async f=>{let u=await se(e,r,a,f);await f.query(`CREATE OR REPLACE TEMP VIEW live_query_${o}_view AS ${u}`);let p=await _e(f,`live_query_${o}_view`);await Ee(f,p,n);let E=[...(await f.query(`
SELECT column_name, data_type, udt_name

@@ -31,3 +31,3 @@ FROM information_schema.columns

'INSERT' AS __op__,
${E.map(({column_name:p})=>`curr."${p}" AS "${p}"`).join(`,
${E.map(({column_name:d})=>`curr."${d}" AS "${d}"`).join(`,
`)},

@@ -42,3 +42,3 @@ ARRAY[]::text[] AS __changed_columns__

'DELETE' AS __op__,
${E.map(({column_name:p,data_type:P,udt_name:ee})=>p===i?`prev."${p}" AS "${p}"`:`NULL${P==="USER-DEFINED"?`::${ee}`:""} AS "${p}"`).join(`,
${E.map(({column_name:d,data_type:P,udt_name:ee})=>d===i?`prev."${d}" AS "${d}"`:`NULL${P==="USER-DEFINED"?`::${ee}`:""} AS "${d}"`).join(`,
`)},

@@ -53,11 +53,11 @@ ARRAY[]::text[] AS __changed_columns__

'UPDATE' AS __op__,
${E.map(({column_name:p,data_type:P,udt_name:ee})=>p===i?`curr."${p}" AS "${p}"`:`CASE
WHEN curr."${p}" IS DISTINCT FROM prev."${p}"
THEN curr."${p}"
${E.map(({column_name:d,data_type:P,udt_name:ee})=>d===i?`curr."${d}" AS "${d}"`:`CASE
WHEN curr."${d}" IS DISTINCT FROM prev."${d}"
THEN curr."${d}"
ELSE NULL${P==="USER-DEFINED"?`::${ee}`:""}
END AS "${p}"`).join(`,
END AS "${d}"`).join(`,
`)},
ARRAY(SELECT unnest FROM unnest(ARRAY[${E.filter(({column_name:p})=>p!==i).map(({column_name:p})=>`CASE
WHEN curr."${p}" IS DISTINCT FROM prev."${p}"
THEN '${p}'
ARRAY(SELECT unnest FROM unnest(ARRAY[${E.filter(({column_name:d})=>d!==i).map(({column_name:d})=>`CASE
WHEN curr."${d}" IS DISTINCT FROM prev."${d}"
THEN '${d}'
ELSE NULL

@@ -70,8 +70,8 @@ END`).join(", ")}]) WHERE unnest IS NOT NULL) AS __changed_columns__

SELECT * FROM data_diff;
`)}D=await Promise.all(d.map(w=>f.listen(`"table_change__${w.schema_oid}__${w.table_oid}"`,async()=>{M()})))})};await I();let M=ie(async()=>{if(l.length===0&&m)return;let f=!1;for(let u=0;u<5;u++)try{await e.transaction(async d=>{await d.exec(`
`)}D=await Promise.all(p.map(w=>f.listen(`"table_change__${w.schema_oid}__${w.table_oid}"`,async()=>{B()})))})};await I();let B=ie(async()=>{if(l.length===0&&m)return;let f=!1;for(let u=0;u<5;u++)try{await e.transaction(async p=>{await p.exec(`
INSERT INTO live_query_${o}_state${_}
SELECT * FROM live_query_${o}_view;
`),m=await d.query(`EXECUTE live_query_${o}_diff${_};`),_=_===1?2:1,await d.exec(`
`),m=await p.query(`EXECUTE live_query_${o}_diff${_};`),_=_===1?2:1,await p.exec(`
TRUNCATE live_query_${o}_state${_};
`)});break}catch(d){if(d.message===`relation "live_query_${o}_state${_}" does not exist`){f=!0,await I();continue}else throw d}It(l,[...f?[{__op__:"RESET"}]:[],...m.rows])}),$=f=>{if(S)throw new Error("Live query is no longer active and cannot be subscribed to");l.push(f)},N=async f=>{f?l=l.filter(u=>u!==u):l=[],l.length===0&&!S&&(S=!0,await e.transaction(async u=>{await Promise.all(D.map(d=>d(u))),await u.exec(`
`)});break}catch(p){if(p.message===`relation "live_query_${o}_state${_}" does not exist`){f=!0,await I();continue}else throw p}It(l,[...f?[{__op__:"RESET"}]:[],...m.rows])}),$=f=>{if(S)throw new Error("Live query is no longer active and cannot be subscribed to");l.push(f)},C=async f=>{f?l=l.filter(u=>u!==f):l=[],l.length===0&&!S&&(S=!0,await e.transaction(async u=>{await Promise.all(D.map(p=>p(u))),await u.exec(`
DROP VIEW IF EXISTS live_query_${o}_view;

@@ -82,3 +82,3 @@ DROP TABLE IF EXISTS live_query_${o}_state1;

DEALLOCATE live_query_${o}_diff2;
`)}))};return y?.aborted?await N():y?.addEventListener("abort",()=>{N()},{once:!0}),await M(),{fields:m.fields.filter(f=>!["__after__","__op__","__changed_columns__"].includes(f.name)),initialChanges:m.rows,subscribe:$,unsubscribe:N,refresh:M}},async incrementalQuery(r,a,i,b){let y;if(typeof r!="string"&&(y=r.signal,a=r.params,i=r.key,b=r.callback,r=r.query),!i)throw new Error("key is required for incremental queries");let l=b?[b]:[],o=new Map,S=new Map,_=[],m=!0,{fields:D,unsubscribe:I,refresh:M}=await s.changes(r,a,i,B=>{for(let d of B){let{__op__:E,__changed_columns__:w,...h}=d;switch(E){case"RESET":o.clear(),S.clear();break;case"INSERT":o.set(h[i],h),S.set(h.__after__,h[i]);break;case"DELETE":{let p=o.get(h[i]);o.delete(h[i]),p.__after__!==null&&S.delete(p.__after__);break}case"UPDATE":{let p={...o.get(h[i])??{}};for(let P of w)p[P]=h[P],P==="__after__"&&S.set(h.__after__,h[i]);o.set(h[i],p);break}}}let f=[],u=null;for(let d=0;d<o.size;d++){let E=S.get(u),w=o.get(E);if(!w)break;let h={...w};delete h.__after__,f.push(h),u=E}_=f,m||Z(l,{rows:f,fields:D})});m=!1,Z(l,{rows:_,fields:D});let $=B=>{l.push(B)},N=async B=>{B?l=l.filter(f=>f!==f):l=[],l.length===0&&await I()};return y?.aborted?await N():y?.addEventListener("abort",()=>{N()},{once:!0}),{initialResults:{rows:_,fields:D},subscribe:$,unsubscribe:N,refresh:M}}};return{namespaceObj:s}},Rt={name:"Live Queries",setup:St};async function _e(e,t){return(await e.query(`
`)}))};return y?.aborted?await C():y?.addEventListener("abort",()=>{C()},{once:!0}),await B(),{fields:m.fields.filter(f=>!["__after__","__op__","__changed_columns__"].includes(f.name)),initialChanges:m.rows,subscribe:$,unsubscribe:C,refresh:B}},async incrementalQuery(r,a,i,b){let y;if(typeof r!="string"&&(y=r.signal,a=r.params,i=r.key,b=r.callback,r=r.query),!i)throw new Error("key is required for incremental queries");let l=b?[b]:[],o=new Map,S=new Map,_=[],m=!0,{fields:D,unsubscribe:I,refresh:B}=await s.changes(r,a,i,O=>{for(let p of O){let{__op__:E,__changed_columns__:w,...h}=p;switch(E){case"RESET":o.clear(),S.clear();break;case"INSERT":o.set(h[i],h),S.set(h.__after__,h[i]);break;case"DELETE":{let d=o.get(h[i]);o.delete(h[i]),d.__after__!==null&&S.delete(d.__after__);break}case"UPDATE":{let d={...o.get(h[i])??{}};for(let P of w)d[P]=h[P],P==="__after__"&&S.set(h.__after__,h[i]);o.set(h[i],d);break}}}let f=[],u=null;for(let p=0;p<o.size;p++){let E=S.get(u),w=o.get(E);if(!w)break;let h={...w};delete h.__after__,f.push(h),u=E}_=f,m||Z(l,{rows:f,fields:D})});m=!1,Z(l,{rows:_,fields:D});let $=O=>{l.push(O)},C=async O=>{O?l=l.filter(f=>f!==O):l=[],l.length===0&&await I()};return y?.aborted?await C():y?.addEventListener("abort",()=>{C()},{once:!0}),{initialResults:{rows:_,fields:D},subscribe:$,unsubscribe:C,refresh:B}}};return{namespaceObj:s}},Rt={name:"Live Queries",setup:St};async function _e(e,t){return(await e.query(`
WITH RECURSIVE view_dependencies AS (

@@ -85,0 +85,0 @@ -- Base case: Get the initial view's dependencies

@@ -1,2 +0,2 @@

import { R as Results, d as PGliteInterface } from '../pglite-CpaPhfpC.cjs';
import { R as Results, d as PGliteInterface } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ interface LiveQueryOptions<T = {

@@ -1,2 +0,2 @@

import { R as Results, d as PGliteInterface } from '../pglite-CpaPhfpC.js';
import { R as Results, d as PGliteInterface } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ interface LiveQueryOptions<T = {

@@ -1,2 +0,2 @@

import{a as O,b as C}from"../chunk-QY575LMP.js";import"../chunk-2B24BK54.js";import{a as I}from"../chunk-VVBUWNGP.js";import{j as P}from"../chunk-QY3QWFKW.js";P();var M=5,U=async(E,y)=>{let p=new Set,g={async query(e,$,a){let m,c,_;if(typeof e!="string"&&(m=e.signal,$=e.params,a=e.callback,c=e.offset,_=e.limit,e=e.query),c===void 0!=(_===void 0))throw new Error("offset and limit must be provided together");let t=c!==void 0&&_!==void 0,T;if(t&&(typeof c!="number"||isNaN(c)||typeof _!="number"||isNaN(_)))throw new Error("offset and limit must be numbers");let d=a?[a]:[],o=I.uuid().replace(/-/g,""),A=!1,v,w,S=async()=>{await E.transaction(async i=>{let n=$&&$.length>0?await O(E,e,$,i):e;await i.exec(`CREATE OR REPLACE TEMP VIEW live_query_${o}_view AS ${n}`);let u=await q(i,`live_query_${o}_view`);await F(i,u,p),t?(await i.exec(`
import{a as O,b as C}from"../chunk-RYDTTX3G.js";import"../chunk-2BOC2OMW.js";import{a as I}from"../chunk-VVBUWNGP.js";import{j as P}from"../chunk-QY3QWFKW.js";P();var M=5,U=async(E,y)=>{let p=new Set,g={async query(e,$,a){let m,c,_;if(typeof e!="string"&&(m=e.signal,$=e.params,a=e.callback,c=e.offset,_=e.limit,e=e.query),c===void 0!=(_===void 0))throw new Error("offset and limit must be provided together");let t=c!==void 0&&_!==void 0,T;if(t&&(typeof c!="number"||isNaN(c)||typeof _!="number"||isNaN(_)))throw new Error("offset and limit must be numbers");let d=a?[a]:[],o=I.uuid().replace(/-/g,""),A=!1,v,h,S=async()=>{await E.transaction(async i=>{let s=$&&$.length>0?await O(E,e,$,i):e;await i.exec(`CREATE OR REPLACE TEMP VIEW live_query_${o}_view AS ${s}`);let u=await q(i,`live_query_${o}_view`);await F(i,u,p),t?(await i.exec(`
PREPARE live_query_${o}_get(int, int) AS

@@ -11,6 +11,6 @@ SELECT * FROM live_query_${o}_view

SELECT * FROM live_query_${o}_view;
`),v=await i.query(`EXECUTE live_query_${o}_get;`)),w=await Promise.all(u.map(f=>i.listen(`"table_change__${f.schema_oid}__${f.table_oid}"`,async()=>{R()})))})};await S();let R=C(async({offset:i,limit:n}={})=>{if(!t&&(i!==void 0||n!==void 0))throw new Error("offset and limit cannot be provided for non-windowed queries");if(i&&(typeof i!="number"||isNaN(i))||n&&(typeof n!="number"||isNaN(n)))throw new Error("offset and limit must be numbers");c=i??c,_=n??_;let u=async(f=0)=>{if(d.length!==0){try{t?v={...await E.query(`EXECUTE live_query_${o}_get(${_}, ${c});`),offset:c,limit:_,totalCount:T}:v=await E.query(`EXECUTE live_query_${o}_get;`)}catch(l){let s=l.message;if(s.startsWith(`prepared statement "live_query_${o}`)&&s.endsWith("does not exist")){if(f>M)throw l;await S(),u(f+1)}else throw l}if(N(d,v),t){let l=(await E.query(`EXECUTE live_query_${o}_get_total_count;`)).rows[0].count;l!==T&&(T=l,R())}}};await u()}),h=i=>{if(A)throw new Error("Live query is no longer active and cannot be subscribed to");d.push(i)},r=async i=>{i?d=d.filter(n=>n!==n):d=[],d.length===0&&!A&&(A=!0,await E.transaction(async n=>{await Promise.all(w.map(u=>u(n))),await n.exec(`
`),v=await i.query(`EXECUTE live_query_${o}_get;`)),h=await Promise.all(u.map(f=>i.listen(`"table_change__${f.schema_oid}__${f.table_oid}"`,async()=>{R()})))})};await S();let R=C(async({offset:i,limit:s}={})=>{if(!t&&(i!==void 0||s!==void 0))throw new Error("offset and limit cannot be provided for non-windowed queries");if(i&&(typeof i!="number"||isNaN(i))||s&&(typeof s!="number"||isNaN(s)))throw new Error("offset and limit must be numbers");c=i??c,_=s??_;let u=async(f=0)=>{if(d.length!==0){try{t?v={...await E.query(`EXECUTE live_query_${o}_get(${_}, ${c});`),offset:c,limit:_,totalCount:T}:v=await E.query(`EXECUTE live_query_${o}_get;`)}catch(l){let n=l.message;if(n.startsWith(`prepared statement "live_query_${o}`)&&n.endsWith("does not exist")){if(f>M)throw l;await S(),u(f+1)}else throw l}if(N(d,v),t){let l=(await E.query(`EXECUTE live_query_${o}_get_total_count;`)).rows[0].count;l!==T&&(T=l,R())}}};await u()}),w=i=>{if(A)throw new Error("Live query is no longer active and cannot be subscribed to");d.push(i)},r=async i=>{i?d=d.filter(s=>s!==i):d=[],d.length===0&&!A&&(A=!0,await E.transaction(async s=>{await Promise.all(h.map(u=>u(s))),await s.exec(`
DROP VIEW IF EXISTS live_query_${o}_view;
DEALLOCATE live_query_${o}_get;
`)}))};return m?.aborted?await r():m?.addEventListener("abort",()=>{r()},{once:!0}),N(d,v),{initialResults:v,subscribe:h,unsubscribe:r,refresh:R}},async changes(e,$,a,m){let c;if(typeof e!="string"&&(c=e.signal,$=e.params,a=e.key,m=e.callback,e=e.query),!a)throw new Error("key is required for changes queries");let _=m?[m]:[],t=I.uuid().replace(/-/g,""),T=!1,d=1,o,A,v=async()=>{await E.transaction(async r=>{let i=await O(E,e,$,r);await r.query(`CREATE OR REPLACE TEMP VIEW live_query_${t}_view AS ${i}`);let n=await q(r,`live_query_${t}_view`);await F(r,n,p);let u=[...(await r.query(`
`)}))};return m?.aborted?await r():m?.addEventListener("abort",()=>{r()},{once:!0}),N(d,v),{initialResults:v,subscribe:w,unsubscribe:r,refresh:R}},async changes(e,$,a,m){let c;if(typeof e!="string"&&(c=e.signal,$=e.params,a=e.key,m=e.callback,e=e.query),!a)throw new Error("key is required for changes queries");let _=m?[m]:[],t=I.uuid().replace(/-/g,""),T=!1,d=1,o,A,v=async()=>{await E.transaction(async r=>{let i=await O(E,e,$,r);await r.query(`CREATE OR REPLACE TEMP VIEW live_query_${t}_view AS ${i}`);let s=await q(r,`live_query_${t}_view`);await F(r,s,p);let u=[...(await r.query(`
SELECT column_name, data_type, udt_name

@@ -31,3 +31,3 @@ FROM information_schema.columns

'INSERT' AS __op__,
${u.map(({column_name:s})=>`curr."${s}" AS "${s}"`).join(`,
${u.map(({column_name:n})=>`curr."${n}" AS "${n}"`).join(`,
`)},

@@ -42,3 +42,3 @@ ARRAY[]::text[] AS __changed_columns__

'DELETE' AS __op__,
${u.map(({column_name:s,data_type:L,udt_name:b})=>s===a?`prev."${s}" AS "${s}"`:`NULL${L==="USER-DEFINED"?`::${b}`:""} AS "${s}"`).join(`,
${u.map(({column_name:n,data_type:L,udt_name:b})=>n===a?`prev."${n}" AS "${n}"`:`NULL${L==="USER-DEFINED"?`::${b}`:""} AS "${n}"`).join(`,
`)},

@@ -53,11 +53,11 @@ ARRAY[]::text[] AS __changed_columns__

'UPDATE' AS __op__,
${u.map(({column_name:s,data_type:L,udt_name:b})=>s===a?`curr."${s}" AS "${s}"`:`CASE
WHEN curr."${s}" IS DISTINCT FROM prev."${s}"
THEN curr."${s}"
${u.map(({column_name:n,data_type:L,udt_name:b})=>n===a?`curr."${n}" AS "${n}"`:`CASE
WHEN curr."${n}" IS DISTINCT FROM prev."${n}"
THEN curr."${n}"
ELSE NULL${L==="USER-DEFINED"?`::${b}`:""}
END AS "${s}"`).join(`,
END AS "${n}"`).join(`,
`)},
ARRAY(SELECT unnest FROM unnest(ARRAY[${u.filter(({column_name:s})=>s!==a).map(({column_name:s})=>`CASE
WHEN curr."${s}" IS DISTINCT FROM prev."${s}"
THEN '${s}'
ARRAY(SELECT unnest FROM unnest(ARRAY[${u.filter(({column_name:n})=>n!==a).map(({column_name:n})=>`CASE
WHEN curr."${n}" IS DISTINCT FROM prev."${n}"
THEN '${n}'
ELSE NULL

@@ -70,8 +70,8 @@ END`).join(", ")}]) WHERE unnest IS NOT NULL) AS __changed_columns__

SELECT * FROM data_diff;
`)}A=await Promise.all(n.map(f=>r.listen(`"table_change__${f.schema_oid}__${f.table_oid}"`,async()=>{w()})))})};await v();let w=C(async()=>{if(_.length===0&&o)return;let r=!1;for(let i=0;i<5;i++)try{await E.transaction(async n=>{await n.exec(`
`)}A=await Promise.all(s.map(f=>r.listen(`"table_change__${f.schema_oid}__${f.table_oid}"`,async()=>{h()})))})};await v();let h=C(async()=>{if(_.length===0&&o)return;let r=!1;for(let i=0;i<5;i++)try{await E.transaction(async s=>{await s.exec(`
INSERT INTO live_query_${t}_state${d}
SELECT * FROM live_query_${t}_view;
`),o=await n.query(`EXECUTE live_query_${t}_diff${d};`),d=d===1?2:1,await n.exec(`
`),o=await s.query(`EXECUTE live_query_${t}_diff${d};`),d=d===1?2:1,await s.exec(`
TRUNCATE live_query_${t}_state${d};
`)});break}catch(n){if(n.message===`relation "live_query_${t}_state${d}" does not exist`){r=!0,await v();continue}else throw n}D(_,[...r?[{__op__:"RESET"}]:[],...o.rows])}),S=r=>{if(T)throw new Error("Live query is no longer active and cannot be subscribed to");_.push(r)},R=async r=>{r?_=_.filter(i=>i!==i):_=[],_.length===0&&!T&&(T=!0,await E.transaction(async i=>{await Promise.all(A.map(n=>n(i))),await i.exec(`
`)});break}catch(s){if(s.message===`relation "live_query_${t}_state${d}" does not exist`){r=!0,await v();continue}else throw s}D(_,[...r?[{__op__:"RESET"}]:[],...o.rows])}),S=r=>{if(T)throw new Error("Live query is no longer active and cannot be subscribed to");_.push(r)},R=async r=>{r?_=_.filter(i=>i!==r):_=[],_.length===0&&!T&&(T=!0,await E.transaction(async i=>{await Promise.all(A.map(s=>s(i))),await i.exec(`
DROP VIEW IF EXISTS live_query_${t}_view;

@@ -82,3 +82,3 @@ DROP TABLE IF EXISTS live_query_${t}_state1;

DEALLOCATE live_query_${t}_diff2;
`)}))};return c?.aborted?await R():c?.addEventListener("abort",()=>{R()},{once:!0}),await w(),{fields:o.fields.filter(r=>!["__after__","__op__","__changed_columns__"].includes(r.name)),initialChanges:o.rows,subscribe:S,unsubscribe:R,refresh:w}},async incrementalQuery(e,$,a,m){let c;if(typeof e!="string"&&(c=e.signal,$=e.params,a=e.key,m=e.callback,e=e.query),!a)throw new Error("key is required for incremental queries");let _=m?[m]:[],t=new Map,T=new Map,d=[],o=!0,{fields:A,unsubscribe:v,refresh:w}=await g.changes(e,$,a,h=>{for(let n of h){let{__op__:u,__changed_columns__:f,...l}=n;switch(u){case"RESET":t.clear(),T.clear();break;case"INSERT":t.set(l[a],l),T.set(l.__after__,l[a]);break;case"DELETE":{let s=t.get(l[a]);t.delete(l[a]),s.__after__!==null&&T.delete(s.__after__);break}case"UPDATE":{let s={...t.get(l[a])??{}};for(let L of f)s[L]=l[L],L==="__after__"&&T.set(l.__after__,l[a]);t.set(l[a],s);break}}}let r=[],i=null;for(let n=0;n<t.size;n++){let u=T.get(i),f=t.get(u);if(!f)break;let l={...f};delete l.__after__,r.push(l),i=u}d=r,o||N(_,{rows:r,fields:A})});o=!1,N(_,{rows:d,fields:A});let S=h=>{_.push(h)},R=async h=>{h?_=_.filter(r=>r!==r):_=[],_.length===0&&await v()};return c?.aborted?await R():c?.addEventListener("abort",()=>{R()},{once:!0}),{initialResults:{rows:d,fields:A},subscribe:S,unsubscribe:R,refresh:w}}};return{namespaceObj:g}},Q={name:"Live Queries",setup:U};async function q(E,y){return(await E.query(`
`)}))};return c?.aborted?await R():c?.addEventListener("abort",()=>{R()},{once:!0}),await h(),{fields:o.fields.filter(r=>!["__after__","__op__","__changed_columns__"].includes(r.name)),initialChanges:o.rows,subscribe:S,unsubscribe:R,refresh:h}},async incrementalQuery(e,$,a,m){let c;if(typeof e!="string"&&(c=e.signal,$=e.params,a=e.key,m=e.callback,e=e.query),!a)throw new Error("key is required for incremental queries");let _=m?[m]:[],t=new Map,T=new Map,d=[],o=!0,{fields:A,unsubscribe:v,refresh:h}=await g.changes(e,$,a,w=>{for(let s of w){let{__op__:u,__changed_columns__:f,...l}=s;switch(u){case"RESET":t.clear(),T.clear();break;case"INSERT":t.set(l[a],l),T.set(l.__after__,l[a]);break;case"DELETE":{let n=t.get(l[a]);t.delete(l[a]),n.__after__!==null&&T.delete(n.__after__);break}case"UPDATE":{let n={...t.get(l[a])??{}};for(let L of f)n[L]=l[L],L==="__after__"&&T.set(l.__after__,l[a]);t.set(l[a],n);break}}}let r=[],i=null;for(let s=0;s<t.size;s++){let u=T.get(i),f=t.get(u);if(!f)break;let l={...f};delete l.__after__,r.push(l),i=u}d=r,o||N(_,{rows:r,fields:A})});o=!1,N(_,{rows:d,fields:A});let S=w=>{_.push(w)},R=async w=>{w?_=_.filter(r=>r!==w):_=[],_.length===0&&await v()};return c?.aborted?await R():c?.addEventListener("abort",()=>{R()},{once:!0}),{initialResults:{rows:d,fields:A},subscribe:S,unsubscribe:R,refresh:h}}};return{namespaceObj:g}},Q={name:"Live Queries",setup:U};async function q(E,y){return(await E.query(`
WITH RECURSIVE view_dependencies AS (

@@ -85,0 +85,0 @@ -- Base case: Get the initial view's dependencies

@@ -1,1 +0,1 @@

{"version":3,"sources":["../../src/live/index.ts"],"sourcesContent":["import type {\n Extension,\n PGliteInterface,\n Results,\n Transaction,\n} from '../interface'\nimport type {\n LiveQueryOptions,\n LiveIncrementalQueryOptions,\n LiveChangesOptions,\n LiveNamespace,\n LiveQuery,\n LiveChanges,\n Change,\n LiveQueryResults,\n} from './interface'\nimport { formatQuery, debounceMutex } from '../utils.js'\nimport { pglUtils } from '@electric-sql/pglite-utils'\n\nexport type {\n LiveNamespace,\n LiveQuery,\n LiveChanges,\n Change,\n LiveQueryResults,\n} from './interface.js'\n\nconst MAX_RETRIES = 5\n\nconst setup = async (pg: PGliteInterface, _emscriptenOpts: any) => {\n // The notify triggers are only ever added and never removed\n // Keep track of which triggers have been added to avoid adding them multiple times\n const tableNotifyTriggersAdded = new Set<string>()\n\n const namespaceObj: LiveNamespace = {\n async query<T>(\n query: string | LiveQueryOptions<T>,\n params?: any[] | null,\n callback?: (results: Results<T>) => void,\n ) {\n let signal: AbortSignal | undefined\n let offset: number | undefined\n let limit: number | undefined\n if (typeof query !== 'string') {\n signal = query.signal\n params = query.params\n callback = query.callback\n offset = query.offset\n limit = query.limit\n query = query.query\n }\n\n // Offset and limit must be provided together\n if ((offset === undefined) !== (limit === undefined)) {\n throw new Error('offset and limit must be provided together')\n }\n\n const isWindowed = offset !== undefined && limit !== undefined\n let totalCount: number | undefined = undefined\n\n if (\n isWindowed &&\n (typeof offset !== 'number' ||\n isNaN(offset) ||\n typeof limit !== 'number' ||\n isNaN(limit))\n ) {\n throw new Error('offset and limit must be numbers')\n }\n\n let callbacks: Array<(results: Results<T>) => void> = callback\n ? [callback]\n : []\n const id = pglUtils.uuid().replace(/-/g, '')\n let dead = false\n\n let results: LiveQueryResults<T>\n\n let unsubList: Array<(tx?: Transaction) => Promise<void>>\n const init = async () => {\n await pg.transaction(async (tx) => {\n // Create a temporary view with the query\n const formattedQuery =\n params && params.length > 0\n ? await formatQuery(pg, query, params, tx)\n : query\n await tx.exec(\n `CREATE OR REPLACE TEMP VIEW live_query_${id}_view AS ${formattedQuery}`,\n )\n\n // Get the tables used in the view and add triggers to notify when they change\n const tables = await getTablesForView(tx, `live_query_${id}_view`)\n await addNotifyTriggersToTables(tx, tables, tableNotifyTriggersAdded)\n\n if (isWindowed) {\n await tx.exec(`\n PREPARE live_query_${id}_get(int, int) AS\n SELECT * FROM live_query_${id}_view\n LIMIT $1 OFFSET $2;\n `)\n await tx.exec(`\n PREPARE live_query_${id}_get_total_count AS\n SELECT COUNT(*) FROM live_query_${id}_view;\n `)\n totalCount = (\n await tx.query<{ count: number }>(\n `EXECUTE live_query_${id}_get_total_count;`,\n )\n ).rows[0].count\n results = {\n ...(await tx.query<T>(\n `EXECUTE live_query_${id}_get(${limit}, ${offset});`,\n )),\n offset,\n limit,\n totalCount,\n }\n } else {\n await tx.exec(`\n PREPARE live_query_${id}_get AS\n SELECT * FROM live_query_${id}_view;\n `)\n results = await tx.query<T>(`EXECUTE live_query_${id}_get;`)\n }\n // Setup the listeners\n unsubList = await Promise.all(\n tables!.map((table) =>\n tx.listen(\n `\"table_change__${table.schema_oid}__${table.table_oid}\"`,\n async () => {\n refresh()\n },\n ),\n ),\n )\n })\n }\n await init()\n\n // Function to refresh the query\n const refresh = debounceMutex(\n async ({\n offset: newOffset,\n limit: newLimit,\n }: {\n offset?: number\n limit?: number\n } = {}) => {\n // We can optionally provide new offset and limit values to refresh with\n if (\n !isWindowed &&\n (newOffset !== undefined || newLimit !== undefined)\n ) {\n throw new Error(\n 'offset and limit cannot be provided for non-windowed queries',\n )\n }\n if (\n (newOffset &&\n (typeof newOffset !== 'number' || isNaN(newOffset))) ||\n (newLimit && (typeof newLimit !== 'number' || isNaN(newLimit)))\n ) {\n throw new Error('offset and limit must be numbers')\n }\n offset = newOffset ?? offset\n limit = newLimit ?? limit\n\n const run = async (count = 0) => {\n if (callbacks.length === 0) {\n return\n }\n try {\n if (isWindowed) {\n // For a windowed query we defer the refresh of the total count until\n // after we have returned the results with the old total count. This\n // is due to a count(*) being a fairly slow query and we want to update\n // the rows on screen as quickly as possible.\n results = {\n ...(await pg.query<T>(\n `EXECUTE live_query_${id}_get(${limit}, ${offset});`,\n )),\n offset,\n limit,\n totalCount, // This is the old total count\n }\n } else {\n results = await pg.query<T>(`EXECUTE live_query_${id}_get;`)\n }\n } catch (e) {\n const msg = (e as Error).message\n if (\n msg.startsWith(`prepared statement \"live_query_${id}`) &&\n msg.endsWith('does not exist')\n ) {\n // If the prepared statement does not exist, reset and try again\n // This can happen if using the multi-tab worker\n if (count > MAX_RETRIES) {\n throw e\n }\n await init()\n run(count + 1)\n } else {\n throw e\n }\n }\n\n runResultCallbacks(callbacks, results)\n\n // Update the total count\n // If the total count has changed, refresh the query\n if (isWindowed) {\n const newTotalCount = (\n await pg.query<{ count: number }>(\n `EXECUTE live_query_${id}_get_total_count;`,\n )\n ).rows[0].count\n if (newTotalCount !== totalCount) {\n // The total count has changed, refresh the query\n totalCount = newTotalCount\n refresh()\n }\n }\n }\n await run()\n },\n )\n\n // Function to subscribe to the query\n const subscribe = (callback: (results: Results<T>) => void) => {\n if (dead) {\n throw new Error(\n 'Live query is no longer active and cannot be subscribed to',\n )\n }\n callbacks.push(callback)\n }\n\n // Function to unsubscribe from the query\n // If no function is provided, unsubscribe all callbacks\n // If there are no callbacks, unsubscribe from the notify triggers\n const unsubscribe = async (callback?: (results: Results<T>) => void) => {\n if (callback) {\n callbacks = callbacks.filter((callback) => callback !== callback)\n } else {\n callbacks = []\n }\n if (callbacks.length === 0 && !dead) {\n dead = true\n await pg.transaction(async (tx) => {\n await Promise.all(unsubList.map((unsub) => unsub(tx)))\n await tx.exec(`\n DROP VIEW IF EXISTS live_query_${id}_view;\n DEALLOCATE live_query_${id}_get;\n `)\n })\n }\n }\n\n // If the signal has already been aborted, unsubscribe\n if (signal?.aborted) {\n await unsubscribe()\n } else {\n // Add an event listener to unsubscribe if the signal is aborted\n signal?.addEventListener(\n 'abort',\n () => {\n unsubscribe()\n },\n { once: true },\n )\n }\n\n // Run the callback with the initial results\n runResultCallbacks(callbacks, results!)\n\n // Return the initial results\n return {\n initialResults: results!,\n subscribe,\n unsubscribe,\n refresh,\n } satisfies LiveQuery<T>\n },\n\n async changes<T>(\n query: string | LiveChangesOptions<T>,\n params?: any[] | null,\n key?: string,\n callback?: (changes: Array<Change<T>>) => void,\n ) {\n let signal: AbortSignal | undefined\n if (typeof query !== 'string') {\n signal = query.signal\n params = query.params\n key = query.key\n callback = query.callback\n query = query.query\n }\n if (!key) {\n throw new Error('key is required for changes queries')\n }\n let callbacks: Array<(changes: Array<Change<T>>) => void> = callback\n ? [callback]\n : []\n const id = pglUtils.uuid().replace(/-/g, '')\n let dead = false\n\n let stateSwitch: 1 | 2 = 1\n let changes: Results<Change<T>>\n\n let unsubList: Array<(tx?: Transaction) => Promise<void>>\n\n const init = async () => {\n await pg.transaction(async (tx) => {\n // Create a temporary view with the query\n const formattedQuery = await formatQuery(pg, query, params, tx)\n await tx.query(\n `CREATE OR REPLACE TEMP VIEW live_query_${id}_view AS ${formattedQuery}`,\n )\n\n // Get the tables used in the view and add triggers to notify when they change\n const tables = await getTablesForView(tx, `live_query_${id}_view`)\n await addNotifyTriggersToTables(tx, tables, tableNotifyTriggersAdded)\n\n // Get the columns of the view\n const columns = [\n ...(\n await tx.query<any>(`\n SELECT column_name, data_type, udt_name\n FROM information_schema.columns \n WHERE table_name = 'live_query_${id}_view'\n `)\n ).rows,\n { column_name: '__after__', data_type: 'integer' },\n ]\n\n // Init state tables as empty temp table\n await tx.exec(`\n CREATE TEMP TABLE live_query_${id}_state1 (LIKE live_query_${id}_view INCLUDING ALL);\n CREATE TEMP TABLE live_query_${id}_state2 (LIKE live_query_${id}_view INCLUDING ALL);\n `)\n\n // Create Diff views and prepared statements\n for (const curr of [1, 2]) {\n const prev = curr === 1 ? 2 : 1\n await tx.exec(`\n PREPARE live_query_${id}_diff${curr} AS\n WITH\n prev AS (SELECT LAG(\"${key}\") OVER () as __after__, * FROM live_query_${id}_state${prev}),\n curr AS (SELECT LAG(\"${key}\") OVER () as __after__, * FROM live_query_${id}_state${curr}),\n data_diff AS (\n -- INSERT operations: Include all columns\n SELECT \n 'INSERT' AS __op__,\n ${columns\n .map(\n ({ column_name }) =>\n `curr.\"${column_name}\" AS \"${column_name}\"`,\n )\n .join(',\\n')},\n ARRAY[]::text[] AS __changed_columns__\n FROM curr\n LEFT JOIN prev ON curr.${key} = prev.${key}\n WHERE prev.${key} IS NULL\n UNION ALL\n -- DELETE operations: Include only the primary key\n SELECT \n 'DELETE' AS __op__,\n ${columns\n .map(({ column_name, data_type, udt_name }) => {\n if (column_name === key) {\n return `prev.\"${column_name}\" AS \"${column_name}\"`\n } else {\n return `NULL${data_type === 'USER-DEFINED' ? `::${udt_name}` : ``} AS \"${column_name}\"`\n }\n })\n .join(',\\n')},\n ARRAY[]::text[] AS __changed_columns__\n FROM prev\n LEFT JOIN curr ON prev.${key} = curr.${key}\n WHERE curr.${key} IS NULL\n UNION ALL\n -- UPDATE operations: Include only changed columns\n SELECT \n 'UPDATE' AS __op__,\n ${columns\n .map(({ column_name, data_type, udt_name }) =>\n column_name === key\n ? `curr.\"${column_name}\" AS \"${column_name}\"`\n : `CASE \n WHEN curr.\"${column_name}\" IS DISTINCT FROM prev.\"${column_name}\" \n THEN curr.\"${column_name}\"\n ELSE NULL${data_type === 'USER-DEFINED' ? `::${udt_name}` : ``}\n END AS \"${column_name}\"`,\n )\n .join(',\\n')},\n ARRAY(SELECT unnest FROM unnest(ARRAY[${columns\n .filter(({ column_name }) => column_name !== key)\n .map(\n ({ column_name }) =>\n `CASE\n WHEN curr.\"${column_name}\" IS DISTINCT FROM prev.\"${column_name}\" \n THEN '${column_name}' \n ELSE NULL \n END`,\n )\n .join(\n ', ',\n )}]) WHERE unnest IS NOT NULL) AS __changed_columns__\n FROM curr\n INNER JOIN prev ON curr.${key} = prev.${key}\n WHERE NOT (curr IS NOT DISTINCT FROM prev)\n )\n SELECT * FROM data_diff;\n `)\n }\n\n // Setup the listeners\n unsubList = await Promise.all(\n tables!.map((table) =>\n tx.listen(\n `\"table_change__${table.schema_oid}__${table.table_oid}\"`,\n async () => {\n refresh()\n },\n ),\n ),\n )\n })\n }\n\n await init()\n\n const refresh = debounceMutex(async () => {\n if (callbacks.length === 0 && changes) {\n return\n }\n let reset = false\n for (let i = 0; i < 5; i++) {\n try {\n await pg.transaction(async (tx) => {\n // Populate the state table\n await tx.exec(`\n INSERT INTO live_query_${id}_state${stateSwitch} \n SELECT * FROM live_query_${id}_view;\n `)\n\n // Get the changes\n changes = await tx.query<any>(\n `EXECUTE live_query_${id}_diff${stateSwitch};`,\n )\n\n // Switch state\n stateSwitch = stateSwitch === 1 ? 2 : 1\n\n // Truncate the old state table\n await tx.exec(`\n TRUNCATE live_query_${id}_state${stateSwitch};\n `)\n })\n break\n } catch (e) {\n const msg = (e as Error).message\n if (\n msg ===\n `relation \"live_query_${id}_state${stateSwitch}\" does not exist`\n ) {\n // If the state table does not exist, reset and try again\n // This can happen if using the multi-tab worker\n reset = true\n await init()\n continue\n } else {\n throw e\n }\n }\n }\n\n runChangeCallbacks(callbacks, [\n ...(reset\n ? [\n {\n __op__: 'RESET' as const,\n },\n ]\n : []),\n ...changes!.rows,\n ])\n })\n\n // Function to subscribe to the query\n const subscribe = (callback: (changes: Array<Change<T>>) => void) => {\n if (dead) {\n throw new Error(\n 'Live query is no longer active and cannot be subscribed to',\n )\n }\n callbacks.push(callback)\n }\n\n // Function to unsubscribe from the query\n const unsubscribe = async (\n callback?: (changes: Array<Change<T>>) => void,\n ) => {\n if (callback) {\n callbacks = callbacks.filter((callback) => callback !== callback)\n } else {\n callbacks = []\n }\n if (callbacks.length === 0 && !dead) {\n dead = true\n await pg.transaction(async (tx) => {\n await Promise.all(unsubList.map((unsub) => unsub(tx)))\n await tx.exec(`\n DROP VIEW IF EXISTS live_query_${id}_view;\n DROP TABLE IF EXISTS live_query_${id}_state1;\n DROP TABLE IF EXISTS live_query_${id}_state2;\n DEALLOCATE live_query_${id}_diff1;\n DEALLOCATE live_query_${id}_diff2;\n `)\n })\n }\n }\n\n // If the signal has already been aborted, unsubscribe\n if (signal?.aborted) {\n await unsubscribe()\n } else {\n // Add an event listener to unsubscribe if the signal is aborted\n signal?.addEventListener(\n 'abort',\n () => {\n unsubscribe()\n },\n { once: true },\n )\n }\n\n // Run the callback with the initial changes\n await refresh()\n\n // Fields\n const fields = changes!.fields.filter(\n (field) =>\n !['__after__', '__op__', '__changed_columns__'].includes(field.name),\n )\n\n // Return the initial results\n return {\n fields,\n initialChanges: changes!.rows,\n subscribe,\n unsubscribe,\n refresh,\n } satisfies LiveChanges<T>\n },\n\n async incrementalQuery<T>(\n query: string | LiveIncrementalQueryOptions<T>,\n params?: any[] | null,\n key?: string,\n callback?: (results: Results<T>) => void,\n ) {\n let signal: AbortSignal | undefined\n if (typeof query !== 'string') {\n signal = query.signal\n params = query.params\n key = query.key\n callback = query.callback\n query = query.query\n }\n if (!key) {\n throw new Error('key is required for incremental queries')\n }\n let callbacks: Array<(results: Results<T>) => void> = callback\n ? [callback]\n : []\n const rowsMap: Map<any, any> = new Map()\n const afterMap: Map<any, any> = new Map()\n let lastRows: T[] = []\n let firstRun = true\n\n const {\n fields,\n unsubscribe: unsubscribeChanges,\n refresh,\n } = await namespaceObj.changes<T>(query, params, key, (changes) => {\n // Process the changes\n for (const change of changes) {\n const {\n __op__: op,\n __changed_columns__: changedColumns,\n ...obj\n } = change as typeof change & { [key: string]: any }\n switch (op) {\n case 'RESET':\n rowsMap.clear()\n afterMap.clear()\n break\n case 'INSERT':\n rowsMap.set(obj[key], obj)\n afterMap.set(obj.__after__, obj[key])\n break\n case 'DELETE': {\n const oldObj = rowsMap.get(obj[key])\n rowsMap.delete(obj[key])\n // null is the starting point, we don't delete it as another insert\n // may have happened thats replacing it\n if (oldObj.__after__ !== null) {\n afterMap.delete(oldObj.__after__)\n }\n break\n }\n case 'UPDATE': {\n const newObj = { ...(rowsMap.get(obj[key]) ?? {}) }\n for (const columnName of changedColumns) {\n newObj[columnName] = obj[columnName]\n if (columnName === '__after__') {\n afterMap.set(obj.__after__, obj[key])\n }\n }\n rowsMap.set(obj[key], newObj)\n break\n }\n }\n }\n\n // Get the rows in order\n const rows: T[] = []\n let lastKey: any = null\n for (let i = 0; i < rowsMap.size; i++) {\n const nextKey = afterMap.get(lastKey)\n const obj = rowsMap.get(nextKey)\n if (!obj) {\n break\n }\n // Remove the __after__ key from the exposed row\n const cleanObj = { ...obj }\n delete cleanObj.__after__\n rows.push(cleanObj)\n lastKey = nextKey\n }\n lastRows = rows\n\n // Run the callbacks\n if (!firstRun) {\n runResultCallbacks(callbacks, {\n rows,\n fields,\n })\n }\n })\n\n firstRun = false\n runResultCallbacks(callbacks, {\n rows: lastRows,\n fields,\n })\n\n const subscribe = (callback: (results: Results<T>) => void) => {\n callbacks.push(callback)\n }\n\n const unsubscribe = async (callback?: (results: Results<T>) => void) => {\n if (callback) {\n callbacks = callbacks.filter((callback) => callback !== callback)\n } else {\n callbacks = []\n }\n if (callbacks.length === 0) {\n await unsubscribeChanges()\n }\n }\n\n if (signal?.aborted) {\n await unsubscribe()\n } else {\n signal?.addEventListener(\n 'abort',\n () => {\n unsubscribe()\n },\n { once: true },\n )\n }\n\n return {\n initialResults: {\n rows: lastRows,\n fields,\n },\n subscribe,\n unsubscribe,\n refresh,\n } satisfies LiveQuery<T>\n },\n }\n\n return {\n namespaceObj,\n }\n}\n\nexport const live = {\n name: 'Live Queries',\n setup,\n} satisfies Extension\n\nexport type PGliteWithLive = PGliteInterface & {\n live: LiveNamespace\n}\n\n/**\n * Get a list of all the tables used in a view, recursively\n * @param tx a transaction or PGlite instance\n * @param viewName the name of the view\n * @returns list of tables used in the view\n */\nasync function getTablesForView(\n tx: Transaction | PGliteInterface,\n viewName: string,\n): Promise<\n {\n table_name: string\n schema_name: string\n table_oid: number\n schema_oid: number\n }[]\n> {\n const result = await tx.query<{\n table_name: string\n schema_name: string\n table_oid: number\n schema_oid: number\n }>(\n `\n WITH RECURSIVE view_dependencies AS (\n -- Base case: Get the initial view's dependencies\n SELECT DISTINCT\n cl.relname AS dependent_name,\n n.nspname AS schema_name,\n cl.oid AS dependent_oid,\n n.oid AS schema_oid,\n cl.relkind = 'v' AS is_view\n FROM pg_rewrite r\n JOIN pg_depend d ON r.oid = d.objid\n JOIN pg_class cl ON d.refobjid = cl.oid\n JOIN pg_namespace n ON cl.relnamespace = n.oid\n WHERE\n r.ev_class = (\n SELECT oid FROM pg_class WHERE relname = $1 AND relkind = 'v'\n )\n AND d.deptype = 'n'\n\n UNION ALL\n\n -- Recursive case: Traverse dependencies for views\n SELECT DISTINCT\n cl.relname AS dependent_name,\n n.nspname AS schema_name,\n cl.oid AS dependent_oid,\n n.oid AS schema_oid,\n cl.relkind = 'v' AS is_view\n FROM view_dependencies vd\n JOIN pg_rewrite r ON vd.dependent_name = (\n SELECT relname FROM pg_class WHERE oid = r.ev_class AND relkind = 'v'\n )\n JOIN pg_depend d ON r.oid = d.objid\n JOIN pg_class cl ON d.refobjid = cl.oid\n JOIN pg_namespace n ON cl.relnamespace = n.oid\n WHERE d.deptype = 'n'\n )\n SELECT DISTINCT\n dependent_name AS table_name,\n schema_name,\n dependent_oid AS table_oid,\n schema_oid\n FROM view_dependencies\n WHERE NOT is_view; -- Exclude intermediate views\n `,\n [viewName],\n )\n\n return result.rows.map((row) => ({\n table_name: row.table_name,\n schema_name: row.schema_name,\n table_oid: row.table_oid,\n schema_oid: row.schema_oid,\n }))\n}\n\n/**\n * Add triggers to tables to notify when they change\n * @param tx a transaction or PGlite instance\n * @param tables list of tables to add triggers to\n */\nasync function addNotifyTriggersToTables(\n tx: Transaction | PGliteInterface,\n tables: {\n table_name: string\n table_oid: number\n schema_name: string\n schema_oid: number\n }[],\n tableNotifyTriggersAdded: Set<string>,\n) {\n const triggers = tables\n .filter(\n (table) =>\n !tableNotifyTriggersAdded.has(`${table.schema_oid}_${table.table_oid}`),\n )\n .map((table) => {\n return `\n CREATE OR REPLACE FUNCTION \"_notify_${table.schema_oid}_${table.table_oid}\"() RETURNS TRIGGER AS $$\n BEGIN\n PERFORM pg_notify('table_change__${table.schema_oid}__${table.table_oid}', '');\n RETURN NULL;\n END;\n $$ LANGUAGE plpgsql;\n CREATE OR REPLACE TRIGGER \"_notify_trigger_${table.schema_oid}_${table.table_oid}\"\n AFTER INSERT OR UPDATE OR DELETE ON \"${table.schema_name}\".\"${table.table_name}\"\n FOR EACH STATEMENT EXECUTE FUNCTION \"_notify_${table.schema_oid}_${table.table_oid}\"();\n `\n })\n .join('\\n')\n if (triggers.trim() !== '') {\n await tx.exec(triggers)\n }\n tables.map((table) =>\n tableNotifyTriggersAdded.add(`${table.schema_oid}_${table.table_oid}`),\n )\n}\n\nconst runResultCallbacks = <T>(\n callbacks: Array<(results: Results<T>) => void>,\n results: Results<T>,\n) => {\n for (const callback of callbacks) {\n callback(results)\n }\n}\n\nconst runChangeCallbacks = <T>(\n callbacks: Array<(changes: Array<Change<T>>) => void>,\n changes: Array<Change<T>>,\n) => {\n for (const callback of callbacks) {\n callback(changes)\n }\n}\n"],"mappings":"+JAAAA,IA2BA,IAAMC,EAAc,EAEdC,EAAQ,MAAOC,EAAqBC,IAAyB,CAGjE,IAAMC,EAA2B,IAAI,IAE/BC,EAA8B,CAClC,MAAM,MACJC,EACAC,EACAC,EACA,CACA,IAAIC,EACAC,EACAC,EAWJ,GAVI,OAAOL,GAAU,WACnBG,EAASH,EAAM,OACfC,EAASD,EAAM,OACfE,EAAWF,EAAM,SACjBI,EAASJ,EAAM,OACfK,EAAQL,EAAM,MACdA,EAAQA,EAAM,OAIXI,IAAW,SAAgBC,IAAU,QACxC,MAAM,IAAI,MAAM,4CAA4C,EAG9D,IAAMC,EAAaF,IAAW,QAAaC,IAAU,OACjDE,EAEJ,GACED,IACC,OAAOF,GAAW,UACjB,MAAMA,CAAM,GACZ,OAAOC,GAAU,UACjB,MAAMA,CAAK,GAEb,MAAM,IAAI,MAAM,kCAAkC,EAGpD,IAAIG,EAAkDN,EAClD,CAACA,CAAQ,EACT,CAAC,EACCO,EAAKC,EAAS,KAAK,EAAE,QAAQ,KAAM,EAAE,EACvCC,EAAO,GAEPC,EAEAC,EACEC,EAAO,SAAY,CACvB,MAAMlB,EAAG,YAAY,MAAOmB,GAAO,CAEjC,IAAMC,EACJf,GAAUA,EAAO,OAAS,EACtB,MAAMgB,EAAYrB,EAAII,EAAOC,EAAQc,CAAE,EACvCf,EACN,MAAMe,EAAG,KACP,0CAA0CN,C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AKG,GACVvB,EAAyB,IAAI,GAAGuB,EAAM,UAAU,IAAIA,EAAM,SAAS,EAAE,CACvE,CACF,CAEA,IAAMS,EAAqB,CACzBtB,EACAI,IACG,CACH,QAAWV,KAAYM,EACrBN,EAASU,CAAO,CAEpB,EAEMiC,EAAqB,CACzBrC,EACA6B,IACG,CACH,QAAWnC,KAAYM,EACrBN,EAASmC,CAAO,CAEpB","names":["init_esm_shims","MAX_RETRIES","setup","pg","_emscriptenOpts","tableNotifyTriggersAdded","namespaceObj","query","params","callback","signal","offset","limit","isWindowed","totalCount","callbacks","id","f","dead","results","unsubList","init","tx","formattedQuery","formatQuery","tables","getTablesForView","addNotifyTriggersToTables","table","refresh","debounceMutex","newOffset","newLimit","run","count","e","msg","runResultCallbacks","newTotalCount","subscribe","unsubscribe","unsub","key","stateSwitch","changes","columns","curr","prev","column_name","data_type","udt_name","reset","runChangeCallbacks","field","rowsMap","afterMap","lastRows","firstRun","fields","unsubscribeChanges","change","op","changedColumns","obj","oldObj","newObj","columnName","rows","lastKey","i","nextKey","cleanObj","live","viewName","row","triggers"]}
{"version":3,"sources":["../../src/live/index.ts"],"sourcesContent":["import type {\n Extension,\n PGliteInterface,\n Results,\n Transaction,\n} from '../interface'\nimport type {\n LiveQueryOptions,\n LiveIncrementalQueryOptions,\n LiveChangesOptions,\n LiveNamespace,\n LiveQuery,\n LiveChanges,\n Change,\n LiveQueryResults,\n} from './interface'\nimport { formatQuery, debounceMutex } from '../utils.js'\nimport { pglUtils } from '@electric-sql/pglite-utils'\n\nexport type {\n LiveNamespace,\n LiveQuery,\n LiveChanges,\n Change,\n LiveQueryResults,\n} from './interface.js'\n\nconst MAX_RETRIES = 5\n\nconst setup = async (pg: PGliteInterface, _emscriptenOpts: any) => {\n // The notify triggers are only ever added and never removed\n // Keep track of which triggers have been added to avoid adding them multiple times\n const tableNotifyTriggersAdded = new Set<string>()\n\n const namespaceObj: LiveNamespace = {\n async query<T>(\n query: string | LiveQueryOptions<T>,\n params?: any[] | null,\n callback?: (results: Results<T>) => void,\n ) {\n let signal: AbortSignal | undefined\n let offset: number | undefined\n let limit: number | undefined\n if (typeof query !== 'string') {\n signal = query.signal\n params = query.params\n callback = query.callback\n offset = query.offset\n limit = query.limit\n query = query.query\n }\n\n // Offset and limit must be provided together\n if ((offset === undefined) !== (limit === undefined)) {\n throw new Error('offset and limit must be provided together')\n }\n\n const isWindowed = offset !== undefined && limit !== undefined\n let totalCount: number | undefined = undefined\n\n if (\n isWindowed &&\n (typeof offset !== 'number' ||\n isNaN(offset) ||\n typeof limit !== 'number' ||\n isNaN(limit))\n ) {\n throw new Error('offset and limit must be numbers')\n }\n\n let callbacks: Array<(results: Results<T>) => void> = callback\n ? [callback]\n : []\n const id = pglUtils.uuid().replace(/-/g, '')\n let dead = false\n\n let results: LiveQueryResults<T>\n\n let unsubList: Array<(tx?: Transaction) => Promise<void>>\n const init = async () => {\n await pg.transaction(async (tx) => {\n // Create a temporary view with the query\n const formattedQuery =\n params && params.length > 0\n ? await formatQuery(pg, query, params, tx)\n : query\n await tx.exec(\n `CREATE OR REPLACE TEMP VIEW live_query_${id}_view AS ${formattedQuery}`,\n )\n\n // Get the tables used in the view and add triggers to notify when they change\n const tables = await getTablesForView(tx, `live_query_${id}_view`)\n await addNotifyTriggersToTables(tx, tables, tableNotifyTriggersAdded)\n\n if (isWindowed) {\n await tx.exec(`\n PREPARE live_query_${id}_get(int, int) AS\n SELECT * FROM live_query_${id}_view\n LIMIT $1 OFFSET $2;\n `)\n await tx.exec(`\n PREPARE live_query_${id}_get_total_count AS\n SELECT COUNT(*) FROM live_query_${id}_view;\n `)\n totalCount = (\n await tx.query<{ count: number }>(\n `EXECUTE live_query_${id}_get_total_count;`,\n )\n ).rows[0].count\n results = {\n ...(await tx.query<T>(\n `EXECUTE live_query_${id}_get(${limit}, ${offset});`,\n )),\n offset,\n limit,\n totalCount,\n }\n } else {\n await tx.exec(`\n PREPARE live_query_${id}_get AS\n SELECT * FROM live_query_${id}_view;\n `)\n results = await tx.query<T>(`EXECUTE live_query_${id}_get;`)\n }\n // Setup the listeners\n unsubList = await Promise.all(\n tables!.map((table) =>\n tx.listen(\n `\"table_change__${table.schema_oid}__${table.table_oid}\"`,\n async () => {\n refresh()\n },\n ),\n ),\n )\n })\n }\n await init()\n\n // Function to refresh the query\n const refresh = debounceMutex(\n async ({\n offset: newOffset,\n limit: newLimit,\n }: {\n offset?: number\n limit?: number\n } = {}) => {\n // We can optionally provide new offset and limit values to refresh with\n if (\n !isWindowed &&\n (newOffset !== undefined || newLimit !== undefined)\n ) {\n throw new Error(\n 'offset and limit cannot be provided for non-windowed queries',\n )\n }\n if (\n (newOffset &&\n (typeof newOffset !== 'number' || isNaN(newOffset))) ||\n (newLimit && (typeof newLimit !== 'number' || isNaN(newLimit)))\n ) {\n throw new Error('offset and limit must be numbers')\n }\n offset = newOffset ?? offset\n limit = newLimit ?? limit\n\n const run = async (count = 0) => {\n if (callbacks.length === 0) {\n return\n }\n try {\n if (isWindowed) {\n // For a windowed query we defer the refresh of the total count until\n // after we have returned the results with the old total count. This\n // is due to a count(*) being a fairly slow query and we want to update\n // the rows on screen as quickly as possible.\n results = {\n ...(await pg.query<T>(\n `EXECUTE live_query_${id}_get(${limit}, ${offset});`,\n )),\n offset,\n limit,\n totalCount, // This is the old total count\n }\n } else {\n results = await pg.query<T>(`EXECUTE live_query_${id}_get;`)\n }\n } catch (e) {\n const msg = (e as Error).message\n if (\n msg.startsWith(`prepared statement \"live_query_${id}`) &&\n msg.endsWith('does not exist')\n ) {\n // If the prepared statement does not exist, reset and try again\n // This can happen if using the multi-tab worker\n if (count > MAX_RETRIES) {\n throw e\n }\n await init()\n run(count + 1)\n } else {\n throw e\n }\n }\n\n runResultCallbacks(callbacks, results)\n\n // Update the total count\n // If the total count has changed, refresh the query\n if (isWindowed) {\n const newTotalCount = (\n await pg.query<{ count: number }>(\n `EXECUTE live_query_${id}_get_total_count;`,\n )\n ).rows[0].count\n if (newTotalCount !== totalCount) {\n // The total count has changed, refresh the query\n totalCount = newTotalCount\n refresh()\n }\n }\n }\n await run()\n },\n )\n\n // Function to subscribe to the query\n const subscribe = (callback: (results: Results<T>) => void) => {\n if (dead) {\n throw new Error(\n 'Live query is no longer active and cannot be subscribed to',\n )\n }\n callbacks.push(callback)\n }\n\n // Function to unsubscribe from the query\n // If no function is provided, unsubscribe all callbacks\n // If there are no callbacks, unsubscribe from the notify triggers\n const unsubscribe = async (callback?: (results: Results<T>) => void) => {\n if (callback) {\n callbacks = callbacks.filter((cb) => cb !== callback)\n } else {\n callbacks = []\n }\n if (callbacks.length === 0 && !dead) {\n dead = true\n await pg.transaction(async (tx) => {\n await Promise.all(unsubList.map((unsub) => unsub(tx)))\n await tx.exec(`\n DROP VIEW IF EXISTS live_query_${id}_view;\n DEALLOCATE live_query_${id}_get;\n `)\n })\n }\n }\n\n // If the signal has already been aborted, unsubscribe\n if (signal?.aborted) {\n await unsubscribe()\n } else {\n // Add an event listener to unsubscribe if the signal is aborted\n signal?.addEventListener(\n 'abort',\n () => {\n unsubscribe()\n },\n { once: true },\n )\n }\n\n // Run the callback with the initial results\n runResultCallbacks(callbacks, results!)\n\n // Return the initial results\n return {\n initialResults: results!,\n subscribe,\n unsubscribe,\n refresh,\n } satisfies LiveQuery<T>\n },\n\n async changes<T>(\n query: string | LiveChangesOptions<T>,\n params?: any[] | null,\n key?: string,\n callback?: (changes: Array<Change<T>>) => void,\n ) {\n let signal: AbortSignal | undefined\n if (typeof query !== 'string') {\n signal = query.signal\n params = query.params\n key = query.key\n callback = query.callback\n query = query.query\n }\n if (!key) {\n throw new Error('key is required for changes queries')\n }\n let callbacks: Array<(changes: Array<Change<T>>) => void> = callback\n ? [callback]\n : []\n const id = pglUtils.uuid().replace(/-/g, '')\n let dead = false\n\n let stateSwitch: 1 | 2 = 1\n let changes: Results<Change<T>>\n\n let unsubList: Array<(tx?: Transaction) => Promise<void>>\n\n const init = async () => {\n await pg.transaction(async (tx) => {\n // Create a temporary view with the query\n const formattedQuery = await formatQuery(pg, query, params, tx)\n await tx.query(\n `CREATE OR REPLACE TEMP VIEW live_query_${id}_view AS ${formattedQuery}`,\n )\n\n // Get the tables used in the view and add triggers to notify when they change\n const tables = await getTablesForView(tx, `live_query_${id}_view`)\n await addNotifyTriggersToTables(tx, tables, tableNotifyTriggersAdded)\n\n // Get the columns of the view\n const columns = [\n ...(\n await tx.query<any>(`\n SELECT column_name, data_type, udt_name\n FROM information_schema.columns \n WHERE table_name = 'live_query_${id}_view'\n `)\n ).rows,\n { column_name: '__after__', data_type: 'integer' },\n ]\n\n // Init state tables as empty temp table\n await tx.exec(`\n CREATE TEMP TABLE live_query_${id}_state1 (LIKE live_query_${id}_view INCLUDING ALL);\n CREATE TEMP TABLE live_query_${id}_state2 (LIKE live_query_${id}_view INCLUDING ALL);\n `)\n\n // Create Diff views and prepared statements\n for (const curr of [1, 2]) {\n const prev = curr === 1 ? 2 : 1\n await tx.exec(`\n PREPARE live_query_${id}_diff${curr} AS\n WITH\n prev AS (SELECT LAG(\"${key}\") OVER () as __after__, * FROM live_query_${id}_state${prev}),\n curr AS (SELECT LAG(\"${key}\") OVER () as __after__, * FROM live_query_${id}_state${curr}),\n data_diff AS (\n -- INSERT operations: Include all columns\n SELECT \n 'INSERT' AS __op__,\n ${columns\n .map(\n ({ column_name }) =>\n `curr.\"${column_name}\" AS \"${column_name}\"`,\n )\n .join(',\\n')},\n ARRAY[]::text[] AS __changed_columns__\n FROM curr\n LEFT JOIN prev ON curr.${key} = prev.${key}\n WHERE prev.${key} IS NULL\n UNION ALL\n -- DELETE operations: Include only the primary key\n SELECT \n 'DELETE' AS __op__,\n ${columns\n .map(({ column_name, data_type, udt_name }) => {\n if (column_name === key) {\n return `prev.\"${column_name}\" AS \"${column_name}\"`\n } else {\n return `NULL${data_type === 'USER-DEFINED' ? `::${udt_name}` : ``} AS \"${column_name}\"`\n }\n })\n .join(',\\n')},\n ARRAY[]::text[] AS __changed_columns__\n FROM prev\n LEFT JOIN curr ON prev.${key} = curr.${key}\n WHERE curr.${key} IS NULL\n UNION ALL\n -- UPDATE operations: Include only changed columns\n SELECT \n 'UPDATE' AS __op__,\n ${columns\n .map(({ column_name, data_type, udt_name }) =>\n column_name === key\n ? `curr.\"${column_name}\" AS \"${column_name}\"`\n : `CASE \n WHEN curr.\"${column_name}\" IS DISTINCT FROM prev.\"${column_name}\" \n THEN curr.\"${column_name}\"\n ELSE NULL${data_type === 'USER-DEFINED' ? `::${udt_name}` : ``}\n END AS \"${column_name}\"`,\n )\n .join(',\\n')},\n ARRAY(SELECT unnest FROM unnest(ARRAY[${columns\n .filter(({ column_name }) => column_name !== key)\n .map(\n ({ column_name }) =>\n `CASE\n WHEN curr.\"${column_name}\" IS DISTINCT FROM prev.\"${column_name}\" \n THEN '${column_name}' \n ELSE NULL \n END`,\n )\n .join(\n ', ',\n )}]) WHERE unnest IS NOT NULL) AS __changed_columns__\n FROM curr\n INNER JOIN prev ON curr.${key} = prev.${key}\n WHERE NOT (curr IS NOT DISTINCT FROM prev)\n )\n SELECT * FROM data_diff;\n `)\n }\n\n // Setup the listeners\n unsubList = await Promise.all(\n tables!.map((table) =>\n tx.listen(\n `\"table_change__${table.schema_oid}__${table.table_oid}\"`,\n async () => {\n refresh()\n },\n ),\n ),\n )\n })\n }\n\n await init()\n\n const refresh = debounceMutex(async () => {\n if (callbacks.length === 0 && changes) {\n return\n }\n let reset = false\n for (let i = 0; i < 5; i++) {\n try {\n await pg.transaction(async (tx) => {\n // Populate the state table\n await tx.exec(`\n INSERT INTO live_query_${id}_state${stateSwitch} \n SELECT * FROM live_query_${id}_view;\n `)\n\n // Get the changes\n changes = await tx.query<any>(\n `EXECUTE live_query_${id}_diff${stateSwitch};`,\n )\n\n // Switch state\n stateSwitch = stateSwitch === 1 ? 2 : 1\n\n // Truncate the old state table\n await tx.exec(`\n TRUNCATE live_query_${id}_state${stateSwitch};\n `)\n })\n break\n } catch (e) {\n const msg = (e as Error).message\n if (\n msg ===\n `relation \"live_query_${id}_state${stateSwitch}\" does not exist`\n ) {\n // If the state table does not exist, reset and try again\n // This can happen if using the multi-tab worker\n reset = true\n await init()\n continue\n } else {\n throw e\n }\n }\n }\n\n runChangeCallbacks(callbacks, [\n ...(reset\n ? [\n {\n __op__: 'RESET' as const,\n },\n ]\n : []),\n ...changes!.rows,\n ])\n })\n\n // Function to subscribe to the query\n const subscribe = (callback: (changes: Array<Change<T>>) => void) => {\n if (dead) {\n throw new Error(\n 'Live query is no longer active and cannot be subscribed to',\n )\n }\n callbacks.push(callback)\n }\n\n // Function to unsubscribe from the query\n const unsubscribe = async (\n callback?: (changes: Array<Change<T>>) => void,\n ) => {\n if (callback) {\n callbacks = callbacks.filter((cb) => cb !== callback)\n } else {\n callbacks = []\n }\n if (callbacks.length === 0 && !dead) {\n dead = true\n await pg.transaction(async (tx) => {\n await Promise.all(unsubList.map((unsub) => unsub(tx)))\n await tx.exec(`\n DROP VIEW IF EXISTS live_query_${id}_view;\n DROP TABLE IF EXISTS live_query_${id}_state1;\n DROP TABLE IF EXISTS live_query_${id}_state2;\n DEALLOCATE live_query_${id}_diff1;\n DEALLOCATE live_query_${id}_diff2;\n `)\n })\n }\n }\n\n // If the signal has already been aborted, unsubscribe\n if (signal?.aborted) {\n await unsubscribe()\n } else {\n // Add an event listener to unsubscribe if the signal is aborted\n signal?.addEventListener(\n 'abort',\n () => {\n unsubscribe()\n },\n { once: true },\n )\n }\n\n // Run the callback with the initial changes\n await refresh()\n\n // Fields\n const fields = changes!.fields.filter(\n (field) =>\n !['__after__', '__op__', '__changed_columns__'].includes(field.name),\n )\n\n // Return the initial results\n return {\n fields,\n initialChanges: changes!.rows,\n subscribe,\n unsubscribe,\n refresh,\n } satisfies LiveChanges<T>\n },\n\n async incrementalQuery<T>(\n query: string | LiveIncrementalQueryOptions<T>,\n params?: any[] | null,\n key?: string,\n callback?: (results: Results<T>) => void,\n ) {\n let signal: AbortSignal | undefined\n if (typeof query !== 'string') {\n signal = query.signal\n params = query.params\n key = query.key\n callback = query.callback\n query = query.query\n }\n if (!key) {\n throw new Error('key is required for incremental queries')\n }\n let callbacks: Array<(results: Results<T>) => void> = callback\n ? [callback]\n : []\n const rowsMap: Map<any, any> = new Map()\n const afterMap: Map<any, any> = new Map()\n let lastRows: T[] = []\n let firstRun = true\n\n const {\n fields,\n unsubscribe: unsubscribeChanges,\n refresh,\n } = await namespaceObj.changes<T>(query, params, key, (changes) => {\n // Process the changes\n for (const change of changes) {\n const {\n __op__: op,\n __changed_columns__: changedColumns,\n ...obj\n } = change as typeof change & { [key: string]: any }\n switch (op) {\n case 'RESET':\n rowsMap.clear()\n afterMap.clear()\n break\n case 'INSERT':\n rowsMap.set(obj[key], obj)\n afterMap.set(obj.__after__, obj[key])\n break\n case 'DELETE': {\n const oldObj = rowsMap.get(obj[key])\n rowsMap.delete(obj[key])\n // null is the starting point, we don't delete it as another insert\n // may have happened thats replacing it\n if (oldObj.__after__ !== null) {\n afterMap.delete(oldObj.__after__)\n }\n break\n }\n case 'UPDATE': {\n const newObj = { ...(rowsMap.get(obj[key]) ?? {}) }\n for (const columnName of changedColumns) {\n newObj[columnName] = obj[columnName]\n if (columnName === '__after__') {\n afterMap.set(obj.__after__, obj[key])\n }\n }\n rowsMap.set(obj[key], newObj)\n break\n }\n }\n }\n\n // Get the rows in order\n const rows: T[] = []\n let lastKey: any = null\n for (let i = 0; i < rowsMap.size; i++) {\n const nextKey = afterMap.get(lastKey)\n const obj = rowsMap.get(nextKey)\n if (!obj) {\n break\n }\n // Remove the __after__ key from the exposed row\n const cleanObj = { ...obj }\n delete cleanObj.__after__\n rows.push(cleanObj)\n lastKey = nextKey\n }\n lastRows = rows\n\n // Run the callbacks\n if (!firstRun) {\n runResultCallbacks(callbacks, {\n rows,\n fields,\n })\n }\n })\n\n firstRun = false\n runResultCallbacks(callbacks, {\n rows: lastRows,\n fields,\n })\n\n const subscribe = (callback: (results: Results<T>) => void) => {\n callbacks.push(callback)\n }\n\n const unsubscribe = async (callback?: (results: Results<T>) => void) => {\n if (callback) {\n callbacks = callbacks.filter((cb) => cb !== callback)\n } else {\n callbacks = []\n }\n if (callbacks.length === 0) {\n await unsubscribeChanges()\n }\n }\n\n if (signal?.aborted) {\n await unsubscribe()\n } else {\n signal?.addEventListener(\n 'abort',\n () => {\n unsubscribe()\n },\n { once: true },\n )\n }\n\n return {\n initialResults: {\n rows: lastRows,\n fields,\n },\n subscribe,\n unsubscribe,\n refresh,\n } satisfies LiveQuery<T>\n },\n }\n\n return {\n namespaceObj,\n }\n}\n\nexport const live = {\n name: 'Live Queries',\n setup,\n} satisfies Extension\n\nexport type PGliteWithLive = PGliteInterface & {\n live: LiveNamespace\n}\n\n/**\n * Get a list of all the tables used in a view, recursively\n * @param tx a transaction or PGlite instance\n * @param viewName the name of the view\n * @returns list of tables used in the view\n */\nasync function getTablesForView(\n tx: Transaction | PGliteInterface,\n viewName: string,\n): Promise<\n {\n table_name: string\n schema_name: string\n table_oid: number\n schema_oid: number\n }[]\n> {\n const result = await tx.query<{\n table_name: string\n schema_name: string\n table_oid: number\n schema_oid: number\n }>(\n `\n WITH RECURSIVE view_dependencies AS (\n -- Base case: Get the initial view's dependencies\n SELECT DISTINCT\n cl.relname AS dependent_name,\n n.nspname AS schema_name,\n cl.oid AS dependent_oid,\n n.oid AS schema_oid,\n cl.relkind = 'v' AS is_view\n FROM pg_rewrite r\n JOIN pg_depend d ON r.oid = d.objid\n JOIN pg_class cl ON d.refobjid = cl.oid\n JOIN pg_namespace n ON cl.relnamespace = n.oid\n WHERE\n r.ev_class = (\n SELECT oid FROM pg_class WHERE relname = $1 AND relkind = 'v'\n )\n AND d.deptype = 'n'\n\n UNION ALL\n\n -- Recursive case: Traverse dependencies for views\n SELECT DISTINCT\n cl.relname AS dependent_name,\n n.nspname AS schema_name,\n cl.oid AS dependent_oid,\n n.oid AS schema_oid,\n cl.relkind = 'v' AS is_view\n FROM view_dependencies vd\n JOIN pg_rewrite r ON vd.dependent_name = (\n SELECT relname FROM pg_class WHERE oid = r.ev_class AND relkind = 'v'\n )\n JOIN pg_depend d ON r.oid = d.objid\n JOIN pg_class cl ON d.refobjid = cl.oid\n JOIN pg_namespace n ON cl.relnamespace = n.oid\n WHERE d.deptype = 'n'\n )\n SELECT DISTINCT\n dependent_name AS table_name,\n schema_name,\n dependent_oid AS table_oid,\n schema_oid\n FROM view_dependencies\n WHERE NOT is_view; -- Exclude intermediate views\n `,\n [viewName],\n )\n\n return result.rows.map((row) => ({\n table_name: row.table_name,\n schema_name: row.schema_name,\n table_oid: row.table_oid,\n schema_oid: row.schema_oid,\n }))\n}\n\n/**\n * Add triggers to tables to notify when they change\n * @param tx a transaction or PGlite instance\n * @param tables list of tables to add triggers to\n */\nasync function addNotifyTriggersToTables(\n tx: Transaction | PGliteInterface,\n tables: {\n table_name: string\n table_oid: number\n schema_name: string\n schema_oid: number\n }[],\n tableNotifyTriggersAdded: Set<string>,\n) {\n const triggers = tables\n .filter(\n (table) =>\n !tableNotifyTriggersAdded.has(`${table.schema_oid}_${table.table_oid}`),\n )\n .map((table) => {\n return `\n CREATE OR REPLACE FUNCTION \"_notify_${table.schema_oid}_${table.table_oid}\"() RETURNS TRIGGER AS $$\n BEGIN\n PERFORM pg_notify('table_change__${table.schema_oid}__${table.table_oid}', '');\n RETURN NULL;\n END;\n $$ LANGUAGE plpgsql;\n CREATE OR REPLACE TRIGGER \"_notify_trigger_${table.schema_oid}_${table.table_oid}\"\n AFTER INSERT OR UPDATE OR DELETE ON \"${table.schema_name}\".\"${table.table_name}\"\n FOR EACH STATEMENT EXECUTE FUNCTION \"_notify_${table.schema_oid}_${table.table_oid}\"();\n `\n })\n .join('\\n')\n if (triggers.trim() !== '') {\n await tx.exec(triggers)\n }\n tables.map((table) =>\n tableNotifyTriggersAdded.add(`${table.schema_oid}_${table.table_oid}`),\n )\n}\n\nconst runResultCallbacks = <T>(\n callbacks: Array<(results: Results<T>) => void>,\n results: Results<T>,\n) => {\n for (const callback of callbacks) {\n callback(results)\n }\n}\n\nconst runChangeCallbacks = <T>(\n callbacks: Array<(changes: Array<Change<T>>) => void>,\n changes: Array<Change<T>>,\n) => {\n for (const callback of callbacks) {\n callback(changes)\n }\n}\n"],"mappings":"+JAAAA,IA2BA,IAAMC,EAAc,EAEdC,EAAQ,MAAOC,EAAqBC,IAAyB,CAGjE,IAAMC,EAA2B,IAAI,IAE/BC,EAA8B,CAClC,MAAM,MACJC,EACAC,EACAC,EACA,CACA,IAAIC,EACAC,EACAC,EAWJ,GAVI,OAAOL,GAAU,WACnBG,EAASH,EAAM,OACfC,EAASD,EAAM,OACfE,EAAWF,EAAM,SACjBI,EAASJ,EAAM,OACfK,EAAQL,EAAM,MACdA,EAAQA,EAAM,OAIXI,IAAW,SAAgBC,IAAU,QACxC,MAAM,IAAI,MAAM,4CAA4C,EAG9D,IAAMC,EAAaF,IAAW,QAAaC,IAAU,OACjDE,EAEJ,GACED,IACC,OAAOF,GAAW,UACjB,MAAMA,CAAM,GACZ,OAAOC,GAAU,UACjB,MAAMA,CAAK,GAEb,MAAM,IAAI,MAAM,kCAAkC,EAGpD,IAAIG,EAAkDN,EAClD,CAACA,CAAQ,EACT,CAAC,EACCO,EAAKC,EAAS,KAAK,EAAE,QAAQ,KAAM,EAAE,EACvCC,EAAO,GAEPC,EAEAC,EACEC,EAAO,SAAY,CACvB,MAAMlB,EAAG,YAAY,MAAOmB,GAAO,CAEjC,IAAMC,EACJf,GAAUA,EAAO,OAAS,EACtB,MAAMgB,EAAYrB,EAAII,EAAOC,EAAQc,CAAE,EACvCf,EACN,MAAMe,EAAG,KACP,0CAA0CN,CAAE,YAAYO,CAAc,EACxE,EAGA,IAAME,EAAS,MAAMC,EAAiBJ,EAAI,cAAcN,CAAE,OAAO,EACjE,MAAMW,EAA0BL,EAAIG,EAAQpB,CAAwB,EAEhEQ,GACF,MAAMS,EAAG,KAAK;AAAA,mCACSN,CAAE;AAAA,yCACIA,CAAE;AAAA;AAAA,aAE9B,EACD,MAAMM,EAAG,KAA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ASoC,CAAO,CAEpB","names":["init_esm_shims","MAX_RETRIES","setup","pg","_emscriptenOpts","tableNotifyTriggersAdded","namespaceObj","query","params","callback","signal","offset","limit","isWindowed","totalCount","callbacks","id","f","dead","results","unsubList","init","tx","formattedQuery","formatQuery","tables","getTablesForView","addNotifyTriggersToTables","table","refresh","debounceMutex","newOffset","newLimit","run","count","e","msg","runResultCallbacks","newTotalCount","subscribe","unsubscribe","cb","unsub","key","stateSwitch","changes","columns","curr","prev","column_name","data_type","udt_name","reset","runChangeCallbacks","field","rowsMap","afterMap","lastRows","firstRun","fields","unsubscribeChanges","change","op","changedColumns","obj","oldObj","newObj","columnName","rows","lastKey","i","nextKey","cleanObj","live","viewName","row","triggers"]}

@@ -1,2 +0,2 @@

"use strict";var Ke=Object.create;var ne=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var Ze=Object.getPrototypeOf,et=Object.prototype.hasOwnProperty;var Ie=e=>{throw TypeError(e)};var tt=(e,t)=>{for(var r in t)ne(e,r,{get:t[r],enumerable:!0})},Le=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Xe(t))!et.call(e,a)&&a!==r&&ne(e,a,{get:()=>t[a],enumerable:!(n=Je(t,a))||n.enumerable});return e};var Ce=(e,t,r)=>(r=e!=null?Ke(Ze(e)):{},Le(t||!e||!e.__esModule?ne(r,"default",{value:e,enumerable:!0}):r,e)),rt=e=>Le(ne({},"__esModule",{value:!0}),e);var fe=(e,t,r)=>t.has(e)||Ie("Cannot "+r);var i=(e,t,r)=>(fe(e,t,"read from private field"),r?r.call(e):t.get(e)),p=(e,t,r)=>t.has(e)?Ie("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),d=(e,t,r,n)=>(fe(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r),c=(e,t,r)=>(fe(e,t,"access private method"),r);var ge=(e,t,r,n)=>({set _(a){d(e,t,a,r)},get _(){return i(e,t,n)}});var or={};tt(or,{LeaderChangedError:()=>me,PGliteWorker:()=>Be,worker:()=>sr});module.exports=rt(or);var nt=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href,P=nt();var Oe={part:"part",container:"container"};function se(e,t,...r){let n=e.length-1,a=r.length-1;if(a!==-1){if(a===0){e[n]=e[n]+r[0]+t;return}e[n]=e[n]+r[0],e.push(...r.slice(1,a)),e.push(r[a]+t)}}function st(e,...t){let r=[e[0]];r.raw=[e.raw[0]];let n=[];for(let a=0;a<t.length;a++){let s=t[a],o=a+1;if(s?._templateType===Oe.part){se(r,e[o],s.str),se(r.raw,e.raw[o],s.str);continue}if(s?._templateType===Oe.container){se(r,e[o],...s.strings),se(r.raw,e.raw[o],...s.strings.raw),n.push(...s.values);continue}r.push(e[o]),r.raw.push(e.raw[o]),n.push(s)}return{_templateType:"container",strings:r,values:n}}function be(e,...t){let{strings:r,values:n}=st(e,...t);return{query:[r[0],...n.flatMap((a,s)=>[`$${s+1}`,r[s+1]])].join(""),params:n}}var at=globalThis.JSON.parse,it=globalThis.JSON.stringify,ve=16,Ue=17;var Ne=20,ot=21,ct=23;var _e=25,lt=26;var We=114;var ut=700,pt=701;var dt=1042,yt=1043,mt=1082;var ht=1114,Ge=1184;var ft=3802;var gt={string:{to:_e,from:[_e,yt,dt],serialize:e=>e instanceof Date?e.toISOString():e.toString(),parse:e=>e},number:{to:0,from:[ot,ct,lt,ut,pt],serialize:e=>e.toString(),parse:e=>+e},bigint:{to:Ne,from:[Ne],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:We,from:[We,ft],serialize:e=>typeof e=="string"?e:it(e,(t,r)=>typeof r=="bigint"?r.toString():r),parse:e=>at(e)},boolean:{to:ve,from:[ve],serialize:e=>{if(typeof e=="boolean")return e?"t":"f";if(typeof e=="number"){if(e===1)return"t";if(e===0)return"f"}else if(typeof e=="string"){let t=e.trim().toLowerCase();if(["true","t","yes","y","on","1"].includes(t))return"t";if(["false","f","no","n","off","0"].includes(t))return"f"}throw new Error("Invalid input for boolean type")},parse:e=>e==="t"},date:{to:Ge,from:[mt,ht,Ge],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:Ue,from:[Ue],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,n)=>parseInt(t.substring(n*2,(n+1)*2),16))}}},Pe=bt(gt),Fe=Pe.parsers,Ve=Pe.serializers;function xe(e,t,r){if(e===null)return null;let n=r?.[t]??Pe.parsers[t];return n?n(e,t):e}function bt(e){return Object.keys(e).reduce(({parsers:t,serializers:r},n)=>{let{to:a,from:s,serialize:o,parse:u}=e[n];return r[a]=o,r[n]=o,t[n]=u,Array.isArray(s)?s.forEach(l=>{t[l]=u,r[l]=o}):(t[s]=u,r[s]=o),{parsers:t,serializers:r}},{parsers:{},serializers:{}})}var wt=/\\/g,Pt=/"/g;function xt(e){return e.replace(wt,"\\\\").replace(Pt,'\\"')}function Te(e,t,r){if(Array.isArray(e)===!1)return e;if(!e.length)return"{}";let n=e[0],a=r===1020?";":",";return Array.isArray(n)?`{${e.map(s=>Te(s,t,r)).join(a)}}`:`{${e.map(s=>(s===void 0&&(s=null),s===null?"null":'"'+xt(t?t(s):s.toString())+'"')).join(a)}}`}var we={i:0,char:null,str:"",quoted:!1,last:0,p:null};function Qe(e,t,r){return we.i=we.last=0,qe(we,e,t,r)[0]}function qe(e,t,r,n){let a=[],s=n===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==='"'?(a.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,a.push(qe(e,t,r,n));else if(e.char==="}"){if(e.last<e.i){let o=t.slice(e.last,e.i);o==="NULL"&&!e.quoted?a.push(null):a.push(r?r(o):o)}e.quoted=!1,e.last=e.i+1;break}else if(e.char===s&&e.p!=="}"&&e.p!=='"'){let o=t.slice(e.last,e.i);o==="NULL"&&!e.quoted?a.push(null):a.push(r?r(o):o),e.last=e.i+1}e.p=e.char}return e.last<e.i&&a.push(r?r(t.slice(e.last,e.i+1)):t.slice(e.last,e.i+1)),a}function Ae(e,t,r,n){let a=[],s={rows:[],fields:[]},o=0,u={...t,...r?.parsers};return e.forEach(l=>{switch(l.name){case"rowDescription":{let m=l;s.fields=m.fields.map(y=>({name:y.name,dataTypeID:y.dataTypeID}));break}case"dataRow":{if(!s)break;let m=l;r?.rowMode==="array"?s.rows.push(m.fields.map((y,T)=>xe(y,s.fields[T].dataTypeID,u))):s.rows.push(Object.fromEntries(m.fields.map((y,T)=>[s.fields[T].name,xe(y,s.fields[T].dataTypeID,u)])));break}case"commandComplete":{o+=Tt(l),a.push({...s,affectedRows:o,...n?{blob:n}:{}}),s={rows:[],fields:[]};break}}}),a.length===0&&a.push({affectedRows:0,rows:[],fields:[]}),a}function Tt(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 ze(e){let t=e.find(r=>r.name==="parameterDescription");return t?t.dataTypeIDs:[]}function W(e){let t=e.length;for(let r=e.length-1;r>=0;r--){let n=e.charCodeAt(r);n>127&&n<=2047?t++:n>2047&&n<=65535&&(t+=2),n>=56320&&n<=57343&&r--}return t}var b,w,F,ie,V,A,ae,G,je,L=class{constructor(t=256){this.size=t;p(this,A);p(this,b);p(this,w,5);p(this,F,!1);p(this,ie,new TextEncoder);p(this,V,0);d(this,b,c(this,A,ae).call(this,t))}addInt32(t){return c(this,A,G).call(this,4),i(this,b).setInt32(i(this,w),t,i(this,F)),d(this,w,i(this,w)+4),this}addInt16(t){return c(this,A,G).call(this,2),i(this,b).setInt16(i(this,w),t,i(this,F)),d(this,w,i(this,w)+2),this}addCString(t){return t&&this.addString(t),c(this,A,G).call(this,1),i(this,b).setUint8(i(this,w),0),ge(this,w)._++,this}addString(t=""){let r=W(t);return c(this,A,G).call(this,r),i(this,ie).encodeInto(t,new Uint8Array(i(this,b).buffer,i(this,w))),d(this,w,i(this,w)+r),this}add(t){return c(this,A,G).call(this,t.byteLength),new Uint8Array(i(this,b).buffer).set(new Uint8Array(t),i(this,w)),d(this,w,i(this,w)+t.byteLength),this}flush(t){let r=c(this,A,je).call(this,t);return d(this,w,5),d(this,b,c(this,A,ae).call(this,this.size)),new Uint8Array(r)}};b=new WeakMap,w=new WeakMap,F=new WeakMap,ie=new WeakMap,V=new WeakMap,A=new WeakSet,ae=function(t){return new DataView(new ArrayBuffer(t))},G=function(t){if(i(this,b).byteLength-i(this,w)<t){let n=i(this,b).buffer,a=n.byteLength+(n.byteLength>>1)+t;d(this,b,c(this,A,ae).call(this,a)),new Uint8Array(i(this,b).buffer).set(new Uint8Array(n))}},je=function(t){if(t){i(this,b).setUint8(i(this,V),t);let r=i(this,w)-(i(this,V)+1);i(this,b).setInt32(i(this,V)+1,r,i(this,F))}return i(this,b).buffer.slice(t?0:5,i(this,w))};var g=new L,At=e=>{g.addInt16(3).addInt16(0);for(let n of Object.keys(e))g.addCString(n).addCString(e[n]);g.addCString("client_encoding").addCString("UTF8");let t=g.addCString("").flush(),r=t.byteLength+4;return new L().addInt32(r).add(t).flush()},Rt=()=>{let e=new DataView(new ArrayBuffer(8));return e.setInt32(0,8,!1),e.setInt32(4,80877103,!1),new Uint8Array(e.buffer)},Et=e=>g.addCString(e).flush(112),St=(e,t)=>(g.addCString(e).addInt32(W(t)).addString(t),g.flush(112)),Bt=e=>g.addString(e).flush(112),Dt=e=>g.addCString(e).flush(81),kt=[],Mt=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=g.addCString(t).addCString(e.text).addInt16(e.types?.length??0);return e.types?.forEach(n=>r.addInt32(n)),g.flush(80)},Q=new L;var It=(e,t)=>{for(let r=0;r<e.length;r++){let n=t?t(e[r],r):e[r];if(n===null)g.addInt16(0),Q.addInt32(-1);else if(n instanceof ArrayBuffer||ArrayBuffer.isView(n)){let a=ArrayBuffer.isView(n)?n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength):n;g.addInt16(1),Q.addInt32(a.byteLength),Q.add(a)}else g.addInt16(0),Q.addInt32(W(n)),Q.addString(n)}},Lt=(e={})=>{let t=e.portal??"",r=e.statement??"",n=e.binary??!1,a=e.values??kt,s=a.length;return g.addCString(t).addCString(r),g.addInt16(s),It(a,e.valueMapper),g.addInt16(s),g.add(Q.flush()),g.addInt16(n?1:0),g.flush(66)},Ct=new Uint8Array([69,0,0,0,9,0,0,0,0,0]),Ot=e=>{if(!e||!e.portal&&!e.rows)return Ct;let t=e.portal??"",r=e.rows??0,n=W(t),a=4+n+1+4,s=new DataView(new ArrayBuffer(1+a));return s.setUint8(0,69),s.setInt32(1,a,!1),new TextEncoder().encodeInto(t,new Uint8Array(s.buffer,5)),s.setUint8(n+5,0),s.setUint32(s.byteLength-4,r,!1),new Uint8Array(s.buffer)},vt=(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)},Re=(e,t)=>{let r=new L;return r.addCString(t),r.flush(e)},Ut=g.addCString("P").flush(68),Nt=g.addCString("S").flush(68),_t=e=>e.name?Re(68,`${e.type}${e.name??""}`):e.type==="P"?Ut:Nt,Wt=e=>{let t=`${e.type}${e.name??""}`;return Re(67,t)},Gt=e=>g.add(e).flush(100),Ft=e=>Re(102,e),oe=e=>new Uint8Array([e,0,0,0,4]),Vt=oe(72),Qt=oe(83),qt=oe(88),zt=oe(99),E={startup:At,password:Et,requestSsl:Rt,sendSASLInitialResponseMessage:St,sendSCRAMClientFinalMessage:Bt,query:Dt,parse:Mt,bind:Lt,execute:Ot,describe:_t,close:Wt,flush:()=>Vt,sync:()=>Qt,end:()=>qt,copyData:Gt,copyDone:()=>zt,copyFail:Ft,cancel:vt};var C=class extends Error{constructor(r,n,a){super(r);this.length=n;this.name=a}};var Mr=new ArrayBuffer(0);var $t=1,Ht=4,fn=$t+Ht,gn=new ArrayBuffer(0);function ce(e){let t=e.e;return t.query=e.query,t.params=e.params,t.queryOptions=e.options,t}var j,I,h,S,le,O,Ee,ue=class{constructor(){p(this,h);this.serializers={...Ve};this.parsers={...Fe};p(this,j,!1);p(this,I,!1)}async _initArrayTypes({force:t=!1}={}){if(i(this,j)&&!t)return;d(this,j,!0);let r=await this.query(`
"use strict";var Ke=Object.create;var se=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var Ze=Object.getPrototypeOf,et=Object.prototype.hasOwnProperty;var Ie=e=>{throw TypeError(e)};var tt=(e,r)=>{for(var t in r)se(e,t,{get:r[t],enumerable:!0})},Le=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of Xe(r))!et.call(e,a)&&a!==t&&se(e,a,{get:()=>r[a],enumerable:!(n=Je(r,a))||n.enumerable});return e};var Ce=(e,r,t)=>(t=e!=null?Ke(Ze(e)):{},Le(r||!e||!e.__esModule?se(t,"default",{value:e,enumerable:!0}):t,e)),rt=e=>Le(se({},"__esModule",{value:!0}),e);var ge=(e,r,t)=>r.has(e)||Ie("Cannot "+t);var i=(e,r,t)=>(ge(e,r,"read from private field"),t?t.call(e):r.get(e)),d=(e,r,t)=>r.has(e)?Ie("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(e):r.set(e,t),y=(e,r,t,n)=>(ge(e,r,"write to private field"),n?n.call(e,t):r.set(e,t),t),c=(e,r,t)=>(ge(e,r,"access private method"),t);var be=(e,r,t,n)=>({set _(a){y(e,r,a,t)},get _(){return i(e,r,n)}});var ir={};tt(ir,{LeaderChangedError:()=>he,PGliteWorker:()=>De,worker:()=>nr});module.exports=rt(ir);var nt=()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href,T=nt();var Oe={part:"part",container:"container"};function ae(e,r,...t){let n=e.length-1,a=t.length-1;if(a!==-1){if(a===0){e[n]=e[n]+t[0]+r;return}e[n]=e[n]+t[0],e.push(...t.slice(1,a)),e.push(t[a]+r)}}function st(e,...r){let t=[e[0]];t.raw=[e.raw[0]];let n=[];for(let a=0;a<r.length;a++){let s=r[a],o=a+1;if(s?._templateType===Oe.part){ae(t,e[o],s.str),ae(t.raw,e.raw[o],s.str);continue}if(s?._templateType===Oe.container){ae(t,e[o],...s.strings),ae(t.raw,e.raw[o],...s.strings.raw),n.push(...s.values);continue}t.push(e[o]),t.raw.push(e.raw[o]),n.push(s)}return{_templateType:"container",strings:t,values:n}}function we(e,...r){let{strings:t,values:n}=st(e,...r);return{query:[t[0],...n.flatMap((a,s)=>[`$${s+1}`,t[s+1]])].join(""),params:n}}var at=globalThis.JSON.parse,it=globalThis.JSON.stringify,ve=16,Ue=17;var Ne=20,ot=21,ct=23;var _e=25,lt=26;var We=114;var ut=700,pt=701;var dt=1042,yt=1043,mt=1082;var ht=1114,Ge=1184;var ft=3802;var gt={string:{to:_e,from:[_e,yt,dt],serialize:e=>e instanceof Date?e.toISOString():e.toString(),parse:e=>e},number:{to:0,from:[ot,ct,lt,ut,pt],serialize:e=>e.toString(),parse:e=>+e},bigint:{to:Ne,from:[Ne],serialize:e=>e.toString(),parse:e=>{let r=BigInt(e);return r<Number.MIN_SAFE_INTEGER||r>Number.MAX_SAFE_INTEGER?r:Number(r)}},json:{to:We,from:[We,ft],serialize:e=>typeof e=="string"?e:it(e,(r,t)=>typeof t=="bigint"?t.toString():t),parse:e=>at(e)},boolean:{to:ve,from:[ve],serialize:e=>{if(typeof e=="boolean")return e?"t":"f";if(typeof e=="number"){if(e===1)return"t";if(e===0)return"f"}else if(typeof e=="string"){let r=e.trim().toLowerCase();if(["true","t","yes","y","on","1"].includes(r))return"t";if(["false","f","no","n","off","0"].includes(r))return"f"}throw new Error("Invalid input for boolean type")},parse:e=>e==="t"},date:{to:Ge,from:[mt,ht,Ge],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:Ue,from:[Ue],serialize:e=>{if(!(e instanceof Uint8Array))throw new Error("Invalid input for bytea type");return"\\x"+Array.from(e).map(r=>r.toString(16).padStart(2,"0")).join("")},parse:e=>{let r=e.slice(2);return Uint8Array.from({length:r.length/2},(t,n)=>parseInt(r.substring(n*2,(n+1)*2),16))}}},xe=bt(gt),Fe=xe.parsers,Ve=xe.serializers;function Te(e,r,t){if(e===null)return null;let n=t?.[r]??xe.parsers[r];return n?n(e,r):e}function bt(e){return Object.keys(e).reduce(({parsers:r,serializers:t},n)=>{let{to:a,from:s,serialize:o,parse:u}=e[n];return t[a]=o,t[n]=o,r[n]=u,Array.isArray(s)?s.forEach(l=>{r[l]=u,t[l]=o}):(r[s]=u,t[s]=o),{parsers:r,serializers:t}},{parsers:{},serializers:{}})}var wt=/\\/g,Pt=/"/g;function xt(e){return e.replace(wt,"\\\\").replace(Pt,'\\"')}function Ae(e,r,t){if(Array.isArray(e)===!1)return e;if(!e.length)return"{}";let n=e[0],a=t===1020?";":",";return Array.isArray(n)?`{${e.map(s=>Ae(s,r,t)).join(a)}}`:`{${e.map(s=>(s===void 0&&(s=null),s===null?"null":'"'+xt(r?r(s):s.toString())+'"')).join(a)}}`}var Pe={i:0,char:null,str:"",quoted:!1,last:0,p:null};function Qe(e,r,t){return Pe.i=Pe.last=0,qe(Pe,e,r,t)[0]}function qe(e,r,t,n){let a=[],s=n===1020?";":",";for(;e.i<r.length;e.i++){if(e.char=r[e.i],e.quoted)e.char==="\\"?e.str+=r[++e.i]:e.char==='"'?(a.push(t?t(e.str):e.str),e.str="",e.quoted=r[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,a.push(qe(e,r,t,n));else if(e.char==="}"){if(e.last<e.i){let o=r.slice(e.last,e.i);o==="NULL"&&!e.quoted?a.push(null):a.push(t?t(o):o)}e.quoted=!1,e.last=e.i+1;break}else if(e.char===s&&e.p!=="}"&&e.p!=='"'){let o=r.slice(e.last,e.i);o==="NULL"&&!e.quoted?a.push(null):a.push(t?t(o):o),e.last=e.i+1}e.p=e.char}return e.last<e.i&&a.push(t?t(r.slice(e.last,e.i+1)):r.slice(e.last,e.i+1)),a}function Ee(e,r,t,n){let a=[],s={rows:[],fields:[]},o=0,u={...r,...t?.parsers};return e.forEach(l=>{switch(l.name){case"rowDescription":{let m=l;s.fields=m.fields.map(p=>({name:p.name,dataTypeID:p.dataTypeID}));break}case"dataRow":{if(!s)break;let m=l;t?.rowMode==="array"?s.rows.push(m.fields.map((p,b)=>Te(p,s.fields[b].dataTypeID,u))):s.rows.push(Object.fromEntries(m.fields.map((p,b)=>[s.fields[b].name,Te(p,s.fields[b].dataTypeID,u)])));break}case"commandComplete":{let p=l.text.split(" "),b=p[0],w=parseInt(p[p.length-1],10);switch(b){case"INSERT":case"UPDATE":case"DELETE":case"COPY":case"MERGE":o+=w;break}let W={...s,command:b,affectedRows:o};Number.isNaN(w)||(W.rowCount=w),n&&(W.blob=n),a.push(W),s={rows:[],fields:[]};break}}}),a.length===0&&a.push({affectedRows:0,rows:[],fields:[]}),a}function ze(e){let r=e.find(t=>t.name==="parameterDescription");return r?r.dataTypeIDs:[]}function G(e){let r=e.length;for(let t=e.length-1;t>=0;t--){let n=e.charCodeAt(t);n>127&&n<=2047?r++:n>2047&&n<=65535&&(r+=2),n>=56320&&n<=57343&&t--}return r}var P,x,V,oe,Q,E,ie,F,je,L=class{constructor(r=256){this.size=r;d(this,E);d(this,P);d(this,x,5);d(this,V,!1);d(this,oe,new TextEncoder);d(this,Q,0);y(this,P,c(this,E,ie).call(this,r))}addInt32(r){return c(this,E,F).call(this,4),i(this,P).setInt32(i(this,x),r,i(this,V)),y(this,x,i(this,x)+4),this}addInt16(r){return c(this,E,F).call(this,2),i(this,P).setInt16(i(this,x),r,i(this,V)),y(this,x,i(this,x)+2),this}addCString(r){return r&&this.addString(r),c(this,E,F).call(this,1),i(this,P).setUint8(i(this,x),0),be(this,x)._++,this}addString(r=""){let t=G(r);return c(this,E,F).call(this,t),i(this,oe).encodeInto(r,new Uint8Array(i(this,P).buffer,i(this,x))),y(this,x,i(this,x)+t),this}add(r){return c(this,E,F).call(this,r.byteLength),new Uint8Array(i(this,P).buffer).set(new Uint8Array(r),i(this,x)),y(this,x,i(this,x)+r.byteLength),this}flush(r){let t=c(this,E,je).call(this,r);return y(this,x,5),y(this,P,c(this,E,ie).call(this,this.size)),new Uint8Array(t)}};P=new WeakMap,x=new WeakMap,V=new WeakMap,oe=new WeakMap,Q=new WeakMap,E=new WeakSet,ie=function(r){return new DataView(new ArrayBuffer(r))},F=function(r){if(i(this,P).byteLength-i(this,x)<r){let n=i(this,P).buffer,a=n.byteLength+(n.byteLength>>1)+r;y(this,P,c(this,E,ie).call(this,a)),new Uint8Array(i(this,P).buffer).set(new Uint8Array(n))}},je=function(r){if(r){i(this,P).setUint8(i(this,Q),r);let t=i(this,x)-(i(this,Q)+1);i(this,P).setInt32(i(this,Q)+1,t,i(this,V))}return i(this,P).buffer.slice(r?0:5,i(this,x))};var g=new L,Tt=e=>{g.addInt16(3).addInt16(0);for(let n of Object.keys(e))g.addCString(n).addCString(e[n]);g.addCString("client_encoding").addCString("UTF8");let r=g.addCString("").flush(),t=r.byteLength+4;return new L().addInt32(t).add(r).flush()},At=()=>{let e=new DataView(new ArrayBuffer(8));return e.setInt32(0,8,!1),e.setInt32(4,80877103,!1),new Uint8Array(e.buffer)},Et=e=>g.addCString(e).flush(112),Rt=(e,r)=>(g.addCString(e).addInt32(G(r)).addString(r),g.flush(112)),St=e=>g.addString(e).flush(112),Bt=e=>g.addCString(e).flush(81),Dt=[],kt=e=>{let r=e.name??"";r.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",r,r.length),console.error("This can cause conflicts and silent errors executing queries"));let t=g.addCString(r).addCString(e.text).addInt16(e.types?.length??0);return e.types?.forEach(n=>t.addInt32(n)),g.flush(80)},q=new L;var Mt=(e,r)=>{for(let t=0;t<e.length;t++){let n=r?r(e[t],t):e[t];if(n===null)g.addInt16(0),q.addInt32(-1);else if(n instanceof ArrayBuffer||ArrayBuffer.isView(n)){let a=ArrayBuffer.isView(n)?n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength):n;g.addInt16(1),q.addInt32(a.byteLength),q.add(a)}else g.addInt16(0),q.addInt32(G(n)),q.addString(n)}},It=(e={})=>{let r=e.portal??"",t=e.statement??"",n=e.binary??!1,a=e.values??Dt,s=a.length;return g.addCString(r).addCString(t),g.addInt16(s),Mt(a,e.valueMapper),g.addInt16(s),g.add(q.flush()),g.addInt16(n?1:0),g.flush(66)},Lt=new Uint8Array([69,0,0,0,9,0,0,0,0,0]),Ct=e=>{if(!e||!e.portal&&!e.rows)return Lt;let r=e.portal??"",t=e.rows??0,n=G(r),a=4+n+1+4,s=new DataView(new ArrayBuffer(1+a));return s.setUint8(0,69),s.setInt32(1,a,!1),new TextEncoder().encodeInto(r,new Uint8Array(s.buffer,5)),s.setUint8(n+5,0),s.setUint32(s.byteLength-4,t,!1),new Uint8Array(s.buffer)},Ot=(e,r)=>{let t=new DataView(new ArrayBuffer(16));return t.setInt32(0,16,!1),t.setInt16(4,1234,!1),t.setInt16(6,5678,!1),t.setInt32(8,e,!1),t.setInt32(12,r,!1),new Uint8Array(t.buffer)},Re=(e,r)=>{let t=new L;return t.addCString(r),t.flush(e)},vt=g.addCString("P").flush(68),Ut=g.addCString("S").flush(68),Nt=e=>e.name?Re(68,`${e.type}${e.name??""}`):e.type==="P"?vt:Ut,_t=e=>{let r=`${e.type}${e.name??""}`;return Re(67,r)},Wt=e=>g.add(e).flush(100),Gt=e=>Re(102,e),ce=e=>new Uint8Array([e,0,0,0,4]),Ft=ce(72),Vt=ce(83),Qt=ce(88),qt=ce(99),R={startup:Tt,password:Et,requestSsl:At,sendSASLInitialResponseMessage:Rt,sendSCRAMClientFinalMessage:St,query:Bt,parse:kt,bind:It,execute:Ct,describe:Nt,close:_t,flush:()=>Ft,sync:()=>Vt,end:()=>Qt,copyData:Wt,copyDone:()=>qt,copyFail:Gt,cancel:Ot};var C=class extends Error{constructor(t,n,a){super(t);this.length=n;this.name=a}};var kr=new ArrayBuffer(0);var jt=1,$t=4,hn=jt+$t,fn=new ArrayBuffer(0);function le(e){let r=e.e;return r.query=e.query,r.params=e.params,r.queryOptions=e.options,r}var $,I,h,S,ue,O,Se,pe=class{constructor(){d(this,h);this.serializers={...Ve};this.parsers={...Fe};d(this,$,!1);d(this,I,!1)}async _initArrayTypes({force:r=!1}={}){if(i(this,$)&&!r)return;y(this,$,!0);let t=await this.query(`
SELECT b.oid, b.typarray

@@ -8,3 +8,3 @@ FROM pg_catalog.pg_type a

ORDER BY b.oid
`);for(let n of r.rows)this.serializers[n.typarray]=a=>Te(a,this.serializers[n.oid],n.typarray),this.parsers[n.typarray]=a=>Qe(a,this.parsers[n.oid],n.typarray)}async refreshArrayTypes(){await this._initArrayTypes({force:!0})}async query(t,r,n){return await this._checkReady(),await this._runExclusiveTransaction(async()=>await c(this,h,le).call(this,t,r,n))}async sql(t,...r){let{query:n,params:a}=be(t,...r);return await this.query(n,a)}async exec(t,r){return await this._checkReady(),await this._runExclusiveTransaction(async()=>await c(this,h,O).call(this,t,r))}async describeQuery(t,r){let n=[];try{await c(this,h,S).call(this,E.parse({text:t,types:r?.paramTypes}),r),n=await c(this,h,S).call(this,E.describe({type:"S"}),r)}catch(l){throw l instanceof C?ce({e:l,options:r,params:void 0,query:t}):l}finally{n.push(...await c(this,h,S).call(this,E.sync(),r))}let a=n.find(l=>l.name==="parameterDescription"),s=n.find(l=>l.name==="rowDescription"),o=a?.dataTypeIDs.map(l=>({dataTypeID:l,serializer:this.serializers[l]}))??[],u=s?.fields.map(l=>({name:l.name,dataTypeID:l.dataTypeID,parser:this.parsers[l.dataTypeID]}))??[];return{queryParams:o,resultFields:u}}async transaction(t){return await this._checkReady(),await this._runExclusiveTransaction(async()=>{await c(this,h,O).call(this,"BEGIN"),d(this,I,!0);let r=!1,n=()=>{if(r)throw new Error("Transaction is closed")},a={query:async(s,o,u)=>(n(),await c(this,h,le).call(this,s,o,u)),sql:async(s,...o)=>{let{query:u,params:l}=be(s,...o);return await c(this,h,le).call(this,u,l)},exec:async(s,o)=>(n(),await c(this,h,O).call(this,s,o)),rollback:async()=>{n(),await c(this,h,O).call(this,"ROLLBACK"),r=!0},listen:async(s,o)=>(n(),await this.listen(s,o,a)),get closed(){return r}};try{let s=await t(a);return r||(r=!0,await c(this,h,O).call(this,"COMMIT")),d(this,I,!1),s}catch(s){throw r||await c(this,h,O).call(this,"ROLLBACK"),d(this,I,!1),s}})}async runExclusive(t){return await this._runExclusiveQuery(t)}};j=new WeakMap,I=new WeakMap,h=new WeakSet,S=async function(t,r={}){return await this.execProtocolStream(t,{...r,syncToFs:!1})},le=async function(t,r=[],n){return await this._runExclusiveQuery(async()=>{c(this,h,Ee).call(this,"runQuery",t,r,n),await this._handleBlob(n?.blob);let a=[];try{let o=await c(this,h,S).call(this,E.parse({text:t,types:n?.paramTypes}),n),u=ze(await c(this,h,S).call(this,E.describe({type:"S"}),n)),l=r.map((m,y)=>{let T=u[y];if(m==null)return null;let R=n?.serializers?.[T]??this.serializers[T];return R?R(m):m.toString()});a=[...o,...await c(this,h,S).call(this,E.bind({values:l}),n),...await c(this,h,S).call(this,E.describe({type:"P"}),n),...await c(this,h,S).call(this,E.execute({}),n)]}catch(o){throw o instanceof C?ce({e:o,options:n,params:r,query:t}):o}finally{a.push(...await c(this,h,S).call(this,E.sync(),n))}await this._cleanupBlob(),i(this,I)||await this.syncToFs();let s=await this._getWrittenBlob();return Ae(a,this.parsers,n,s)[0]})},O=async function(t,r){return await this._runExclusiveQuery(async()=>{c(this,h,Ee).call(this,"runExec",t,r),await this._handleBlob(r?.blob);let n=[];try{n=await c(this,h,S).call(this,E.query(t),r)}catch(s){throw s instanceof C?ce({e:s,options:r,params:void 0,query:t}):s}finally{n.push(...await c(this,h,S).call(this,E.sync(),r))}this._cleanupBlob(),i(this,I)||await this.syncToFs();let a=await this._getWrittenBlob();return Ae(n,this.parsers,r,a)})},Ee=function(...t){this.debug>0&&console.log(...t)};var Yt=Object.defineProperty,Kt=(e,t)=>{for(var r in t)Yt(e,r,{get:t[r],enumerable:!0})},H={};Kt(H,{IN_NODE:()=>de,WASM_PREFIX:()=>Xt,getFsBundle:()=>tr,instantiateWasm:()=>er,pgliteProc:()=>Zt,rmdirRecursive:()=>$e,startArtifactDownload:()=>Se,toPostgresName:()=>nr,uuid:()=>rr});function Jt(){let e=process.type;return e==="renderer"||e==="worker"||e==="service-worker"}var de=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&!Jt(),Xt="/pglite",$=new Map;async function Se(e){de||$.has(e.toString())||$.set(e.toString(),fetch(e))}var pe=new Map,Zt=globalThis&&typeof globalThis.process<"u"?globalThis.process:{exitCode:void 0};async function er(e,t,r){if(r||pe.has(t.toString())){let n=r||pe.get(t.toString());return{instance:await WebAssembly.instantiate(n,e),module:n}}if(de){let n=await(await import("fs/promises")).readFile(t),{module:a,instance:s}=await WebAssembly.instantiate(n,e);return pe.set(t.toString(),a),{instance:s,module:a}}else{$.has(t.toString())||Se(t);let n=await $.get(t.toString()),{module:a,instance:s}=await WebAssembly.instantiateStreaming(n.clone(),e);return pe.set(t.toString(),a),{instance:s,module:a}}}async function tr(e){return de?(await(await import("fs/promises")).readFile(e)).buffer:(Se(e),(await $.get(e.toString())).clone().arrayBuffer())}var rr=()=>{if(globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e=new Uint8Array(16);if(globalThis.crypto?.getRandomValues)globalThis.crypto.getRandomValues(e);else for(let r=0;r<e.length;r++)e[r]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[];return e.forEach(r=>{t.push(r.toString(16).padStart(2,"0"))}),t.slice(0,4).join("")+"-"+t.slice(4,6).join("")+"-"+t.slice(6,8).join("")+"-"+t.slice(8,10).join("")+"-"+t.slice(10).join("")};function nr(e){let t;return e.startsWith('"')&&e.endsWith('"')?t=e.substring(1,e.length-1):t=e.toLowerCase(),t}function $e(e,t){try{let r=e.readdir(t).filter(n=>n!=="."&&n!=="..");for(let n of r){let a=t+"/"+n;try{e.readdir(a),$e(e,a)}catch{e.unlink(a)}}e.rmdir(t)}catch{try{e.unlink(t)}catch{}}}var q,Y,K,z,J,B,v,U,D,X,Z,ee,N,M,te,k,_,re,he,f,He,ye,x,Ye,ke=class ke extends ue{constructor(r,n){super();p(this,f);p(this,q);p(this,Y,0);p(this,K,!1);p(this,z,!1);p(this,J,!1);p(this,B,new EventTarget);p(this,v);p(this,U,!1);p(this,D);p(this,X);p(this,Z);p(this,ee);p(this,N);p(this,M);p(this,te);p(this,k,new Map);p(this,_,new Set);p(this,re);p(this,he,[]);d(this,D,r),d(this,v,H.uuid()),d(this,re,n?.extensions??{}),d(this,Z,new Promise(a=>{i(this,D).addEventListener("message",s=>{if(s.data.type==="here")a();else throw new Error("Invalid message")},{once:!0})})),d(this,ee,new Promise(a=>{let s=o=>{o.data.type==="ready"&&(d(this,X,o.data.id),i(this,D).removeEventListener("message",s),a())};i(this,D).addEventListener("message",s)})),d(this,q,c(this,f,He).call(this,n))}static async create(r,n){let a=new ke(r,n);return await i(a,q),a}get waitReady(){return new Promise(r=>{i(this,q).then(()=>{i(this,U)?r():r(new Promise(n=>{i(this,B).addEventListener("connected",()=>{n()})}))})})}get debug(){return i(this,Y)}get ready(){return i(this,K)}get closed(){return i(this,z)}get isLeader(){return i(this,J)}async close(){var r;i(this,z)||(d(this,z,!0),i(this,N)?.close(),i(this,M)?.close(),(r=i(this,te))==null||r.call(this),i(this,D).terminate())}async[Symbol.asyncDispose](){await this.close()}async execProtocolRaw(r){return await c(this,f,x).call(this,"execProtocolRaw",r)}async execProtocol(r){return await c(this,f,x).call(this,"execProtocol",r)}async execProtocolStream(r){return await c(this,f,x).call(this,"execProtocolStream",r)}async execProtocolRawStream(r,n){await c(this,f,x).call(this,"execProtocolRawStream",r,n)}async syncToFs(){await c(this,f,x).call(this,"syncToFs")}async listen(r,n,a){let s=H.toPostgresName(r),o=a??this;return i(this,k).has(s)||i(this,k).set(s,new Set),i(this,k).get(s).add(n),await o.exec(`LISTEN ${r}`),async u=>{await this.unlisten(s,n,u)}}async unlisten(r,n,a){await this.waitReady;let s=a??this;n?i(this,k).get(r)?.delete(n):i(this,k).delete(r),i(this,k).get(r)?.size===0&&await s.exec(`UNLISTEN ${r}`)}onNotification(r){return i(this,_).add(r),()=>{i(this,_).delete(r)}}offNotification(r){i(this,_).delete(r)}async dumpDataDir(r){return await c(this,f,x).call(this,"dumpDataDir",r)}onLeaderChange(r){return i(this,B).addEventListener("leader-change",r),()=>{i(this,B).removeEventListener("leader-change",r)}}offLeaderChange(r){i(this,B).removeEventListener("leader-change",r)}async _handleBlob(r){await c(this,f,x).call(this,"_handleBlob",r)}async _getWrittenBlob(){return await c(this,f,x).call(this,"_getWrittenBlob")}async _cleanupBlob(){await c(this,f,x).call(this,"_cleanupBlob")}async _checkReady(){await this.waitReady}async _runExclusiveQuery(r){await c(this,f,x).call(this,"_acquireQueryLock");try{return await r()}finally{await c(this,f,x).call(this,"_releaseQueryLock")}}async _runExclusiveTransaction(r){await c(this,f,x).call(this,"_acquireTransactionLock");try{return await r()}finally{await c(this,f,x).call(this,"_releaseTransactionLock")}}};q=new WeakMap,Y=new WeakMap,K=new WeakMap,z=new WeakMap,J=new WeakMap,B=new WeakMap,v=new WeakMap,U=new WeakMap,D=new WeakMap,X=new WeakMap,Z=new WeakMap,ee=new WeakMap,N=new WeakMap,M=new WeakMap,te=new WeakMap,k=new WeakMap,_=new WeakMap,re=new WeakMap,he=new WeakMap,f=new WeakSet,He=async function(r={}){for(let[l,m]of Object.entries(i(this,re))){if(m instanceof URL)throw new Error("URL extensions are not supported on the client side of a worker");{let y=await m.setup(this,{},!0);if(y.emscriptenOpts&&console.warn(`PGlite extension ${l} returned emscriptenOpts, these are not supported on the client side of a worker`),y.namespaceObj){let T=this;T[l]=y.namespaceObj}y.bundlePath&&console.warn(`PGlite extension ${l} returned bundlePath, this is not supported on the client side of a worker`),y.init&&await y.init(),y.close&&i(this,he).push(y.close)}}await i(this,Z);let{extensions:n,...a}=r;i(this,D).postMessage({type:"init",options:a}),await i(this,ee);let s=`pglite-tab-close:${i(this,v)}`;d(this,te,await De(s));let o=`pglite-broadcast:${i(this,X)}`;d(this,N,new BroadcastChannel(o));let u=`pglite-tab:${i(this,v)}`;d(this,M,new BroadcastChannel(u)),i(this,N).addEventListener("message",async l=>{l.data.type==="leader-here"?(d(this,U,!1),i(this,B).dispatchEvent(new Event("leader-change")),c(this,f,ye).call(this)):l.data.type==="notify"&&c(this,f,Ye).call(this,l.data.channel,l.data.payload)}),i(this,M).addEventListener("message",async l=>{l.data.type==="connected"&&(d(this,U,!0),i(this,B).dispatchEvent(new Event("connected")),d(this,Y,await c(this,f,x).call(this,"getDebugLevel")),d(this,K,!0))}),i(this,D).addEventListener("message",async l=>{l.data.type==="leader-now"&&(d(this,J,!0),i(this,B).dispatchEvent(new Event("leader-change")))}),c(this,f,ye).call(this),this._initArrayTypes()},ye=async function(){i(this,U)||(i(this,N).postMessage({type:"tab-here",id:i(this,v)}),setTimeout(()=>c(this,f,ye).call(this),16))},x=async function(r,...n){let a=H.uuid(),s={type:"rpc-call",callId:a,method:r,args:n};return i(this,M).postMessage(s),await new Promise((o,u)=>{let l=T=>{if(T.data.callId!==a)return;y();let R=T.data;if(R.type==="rpc-return")o(R.result);else if(R.type==="rpc-error"){let Me=new Error(R.error.message);Object.assign(Me,R.error),u(Me)}else u(new Error("Invalid message"))},m=()=>{y(),u(new me)},y=()=>{i(this,M).removeEventListener("message",l),i(this,B).removeEventListener("leader-change",m)};i(this,B).addEventListener("leader-change",m),i(this,M).addEventListener("message",l)})},Ye=function(r,n){let a=i(this,k).get(r);if(a)for(let s of a)queueMicrotask(()=>s(n));for(let s of i(this,_))queueMicrotask(()=>s(r,n))};var Be=ke;async function sr({init:e}){postMessage({type:"here"});let t=await new Promise(m=>{addEventListener("message",y=>{y.data.type==="init"&&m(y.data.options)},{once:!0})}),r=t.id??`${P}:${t.dataDir??""}`;postMessage({type:"ready",id:r});let n=`pglite-election-lock:${r}`,a=`pglite-broadcast:${r}`,s=new BroadcastChannel(a),o=new Set;await De(n);let u=e(t);s.onmessage=async m=>{let y=m.data;switch(y.type){case"tab-here":ar(y.id,await u,o);break}},s.postMessage({type:"leader-here",id:r}),postMessage({type:"leader-now"}),(await u).onNotification((m,y)=>{s.postMessage({type:"notify",channel:m,payload:y})})}function ar(e,t,r){if(r.has(e))return;r.add(e);let n=`pglite-tab:${e}`,a=`pglite-tab-close:${e}`,s=new BroadcastChannel(n);navigator.locks.request(a,()=>new Promise(u=>{s.close(),r.delete(e),u()}));let o=ir(e,t);s.addEventListener("message",async u=>{let l=u.data;switch(l.type){case"rpc-call":{await t.waitReady;let{callId:m,method:y,args:T}=l;try{let R=await o[y](...T);s.postMessage({type:"rpc-return",callId:m,result:R})}catch(R){console.error(R),s.postMessage({type:"rpc-error",callId:m,error:{message:R.message}})}break}}}),s.postMessage({type:"connected"})}function ir(e,t){let r=null,n=null,a=`pglite-tab-close:${e}`;return De(a).then(()=>{n&&t.exec("ROLLBACK"),r?.(),n?.()}),{async getDebugLevel(){return t.debug},async close(){await t.close()},async execProtocol(s){let{messages:o,data:u}=await t.execProtocol(s);if(u.byteLength!==u.buffer.byteLength){let l=new ArrayBuffer(u.byteLength),m=new Uint8Array(l);return m.set(u),{messages:o,data:m}}else return{messages:o,data:u}},async execProtocolStream(s){return await t.execProtocolStream(s)},async execProtocolRawStream(s,o){return await t.execProtocolRawStream(s,o)},async execProtocolRaw(s){let o=await t.execProtocolRaw(s);if(o.byteLength!==o.buffer.byteLength){let u=new ArrayBuffer(o.byteLength),l=new Uint8Array(u);return l.set(o),l}else return o},async dumpDataDir(s){return await t.dumpDataDir(s)},async syncToFs(){return await t.syncToFs()},async _handleBlob(s){return await t._handleBlob(s)},async _getWrittenBlob(){return await t._getWrittenBlob()},async _cleanupBlob(){return await t._cleanupBlob()},async _checkReady(){return await t._checkReady()},async _acquireQueryLock(){return new Promise(s=>{t._runExclusiveQuery(()=>new Promise(o=>{r=o,s()}))})},async _releaseQueryLock(){r?.(),r=null},async _acquireTransactionLock(){return new Promise(s=>{t._runExclusiveTransaction(()=>new Promise(o=>{n=o,s()}))})},async _releaseTransactionLock(){n?.(),n=null}}}var me=class extends Error{constructor(){super("Leader changed, pending operation in indeterminate state")}};async function De(e){let t;return await new Promise(r=>{navigator.locks.request(e,()=>new Promise(n=>{t=n,r()}))}),t}0&&(module.exports={LeaderChangedError,PGliteWorker,worker});
`);for(let n of t.rows)this.serializers[n.typarray]=a=>Ae(a,this.serializers[n.oid],n.typarray),this.parsers[n.typarray]=a=>Qe(a,this.parsers[n.oid],n.typarray)}async refreshArrayTypes(){await this._initArrayTypes({force:!0})}async query(r,t,n){return await this._checkReady(),await this._runExclusiveTransaction(async()=>await c(this,h,ue).call(this,r,t,n))}async sql(r,...t){let{query:n,params:a}=we(r,...t);return await this.query(n,a)}async exec(r,t){return await this._checkReady(),await this._runExclusiveTransaction(async()=>await c(this,h,O).call(this,r,t))}async describeQuery(r,t){let n=[];try{await c(this,h,S).call(this,R.parse({text:r,types:t?.paramTypes}),t),n=await c(this,h,S).call(this,R.describe({type:"S"}),t)}catch(l){throw l instanceof C?le({e:l,options:t,params:void 0,query:r}):l}finally{n.push(...await c(this,h,S).call(this,R.sync(),t))}let a=n.find(l=>l.name==="parameterDescription"),s=n.find(l=>l.name==="rowDescription"),o=a?.dataTypeIDs.map(l=>({dataTypeID:l,serializer:this.serializers[l]}))??[],u=s?.fields.map(l=>({name:l.name,dataTypeID:l.dataTypeID,parser:this.parsers[l.dataTypeID]}))??[];return{queryParams:o,resultFields:u}}async transaction(r){return await this._checkReady(),await this._runExclusiveTransaction(async()=>{await c(this,h,O).call(this,"BEGIN"),y(this,I,!0);let t=!1,n=()=>{if(t)throw new Error("Transaction is closed")},a={query:async(s,o,u)=>(n(),await c(this,h,ue).call(this,s,o,u)),sql:async(s,...o)=>{n();let{query:u,params:l}=we(s,...o);return await c(this,h,ue).call(this,u,l)},exec:async(s,o)=>(n(),await c(this,h,O).call(this,s,o)),rollback:async()=>{n(),await c(this,h,O).call(this,"ROLLBACK"),t=!0},listen:async(s,o)=>(n(),await this.listen(s,o,a)),get closed(){return t}};try{let s=await r(a);return t||(t=!0,await c(this,h,O).call(this,"COMMIT")),y(this,I,!1),s}catch(s){throw t||(t=!0,await c(this,h,O).call(this,"ROLLBACK")),y(this,I,!1),s}})}async runExclusive(r){return await this._runExclusiveQuery(r)}};$=new WeakMap,I=new WeakMap,h=new WeakSet,S=async function(r,t={}){return await this.execProtocolStream(r,{...t,syncToFs:!1})},ue=async function(r,t=[],n){return await this._runExclusiveQuery(async()=>{c(this,h,Se).call(this,"runQuery",r,t,n),await this._handleBlob(n?.blob);let a=[];try{let o=await c(this,h,S).call(this,R.parse({text:r,types:n?.paramTypes}),n),u=ze(await c(this,h,S).call(this,R.describe({type:"S"}),n)),l=t.map((m,p)=>{let b=u[p];if(m==null)return null;let w=n?.serializers?.[b]??this.serializers[b];return w?w(m):m.toString()});a=[...o,...await c(this,h,S).call(this,R.bind({values:l}),n),...await c(this,h,S).call(this,R.describe({type:"P"}),n),...await c(this,h,S).call(this,R.execute({}),n)]}catch(o){throw o instanceof C?le({e:o,options:n,params:t,query:r}):o}finally{a.push(...await c(this,h,S).call(this,R.sync(),n))}await this._cleanupBlob(),i(this,I)||await this.syncToFs();let s=await this._getWrittenBlob();return Ee(a,this.parsers,n,s)[0]})},O=async function(r,t){return await this._runExclusiveQuery(async()=>{c(this,h,Se).call(this,"runExec",r,t),await this._handleBlob(t?.blob);let n=[];try{n=await c(this,h,S).call(this,R.query(r),t)}catch(s){throw s instanceof C?le({e:s,options:t,params:void 0,query:r}):s}finally{n.push(...await c(this,h,S).call(this,R.sync(),t))}this._cleanupBlob(),i(this,I)||await this.syncToFs();let a=await this._getWrittenBlob();return Ee(n,this.parsers,t,a)})},Se=function(...r){this.debug>0&&console.log(...r)};var Ht=Object.defineProperty,Yt=(e,r)=>{for(var t in r)Ht(e,t,{get:r[t],enumerable:!0})},Y={};Yt(Y,{IN_NODE:()=>ye,WASM_PREFIX:()=>Jt,getFsBundle:()=>er,instantiateWasm:()=>Zt,pgliteProc:()=>Xt,rmdirRecursive:()=>$e,startArtifactDownload:()=>Be,toPostgresName:()=>rr,uuid:()=>tr});function Kt(){let e=process.type;return e==="renderer"||e==="worker"||e==="service-worker"}var ye=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&!Kt(),Jt="/pglite",H=new Map;async function Be(e){ye||H.has(e.toString())||H.set(e.toString(),fetch(e))}var de=new Map,Xt=globalThis&&typeof globalThis.process<"u"?globalThis.process:{exitCode:void 0};async function Zt(e,r,t){if(t||de.has(r.toString())){let n=t||de.get(r.toString());return{instance:await WebAssembly.instantiate(n,e),module:n}}if(ye){let n=await(await import("fs/promises")).readFile(r),{module:a,instance:s}=await WebAssembly.instantiate(n,e);return de.set(r.toString(),a),{instance:s,module:a}}else{H.has(r.toString())||Be(r);let n=await H.get(r.toString()),{module:a,instance:s}=await WebAssembly.instantiateStreaming(n.clone(),e);return de.set(r.toString(),a),{instance:s,module:a}}}async function er(e){return ye?(await(await import("fs/promises")).readFile(e)).buffer:(Be(e),(await H.get(e.toString())).clone().arrayBuffer())}var tr=()=>{if(globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e=new Uint8Array(16);if(globalThis.crypto?.getRandomValues)globalThis.crypto.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];return e.forEach(t=>{r.push(t.toString(16).padStart(2,"0"))}),r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10).join("")};function rr(e){let r;return e.startsWith('"')&&e.endsWith('"')?r=e.substring(1,e.length-1):r=e.toLowerCase(),r}function $e(e,r){try{let t=e.readdir(r).filter(n=>n!=="."&&n!=="..");for(let n of t){let a=r+"/"+n;try{e.readdir(a),$e(e,a)}catch{e.unlink(a)}}e.rmdir(r)}catch{try{e.unlink(r)}catch{}}}var z,K,J,j,X,B,v,U,D,Z,ee,te,N,M,re,k,_,ne,fe,f,He,me,A,Ye,Me=class Me extends pe{constructor(t,n){super();d(this,f);d(this,z);d(this,K,0);d(this,J,!1);d(this,j,!1);d(this,X,!1);d(this,B,new EventTarget);d(this,v);d(this,U,!1);d(this,D);d(this,Z);d(this,ee);d(this,te);d(this,N);d(this,M);d(this,re);d(this,k,new Map);d(this,_,new Set);d(this,ne);d(this,fe,[]);y(this,D,t),y(this,v,Y.uuid()),y(this,ne,n?.extensions??{}),y(this,ee,new Promise(a=>{i(this,D).addEventListener("message",s=>{if(s.data.type==="here")a();else throw new Error("Invalid message")},{once:!0})})),y(this,te,new Promise(a=>{let s=o=>{o.data.type==="ready"&&(y(this,Z,o.data.id),i(this,D).removeEventListener("message",s),a())};i(this,D).addEventListener("message",s)})),y(this,z,c(this,f,He).call(this,n))}static async create(t,n){let a=new Me(t,n);return await i(a,z),a}get waitReady(){return new Promise(t=>{i(this,z).then(()=>{i(this,U)?t():t(new Promise(n=>{i(this,B).addEventListener("connected",()=>{n()})}))})})}get debug(){return i(this,K)}get ready(){return i(this,J)}get closed(){return i(this,j)}get isLeader(){return i(this,X)}async close(){var t;i(this,j)||(y(this,j,!0),i(this,N)?.close(),i(this,M)?.close(),(t=i(this,re))==null||t.call(this),i(this,D).terminate())}async[Symbol.asyncDispose](){await this.close()}async execProtocolRaw(t){return await c(this,f,A).call(this,"execProtocolRaw",t)}async execProtocol(t){return await c(this,f,A).call(this,"execProtocol",t)}async execProtocolStream(t){return await c(this,f,A).call(this,"execProtocolStream",t)}async execProtocolRawStream(t,n){await c(this,f,A).call(this,"execProtocolRawStream",t,n)}async syncToFs(){await c(this,f,A).call(this,"syncToFs")}async listen(t,n,a){let s=Y.toPostgresName(t),o=a??this;return i(this,k).has(s)||i(this,k).set(s,new Set),i(this,k).get(s).add(n),await o.exec(`LISTEN ${t}`),async u=>{await this.unlisten(s,n,u)}}async unlisten(t,n,a){await this.waitReady;let s=a??this;n?i(this,k).get(t)?.delete(n):i(this,k).delete(t),i(this,k).get(t)?.size===0&&await s.exec(`UNLISTEN ${t}`)}onNotification(t){return i(this,_).add(t),()=>{i(this,_).delete(t)}}offNotification(t){i(this,_).delete(t)}async dumpDataDir(t){return await c(this,f,A).call(this,"dumpDataDir",t)}onLeaderChange(t){return i(this,B).addEventListener("leader-change",t),()=>{i(this,B).removeEventListener("leader-change",t)}}offLeaderChange(t){i(this,B).removeEventListener("leader-change",t)}async _handleBlob(t){await c(this,f,A).call(this,"_handleBlob",t)}async _getWrittenBlob(){return await c(this,f,A).call(this,"_getWrittenBlob")}async _cleanupBlob(){await c(this,f,A).call(this,"_cleanupBlob")}async _checkReady(){await this.waitReady}async _runExclusiveQuery(t){await c(this,f,A).call(this,"_acquireQueryLock");try{return await t()}finally{await c(this,f,A).call(this,"_releaseQueryLock")}}async _runExclusiveTransaction(t){await c(this,f,A).call(this,"_acquireTransactionLock");try{return await t()}finally{await c(this,f,A).call(this,"_releaseTransactionLock")}}};z=new WeakMap,K=new WeakMap,J=new WeakMap,j=new WeakMap,X=new WeakMap,B=new WeakMap,v=new WeakMap,U=new WeakMap,D=new WeakMap,Z=new WeakMap,ee=new WeakMap,te=new WeakMap,N=new WeakMap,M=new WeakMap,re=new WeakMap,k=new WeakMap,_=new WeakMap,ne=new WeakMap,fe=new WeakMap,f=new WeakSet,He=async function(t={}){for(let[l,m]of Object.entries(i(this,ne))){if(m instanceof URL)throw new Error("URL extensions are not supported on the client side of a worker");{let p=await m.setup(this,{},!0);if(p.emscriptenOpts&&console.warn(`PGlite extension ${l} returned emscriptenOpts, these are not supported on the client side of a worker`),p.namespaceObj){let b=this;b[l]=p.namespaceObj}p.bundlePath&&console.warn(`PGlite extension ${l} returned bundlePath, this is not supported on the client side of a worker`),p.init&&await p.init(),p.close&&i(this,fe).push(p.close)}}await i(this,ee);let{extensions:n,...a}=t;i(this,D).postMessage({type:"init",options:a}),await i(this,te);let s=`pglite-tab-close:${i(this,v)}`;y(this,re,await ke(s));let o=`pglite-broadcast:${i(this,Z)}`;y(this,N,new BroadcastChannel(o));let u=`pglite-tab:${i(this,v)}`;y(this,M,new BroadcastChannel(u)),i(this,N).addEventListener("message",async l=>{l.data.type==="leader-here"?(y(this,U,!1),i(this,B).dispatchEvent(new Event("leader-change")),c(this,f,me).call(this)):l.data.type==="notify"&&c(this,f,Ye).call(this,l.data.channel,l.data.payload)}),i(this,M).addEventListener("message",async l=>{l.data.type==="connected"&&(y(this,U,!0),i(this,B).dispatchEvent(new Event("connected")),y(this,K,await c(this,f,A).call(this,"getDebugLevel")),y(this,J,!0))}),i(this,D).addEventListener("message",async l=>{l.data.type==="leader-now"&&(y(this,X,!0),i(this,B).dispatchEvent(new Event("leader-change")))}),c(this,f,me).call(this),this._initArrayTypes()},me=async function(){i(this,U)||(i(this,N).postMessage({type:"tab-here",id:i(this,v)}),setTimeout(()=>c(this,f,me).call(this),16))},A=async function(t,...n){let a=Y.uuid(),s={type:"rpc-call",callId:a,method:t,args:n};return i(this,M).postMessage(s),await new Promise((o,u)=>{let l=b=>{if(b.data.callId!==a)return;p();let w=b.data;if(w.type==="rpc-return")o(w.result);else if(w.type==="rpc-error"){let W=new Error(w.error.message);Object.assign(W,w.error),u(W)}else u(new Error("Invalid message"))},m=()=>{p(),u(new he)},p=()=>{i(this,M).removeEventListener("message",l),i(this,B).removeEventListener("leader-change",m)};i(this,B).addEventListener("leader-change",m),i(this,M).addEventListener("message",l)})},Ye=function(t,n){let a=i(this,k).get(t);if(a)for(let s of a)queueMicrotask(()=>s(n));for(let s of i(this,_))queueMicrotask(()=>s(t,n))};var De=Me;async function nr({init:e}){postMessage({type:"here"});let r=await new Promise(m=>{addEventListener("message",p=>{p.data.type==="init"&&m(p.data.options)},{once:!0})}),t=r.id??`${T}:${r.dataDir??""}`;postMessage({type:"ready",id:t});let n=`pglite-election-lock:${t}`,a=`pglite-broadcast:${t}`,s=new BroadcastChannel(a),o=new Set;await ke(n);let u=e(r);s.onmessage=async m=>{let p=m.data;switch(p.type){case"tab-here":sr(p.id,await u,o);break}},s.postMessage({type:"leader-here",id:t}),postMessage({type:"leader-now"}),(await u).onNotification((m,p)=>{s.postMessage({type:"notify",channel:m,payload:p})})}function sr(e,r,t){if(t.has(e))return;t.add(e);let n=`pglite-tab:${e}`,a=`pglite-tab-close:${e}`,s=new BroadcastChannel(n);navigator.locks.request(a,()=>new Promise(u=>{s.close(),t.delete(e),u()}));let o=ar(e,r);s.addEventListener("message",async u=>{let l=u.data;switch(l.type){case"rpc-call":{await r.waitReady;let{callId:m,method:p,args:b}=l;try{let w=await o[p](...b);s.postMessage({type:"rpc-return",callId:m,result:w})}catch(w){console.error(w),s.postMessage({type:"rpc-error",callId:m,error:{message:w.message}})}break}}}),s.postMessage({type:"connected"})}function ar(e,r){let t=null,n=null,a=`pglite-tab-close:${e}`;return ke(a).then(()=>{n&&r.exec("ROLLBACK"),t?.(),n?.()}),{async getDebugLevel(){return r.debug},async close(){await r.close()},async execProtocol(s){let{messages:o,data:u}=await r.execProtocol(s);if(u.byteLength!==u.buffer.byteLength){let l=new ArrayBuffer(u.byteLength),m=new Uint8Array(l);return m.set(u),{messages:o,data:m}}else return{messages:o,data:u}},async execProtocolStream(s){return await r.execProtocolStream(s)},async execProtocolRawStream(s,o){return await r.execProtocolRawStream(s,o)},async execProtocolRaw(s){let o=await r.execProtocolRaw(s);if(o.byteLength!==o.buffer.byteLength){let u=new ArrayBuffer(o.byteLength),l=new Uint8Array(u);return l.set(o),l}else return o},async dumpDataDir(s){return await r.dumpDataDir(s)},async syncToFs(){return await r.syncToFs()},async _handleBlob(s){return await r._handleBlob(s)},async _getWrittenBlob(){return await r._getWrittenBlob()},async _cleanupBlob(){return await r._cleanupBlob()},async _checkReady(){return await r._checkReady()},async _acquireQueryLock(){return new Promise(s=>{r._runExclusiveQuery(()=>new Promise(o=>{t=o,s()}))})},async _releaseQueryLock(){t?.(),t=null},async _acquireTransactionLock(){return new Promise(s=>{r._runExclusiveTransaction(()=>new Promise(o=>{n=o,s()}))})},async _releaseTransactionLock(){n?.(),n=null}}}var he=class extends Error{constructor(){super("Leader changed, pending operation in indeterminate state")}};async function ke(e){let r;return await new Promise(t=>{navigator.locks.request(e,()=>new Promise(n=>{r=n,t()}))}),r}0&&(module.exports={LeaderChangedError,PGliteWorker,worker});
//# sourceMappingURL=index.cjs.map

@@ -1,2 +0,2 @@

import { n as Extensions, r as PGliteOptions, y as BasePGlite, d as PGliteInterface, s as PGliteInterfaceExtensions, D as DebugLevel, o as ExecProtocolResult, B as BackendMessage, T as Transaction, z as DumpTarCompressionOptions, b as PGlite } from '../pglite-CpaPhfpC.cjs';
import { n as Extensions, r as PGliteOptions, y as BasePGlite, d as PGliteInterface, s as PGliteInterfaceExtensions, D as DebugLevel, o as ExecProtocolResult, B as BackendMessage, T as Transaction, z as DumpTarCompressionOptions, b as PGlite } from '../pglite-DIqDo27J.cjs';

@@ -3,0 +3,0 @@ type PGliteWorkerOptions<E extends Extensions = Extensions> = PGliteOptions<E> & {

@@ -1,2 +0,2 @@

import { n as Extensions, r as PGliteOptions, y as BasePGlite, d as PGliteInterface, s as PGliteInterfaceExtensions, D as DebugLevel, o as ExecProtocolResult, B as BackendMessage, T as Transaction, z as DumpTarCompressionOptions, b as PGlite } from '../pglite-CpaPhfpC.js';
import { n as Extensions, r as PGliteOptions, y as BasePGlite, d as PGliteInterface, s as PGliteInterfaceExtensions, D as DebugLevel, o as ExecProtocolResult, B as BackendMessage, T as Transaction, z as DumpTarCompressionOptions, b as PGlite } from '../pglite-DIqDo27J.js';

@@ -3,0 +3,0 @@ type PGliteWorkerOptions<E extends Extensions = Extensions> = PGliteOptions<E> & {

@@ -1,2 +0,2 @@

import{a as j}from"../chunk-SRXPYZFS.js";import"../chunk-2B24BK54.js";import{a as I}from"../chunk-VVBUWNGP.js";import"../chunk-F4GETNPB.js";import{e as t,f as p,g as u,h,j as Q}from"../chunk-QY3QWFKW.js";Q();var W,T,C,M,B,w,x,L,P,A,_,O,R,v,G,k,E,D,S,i,H,U,g,K,q=class q extends j{constructor(e,r){super();p(this,i);p(this,W);p(this,T,0);p(this,C,!1);p(this,M,!1);p(this,B,!1);p(this,w,new EventTarget);p(this,x);p(this,L,!1);p(this,P);p(this,A);p(this,_);p(this,O);p(this,R);p(this,v);p(this,G);p(this,k,new Map);p(this,E,new Set);p(this,D);p(this,S,[]);u(this,P,e),u(this,x,I.uuid()),u(this,D,r?.extensions??{}),u(this,_,new Promise(o=>{t(this,P).addEventListener("message",s=>{if(s.data.type==="here")o();else throw new Error("Invalid message")},{once:!0})})),u(this,O,new Promise(o=>{let s=a=>{a.data.type==="ready"&&(u(this,A,a.data.id),t(this,P).removeEventListener("message",s),o())};t(this,P).addEventListener("message",s)})),u(this,W,h(this,i,H).call(this,r))}static async create(e,r){let o=new q(e,r);return await t(o,W),o}get waitReady(){return new Promise(e=>{t(this,W).then(()=>{t(this,L)?e():e(new Promise(r=>{t(this,w).addEventListener("connected",()=>{r()})}))})})}get debug(){return t(this,T)}get ready(){return t(this,C)}get closed(){return t(this,M)}get isLeader(){return t(this,B)}async close(){var e;t(this,M)||(u(this,M,!0),t(this,R)?.close(),t(this,v)?.close(),(e=t(this,G))==null||e.call(this),t(this,P).terminate())}async[Symbol.asyncDispose](){await this.close()}async execProtocolRaw(e){return await h(this,i,g).call(this,"execProtocolRaw",e)}async execProtocol(e){return await h(this,i,g).call(this,"execProtocol",e)}async execProtocolStream(e){return await h(this,i,g).call(this,"execProtocolStream",e)}async execProtocolRawStream(e,r){await h(this,i,g).call(this,"execProtocolRawStream",e,r)}async syncToFs(){await h(this,i,g).call(this,"syncToFs")}async listen(e,r,o){let s=I.toPostgresName(e),a=o??this;return t(this,k).has(s)||t(this,k).set(s,new Set),t(this,k).get(s).add(r),await a.exec(`LISTEN ${e}`),async l=>{await this.unlisten(s,r,l)}}async unlisten(e,r,o){await this.waitReady;let s=o??this;r?t(this,k).get(e)?.delete(r):t(this,k).delete(e),t(this,k).get(e)?.size===0&&await s.exec(`UNLISTEN ${e}`)}onNotification(e){return t(this,E).add(e),()=>{t(this,E).delete(e)}}offNotification(e){t(this,E).delete(e)}async dumpDataDir(e){return await h(this,i,g).call(this,"dumpDataDir",e)}onLeaderChange(e){return t(this,w).addEventListener("leader-change",e),()=>{t(this,w).removeEventListener("leader-change",e)}}offLeaderChange(e){t(this,w).removeEventListener("leader-change",e)}async _handleBlob(e){await h(this,i,g).call(this,"_handleBlob",e)}async _getWrittenBlob(){return await h(this,i,g).call(this,"_getWrittenBlob")}async _cleanupBlob(){await h(this,i,g).call(this,"_cleanupBlob")}async _checkReady(){await this.waitReady}async _runExclusiveQuery(e){await h(this,i,g).call(this,"_acquireQueryLock");try{return await e()}finally{await h(this,i,g).call(this,"_releaseQueryLock")}}async _runExclusiveTransaction(e){await h(this,i,g).call(this,"_acquireTransactionLock");try{return await e()}finally{await h(this,i,g).call(this,"_releaseTransactionLock")}}};W=new WeakMap,T=new WeakMap,C=new WeakMap,M=new WeakMap,B=new WeakMap,w=new WeakMap,x=new WeakMap,L=new WeakMap,P=new WeakMap,A=new WeakMap,_=new WeakMap,O=new WeakMap,R=new WeakMap,v=new WeakMap,G=new WeakMap,k=new WeakMap,E=new WeakMap,D=new WeakMap,S=new WeakMap,i=new WeakSet,H=async function(e={}){for(let[c,y]of Object.entries(t(this,D))){if(y instanceof URL)throw new Error("URL extensions are not supported on the client side of a worker");{let d=await y.setup(this,{},!0);if(d.emscriptenOpts&&console.warn(`PGlite extension ${c} returned emscriptenOpts, these are not supported on the client side of a worker`),d.namespaceObj){let b=this;b[c]=d.namespaceObj}d.bundlePath&&console.warn(`PGlite extension ${c} returned bundlePath, this is not supported on the client side of a worker`),d.init&&await d.init(),d.close&&t(this,S).push(d.close)}}await t(this,_);let{extensions:r,...o}=e;t(this,P).postMessage({type:"init",options:o}),await t(this,O);let s=`pglite-tab-close:${t(this,x)}`;u(this,G,await N(s));let a=`pglite-broadcast:${t(this,A)}`;u(this,R,new BroadcastChannel(a));let l=`pglite-tab:${t(this,x)}`;u(this,v,new BroadcastChannel(l)),t(this,R).addEventListener("message",async c=>{c.data.type==="leader-here"?(u(this,L,!1),t(this,w).dispatchEvent(new Event("leader-change")),h(this,i,U).call(this)):c.data.type==="notify"&&h(this,i,K).call(this,c.data.channel,c.data.payload)}),t(this,v).addEventListener("message",async c=>{c.data.type==="connected"&&(u(this,L,!0),t(this,w).dispatchEvent(new Event("connected")),u(this,T,await h(this,i,g).call(this,"getDebugLevel")),u(this,C,!0))}),t(this,P).addEventListener("message",async c=>{c.data.type==="leader-now"&&(u(this,B,!0),t(this,w).dispatchEvent(new Event("leader-change")))}),h(this,i,U).call(this),this._initArrayTypes()},U=async function(){t(this,L)||(t(this,R).postMessage({type:"tab-here",id:t(this,x)}),setTimeout(()=>h(this,i,U).call(this),16))},g=async function(e,...r){let o=I.uuid(),s={type:"rpc-call",callId:o,method:e,args:r};return t(this,v).postMessage(s),await new Promise((a,l)=>{let c=b=>{if(b.data.callId!==o)return;d();let f=b.data;if(f.type==="rpc-return")a(f.result);else if(f.type==="rpc-error"){let F=new Error(f.error.message);Object.assign(F,f.error),l(F)}else l(new Error("Invalid message"))},y=()=>{d(),l(new $)},d=()=>{t(this,v).removeEventListener("message",c),t(this,w).removeEventListener("leader-change",y)};t(this,w).addEventListener("leader-change",y),t(this,v).addEventListener("message",c)})},K=function(e,r){let o=t(this,k).get(e);if(o)for(let s of o)queueMicrotask(()=>s(r));for(let s of t(this,E))queueMicrotask(()=>s(e,r))};var z=q;async function te({init:m}){postMessage({type:"here"});let n=await new Promise(y=>{addEventListener("message",d=>{d.data.type==="init"&&y(d.data.options)},{once:!0})}),e=n.id??`${import.meta.url}:${n.dataDir??""}`;postMessage({type:"ready",id:e});let r=`pglite-election-lock:${e}`,o=`pglite-broadcast:${e}`,s=new BroadcastChannel(o),a=new Set;await N(r);let l=m(n);s.onmessage=async y=>{let d=y.data;switch(d.type){case"tab-here":J(d.id,await l,a);break}},s.postMessage({type:"leader-here",id:e}),postMessage({type:"leader-now"}),(await l).onNotification((y,d)=>{s.postMessage({type:"notify",channel:y,payload:d})})}function J(m,n,e){if(e.has(m))return;e.add(m);let r=`pglite-tab:${m}`,o=`pglite-tab-close:${m}`,s=new BroadcastChannel(r);navigator.locks.request(o,()=>new Promise(l=>{s.close(),e.delete(m),l()}));let a=V(m,n);s.addEventListener("message",async l=>{let c=l.data;switch(c.type){case"rpc-call":{await n.waitReady;let{callId:y,method:d,args:b}=c;try{let f=await a[d](...b);s.postMessage({type:"rpc-return",callId:y,result:f})}catch(f){console.error(f),s.postMessage({type:"rpc-error",callId:y,error:{message:f.message}})}break}}}),s.postMessage({type:"connected"})}function V(m,n){let e=null,r=null,o=`pglite-tab-close:${m}`;return N(o).then(()=>{r&&n.exec("ROLLBACK"),e?.(),r?.()}),{async getDebugLevel(){return n.debug},async close(){await n.close()},async execProtocol(s){let{messages:a,data:l}=await n.execProtocol(s);if(l.byteLength!==l.buffer.byteLength){let c=new ArrayBuffer(l.byteLength),y=new Uint8Array(c);return y.set(l),{messages:a,data:y}}else return{messages:a,data:l}},async execProtocolStream(s){return await n.execProtocolStream(s)},async execProtocolRawStream(s,a){return await n.execProtocolRawStream(s,a)},async execProtocolRaw(s){let a=await n.execProtocolRaw(s);if(a.byteLength!==a.buffer.byteLength){let l=new ArrayBuffer(a.byteLength),c=new Uint8Array(l);return c.set(a),c}else return a},async dumpDataDir(s){return await n.dumpDataDir(s)},async syncToFs(){return await n.syncToFs()},async _handleBlob(s){return await n._handleBlob(s)},async _getWrittenBlob(){return await n._getWrittenBlob()},async _cleanupBlob(){return await n._cleanupBlob()},async _checkReady(){return await n._checkReady()},async _acquireQueryLock(){return new Promise(s=>{n._runExclusiveQuery(()=>new Promise(a=>{e=a,s()}))})},async _releaseQueryLock(){e?.(),e=null},async _acquireTransactionLock(){return new Promise(s=>{n._runExclusiveTransaction(()=>new Promise(a=>{r=a,s()}))})},async _releaseTransactionLock(){r?.(),r=null}}}var $=class extends Error{constructor(){super("Leader changed, pending operation in indeterminate state")}};async function N(m){let n;return await new Promise(e=>{navigator.locks.request(m,()=>new Promise(r=>{n=r,e()}))}),n}export{$ as LeaderChangedError,z as PGliteWorker,te as worker};
import{a as j}from"../chunk-JDT7TZ73.js";import"../chunk-2BOC2OMW.js";import{a as I}from"../chunk-VVBUWNGP.js";import"../chunk-F4GETNPB.js";import{e as t,f as p,g as u,h,j as Q}from"../chunk-QY3QWFKW.js";Q();var W,T,C,M,B,w,x,L,P,A,_,O,R,v,G,k,E,D,S,i,H,U,g,K,q=class q extends j{constructor(e,r){super();p(this,i);p(this,W);p(this,T,0);p(this,C,!1);p(this,M,!1);p(this,B,!1);p(this,w,new EventTarget);p(this,x);p(this,L,!1);p(this,P);p(this,A);p(this,_);p(this,O);p(this,R);p(this,v);p(this,G);p(this,k,new Map);p(this,E,new Set);p(this,D);p(this,S,[]);u(this,P,e),u(this,x,I.uuid()),u(this,D,r?.extensions??{}),u(this,_,new Promise(o=>{t(this,P).addEventListener("message",s=>{if(s.data.type==="here")o();else throw new Error("Invalid message")},{once:!0})})),u(this,O,new Promise(o=>{let s=a=>{a.data.type==="ready"&&(u(this,A,a.data.id),t(this,P).removeEventListener("message",s),o())};t(this,P).addEventListener("message",s)})),u(this,W,h(this,i,H).call(this,r))}static async create(e,r){let o=new q(e,r);return await t(o,W),o}get waitReady(){return new Promise(e=>{t(this,W).then(()=>{t(this,L)?e():e(new Promise(r=>{t(this,w).addEventListener("connected",()=>{r()})}))})})}get debug(){return t(this,T)}get ready(){return t(this,C)}get closed(){return t(this,M)}get isLeader(){return t(this,B)}async close(){var e;t(this,M)||(u(this,M,!0),t(this,R)?.close(),t(this,v)?.close(),(e=t(this,G))==null||e.call(this),t(this,P).terminate())}async[Symbol.asyncDispose](){await this.close()}async execProtocolRaw(e){return await h(this,i,g).call(this,"execProtocolRaw",e)}async execProtocol(e){return await h(this,i,g).call(this,"execProtocol",e)}async execProtocolStream(e){return await h(this,i,g).call(this,"execProtocolStream",e)}async execProtocolRawStream(e,r){await h(this,i,g).call(this,"execProtocolRawStream",e,r)}async syncToFs(){await h(this,i,g).call(this,"syncToFs")}async listen(e,r,o){let s=I.toPostgresName(e),a=o??this;return t(this,k).has(s)||t(this,k).set(s,new Set),t(this,k).get(s).add(r),await a.exec(`LISTEN ${e}`),async l=>{await this.unlisten(s,r,l)}}async unlisten(e,r,o){await this.waitReady;let s=o??this;r?t(this,k).get(e)?.delete(r):t(this,k).delete(e),t(this,k).get(e)?.size===0&&await s.exec(`UNLISTEN ${e}`)}onNotification(e){return t(this,E).add(e),()=>{t(this,E).delete(e)}}offNotification(e){t(this,E).delete(e)}async dumpDataDir(e){return await h(this,i,g).call(this,"dumpDataDir",e)}onLeaderChange(e){return t(this,w).addEventListener("leader-change",e),()=>{t(this,w).removeEventListener("leader-change",e)}}offLeaderChange(e){t(this,w).removeEventListener("leader-change",e)}async _handleBlob(e){await h(this,i,g).call(this,"_handleBlob",e)}async _getWrittenBlob(){return await h(this,i,g).call(this,"_getWrittenBlob")}async _cleanupBlob(){await h(this,i,g).call(this,"_cleanupBlob")}async _checkReady(){await this.waitReady}async _runExclusiveQuery(e){await h(this,i,g).call(this,"_acquireQueryLock");try{return await e()}finally{await h(this,i,g).call(this,"_releaseQueryLock")}}async _runExclusiveTransaction(e){await h(this,i,g).call(this,"_acquireTransactionLock");try{return await e()}finally{await h(this,i,g).call(this,"_releaseTransactionLock")}}};W=new WeakMap,T=new WeakMap,C=new WeakMap,M=new WeakMap,B=new WeakMap,w=new WeakMap,x=new WeakMap,L=new WeakMap,P=new WeakMap,A=new WeakMap,_=new WeakMap,O=new WeakMap,R=new WeakMap,v=new WeakMap,G=new WeakMap,k=new WeakMap,E=new WeakMap,D=new WeakMap,S=new WeakMap,i=new WeakSet,H=async function(e={}){for(let[c,y]of Object.entries(t(this,D))){if(y instanceof URL)throw new Error("URL extensions are not supported on the client side of a worker");{let d=await y.setup(this,{},!0);if(d.emscriptenOpts&&console.warn(`PGlite extension ${c} returned emscriptenOpts, these are not supported on the client side of a worker`),d.namespaceObj){let b=this;b[c]=d.namespaceObj}d.bundlePath&&console.warn(`PGlite extension ${c} returned bundlePath, this is not supported on the client side of a worker`),d.init&&await d.init(),d.close&&t(this,S).push(d.close)}}await t(this,_);let{extensions:r,...o}=e;t(this,P).postMessage({type:"init",options:o}),await t(this,O);let s=`pglite-tab-close:${t(this,x)}`;u(this,G,await N(s));let a=`pglite-broadcast:${t(this,A)}`;u(this,R,new BroadcastChannel(a));let l=`pglite-tab:${t(this,x)}`;u(this,v,new BroadcastChannel(l)),t(this,R).addEventListener("message",async c=>{c.data.type==="leader-here"?(u(this,L,!1),t(this,w).dispatchEvent(new Event("leader-change")),h(this,i,U).call(this)):c.data.type==="notify"&&h(this,i,K).call(this,c.data.channel,c.data.payload)}),t(this,v).addEventListener("message",async c=>{c.data.type==="connected"&&(u(this,L,!0),t(this,w).dispatchEvent(new Event("connected")),u(this,T,await h(this,i,g).call(this,"getDebugLevel")),u(this,C,!0))}),t(this,P).addEventListener("message",async c=>{c.data.type==="leader-now"&&(u(this,B,!0),t(this,w).dispatchEvent(new Event("leader-change")))}),h(this,i,U).call(this),this._initArrayTypes()},U=async function(){t(this,L)||(t(this,R).postMessage({type:"tab-here",id:t(this,x)}),setTimeout(()=>h(this,i,U).call(this),16))},g=async function(e,...r){let o=I.uuid(),s={type:"rpc-call",callId:o,method:e,args:r};return t(this,v).postMessage(s),await new Promise((a,l)=>{let c=b=>{if(b.data.callId!==o)return;d();let f=b.data;if(f.type==="rpc-return")a(f.result);else if(f.type==="rpc-error"){let F=new Error(f.error.message);Object.assign(F,f.error),l(F)}else l(new Error("Invalid message"))},y=()=>{d(),l(new $)},d=()=>{t(this,v).removeEventListener("message",c),t(this,w).removeEventListener("leader-change",y)};t(this,w).addEventListener("leader-change",y),t(this,v).addEventListener("message",c)})},K=function(e,r){let o=t(this,k).get(e);if(o)for(let s of o)queueMicrotask(()=>s(r));for(let s of t(this,E))queueMicrotask(()=>s(e,r))};var z=q;async function te({init:m}){postMessage({type:"here"});let n=await new Promise(y=>{addEventListener("message",d=>{d.data.type==="init"&&y(d.data.options)},{once:!0})}),e=n.id??`${import.meta.url}:${n.dataDir??""}`;postMessage({type:"ready",id:e});let r=`pglite-election-lock:${e}`,o=`pglite-broadcast:${e}`,s=new BroadcastChannel(o),a=new Set;await N(r);let l=m(n);s.onmessage=async y=>{let d=y.data;switch(d.type){case"tab-here":J(d.id,await l,a);break}},s.postMessage({type:"leader-here",id:e}),postMessage({type:"leader-now"}),(await l).onNotification((y,d)=>{s.postMessage({type:"notify",channel:y,payload:d})})}function J(m,n,e){if(e.has(m))return;e.add(m);let r=`pglite-tab:${m}`,o=`pglite-tab-close:${m}`,s=new BroadcastChannel(r);navigator.locks.request(o,()=>new Promise(l=>{s.close(),e.delete(m),l()}));let a=V(m,n);s.addEventListener("message",async l=>{let c=l.data;switch(c.type){case"rpc-call":{await n.waitReady;let{callId:y,method:d,args:b}=c;try{let f=await a[d](...b);s.postMessage({type:"rpc-return",callId:y,result:f})}catch(f){console.error(f),s.postMessage({type:"rpc-error",callId:y,error:{message:f.message}})}break}}}),s.postMessage({type:"connected"})}function V(m,n){let e=null,r=null,o=`pglite-tab-close:${m}`;return N(o).then(()=>{r&&n.exec("ROLLBACK"),e?.(),r?.()}),{async getDebugLevel(){return n.debug},async close(){await n.close()},async execProtocol(s){let{messages:a,data:l}=await n.execProtocol(s);if(l.byteLength!==l.buffer.byteLength){let c=new ArrayBuffer(l.byteLength),y=new Uint8Array(c);return y.set(l),{messages:a,data:y}}else return{messages:a,data:l}},async execProtocolStream(s){return await n.execProtocolStream(s)},async execProtocolRawStream(s,a){return await n.execProtocolRawStream(s,a)},async execProtocolRaw(s){let a=await n.execProtocolRaw(s);if(a.byteLength!==a.buffer.byteLength){let l=new ArrayBuffer(a.byteLength),c=new Uint8Array(l);return c.set(a),c}else return a},async dumpDataDir(s){return await n.dumpDataDir(s)},async syncToFs(){return await n.syncToFs()},async _handleBlob(s){return await n._handleBlob(s)},async _getWrittenBlob(){return await n._getWrittenBlob()},async _cleanupBlob(){return await n._cleanupBlob()},async _checkReady(){return await n._checkReady()},async _acquireQueryLock(){return new Promise(s=>{n._runExclusiveQuery(()=>new Promise(a=>{e=a,s()}))})},async _releaseQueryLock(){e?.(),e=null},async _acquireTransactionLock(){return new Promise(s=>{n._runExclusiveTransaction(()=>new Promise(a=>{r=a,s()}))})},async _releaseTransactionLock(){r?.(),r=null}}}var $=class extends Error{constructor(){super("Leader changed, pending operation in indeterminate state")}};async function N(m){let n;return await new Promise(e=>{navigator.locks.request(m,()=>new Promise(r=>{n=r,e()}))}),n}export{$ as LeaderChangedError,z as PGliteWorker,te as worker};
//# sourceMappingURL=index.js.map
{
"name": "@electric-sql/pglite",
"version": "0.5.4",
"version": "0.5.5",
"private": false,

@@ -113,3 +113,2 @@ "publishConfig": {

"!dist/pgstattuple.tar.gz",
"!dist/spi.tar.gz",
"!dist/test_decoding.tar.gz",

@@ -116,0 +115,0 @@ "!dist/vacuumlo.tar.gz",

import{b as ne,e as r,f as h,g as d,h as p,i as re,j as y}from"./chunk-QY3QWFKW.js";var dn={};ne(dn,{ABSTIME:()=>xt,ACLITEM:()=>Lt,BIT:()=>Vt,BOOL:()=>fe,BPCHAR:()=>Ge,BYTEA:()=>me,CHAR:()=>mt,CID:()=>gt,CIDR:()=>It,CIRCLE:()=>Ct,DATE:()=>_e,FLOAT4:()=>Ve,FLOAT8:()=>Fe,GTSVECTOR:()=>Zt,INET:()=>Pt,INT2:()=>Oe,INT4:()=>Ue,INT8:()=>ye,INTERVAL:()=>Ut,JSON:()=>be,JSONB:()=>He,MACADDR:()=>Nt,MACADDR8:()=>Et,MONEY:()=>Tt,NUMERIC:()=>Gt,OID:()=>ke,PATH:()=>Bt,PG_DEPENDENCIES:()=>Jt,PG_LSN:()=>Wt,PG_NDISTINCT:()=>Kt,PG_NODE_TREE:()=>At,POLYGON:()=>Dt,REFCURSOR:()=>Qt,REGCLASS:()=>zt,REGCONFIG:()=>en,REGDICTIONARY:()=>tn,REGNAMESPACE:()=>nn,REGOPER:()=>vt,REGOPERATOR:()=>Ht,REGPROC:()=>yt,REGPROCEDURE:()=>_t,REGROLE:()=>rn,REGTYPE:()=>qt,RELTIME:()=>Mt,SMGR:()=>St,TEXT:()=>he,TID:()=>ht,TIME:()=>Ot,TIMESTAMP:()=>ve,TIMESTAMPTZ:()=>ge,TIMETZ:()=>kt,TINTERVAL:()=>Rt,TSQUERY:()=>Xt,TSVECTOR:()=>$t,TXID_SNAPSHOT:()=>jt,UUID:()=>Yt,VARBIT:()=>Ft,VARCHAR:()=>Qe,XID:()=>bt,XML:()=>wt,arrayParser:()=>pn,arraySerializer:()=>qe,parseType:()=>se,parsers:()=>sn,serializers:()=>an,types:()=>ze});y();var dt=globalThis.JSON.parse,ft=globalThis.JSON.stringify,fe=16,me=17,mt=18,ye=20,Oe=21,Ue=23,yt=24,he=25,ke=26,ht=27,bt=28,gt=29,be=114,wt=142,At=194,St=210,Bt=602,Dt=604,It=650,Ve=700,Fe=701,xt=702,Mt=703,Rt=704,Ct=718,Et=774,Tt=790,Nt=829,Pt=869,Lt=1033,Ge=1042,Qe=1043,_e=1082,Ot=1083,ve=1114,ge=1184,Ut=1186,kt=1266,Vt=1560,Ft=1562,Gt=1700,Qt=1790,_t=2202,vt=2203,Ht=2204,zt=2205,qt=2206,Yt=2950,jt=2970,Wt=3220,Kt=3361,Jt=3402,$t=3614,Xt=3615,Zt=3642,en=3734,tn=3769,He=3802,nn=4089,rn=4096,ze={string:{to:he,from:[he,Qe,Ge],serialize:t=>t instanceof Date?t.toISOString():t.toString(),parse:t=>t},number:{to:0,from:[Oe,Ue,ke,Ve,Fe],serialize:t=>t.toString(),parse:t=>+t},bigint:{to:ye,from:[ye],serialize:t=>t.toString(),parse:t=>{let e=BigInt(t);return e<Number.MIN_SAFE_INTEGER||e>Number.MAX_SAFE_INTEGER?e:Number(e)}},json:{to:be,from:[be,He],serialize:t=>typeof t=="string"?t:ft(t,(e,n)=>typeof n=="bigint"?n.toString():n),parse:t=>dt(t)},boolean:{to:fe,from:[fe],serialize:t=>{if(typeof t=="boolean")return t?"t":"f";if(typeof t=="number"){if(t===1)return"t";if(t===0)return"f"}else if(typeof t=="string"){let e=t.trim().toLowerCase();if(["true","t","yes","y","on","1"].includes(e))return"t";if(["false","f","no","n","off","0"].includes(e))return"f"}throw new Error("Invalid input for boolean type")},parse:t=>t==="t"},date:{to:ge,from:[_e,ve,ge],serialize:t=>{if(typeof t=="string")return t;if(typeof t=="number")return new Date(t).toISOString();if(t instanceof Date)return t.toISOString();throw new Error("Invalid input for date type")},parse:t=>new Date(t)},bytea:{to:me,from:[me],serialize:t=>{if(!(t instanceof Uint8Array))throw new Error("Invalid input for bytea type");return"\\x"+Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")},parse:t=>{let e=t.slice(2);return Uint8Array.from({length:e.length/2},(n,s)=>parseInt(e.substring(s*2,(s+1)*2),16))}}},we=on(ze),sn=we.parsers,an=we.serializers;function se(t,e,n){if(t===null)return null;let s=n?.[e]??we.parsers[e];return s?s(t,e):t}function on(t){return Object.keys(t).reduce(({parsers:e,serializers:n},s)=>{let{to:i,from:a,serialize:u,parse:m}=t[s];return n[i]=u,n[s]=u,e[s]=m,Array.isArray(a)?a.forEach(l=>{e[l]=m,n[l]=u}):(e[a]=m,n[a]=u),{parsers:e,serializers:n}},{parsers:{},serializers:{}})}var un=/\\/g,cn=/"/g;function ln(t){return t.replace(un,"\\\\").replace(cn,'\\"')}function qe(t,e,n){if(Array.isArray(t)===!1)return t;if(!t.length)return"{}";let s=t[0],i=n===1020?";":",";return Array.isArray(s)?`{${t.map(a=>qe(a,e,n)).join(i)}}`:`{${t.map(a=>(a===void 0&&(a=null),a===null?"null":'"'+ln(e?e(a):a.toString())+'"')).join(i)}}`}var de={i:0,char:null,str:"",quoted:!1,last:0,p:null};function pn(t,e,n){return de.i=de.last=0,Ye(de,t,e,n)[0]}function Ye(t,e,n,s){let i=[],a=s===1020?";":",";for(;t.i<e.length;t.i++){if(t.char=e[t.i],t.quoted)t.char==="\\"?t.str+=e[++t.i]:t.char==='"'?(i.push(n?n(t.str):t.str),t.str="",t.quoted=e[t.i+1]==='"',t.last=t.i+2):t.str+=t.char;else if(t.char==='"')t.quoted=!0;else if(t.char==="{")t.last=++t.i,i.push(Ye(t,e,n,s));else if(t.char==="}"){if(t.last<t.i){let u=e.slice(t.last,t.i);u==="NULL"&&!t.quoted?i.push(null):i.push(n?n(u):u)}t.quoted=!1,t.last=t.i+1;break}else if(t.char===a&&t.p!=="}"&&t.p!=='"'){let u=e.slice(t.last,t.i);u==="NULL"&&!t.quoted?i.push(null):i.push(n?n(u):u),t.last=t.i+1}t.p=t.char}return t.last<t.i&&i.push(n?n(e.slice(t.last,t.i+1)):e.slice(t.last,t.i+1)),i}var hn={};ne(hn,{parseDescribeStatementResults:()=>yn,parseResults:()=>fn});y();function fn(t,e,n,s){let i=[],a={rows:[],fields:[]},u=0,m={...e,...n?.parsers};return t.forEach(l=>{switch(l.name){case"rowDescription":{let U=l;a.fields=U.fields.map(C=>({name:C.name,dataTypeID:C.dataTypeID}));break}case"dataRow":{if(!a)break;let U=l;n?.rowMode==="array"?a.rows.push(U.fields.map((C,te)=>se(C,a.fields[te].dataTypeID,m))):a.rows.push(Object.fromEntries(U.fields.map((C,te)=>[a.fields[te].name,se(C,a.fields[te].dataTypeID,m)])));break}case"commandComplete":{u+=mn(l),i.push({...a,affectedRows:u,...s?{blob:s}:{}}),a={rows:[],fields:[]};break}}}),i.length===0&&i.push({affectedRows:0,rows:[],fields:[]}),i}function mn(t){let e=t.text.split(" ");switch(e[0]){case"INSERT":return parseInt(e[2],10);case"UPDATE":case"DELETE":case"COPY":case"MERGE":return parseInt(e[1],10);default:return 0}}function yn(t){let e=t.find(n=>n.name==="parameterDescription");return e?e.dataTypeIDs:[]}var Ce={};ne(Ce,{AuthenticationCleartextPassword:()=>V,AuthenticationMD5Password:()=>F,AuthenticationOk:()=>k,AuthenticationSASL:()=>G,AuthenticationSASLContinue:()=>Q,AuthenticationSASLFinal:()=>_,BackendKeyDataMessage:()=>W,CommandCompleteMessage:()=>$,CopyDataMessage:()=>v,CopyResponse:()=>H,DataRowMessage:()=>X,DatabaseError:()=>E,Field:()=>z,NoticeMessage:()=>Z,NotificationResponseMessage:()=>K,ParameterDescriptionMessage:()=>Y,ParameterStatusMessage:()=>j,ReadyForQueryMessage:()=>J,RowDescriptionMessage:()=>q,bindComplete:()=>Se,closeComplete:()=>Be,copyDone:()=>Re,emptyQuery:()=>Me,noData:()=>De,parseComplete:()=>Ae,portalSuspended:()=>Ie,replicationStart:()=>xe});y();var Ae={name:"parseComplete",length:5},Se={name:"bindComplete",length:5},Be={name:"closeComplete",length:5},De={name:"noData",length:5},Ie={name:"portalSuspended",length:5},xe={name:"replicationStart",length:4},Me={name:"emptyQuery",length:4},Re={name:"copyDone",length:4},k=class{constructor(e){this.length=e;this.name="authenticationOk"}},V=class{constructor(e){this.length=e;this.name="authenticationCleartextPassword"}},F=class{constructor(e,n){this.length=e;this.salt=n;this.name="authenticationMD5Password"}},G=class{constructor(e,n){this.length=e;this.mechanisms=n;this.name="authenticationSASL"}},Q=class{constructor(e,n){this.length=e;this.data=n;this.name="authenticationSASLContinue"}},_=class{constructor(e,n){this.length=e;this.data=n;this.name="authenticationSASLFinal"}},E=class extends Error{constructor(n,s,i){super(n);this.length=s;this.name=i}},v=class{constructor(e,n){this.length=e;this.chunk=n;this.name="copyData"}},H=class{constructor(e,n,s,i){this.length=e;this.name=n;this.binary=s;this.columnTypes=new Array(i)}},z=class{constructor(e,n,s,i,a,u,m){this.name=e;this.tableID=n;this.columnID=s;this.dataTypeID=i;this.dataTypeSize=a;this.dataTypeModifier=u;this.format=m}},q=class{constructor(e,n){this.length=e;this.fieldCount=n;this.name="rowDescription";this.fields=new Array(this.fieldCount)}},Y=class{constructor(e,n){this.length=e;this.parameterCount=n;this.name="parameterDescription";this.dataTypeIDs=new Array(this.parameterCount)}},j=class{constructor(e,n,s){this.length=e;this.parameterName=n;this.parameterValue=s;this.name="parameterStatus"}},W=class{constructor(e,n,s){this.length=e;this.processID=n;this.secretKey=s;this.name="backendKeyData"}},K=class{constructor(e,n,s,i){this.length=e;this.processId=n;this.channel=s;this.payload=i;this.name="notification"}},J=class{constructor(e,n){this.length=e;this.status=n;this.name="readyForQuery"}},$=class{constructor(e,n){this.length=e;this.text=n;this.name="commandComplete"}},X=class{constructor(e,n){this.length=e;this.fields=n;this.name="dataRow";this.fieldCount=n.length}},Z=class{constructor(e,n){this.length=e;this.message=n;this.name="notice"}};var vn={};ne(vn,{Parser:()=>pe,messages:()=>Ce,serialize:()=>We});y();y();y();y();function T(t){let e=t.length;for(let n=t.length-1;n>=0;n--){let s=t.charCodeAt(n);s>127&&s<=2047?e++:s>2047&&s<=65535&&(e+=2),s>=56320&&s<=57343&&n--}return e}var b,g,P,ae,L,S,ie,N,je,R=class{constructor(e=256){this.size=e;h(this,S);h(this,b);h(this,g,5);h(this,P,!1);h(this,ae,new TextEncoder);h(this,L,0);d(this,b,p(this,S,ie).call(this,e))}addInt32(e){return p(this,S,N).call(this,4),r(this,b).setInt32(r(this,g),e,r(this,P)),d(this,g,r(this,g)+4),this}addInt16(e){return p(this,S,N).call(this,2),r(this,b).setInt16(r(this,g),e,r(this,P)),d(this,g,r(this,g)+2),this}addCString(e){return e&&this.addString(e),p(this,S,N).call(this,1),r(this,b).setUint8(r(this,g),0),re(this,g)._++,this}addString(e=""){let n=T(e);return p(this,S,N).call(this,n),r(this,ae).encodeInto(e,new Uint8Array(r(this,b).buffer,r(this,g))),d(this,g,r(this,g)+n),this}add(e){return p(this,S,N).call(this,e.byteLength),new Uint8Array(r(this,b).buffer).set(new Uint8Array(e),r(this,g)),d(this,g,r(this,g)+e.byteLength),this}flush(e){let n=p(this,S,je).call(this,e);return d(this,g,5),d(this,b,p(this,S,ie).call(this,this.size)),new Uint8Array(n)}};b=new WeakMap,g=new WeakMap,P=new WeakMap,ae=new WeakMap,L=new WeakMap,S=new WeakSet,ie=function(e){return new DataView(new ArrayBuffer(e))},N=function(e){if(r(this,b).byteLength-r(this,g)<e){let s=r(this,b).buffer,i=s.byteLength+(s.byteLength>>1)+e;d(this,b,p(this,S,ie).call(this,i)),new Uint8Array(r(this,b).buffer).set(new Uint8Array(s))}},je=function(e){if(e){r(this,b).setUint8(r(this,L),e);let n=r(this,g)-(r(this,L)+1);r(this,b).setInt32(r(this,L)+1,n,r(this,P))}return r(this,b).buffer.slice(e?0:5,r(this,g))};var f=new R,bn=t=>{f.addInt16(3).addInt16(0);for(let s of Object.keys(t))f.addCString(s).addCString(t[s]);f.addCString("client_encoding").addCString("UTF8");let e=f.addCString("").flush(),n=e.byteLength+4;return new R().addInt32(n).add(e).flush()},gn=()=>{let t=new DataView(new ArrayBuffer(8));return t.setInt32(0,8,!1),t.setInt32(4,80877103,!1),new Uint8Array(t.buffer)},wn=t=>f.addCString(t).flush(112),An=(t,e)=>(f.addCString(t).addInt32(T(e)).addString(e),f.flush(112)),Sn=t=>f.addString(t).flush(112),Bn=t=>f.addCString(t).flush(81),Dn=[],In=t=>{let e=t.name??"";e.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",e,e.length),console.error("This can cause conflicts and silent errors executing queries"));let n=f.addCString(e).addCString(t.text).addInt16(t.types?.length??0);return t.types?.forEach(s=>n.addInt32(s)),f.flush(80)},O=new R;var xn=(t,e)=>{for(let n=0;n<t.length;n++){let s=e?e(t[n],n):t[n];if(s===null)f.addInt16(0),O.addInt32(-1);else if(s instanceof ArrayBuffer||ArrayBuffer.isView(s)){let i=ArrayBuffer.isView(s)?s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength):s;f.addInt16(1),O.addInt32(i.byteLength),O.add(i)}else f.addInt16(0),O.addInt32(T(s)),O.addString(s)}},Mn=(t={})=>{let e=t.portal??"",n=t.statement??"",s=t.binary??!1,i=t.values??Dn,a=i.length;return f.addCString(e).addCString(n),f.addInt16(a),xn(i,t.valueMapper),f.addInt16(a),f.add(O.flush()),f.addInt16(s?1:0),f.flush(66)},Rn=new Uint8Array([69,0,0,0,9,0,0,0,0,0]),Cn=t=>{if(!t||!t.portal&&!t.rows)return Rn;let e=t.portal??"",n=t.rows??0,s=T(e),i=4+s+1+4,a=new DataView(new ArrayBuffer(1+i));return a.setUint8(0,69),a.setInt32(1,i,!1),new TextEncoder().encodeInto(e,new Uint8Array(a.buffer,5)),a.setUint8(s+5,0),a.setUint32(a.byteLength-4,n,!1),new Uint8Array(a.buffer)},En=(t,e)=>{let n=new DataView(new ArrayBuffer(16));return n.setInt32(0,16,!1),n.setInt16(4,1234,!1),n.setInt16(6,5678,!1),n.setInt32(8,t,!1),n.setInt32(12,e,!1),new Uint8Array(n.buffer)},Ee=(t,e)=>{let n=new R;return n.addCString(e),n.flush(t)},Tn=f.addCString("P").flush(68),Nn=f.addCString("S").flush(68),Pn=t=>t.name?Ee(68,`${t.type}${t.name??""}`):t.type==="P"?Tn:Nn,Ln=t=>{let e=`${t.type}${t.name??""}`;return Ee(67,e)},On=t=>f.add(t).flush(100),Un=t=>Ee(102,t),oe=t=>new Uint8Array([t,0,0,0,4]),kn=oe(72),Vn=oe(83),Fn=oe(88),Gn=oe(99),We={startup:bn,password:wn,requestSsl:gn,sendSASLInitialResponseMessage:An,sendSCRAMClientFinalMessage:Sn,query:Bn,parse:In,bind:Mn,execute:Cn,describe:Pn,close:Ln,flush:()=>kn,sync:()=>Vn,end:()=>Fn,copyData:On,copyDone:()=>Gn,copyFail:Un,cancel:En};y();y();var Te={text:0,binary:1};y();var Qn=new ArrayBuffer(0),M,w,ce,le,ee,ue=class{constructor(e=0){h(this,M,new DataView(Qn));h(this,w);h(this,ce,"utf-8");h(this,le,new TextDecoder(r(this,ce)));h(this,ee,!1);d(this,w,e)}setBuffer(e,n){d(this,w,e),d(this,M,new DataView(n))}int16(){let e=r(this,M).getInt16(r(this,w),r(this,ee));return d(this,w,r(this,w)+2),e}byte(){let e=r(this,M).getUint8(r(this,w));return re(this,w)._++,e}int32(){let e=r(this,M).getInt32(r(this,w),r(this,ee));return d(this,w,r(this,w)+4),e}string(e){return r(this,le).decode(this.bytes(e))}cstring(){let e=r(this,w),n=e;for(;r(this,M).getUint8(n++)!==0;);let s=this.string(n-e-1);return d(this,w,n),s}bytes(e){let n=r(this,M).buffer.slice(r(this,w),r(this,w)+e);return d(this,w,r(this,w)+e),new Uint8Array(n)}};M=new WeakMap,w=new WeakMap,ce=new WeakMap,le=new WeakMap,ee=new WeakMap;var Ne=1,_n=4,Ke=Ne+_n,Je=new ArrayBuffer(0);var A,B,D,o,c,$e,Xe,Ze,et,tt,nt,rt,Pe,st,it,at,ot,ut,ct,lt,pt,Le,pe=class{constructor(){h(this,c);h(this,A,new DataView(Je));h(this,B,0);h(this,D,0);h(this,o,new ue)}parse(e,n){p(this,c,$e).call(this,ArrayBuffer.isView(e)?e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength):e);let s=r(this,D)+r(this,B),i=r(this,D);for(;i+Ke<=s;){let a=r(this,A).getUint8(i),u=r(this,A).getUint32(i+Ne,!1),m=Ne+u;if(m+i<=s&&u>0){let l=p(this,c,Xe).call(this,i+Ke,a,u,r(this,A).buffer);n(l),i+=m}else break}i===s?(d(this,A,new DataView(Je)),d(this,B,0),d(this,D,0)):(d(this,B,s-i),d(this,D,i))}};A=new WeakMap,B=new WeakMap,D=new WeakMap,o=new WeakMap,c=new WeakSet,$e=function(e){if(r(this,B)>0){let n=r(this,B)+e.byteLength;if(n+r(this,D)>r(this,A).byteLength){let i;if(n<=r(this,A).byteLength&&r(this,D)>=r(this,B))i=r(this,A).buffer;else{let a=r(this,A).byteLength*2;for(;n>=a;)a*=2;i=new ArrayBuffer(a)}new Uint8Array(i).set(new Uint8Array(r(this,A).buffer,r(this,D),r(this,B))),d(this,A,new DataView(i)),d(this,D,0)}new Uint8Array(r(this,A).buffer).set(new Uint8Array(e),r(this,D)+r(this,B)),d(this,B,n)}else d(this,A,new DataView(e)),d(this,D,0),d(this,B,e.byteLength)},Xe=function(e,n,s,i){switch(n){case 50:return Se;case 49:return Ae;case 51:return Be;case 110:return De;case 115:return Ie;case 99:return Re;case 87:return xe;case 73:return Me;case 68:return p(this,c,ut).call(this,e,s,i);case 67:return p(this,c,et).call(this,e,s,i);case 90:return p(this,c,Ze).call(this,e,s,i);case 65:return p(this,c,st).call(this,e,s,i);case 82:return p(this,c,pt).call(this,e,s,i);case 83:return p(this,c,ct).call(this,e,s,i);case 75:return p(this,c,lt).call(this,e,s,i);case 69:return p(this,c,Le).call(this,e,s,i,"error");case 78:return p(this,c,Le).call(this,e,s,i,"notice");case 84:return p(this,c,it).call(this,e,s,i);case 116:return p(this,c,ot).call(this,e,s,i);case 71:return p(this,c,nt).call(this,e,s,i);case 72:return p(this,c,rt).call(this,e,s,i);case 100:return p(this,c,tt).call(this,e,s,i);default:return new E("received invalid response: "+n.toString(16),s,"error")}},Ze=function(e,n,s){r(this,o).setBuffer(e,s);let i=r(this,o).string(1);return new J(n,i)},et=function(e,n,s){r(this,o).setBuffer(e,s);let i=r(this,o).cstring();return new $(n,i)},tt=function(e,n,s){let i=s.slice(e,e+(n-4));return new v(n,new Uint8Array(i))},nt=function(e,n,s){return p(this,c,Pe).call(this,e,n,s,"copyInResponse")},rt=function(e,n,s){return p(this,c,Pe).call(this,e,n,s,"copyOutResponse")},Pe=function(e,n,s,i){r(this,o).setBuffer(e,s);let a=r(this,o).byte()!==0,u=r(this,o).int16(),m=new H(n,i,a,u);for(let l=0;l<u;l++)m.columnTypes[l]=r(this,o).int16();return m},st=function(e,n,s){r(this,o).setBuffer(e,s);let i=r(this,o).int32(),a=r(this,o).cstring(),u=r(this,o).cstring();return new K(n,i,a,u)},it=function(e,n,s){r(this,o).setBuffer(e,s);let i=r(this,o).int16(),a=new q(n,i);for(let u=0;u<i;u++)a.fields[u]=p(this,c,at).call(this);return a},at=function(){let e=r(this,o).cstring(),n=r(this,o).int32(),s=r(this,o).int16(),i=r(this,o).int32(),a=r(this,o).int16(),u=r(this,o).int32(),m=r(this,o).int16()===0?Te.text:Te.binary;return new z(e,n,s,i,a,u,m)},ot=function(e,n,s){r(this,o).setBuffer(e,s);let i=r(this,o).int16(),a=new Y(n,i);for(let u=0;u<i;u++)a.dataTypeIDs[u]=r(this,o).int32();return a},ut=function(e,n,s){r(this,o).setBuffer(e,s);let i=r(this,o).int16(),a=new Array(i);for(let u=0;u<i;u++){let m=r(this,o).int32();a[u]=m===-1?null:r(this,o).string(m)}return new X(n,a)},ct=function(e,n,s){r(this,o).setBuffer(e,s);let i=r(this,o).cstring(),a=r(this,o).cstring();return new j(n,i,a)},lt=function(e,n,s){r(this,o).setBuffer(e,s);let i=r(this,o).int32(),a=r(this,o).int32();return new W(n,i,a)},pt=function(e,n,s){r(this,o).setBuffer(e,s);let i=r(this,o).int32();switch(i){case 0:return new k(n);case 3:return new V(n);case 5:return new F(n,r(this,o).bytes(4));case 10:{let a=[];for(;;){let u=r(this,o).cstring();if(u.length===0)return new G(n,a);a.push(u)}}case 11:return new Q(n,r(this,o).string(n-8));case 12:return new _(n,r(this,o).string(n-8));default:throw new Error("Unknown authenticationOk message type "+i)}},Le=function(e,n,s,i){r(this,o).setBuffer(e,s);let a={},u=r(this,o).string(1);for(;u!=="\0";)a[u]=r(this,o).cstring(),u=r(this,o).string(1);let m=a.M,l=i==="notice"?new Z(n,m):new E(m,n,i);return l.severity=a.S,l.code=a.C,l.detail=a.D,l.hint=a.H,l.position=a.P,l.internalPosition=a.p,l.internalQuery=a.q,l.where=a.W,l.schema=a.s,l.table=a.t,l.column=a.c,l.dataType=a.d,l.constraint=a.n,l.file=a.F,l.line=a.L,l.routine=a.R,l};export{he as a,sn as b,an as c,qe as d,pn as e,dn as f,fn as g,yn as h,hn as i,We as j,E as k,K as l,Z as m,Ce as n,pe as o,vn as p};
//# sourceMappingURL=chunk-2B24BK54.js.map

Sorry, the diff of this file is too big to display

import{a as u,h as y,j as c}from"./chunk-2B24BK54.js";import{j as f}from"./chunk-QY3QWFKW.js";f();async function v(s,e,r,n){if(!r||r.length===0)return e;n=n??s;let t=[];try{await s.execProtocol(c.parse({text:e}),{syncToFs:!1}),t.push(...(await s.execProtocol(c.describe({type:"S"}),{syncToFs:!1})).messages)}finally{t.push(...(await s.execProtocol(c.sync(),{syncToFs:!1})).messages)}let a=y(t),i=e.replace(/\$([0-9]+)/g,(d,l)=>"%"+l+"L");return(await n.query(`SELECT format($1, ${r.map((d,l)=>`$${l+2}`).join(", ")}) as query`,[i,...r],{paramTypes:[u,...a]})).rows[0].query}function x(s){let e,r=!1,n=async()=>{if(!e){r=!1;return}r=!0;let{args:t,resolve:a,reject:i}=e;e=void 0;try{let o=await s(...t);a(o)}catch(o){i(o)}finally{n()}};return async(...t)=>{e&&e.resolve(void 0);let a=new Promise((i,o)=>{e={args:t,resolve:i,reject:o}});return r||n(),a}}export{v as a,x as b};
//# sourceMappingURL=chunk-QY575LMP.js.map
{"version":3,"sources":["../src/utils.ts"],"sourcesContent":["import type { PGliteInterface, Transaction } from './interface.js'\nimport { serialize as serializeProtocol } from '@electric-sql/pg-protocol'\nimport { parseDescribeStatementResults } from './parse.js'\nimport { TEXT } from './types.js'\n\n/**\n * Formats a query with parameters\n * Expects that any tables/relations referenced in the query exist in the database\n * due to requiring them to be present to describe the parameters types.\n * `tx` is optional, and to be used when formatQuery is called during a transaction.\n * @param pg - The PGlite instance\n * @param query - The query to format\n * @param params - The parameters to format the query with\n * @param tx - The transaction to use, defaults to the PGlite instance\n * @returns The formatted query\n */\nexport async function formatQuery(\n pg: PGliteInterface,\n query: string,\n params?: any[] | null,\n tx?: Transaction | PGliteInterface,\n) {\n if (!params || params.length === 0) {\n // no params so no formatting needed\n return query\n }\n\n tx = tx ?? pg\n\n // Get the types of the parameters\n const messages = []\n try {\n await pg.execProtocol(serializeProtocol.parse({ text: query }), {\n syncToFs: false,\n })\n\n messages.push(\n ...(\n await pg.execProtocol(serializeProtocol.describe({ type: 'S' }), {\n syncToFs: false,\n })\n ).messages,\n )\n } finally {\n messages.push(\n ...(await pg.execProtocol(serializeProtocol.sync(), { syncToFs: false }))\n .messages,\n )\n }\n\n const dataTypeIDs = parseDescribeStatementResults(messages)\n\n // replace $1, $2, etc with %1L, %2L, etc\n const subbedQuery = query.replace(/\\$([0-9]+)/g, (_, num) => {\n return '%' + num + 'L'\n })\n\n const ret = await tx.query<{\n query: string\n }>(\n `SELECT format($1, ${params.map((_, i) => `$${i + 2}`).join(', ')}) as query`,\n [subbedQuery, ...params],\n { paramTypes: [TEXT, ...dataTypeIDs] },\n )\n return ret.rows[0].query\n}\n\n/**\n * Debounce a function to ensure that only one instance of the function is running at\n * a time.\n * - If the function is called while an instance is already running, the new\n * call is scheduled to run after the current instance completes.\n * - If there is already a scheduled call, it is replaced with the new call.\n * @param fn - The function to debounce\n * @returns A debounced version of the function\n */\nexport function debounceMutex<A extends any[], R>(\n fn: (...args: A) => Promise<R>,\n): (...args: A) => Promise<R | void> {\n let next:\n | {\n args: A\n resolve: (value: R | void) => void\n reject: (reason?: any) => void\n }\n | undefined = undefined\n\n let isRunning = false\n const processNext = async () => {\n if (!next) {\n isRunning = false\n return\n }\n isRunning = true\n const { args, resolve, reject } = next\n next = undefined\n try {\n const ret = await fn(...args)\n resolve(ret)\n } catch (e) {\n reject(e)\n } finally {\n processNext()\n }\n }\n return async (...args: A) => {\n if (next) {\n next.resolve(undefined)\n }\n const promise = new Promise<R | void>((resolve, reject) => {\n next = { args, resolve, reject }\n })\n if (!isRunning) {\n processNext()\n }\n return promise\n }\n}\n"],"mappings":"8FAAAA,IAgBA,eAAsBC,EACpBC,EACAC,EACAC,EACAC,EACA,CACA,GAAI,CAACD,GAAUA,EAAO,SAAW,EAE/B,OAAOD,EAGTE,EAAKA,GAAMH,EAGX,IAAMI,EAAW,CAAC,EAClB,GAAI,CACF,MAAMJ,EAAG,aAAaK,EAAkB,MAAM,CAAE,KAAMJ,CAAM,CAAC,EAAG,CAC9D,SAAU,EACZ,CAAC,EAEDG,EAAS,KACP,IACE,MAAMJ,EAAG,aAAaK,EAAkB,SAAS,CAAE,KAAM,GAAI,CAAC,EAAG,CAC/D,SAAU,EACZ,CAAC,GACD,QACJ,CACF,QAAE,CACAD,EAAS,KACP,IAAI,MAAMJ,EAAG,aAAaK,EAAkB,KAAK,EAAG,CAAE,SAAU,EAAM,CAAC,GACpE,QACL,CACF,CAEA,IAAMC,EAAcC,EAA8BH,CAAQ,EAGpDI,EAAcP,EAAM,QAAQ,cAAe,CAACQ,EAAGC,IAC5C,IAAMA,EAAM,GACpB,EASD,OAPY,MAAMP,EAAG,MAGnB,qBAAqBD,EAAO,IAAI,CAACO,EAAGE,IAAM,IAAIA,EAAI,CAAC,EAAE,EAAE,KAAK,IAAI,CAAC,aACjE,CAACH,EAAa,GAAGN,CAAM,EACvB,CAAE,WAAY,CAACU,EAAM,GAAGN,CAAW,CAAE,CACvC,GACW,KAAK,CAAC,EAAE,KACrB,CAWO,SAASO,EACdC,EACmC,CACnC,IAAIC,EAQAC,EAAY,GACVC,EAAc,SAAY,CAC9B,GAAI,CAACF,EAAM,CACTC,EAAY,GACZ,MACF,CACAA,EAAY,GACZ,GAAM,CAAE,KAAAE,EAAM,QAAAC,EAAS,OAAAC,CAAO,EAAIL,EAClCA,EAAO,OACP,GAAI,CACF,IAAMM,EAAM,MAAMP,EAAG,GAAGI,CAAI,EAC5BC,EAAQE,CAAG,CACb,OAASC,EAAG,CACVF,EAAOE,CAAC,CACV,QAAE,CACAL,EAAY,CACd,CACF,EACA,MAAO,UAAUC,IAAY,CACvBH,GACFA,EAAK,QAAQ,MAAS,EAExB,IAAMQ,EAAU,IAAI,QAAkB,CAACJ,EAASC,IAAW,CACzDL,EAAO,CAAE,KAAAG,EAAM,QAAAC,EAAS,OAAAC,CAAO,CACjC,CAAC,EACD,OAAKJ,GACHC,EAAY,EAEPM,CACT,CACF","names":["init_esm_shims","formatQuery","pg","query","params","tx","messages","serialize","dataTypeIDs","parseDescribeStatementResults","subbedQuery","_","num","i","TEXT","debounceMutex","fn","next","isRunning","processNext","args","resolve","reject","ret","e","promise"]}
import{b as Q,c as A,d as B,e as S,g as O,h as q,j as l,k as f}from"./chunk-2B24BK54.js";import{d as R}from"./chunk-F4GETNPB.js";import{e as T,f as w,g as d,h as a,j as g}from"./chunk-QY3QWFKW.js";g();g();function E(h){let s=h.e;return s.query=h.query,s.params=h.params,s.queryOptions=h.options,s}var P,p,t,y,x,m,_,z=class{constructor(){w(this,t);this.serializers={...A};this.parsers={...Q};w(this,P,!1);w(this,p,!1)}async _initArrayTypes({force:s=!1}={}){if(T(this,P)&&!s)return;d(this,P,!0);let e=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 r of e.rows)this.serializers[r.typarray]=o=>B(o,this.serializers[r.oid],r.typarray),this.parsers[r.typarray]=o=>S(o,this.parsers[r.oid],r.typarray)}async refreshArrayTypes(){await this._initArrayTypes({force:!0})}async query(s,e,r){return await this._checkReady(),await this._runExclusiveTransaction(async()=>await a(this,t,x).call(this,s,e,r))}async sql(s,...e){let{query:r,params:o}=R(s,...e);return await this.query(r,o)}async exec(s,e){return await this._checkReady(),await this._runExclusiveTransaction(async()=>await a(this,t,m).call(this,s,e))}async describeQuery(s,e){let r=[];try{await a(this,t,y).call(this,l.parse({text:s,types:e?.paramTypes}),e),r=await a(this,t,y).call(this,l.describe({type:"S"}),e)}catch(n){throw n instanceof f?E({e:n,options:e,params:void 0,query:s}):n}finally{r.push(...await a(this,t,y).call(this,l.sync(),e))}let o=r.find(n=>n.name==="parameterDescription"),i=r.find(n=>n.name==="rowDescription"),c=o?.dataTypeIDs.map(n=>({dataTypeID:n,serializer:this.serializers[n]}))??[],u=i?.fields.map(n=>({name:n.name,dataTypeID:n.dataTypeID,parser:this.parsers[n.dataTypeID]}))??[];return{queryParams:c,resultFields:u}}async transaction(s){return await this._checkReady(),await this._runExclusiveTransaction(async()=>{await a(this,t,m).call(this,"BEGIN"),d(this,p,!0);let e=!1,r=()=>{if(e)throw new Error("Transaction is closed")},o={query:async(i,c,u)=>(r(),await a(this,t,x).call(this,i,c,u)),sql:async(i,...c)=>{let{query:u,params:n}=R(i,...c);return await a(this,t,x).call(this,u,n)},exec:async(i,c)=>(r(),await a(this,t,m).call(this,i,c)),rollback:async()=>{r(),await a(this,t,m).call(this,"ROLLBACK"),e=!0},listen:async(i,c)=>(r(),await this.listen(i,c,o)),get closed(){return e}};try{let i=await s(o);return e||(e=!0,await a(this,t,m).call(this,"COMMIT")),d(this,p,!1),i}catch(i){throw e||await a(this,t,m).call(this,"ROLLBACK"),d(this,p,!1),i}})}async runExclusive(s){return await this._runExclusiveQuery(s)}};P=new WeakMap,p=new WeakMap,t=new WeakSet,y=async function(s,e={}){return await this.execProtocolStream(s,{...e,syncToFs:!1})},x=async function(s,e=[],r){return await this._runExclusiveQuery(async()=>{a(this,t,_).call(this,"runQuery",s,e,r),await this._handleBlob(r?.blob);let o=[];try{let c=await a(this,t,y).call(this,l.parse({text:s,types:r?.paramTypes}),r),u=q(await a(this,t,y).call(this,l.describe({type:"S"}),r)),n=e.map((b,k)=>{let D=u[k];if(b==null)return null;let v=r?.serializers?.[D]??this.serializers[D];return v?v(b):b.toString()});o=[...c,...await a(this,t,y).call(this,l.bind({values:n}),r),...await a(this,t,y).call(this,l.describe({type:"P"}),r),...await a(this,t,y).call(this,l.execute({}),r)]}catch(c){throw c instanceof f?E({e:c,options:r,params:e,query:s}):c}finally{o.push(...await a(this,t,y).call(this,l.sync(),r))}await this._cleanupBlob(),T(this,p)||await this.syncToFs();let i=await this._getWrittenBlob();return O(o,this.parsers,r,i)[0]})},m=async function(s,e){return await this._runExclusiveQuery(async()=>{a(this,t,_).call(this,"runExec",s,e),await this._handleBlob(e?.blob);let r=[];try{r=await a(this,t,y).call(this,l.query(s),e)}catch(i){throw i instanceof f?E({e:i,options:e,params:void 0,query:s}):i}finally{r.push(...await a(this,t,y).call(this,l.sync(),e))}this._cleanupBlob(),T(this,p)||await this.syncToFs();let o=await this._getWrittenBlob();return O(r,this.parsers,e,o)})},_=function(...s){this.debug>0&&console.log(...s)};export{z as a};
//# sourceMappingURL=chunk-SRXPYZFS.js.map
{"version":3,"sources":["../src/base.ts","../src/errors.ts"],"sourcesContent":["import { query as queryTemplate } from './templating.js'\nimport { parseDescribeStatementResults, parseResults } from './parse.js'\nimport {\n type Serializer,\n type Parser,\n serializers,\n parsers,\n arraySerializer,\n arrayParser,\n} from './types.js'\nimport type {\n DebugLevel,\n PGliteInterface,\n Results,\n Transaction,\n QueryOptions,\n ExecProtocolOptions,\n ExecProtocolResult,\n DescribeQueryResult,\n ExecProtocolOptionsStream,\n} from './interface.js'\n\nimport { serialize as serializeProtocol } from '@electric-sql/pg-protocol'\nimport {\n RowDescriptionMessage,\n ParameterDescriptionMessage,\n DatabaseError,\n BackendMessage,\n} from '@electric-sql/pg-protocol/messages'\nimport { makePGliteError } from './errors.js'\n\nexport abstract class BasePGlite\n implements Pick<PGliteInterface, 'query' | 'sql' | 'exec' | 'transaction'>\n{\n serializers: Record<number | string, Serializer> = { ...serializers }\n parsers: Record<number | string, Parser> = { ...parsers }\n #arrayTypesInitialized = false\n\n // # Abstract properties:\n abstract debug: DebugLevel\n\n // # Private properties:\n #inTransaction = false\n\n // # Abstract methods:\n\n /**\n * Execute a postgres wire protocol message\n * @param message The postgres wire protocol message to execute\n * @returns The result of the query\n */\n abstract execProtocol(\n message: Uint8Array,\n { syncToFs, onNotice }: ExecProtocolOptions,\n ): Promise<ExecProtocolResult>\n\n /**\n * Execute a postgres wire protocol message\n * @param message The postgres wire protocol message to execute\n * @returns The parsed results of the query\n */\n abstract execProtocolStream(\n message: Uint8Array,\n { syncToFs, onNotice }: ExecProtocolOptions,\n ): Promise<BackendMessage[]>\n\n /**\n * Execute a postgres wire protocol message directly without wrapping the response.\n * Only use if `execProtocol()` doesn't suite your needs.\n *\n * **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,\n * transactions, and notification listeners. Only use if you need to bypass these wrappers and\n * don't intend to use the above features.\n *\n * @param message The postgres wire protocol message to execute\n * @returns The direct message data response produced by Postgres\n */\n abstract execProtocolRaw(\n message: Uint8Array,\n { syncToFs }: ExecProtocolOptions,\n ): Promise<Uint8Array>\n\n /**\n * Execute a postgres wire protocol message directly without wrapping the response.\n * Only use if `execProtocol()` doesn't suite your needs.\n *\n * **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,\n * transactions, and notification listeners. Only use if you need to bypass these wrappers and\n * don't intend to use the above features.\n *\n * @param message The postgres wire protocol message to execute\n * @param options.onRawData Callback to receive streaming data\n */\n abstract execProtocolRawStream(\n message: Uint8Array,\n { syncToFs, onRawData }: ExecProtocolOptionsStream,\n ): Promise<void>\n\n /**\n * Sync the database to the filesystem\n * @returns Promise that resolves when the database is synced to the filesystem\n */\n abstract syncToFs(): Promise<void>\n\n /**\n * Handle a file attached to the current query\n * @param file The file to handle\n */\n abstract _handleBlob(blob?: File | Blob): Promise<void>\n\n /**\n * Get the written file\n */\n abstract _getWrittenBlob(): Promise<File | Blob | undefined>\n\n /**\n * Cleanup the current file\n */\n abstract _cleanupBlob(): Promise<void>\n\n abstract _checkReady(): Promise<void>\n abstract _runExclusiveQuery<T>(fn: () => Promise<T>): Promise<T>\n abstract _runExclusiveTransaction<T>(fn: () => Promise<T>): Promise<T>\n\n /**\n * Listen for notifications on a channel\n */\n abstract listen(\n channel: string,\n callback: (payload: string) => void,\n tx?: Transaction,\n ): Promise<(tx?: Transaction) => Promise<void>>\n\n // # Concrete implementations:\n\n /**\n * Initialize the array types\n * The oid if the type of an element and the typarray is the oid of the type of the\n * array.\n * We extract these from the database then create the serializers/parsers for\n * each type.\n * This should be called at the end of #init() in the implementing class.\n */\n async _initArrayTypes({ force = false } = {}) {\n if (this.#arrayTypesInitialized && !force) return\n this.#arrayTypesInitialized = true\n\n const types = await this.query<{ oid: number; typarray: number }>(`\n SELECT b.oid, b.typarray\n FROM pg_catalog.pg_type a\n LEFT JOIN pg_catalog.pg_type b ON b.oid = a.typelem\n WHERE a.typcategory = 'A'\n GROUP BY b.oid, b.typarray\n ORDER BY b.oid\n `)\n\n for (const type of types.rows) {\n this.serializers[type.typarray] = (x) =>\n arraySerializer(x, this.serializers[type.oid], type.typarray)\n this.parsers[type.typarray] = (x) =>\n arrayParser(x, this.parsers[type.oid], type.typarray)\n }\n }\n\n async #execProtocolNoSync(\n message: Uint8Array,\n options: ExecProtocolOptions = {},\n ): Promise<BackendMessage[]> {\n const results = await this.execProtocolStream(message, {\n ...options,\n syncToFs: false,\n })\n\n return results\n }\n\n /**\n * Re-syncs the array types from the database\n * This is useful if you add a new type to the database and want to use it, otherwise pglite won't recognize it.\n */\n async refreshArrayTypes() {\n await this._initArrayTypes({ force: true })\n }\n\n /**\n * Execute a single SQL statement\n * This uses the \"Extended Query\" postgres wire protocol message.\n * @param query The query to execute\n * @param params Optional parameters for the query\n * @returns The result of the query\n */\n async query<T>(\n query: string,\n params?: any[],\n options?: QueryOptions,\n ): Promise<Results<T>> {\n await this._checkReady()\n // We wrap the public query method in the transaction mutex to ensure that\n // only one query can be executed at a time and not concurrently with a\n // transaction.\n return await this._runExclusiveTransaction(async () => {\n return await this.#runQuery<T>(query, params, options)\n })\n }\n\n /**\n * Execute a single SQL statement like with {@link PGlite.query}, but with a\n * templated statement where template values will be treated as parameters.\n *\n * You can use helpers from `/template` to further format the query with\n * identifiers, raw SQL, and nested statements.\n *\n * This uses the \"Extended Query\" postgres wire protocol message.\n *\n * @param query The query to execute with parameters as template values\n * @returns The result of the query\n *\n * @example\n * ```ts\n * const results = await db.sql`SELECT * FROM ${identifier`foo`} WHERE id = ${id}`\n * ```\n */\n async sql<T>(\n sqlStrings: TemplateStringsArray,\n ...params: any[]\n ): Promise<Results<T>> {\n const { query, params: actualParams } = queryTemplate(sqlStrings, ...params)\n return await this.query(query, actualParams)\n }\n\n /**\n * Execute a SQL query, this can have multiple statements.\n * This uses the \"Simple Query\" postgres wire protocol message.\n * @param query The query to execute\n * @returns The result of the query\n */\n async exec(query: string, options?: QueryOptions): Promise<Array<Results>> {\n await this._checkReady()\n // We wrap the public exec method in the transaction mutex to ensure that\n // only one query can be executed at a time and not concurrently with a\n // transaction.\n return await this._runExclusiveTransaction(async () => {\n return await this.#runExec(query, options)\n })\n }\n\n /**\n * Internal method to execute a query\n * Not protected by the transaction mutex, so it can be used inside a transaction\n * @param query The query to execute\n * @param params Optional parameters for the query\n * @returns The result of the query\n */\n async #runQuery<T>(\n query: string,\n params: any[] = [],\n options?: QueryOptions,\n ): Promise<Results<T>> {\n return await this._runExclusiveQuery(async () => {\n // We need to parse, bind and execute a query with parameters\n this.#log('runQuery', query, params, options)\n await this._handleBlob(options?.blob)\n\n let results = []\n\n try {\n const parseResults = await this.#execProtocolNoSync(\n serializeProtocol.parse({ text: query, types: options?.paramTypes }),\n options,\n )\n\n const dataTypeIDs = parseDescribeStatementResults(\n await this.#execProtocolNoSync(\n serializeProtocol.describe({ type: 'S' }),\n options,\n ),\n )\n\n const values = params.map((param, i) => {\n const oid = dataTypeIDs[i]\n if (param === null || param === undefined) {\n return null\n }\n const serialize = options?.serializers?.[oid] ?? this.serializers[oid]\n if (serialize) {\n return serialize(param)\n } else {\n return param.toString()\n }\n })\n\n results = [\n ...parseResults,\n ...(await this.#execProtocolNoSync(\n serializeProtocol.bind({\n values,\n }),\n options,\n )),\n ...(await this.#execProtocolNoSync(\n serializeProtocol.describe({ type: 'P' }),\n options,\n )),\n ...(await this.#execProtocolNoSync(\n serializeProtocol.execute({}),\n options,\n )),\n ]\n } catch (e) {\n if (e instanceof DatabaseError) {\n const pgError = makePGliteError({ e, options, params, query })\n throw pgError\n }\n throw e\n } finally {\n results.push(\n ...(await this.#execProtocolNoSync(\n serializeProtocol.sync(),\n options,\n )),\n )\n }\n\n await this._cleanupBlob()\n if (!this.#inTransaction) {\n await this.syncToFs()\n }\n const blob = await this._getWrittenBlob()\n return parseResults(results, this.parsers, options, blob)[0] as Results<T>\n })\n }\n\n /**\n * Internal method to execute a query\n * Not protected by the transaction mutex, so it can be used inside a transaction\n * @param query The query to execute\n * @param params Optional parameters for the query\n * @returns The result of the query\n */\n async #runExec(\n query: string,\n options?: QueryOptions,\n ): Promise<Array<Results>> {\n return await this._runExclusiveQuery(async () => {\n // No params so we can just send the query\n this.#log('runExec', query, options)\n await this._handleBlob(options?.blob)\n let results = []\n try {\n results = await this.#execProtocolNoSync(\n serializeProtocol.query(query),\n options,\n )\n } catch (e) {\n if (e instanceof DatabaseError) {\n const pgError = makePGliteError({\n e,\n options,\n params: undefined,\n query,\n })\n throw pgError\n }\n throw e\n } finally {\n results.push(\n ...(await this.#execProtocolNoSync(\n serializeProtocol.sync(),\n options,\n )),\n )\n }\n this._cleanupBlob()\n if (!this.#inTransaction) {\n await this.syncToFs()\n }\n const blob = await this._getWrittenBlob()\n return parseResults(\n results,\n this.parsers,\n options,\n blob,\n ) as Array<Results>\n })\n }\n\n /**\n * Describe a query\n * @param query The query to describe\n * @returns A description of the result types for the query\n */\n async describeQuery(\n query: string,\n options?: QueryOptions,\n ): Promise<DescribeQueryResult> {\n let messages = []\n try {\n await this.#execProtocolNoSync(\n serializeProtocol.parse({ text: query, types: options?.paramTypes }),\n options,\n )\n\n messages = await this.#execProtocolNoSync(\n serializeProtocol.describe({ type: 'S' }),\n options,\n )\n } catch (e) {\n if (e instanceof DatabaseError) {\n const pgError = makePGliteError({\n e,\n options,\n params: undefined,\n query,\n })\n throw pgError\n }\n throw e\n } finally {\n messages.push(\n ...(await this.#execProtocolNoSync(serializeProtocol.sync(), options)),\n )\n }\n\n const paramDescription = messages.find(\n (msg): msg is ParameterDescriptionMessage =>\n msg.name === 'parameterDescription',\n )\n const resultDescription = messages.find(\n (msg): msg is RowDescriptionMessage => msg.name === 'rowDescription',\n )\n\n const queryParams =\n paramDescription?.dataTypeIDs.map((dataTypeID) => ({\n dataTypeID,\n serializer: this.serializers[dataTypeID],\n })) ?? []\n\n const resultFields =\n resultDescription?.fields.map((field) => ({\n name: field.name,\n dataTypeID: field.dataTypeID,\n parser: this.parsers[field.dataTypeID],\n })) ?? []\n\n return { queryParams, resultFields }\n }\n\n /**\n * Execute a transaction\n * @param callback A callback function that takes a transaction object\n * @returns The result of the transaction\n */\n async transaction<T>(callback: (tx: Transaction) => Promise<T>): Promise<T> {\n await this._checkReady()\n return await this._runExclusiveTransaction(async () => {\n await this.#runExec('BEGIN')\n this.#inTransaction = true\n\n // Once a transaction is closed, we throw an error if it's used again\n let closed = false\n const checkClosed = () => {\n if (closed) {\n throw new Error('Transaction is closed')\n }\n }\n\n const tx: Transaction = {\n query: async <T>(\n query: string,\n params?: any[],\n options?: QueryOptions,\n ): Promise<Results<T>> => {\n checkClosed()\n return await this.#runQuery(query, params, options)\n },\n sql: async <T>(\n sqlStrings: TemplateStringsArray,\n ...params: any[]\n ): Promise<Results<T>> => {\n const { query, params: actualParams } = queryTemplate(\n sqlStrings,\n ...params,\n )\n return await this.#runQuery(query, actualParams)\n },\n exec: async (\n query: string,\n options?: QueryOptions,\n ): Promise<Array<Results>> => {\n checkClosed()\n return await this.#runExec(query, options)\n },\n rollback: async () => {\n checkClosed()\n // Rollback and set the closed flag to prevent further use of this\n // transaction\n await this.#runExec('ROLLBACK')\n closed = true\n },\n listen: async (\n channel: string,\n callback: (payload: string) => void,\n ) => {\n checkClosed()\n return await this.listen(channel, callback, tx)\n },\n get closed() {\n return closed\n },\n }\n\n try {\n const result = await callback(tx)\n if (!closed) {\n closed = true\n await this.#runExec('COMMIT')\n }\n this.#inTransaction = false\n return result\n } catch (e) {\n if (!closed) {\n await this.#runExec('ROLLBACK')\n }\n this.#inTransaction = false\n throw e\n }\n })\n }\n\n /**\n * Run a function exclusively, no other transactions or queries will be allowed\n * while the function is running.\n * This is useful when working with the execProtocol methods as they are not blocked,\n * and do not block the locks used by transactions and queries.\n * @param fn The function to run\n * @returns The result of the function\n */\n async runExclusive<T>(fn: () => Promise<T>): Promise<T> {\n return await this._runExclusiveQuery(fn)\n }\n\n /**\n * Internal log function\n */\n #log(...args: any[]) {\n if (this.debug > 0) {\n console.log(...args)\n }\n }\n}\n","import { DatabaseError } from '@electric-sql/pg-protocol/messages'\nimport { QueryOptions } from './interface'\n\nexport interface PGliteError extends DatabaseError {\n query: string | undefined\n params: any[] | undefined\n queryOptions: QueryOptions | undefined\n}\n\nexport function makePGliteError(data: {\n e: DatabaseError\n query: string\n params: any[] | undefined\n options: QueryOptions | undefined\n}) {\n const pgError = data.e as PGliteError\n pgError.query = data.query\n pgError.params = data.params\n pgError.queryOptions = data.options\n return pgError\n}\n"],"mappings":"qMAAAA,ICAAC,IASO,SAASC,EAAgBC,EAK7B,CACD,IAAMC,EAAUD,EAAK,EACrB,OAA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B,EAAAC,GAAL,UACRuB,EAAkB,KAAK,EACvBL,EAEJ,CACF,CAEA,MAAM,KAAK,aAAa,EACnBT,EAAA,KAAKX,IACR,MAAM,KAAK,SAAS,EAEtB,IAAMoD,EAAO,MAAM,KAAK,gBAAgB,EACxC,OAAOP,EAAaD,EAAS,KAAK,QAASxB,EAASgC,CAAI,EAAE,CAAC,CAC7D,CAAC,CACH,EASMhD,EAAQ,eACZc,EACAE,EACyB,CACzB,OAAO,MAAM,KAAK,mBAAmB,SAAY,CAE/CC,EAAA,KAAKpB,EAAAI,GAAL,UAAU,UAAWa,EAAOE,GAC5B,MAAM,KAAK,YAAYA,GAAS,IAAI,EACpC,IAAIwB,EAAU,CAAC,EACf,GAAI,CACFA,EAAU,MAAMvB,EAAA,KAAKpB,EAAAC,GAAL,UACduB,EAAkB,MAAMP,CAAK,EAC7BE,EAEJ,OAASM,EAAG,CACV,MAAIA,aAAaC,EACCC,EAAgB,CAC9B,EAAAF,EACA,QAAAN,EACA,OAAQ,OACR,MAAAF,CACF,CAAC,EAGGQ,CACR,QAAE,CACAkB,EAAQ,KACN,GAAI,MAAMvB,EAAA,KAAKpB,EAAAC,GAAL,UACRuB,EAAkB,KAAK,EACvBL,EAEJ,CACF,CACA,KAAK,aAAa,EACbT,EAAA,KAAKX,IACR,MAAM,KAAK,SAAS,EAEtB,IAAMoD,EAAO,MAAM,KAAK,gBAAgB,EACxC,OAAOP,EACLD,EACA,KAAK,QACLxB,EACAgC,CACF,CACF,CAAC,CACH,EAgKA/C,EAAI,YAAIgD,EAAa,CACf,KAAK,MAAQ,GACf,QAAQ,IAAI,GAAGA,CAAI,CAEvB","names":["init_esm_shims","init_esm_shims","makePGliteError","data","pgError","_arrayTypesInitialized","_inTransaction","_BasePGlite_instances","execProtocolNoSync_fn","runQuery_fn","runExec_fn","log_fn","BasePGlite","__privateAdd","serializers","parsers","force","__privateGet","__privateSet","types","type","x","arraySerializer","arrayParser","query","params","options","__privateMethod","sqlStrings","actualParams","messages","serialize","e","DatabaseError","makePGliteError","paramDescription","msg","resultDescription","queryParams","dataTypeID","resultFields","field","callback","closed","checkClosed","tx","channel","result","fn","message","results","parseResults","dataTypeIDs","parseDescribeStatementResults","values","param","i","oid","blob","args"]}
declare const Modes: {
readonly text: 0;
readonly binary: 1;
};
type Mode = (typeof Modes)[keyof typeof Modes];
type BufferParameter = ArrayBuffer | ArrayBufferView;
type MessageName = 'parseComplete' | 'bindComplete' | 'closeComplete' | 'noData' | 'portalSuspended' | 'replicationStart' | 'emptyQuery' | 'copyDone' | 'copyData' | 'rowDescription' | 'parameterDescription' | 'parameterStatus' | 'backendKeyData' | 'notification' | 'readyForQuery' | 'commandComplete' | 'dataRow' | 'copyInResponse' | 'copyOutResponse' | 'authenticationOk' | 'authenticationMD5Password' | 'authenticationCleartextPassword' | 'authenticationSASL' | 'authenticationSASLContinue' | 'authenticationSASLFinal' | 'error' | 'notice';
type BackendMessage = {
name: MessageName;
length: number;
};
declare const parseComplete: BackendMessage;
declare const bindComplete: BackendMessage;
declare const closeComplete: BackendMessage;
declare const noData: BackendMessage;
declare const portalSuspended: BackendMessage;
declare const replicationStart: BackendMessage;
declare const emptyQuery: BackendMessage;
declare const copyDone: BackendMessage;
declare class AuthenticationOk implements BackendMessage {
readonly length: number;
readonly name = "authenticationOk";
constructor(length: number);
}
declare class AuthenticationCleartextPassword implements BackendMessage {
readonly length: number;
readonly name = "authenticationCleartextPassword";
constructor(length: number);
}
declare class AuthenticationMD5Password implements BackendMessage {
readonly length: number;
readonly salt: Uint8Array;
readonly name = "authenticationMD5Password";
constructor(length: number, salt: Uint8Array);
}
declare class AuthenticationSASL implements BackendMessage {
readonly length: number;
readonly mechanisms: string[];
readonly name = "authenticationSASL";
constructor(length: number, mechanisms: string[]);
}
declare class AuthenticationSASLContinue implements BackendMessage {
readonly length: number;
readonly data: string;
readonly name = "authenticationSASLContinue";
constructor(length: number, data: string);
}
declare class AuthenticationSASLFinal implements BackendMessage {
readonly length: number;
readonly data: string;
readonly name = "authenticationSASLFinal";
constructor(length: number, data: string);
}
type AuthenticationMessage = AuthenticationOk | AuthenticationCleartextPassword | AuthenticationMD5Password | AuthenticationSASL | AuthenticationSASLContinue | AuthenticationSASLFinal;
interface NoticeOrError {
message: string | undefined;
severity: string | undefined;
code: string | undefined;
detail: string | undefined;
hint: string | undefined;
position: string | undefined;
internalPosition: string | undefined;
internalQuery: string | undefined;
where: string | undefined;
schema: string | undefined;
table: string | undefined;
column: string | undefined;
dataType: string | undefined;
constraint: string | undefined;
file: string | undefined;
line: string | undefined;
routine: string | undefined;
}
declare class DatabaseError extends Error implements NoticeOrError {
readonly length: number;
readonly name: MessageName;
severity: string | undefined;
code: string | undefined;
detail: string | undefined;
hint: string | undefined;
position: string | undefined;
internalPosition: string | undefined;
internalQuery: string | undefined;
where: string | undefined;
schema: string | undefined;
table: string | undefined;
column: string | undefined;
dataType: string | undefined;
constraint: string | undefined;
file: string | undefined;
line: string | undefined;
routine: string | undefined;
constructor(message: string, length: number, name: MessageName);
}
declare class CopyDataMessage implements BackendMessage {
readonly length: number;
readonly chunk: Uint8Array;
readonly name = "copyData";
constructor(length: number, chunk: Uint8Array);
}
declare class CopyResponse implements BackendMessage {
readonly length: number;
readonly name: MessageName;
readonly binary: boolean;
readonly columnTypes: number[];
constructor(length: number, name: MessageName, binary: boolean, columnCount: number);
}
declare class Field {
readonly name: string;
readonly tableID: number;
readonly columnID: number;
readonly dataTypeID: number;
readonly dataTypeSize: number;
readonly dataTypeModifier: number;
readonly format: Mode;
constructor(name: string, tableID: number, columnID: number, dataTypeID: number, dataTypeSize: number, dataTypeModifier: number, format: Mode);
}
declare class RowDescriptionMessage implements BackendMessage {
readonly length: number;
readonly fieldCount: number;
readonly name: MessageName;
readonly fields: Field[];
constructor(length: number, fieldCount: number);
}
declare class ParameterDescriptionMessage implements BackendMessage {
readonly length: number;
readonly parameterCount: number;
readonly name: MessageName;
readonly dataTypeIDs: number[];
constructor(length: number, parameterCount: number);
}
declare class ParameterStatusMessage implements BackendMessage {
readonly length: number;
readonly parameterName: string;
readonly parameterValue: string;
readonly name: MessageName;
constructor(length: number, parameterName: string, parameterValue: string);
}
declare class BackendKeyDataMessage implements BackendMessage {
readonly length: number;
readonly processID: number;
readonly secretKey: number;
readonly name: MessageName;
constructor(length: number, processID: number, secretKey: number);
}
declare class NotificationResponseMessage implements BackendMessage {
readonly length: number;
readonly processId: number;
readonly channel: string;
readonly payload: string;
readonly name: MessageName;
constructor(length: number, processId: number, channel: string, payload: string);
}
declare class ReadyForQueryMessage implements BackendMessage {
readonly length: number;
readonly status: string;
readonly name: MessageName;
constructor(length: number, status: string);
}
declare class CommandCompleteMessage implements BackendMessage {
readonly length: number;
readonly text: string;
readonly name: MessageName;
constructor(length: number, text: string);
}
declare class DataRowMessage implements BackendMessage {
length: number;
fields: (string | null)[];
readonly fieldCount: number;
readonly name: MessageName;
constructor(length: number, fields: (string | null)[]);
}
declare class NoticeMessage implements BackendMessage, NoticeOrError {
readonly length: number;
readonly message: string | undefined;
constructor(length: number, message: string | undefined);
readonly name = "notice";
severity: string | undefined;
code: string | undefined;
detail: string | undefined;
hint: string | undefined;
position: string | undefined;
internalPosition: string | undefined;
internalQuery: string | undefined;
where: string | undefined;
schema: string | undefined;
table: string | undefined;
column: string | undefined;
dataType: string | undefined;
constraint: string | undefined;
file: string | undefined;
line: string | undefined;
routine: string | undefined;
}
type messages_AuthenticationCleartextPassword = AuthenticationCleartextPassword;
declare const messages_AuthenticationCleartextPassword: typeof AuthenticationCleartextPassword;
type messages_AuthenticationMD5Password = AuthenticationMD5Password;
declare const messages_AuthenticationMD5Password: typeof AuthenticationMD5Password;
type messages_AuthenticationMessage = AuthenticationMessage;
type messages_AuthenticationOk = AuthenticationOk;
declare const messages_AuthenticationOk: typeof AuthenticationOk;
type messages_AuthenticationSASL = AuthenticationSASL;
declare const messages_AuthenticationSASL: typeof AuthenticationSASL;
type messages_AuthenticationSASLContinue = AuthenticationSASLContinue;
declare const messages_AuthenticationSASLContinue: typeof AuthenticationSASLContinue;
type messages_AuthenticationSASLFinal = AuthenticationSASLFinal;
declare const messages_AuthenticationSASLFinal: typeof AuthenticationSASLFinal;
type messages_BackendKeyDataMessage = BackendKeyDataMessage;
declare const messages_BackendKeyDataMessage: typeof BackendKeyDataMessage;
type messages_BackendMessage = BackendMessage;
type messages_CommandCompleteMessage = CommandCompleteMessage;
declare const messages_CommandCompleteMessage: typeof CommandCompleteMessage;
type messages_CopyDataMessage = CopyDataMessage;
declare const messages_CopyDataMessage: typeof CopyDataMessage;
type messages_CopyResponse = CopyResponse;
declare const messages_CopyResponse: typeof CopyResponse;
type messages_DataRowMessage = DataRowMessage;
declare const messages_DataRowMessage: typeof DataRowMessage;
type messages_DatabaseError = DatabaseError;
declare const messages_DatabaseError: typeof DatabaseError;
type messages_Field = Field;
declare const messages_Field: typeof Field;
type messages_MessageName = MessageName;
type messages_NoticeMessage = NoticeMessage;
declare const messages_NoticeMessage: typeof NoticeMessage;
type messages_NotificationResponseMessage = NotificationResponseMessage;
declare const messages_NotificationResponseMessage: typeof NotificationResponseMessage;
type messages_ParameterDescriptionMessage = ParameterDescriptionMessage;
declare const messages_ParameterDescriptionMessage: typeof ParameterDescriptionMessage;
type messages_ParameterStatusMessage = ParameterStatusMessage;
declare const messages_ParameterStatusMessage: typeof ParameterStatusMessage;
type messages_ReadyForQueryMessage = ReadyForQueryMessage;
declare const messages_ReadyForQueryMessage: typeof ReadyForQueryMessage;
type messages_RowDescriptionMessage = RowDescriptionMessage;
declare const messages_RowDescriptionMessage: typeof RowDescriptionMessage;
declare const messages_bindComplete: typeof bindComplete;
declare const messages_closeComplete: typeof closeComplete;
declare const messages_copyDone: typeof copyDone;
declare const messages_emptyQuery: typeof emptyQuery;
declare const messages_noData: typeof noData;
declare const messages_parseComplete: typeof parseComplete;
declare const messages_portalSuspended: typeof portalSuspended;
declare const messages_replicationStart: typeof replicationStart;
declare namespace messages {
export { messages_AuthenticationCleartextPassword as AuthenticationCleartextPassword, messages_AuthenticationMD5Password as AuthenticationMD5Password, type messages_AuthenticationMessage as AuthenticationMessage, messages_AuthenticationOk as AuthenticationOk, messages_AuthenticationSASL as AuthenticationSASL, messages_AuthenticationSASLContinue as AuthenticationSASLContinue, messages_AuthenticationSASLFinal as AuthenticationSASLFinal, messages_BackendKeyDataMessage as BackendKeyDataMessage, type messages_BackendMessage as BackendMessage, messages_CommandCompleteMessage as CommandCompleteMessage, messages_CopyDataMessage as CopyDataMessage, messages_CopyResponse as CopyResponse, messages_DataRowMessage as DataRowMessage, messages_DatabaseError as DatabaseError, messages_Field as Field, type messages_MessageName as MessageName, messages_NoticeMessage as NoticeMessage, messages_NotificationResponseMessage as NotificationResponseMessage, messages_ParameterDescriptionMessage as ParameterDescriptionMessage, messages_ParameterStatusMessage as ParameterStatusMessage, messages_ReadyForQueryMessage as ReadyForQueryMessage, messages_RowDescriptionMessage as RowDescriptionMessage, messages_bindComplete as bindComplete, messages_closeComplete as closeComplete, messages_copyDone as copyDone, messages_emptyQuery as emptyQuery, messages_noData as noData, messages_parseComplete as parseComplete, messages_portalSuspended as portalSuspended, messages_replicationStart as replicationStart };
}
type IDBFS = Emscripten.FileSystemType & {
quit: () => void;
dbs: Record<string, IDBDatabase>;
};
type FS = typeof FS & {
filesystems: {
MEMFS: Emscripten.FileSystemType;
NODEFS: Emscripten.FileSystemType;
IDBFS: IDBFS;
};
quit: () => void;
};
interface PostgresMod extends Omit<EmscriptenModule, 'preInit' | 'preRun' | 'postRun'> {
preInit: Array<{
(mod: PostgresMod): void;
}>;
preRun: Array<{
(mod: PostgresMod): void;
}>;
postRun: Array<{
(mod: PostgresMod): void;
}>;
thisProgram: string;
stdin: (() => number | null) | null;
FS: FS;
wasmMemory: WebAssembly.Memory;
PROXYFS: Emscripten.FileSystemType;
WASM_PREFIX: string;
pg_extensions: Record<string, Promise<Blob | null>>;
UTF8ToString: (ptr: number, maxBytesToRead?: number) => string;
stringToUTF8OnStack: (s: string) => number;
_pgl_set_system_fn: (system_fn: number) => void;
_pgl_set_popen_fn: (popen_fn: number) => void;
_pgl_set_pclose_fn: (pclose_fn: number) => void;
_pgl_set_rw_cbs: (read_cb: number, write_cb: number) => void;
_pgl_set_pipe_fn: (pipe_fn: number) => number;
_pgl_freopen: (filepath: number, mode: number, stream: number) => number;
_pgl_pq_flush: () => void;
_fopen: (path: number, mode: number) => number;
_fclose: (stream: number) => number;
_fflush: (stream: number) => void;
_pgl_proc_exit: (code: number) => number;
addFunction: (cb: (ptr: any, length: number) => void, signature: string) => number;
removeFunction: (f: number) => void;
callMain: (args?: string[]) => number;
_PostgresMainLoopOnce: () => void;
_PostgresMainLongJmp: () => void;
_PostgresSendReadyForQueryIfNecessary: () => void;
_ProcessStartupPacket: (Port: number, ssl_done: boolean, gss_done: boolean) => number;
_IsTransactionBlock: () => number;
_pgl_setPGliteActive: (newValue: number) => number;
_pgl_startPGlite: () => void;
_pgl_getMyProcPort: () => number;
_pgl_sendConnData: () => void;
ENV: any;
PGLITE_ENV: any;
_emscripten_force_exit: (status: number) => void;
_pgl_run_atexit_funcs: () => void;
_pq_buffer_remaining_data: () => number;
}
type PostgresFactory<T extends PostgresMod = PostgresMod> = (moduleOverrides?: Partial<T>) => Promise<T>;
declare const _default: PostgresFactory<PostgresMod>;
type postgresMod_FS = FS;
type postgresMod_PostgresMod = PostgresMod;
declare namespace postgresMod {
export { type postgresMod_FS as FS, type postgresMod_PostgresMod as PostgresMod, _default as default };
}
type DumpTarCompressionOptions = 'none' | 'gzip' | 'auto';
type FsType = 'nodefs' | 'idbfs' | 'memoryfs' | 'opfs-ahp';
/**
* Filesystem interface.
* All virtual filesystems that are compatible with PGlite must implement
* this interface.
*/
interface Filesystem {
/**
* Initiate the filesystem and return the options to pass to the emscripten module.
*/
init(pg: PGlite, emscriptenOptions: Partial<PostgresMod>): Promise<{
emscriptenOpts: Partial<PostgresMod>;
}>;
/**
* Sync the filesystem to any underlying storage.
*/
syncToFs(relaxedDurability?: boolean): Promise<void>;
/**
* Sync the filesystem from any underlying storage.
*/
initialSyncFs(): Promise<void>;
/**
* Dump the PGDATA dir from the filesystem to a gzipped tarball.
*/
dumpTar(dbname: string, compression?: DumpTarCompressionOptions): Promise<File | Blob>;
/**
* Close the filesystem.
*/
closeFs(): Promise<void>;
}
/**
* Base class for all emscripten built-in filesystems.
*/
declare class EmscriptenBuiltinFilesystem implements Filesystem {
protected dataDir?: string;
protected pg?: PGlite;
constructor(dataDir?: string);
init(pg: PGlite, emscriptenOptions: Partial<PostgresMod>): Promise<{
emscriptenOpts: Partial<PostgresMod>;
}>;
syncToFs(_relaxedDurability?: boolean): Promise<void>;
initialSyncFs(): Promise<void>;
closeFs(): Promise<void>;
dumpTar(dbname: string, compression?: DumpTarCompressionOptions): Promise<Blob | File>;
}
/**
* Abstract base class for all custom virtual filesystems.
* Each custom filesystem needs to implement an interface similar to the NodeJS FS API.
*/
declare abstract class BaseFilesystem implements Filesystem {
protected dataDir?: string;
protected pg?: PGlite;
readonly debug: boolean;
constructor(dataDir?: string, { debug }?: {
debug?: boolean;
});
syncToFs(_relaxedDurability?: boolean): Promise<void>;
initialSyncFs(): Promise<void>;
closeFs(): Promise<void>;
dumpTar(dbname: string, compression?: DumpTarCompressionOptions): Promise<Blob | File>;
init(pg: PGlite, emscriptenOptions: Partial<PostgresMod>): Promise<{
emscriptenOpts: Partial<PostgresMod>;
}>;
abstract chmod(path: string, mode: number): void;
abstract close(fd: number): void;
abstract fstat(fd: number): FsStats;
abstract lstat(path: string): FsStats;
abstract mkdir(path: string, options?: {
recursive?: boolean;
mode?: number;
}): void;
abstract open(path: string, flags?: string, mode?: number): number;
abstract readdir(path: string): string[];
abstract read(fd: number, buffer: Uint8Array, // Buffer to read into
offset: number, // Offset in buffer to start writing to
length: number, // Number of bytes to read
position: number): number;
abstract rename(oldPath: string, newPath: string): void;
abstract rmdir(path: string): void;
abstract truncate(path: string, len: number): void;
abstract unlink(path: string): void;
abstract utimes(path: string, atime: number, mtime: number): void;
abstract writeFile(path: string, data: string | Uint8Array, options?: {
encoding?: string;
mode?: number;
flag?: string;
}): void;
abstract write(fd: number, buffer: Uint8Array, // Buffer to read from
offset: number, // Offset in buffer to start reading from
length: number, // Number of bytes to write
position: number): number;
}
type FsStats = {
dev: number;
ino: number;
mode: number;
nlink: number;
uid: number;
gid: number;
rdev: number;
size: number;
blksize: number;
blocks: number;
atime: number;
mtime: number;
ctime: number;
};
declare const ERRNO_CODES: {
readonly EBADF: 8;
readonly EBADFD: 127;
readonly EEXIST: 20;
readonly EINVAL: 28;
readonly EISDIR: 31;
readonly ENODEV: 43;
readonly ENOENT: 44;
readonly ENOTDIR: 54;
readonly ENOTEMPTY: 55;
};
type FilesystemType = 'nodefs' | 'idbfs' | 'memoryfs';
type DebugLevel = 0 | 1 | 2 | 3 | 4 | 5;
type RowMode = 'array' | 'object';
interface ParserOptions {
[pgType: number]: (value: string) => any;
}
interface SerializerOptions {
[pgType: number]: (value: any) => string;
}
interface QueryOptions {
rowMode?: RowMode;
parsers?: ParserOptions;
serializers?: SerializerOptions;
blob?: Blob | File;
onNotice?: (notice: NoticeMessage) => void;
paramTypes?: number[];
}
interface ExecProtocolOptions {
syncToFs?: boolean;
throwOnError?: boolean;
onNotice?: (notice: NoticeMessage) => void;
}
interface ExecProtocolOptionsStream {
syncToFs?: boolean;
onRawData: (data: Uint8Array) => void;
}
interface ExtensionSetupResult<TNamespace = any> {
emscriptenOpts?: any;
namespaceObj?: TNamespace;
bundlePath?: URL;
sharedPreloadLibraries?: string[];
init?: () => Promise<void>;
close?: () => Promise<void>;
}
type ExtensionSetup<TNamespace = any> = (pg: PGliteInterface, emscriptenOpts: any, clientOnly?: boolean) => Promise<ExtensionSetupResult<TNamespace>>;
interface Extension<TNamespace = any> {
name: string;
setup: ExtensionSetup<TNamespace>;
}
type ExtensionNamespace<T> = T extends Extension<infer TNamespace> ? TNamespace : any;
type Extensions = {
[namespace: string]: Extension | URL;
};
type InitializedExtensions<TExtensions extends Extensions = Extensions> = {
[K in keyof TExtensions]: ExtensionNamespace<TExtensions[K]>;
};
interface ExecProtocolResult {
messages: BackendMessage[];
data: Uint8Array;
}
interface DumpDataDirResult {
tarball: Uint8Array;
extension: '.tar' | '.tgz';
filename: string;
}
interface PGliteOptions<TExtensions extends Extensions = Extensions> {
noInitDb?: boolean;
dataDir?: string;
username?: string;
database?: string;
fs?: Filesystem;
debug?: DebugLevel;
relaxedDurability?: boolean;
extensions?: TExtensions;
loadDataDir?: Blob | File;
icuDataDir?: Blob | File;
initialMemory?: number;
pgliteWasmModule?: WebAssembly.Module;
initdbWasmModule?: WebAssembly.Module;
fsBundle?: Blob | File;
parsers?: ParserOptions;
serializers?: SerializerOptions;
startParams?: string[];
initDbStartParams?: string[];
postgresqlconf?: string[] | string;
}
type PGliteInterface<T extends Extensions = Extensions> = InitializedExtensions<T> & {
readonly waitReady: Promise<void>;
readonly debug: DebugLevel;
readonly ready: boolean;
readonly closed: boolean;
close(): Promise<void>;
query<T>(query: string, params?: any[], options?: QueryOptions): Promise<Results<T>>;
sql<T>(sqlStrings: TemplateStringsArray, ...params: any[]): Promise<Results<T>>;
exec(query: string, options?: QueryOptions): Promise<Array<Results>>;
describeQuery(query: string): Promise<DescribeQueryResult>;
transaction<T>(callback: (tx: Transaction) => Promise<T>): Promise<T>;
execProtocolRaw(message: Uint8Array, options?: ExecProtocolOptions): Promise<Uint8Array>;
execProtocolRawStream(message: Uint8Array, options?: ExecProtocolOptionsStream): Promise<void>;
execProtocol(message: Uint8Array, options?: ExecProtocolOptions): Promise<ExecProtocolResult>;
runExclusive<T>(fn: () => Promise<T>): Promise<T>;
listen(channel: string, callback: (payload: string) => void, tx?: Transaction): Promise<(tx?: Transaction) => Promise<void>>;
unlisten(channel: string, callback?: (payload: string) => void, tx?: Transaction): Promise<void>;
onNotification(callback: (channel: string, payload: string) => void): () => void;
offNotification(callback: (channel: string, payload: string) => void): void;
dumpDataDir(compression?: DumpTarCompressionOptions): Promise<File | Blob>;
refreshArrayTypes(): Promise<void>;
};
type PGliteInterfaceExtensions<E> = E extends Extensions ? {
[K in keyof E]: E[K] extends Extension ? Awaited<ReturnType<E[K]['setup']>>['namespaceObj'] extends infer N ? N extends undefined | null | void ? never : N : never : never;
} : Record<string, never>;
type Row<T = {
[key: string]: any;
}> = T;
type Results<T = {
[key: string]: any;
}> = {
rows: Row<T>[];
affectedRows?: number;
fields: {
name: string;
dataTypeID: number;
}[];
blob?: Blob;
};
interface Transaction {
query<T>(query: string, params?: any[], options?: QueryOptions): Promise<Results<T>>;
sql<T>(sqlStrings: TemplateStringsArray, ...params: any[]): Promise<Results<T>>;
exec(query: string, options?: QueryOptions): Promise<Array<Results>>;
rollback(): Promise<void>;
listen(channel: string, callback: (payload: string) => void): Promise<(tx?: Transaction) => Promise<void>>;
get closed(): boolean;
}
type DescribeQueryResult = {
queryParams: {
dataTypeID: number;
serializer: Serializer;
}[];
resultFields: {
name: string;
dataTypeID: number;
parser: Parser;
}[];
};
declare const BOOL = 16;
declare const BYTEA = 17;
declare const CHAR = 18;
declare const INT8 = 20;
declare const INT2 = 21;
declare const INT4 = 23;
declare const REGPROC = 24;
declare const TEXT = 25;
declare const OID = 26;
declare const TID = 27;
declare const XID = 28;
declare const CID = 29;
declare const JSON = 114;
declare const XML = 142;
declare const PG_NODE_TREE = 194;
declare const SMGR = 210;
declare const PATH = 602;
declare const POLYGON = 604;
declare const CIDR = 650;
declare const FLOAT4 = 700;
declare const FLOAT8 = 701;
declare const ABSTIME = 702;
declare const RELTIME = 703;
declare const TINTERVAL = 704;
declare const CIRCLE = 718;
declare const MACADDR8 = 774;
declare const MONEY = 790;
declare const MACADDR = 829;
declare const INET = 869;
declare const ACLITEM = 1033;
declare const BPCHAR = 1042;
declare const VARCHAR = 1043;
declare const DATE = 1082;
declare const TIME = 1083;
declare const TIMESTAMP = 1114;
declare const TIMESTAMPTZ = 1184;
declare const INTERVAL = 1186;
declare const TIMETZ = 1266;
declare const BIT = 1560;
declare const VARBIT = 1562;
declare const NUMERIC = 1700;
declare const REFCURSOR = 1790;
declare const REGPROCEDURE = 2202;
declare const REGOPER = 2203;
declare const REGOPERATOR = 2204;
declare const REGCLASS = 2205;
declare const REGTYPE = 2206;
declare const UUID = 2950;
declare const TXID_SNAPSHOT = 2970;
declare const PG_LSN = 3220;
declare const PG_NDISTINCT = 3361;
declare const PG_DEPENDENCIES = 3402;
declare const TSVECTOR = 3614;
declare const TSQUERY = 3615;
declare const GTSVECTOR = 3642;
declare const REGCONFIG = 3734;
declare const REGDICTIONARY = 3769;
declare const JSONB = 3802;
declare const REGNAMESPACE = 4089;
declare const REGROLE = 4096;
declare const types: {
string: {
to: number;
from: number[];
serialize: (x: string | number | Date) => string;
parse: (x: string) => string;
};
number: {
to: number;
from: number[];
serialize: (x: number) => string;
parse: (x: string) => number;
};
bigint: {
to: number;
from: number[];
serialize: (x: bigint) => string;
parse: (x: string) => number | bigint;
};
json: {
to: number;
from: number[];
serialize: (x: any) => string;
parse: (x: string) => any;
};
boolean: {
to: number;
from: number[];
serialize: (x: boolean | number | string) => "t" | "f";
parse: (x: string) => x is "t";
};
date: {
to: number;
from: number[];
serialize: (x: Date | string | number) => string;
parse: (x: string | number) => Date;
};
bytea: {
to: number;
from: number[];
serialize: (x: Uint8Array) => string;
parse: (x: string) => Uint8Array;
};
};
type Parser = (x: string, typeId?: number) => any;
type Serializer = (x: any) => string;
type TypeHandler = {
to: number;
from: number | number[];
serialize: Serializer;
parse: Parser;
};
type TypeHandlers = {
[key: string]: TypeHandler;
};
declare const parsers: {
[key: string]: (x: string, typeId?: number) => any;
[key: number]: (x: string, typeId?: number) => any;
};
declare const serializers: {
[key: string]: Serializer;
[key: number]: Serializer;
};
declare function parseType(x: string | null, type: number, parsers?: ParserOptions): any;
declare function arraySerializer(xs: any, serializer: Serializer | undefined, typarray: number): string;
declare function arrayParser(x: string, parser: Parser, typarray: number): any;
declare const types$1_ABSTIME: typeof ABSTIME;
declare const types$1_ACLITEM: typeof ACLITEM;
declare const types$1_BIT: typeof BIT;
declare const types$1_BOOL: typeof BOOL;
declare const types$1_BPCHAR: typeof BPCHAR;
declare const types$1_BYTEA: typeof BYTEA;
declare const types$1_CHAR: typeof CHAR;
declare const types$1_CID: typeof CID;
declare const types$1_CIDR: typeof CIDR;
declare const types$1_CIRCLE: typeof CIRCLE;
declare const types$1_DATE: typeof DATE;
declare const types$1_FLOAT4: typeof FLOAT4;
declare const types$1_FLOAT8: typeof FLOAT8;
declare const types$1_GTSVECTOR: typeof GTSVECTOR;
declare const types$1_INET: typeof INET;
declare const types$1_INT2: typeof INT2;
declare const types$1_INT4: typeof INT4;
declare const types$1_INT8: typeof INT8;
declare const types$1_INTERVAL: typeof INTERVAL;
declare const types$1_JSON: typeof JSON;
declare const types$1_JSONB: typeof JSONB;
declare const types$1_MACADDR: typeof MACADDR;
declare const types$1_MACADDR8: typeof MACADDR8;
declare const types$1_MONEY: typeof MONEY;
declare const types$1_NUMERIC: typeof NUMERIC;
declare const types$1_OID: typeof OID;
declare const types$1_PATH: typeof PATH;
declare const types$1_PG_DEPENDENCIES: typeof PG_DEPENDENCIES;
declare const types$1_PG_LSN: typeof PG_LSN;
declare const types$1_PG_NDISTINCT: typeof PG_NDISTINCT;
declare const types$1_PG_NODE_TREE: typeof PG_NODE_TREE;
declare const types$1_POLYGON: typeof POLYGON;
type types$1_Parser = Parser;
declare const types$1_REFCURSOR: typeof REFCURSOR;
declare const types$1_REGCLASS: typeof REGCLASS;
declare const types$1_REGCONFIG: typeof REGCONFIG;
declare const types$1_REGDICTIONARY: typeof REGDICTIONARY;
declare const types$1_REGNAMESPACE: typeof REGNAMESPACE;
declare const types$1_REGOPER: typeof REGOPER;
declare const types$1_REGOPERATOR: typeof REGOPERATOR;
declare const types$1_REGPROC: typeof REGPROC;
declare const types$1_REGPROCEDURE: typeof REGPROCEDURE;
declare const types$1_REGROLE: typeof REGROLE;
declare const types$1_REGTYPE: typeof REGTYPE;
declare const types$1_RELTIME: typeof RELTIME;
declare const types$1_SMGR: typeof SMGR;
type types$1_Serializer = Serializer;
declare const types$1_TEXT: typeof TEXT;
declare const types$1_TID: typeof TID;
declare const types$1_TIME: typeof TIME;
declare const types$1_TIMESTAMP: typeof TIMESTAMP;
declare const types$1_TIMESTAMPTZ: typeof TIMESTAMPTZ;
declare const types$1_TIMETZ: typeof TIMETZ;
declare const types$1_TINTERVAL: typeof TINTERVAL;
declare const types$1_TSQUERY: typeof TSQUERY;
declare const types$1_TSVECTOR: typeof TSVECTOR;
declare const types$1_TXID_SNAPSHOT: typeof TXID_SNAPSHOT;
type types$1_TypeHandler = TypeHandler;
type types$1_TypeHandlers = TypeHandlers;
declare const types$1_UUID: typeof UUID;
declare const types$1_VARBIT: typeof VARBIT;
declare const types$1_VARCHAR: typeof VARCHAR;
declare const types$1_XID: typeof XID;
declare const types$1_XML: typeof XML;
declare const types$1_arrayParser: typeof arrayParser;
declare const types$1_arraySerializer: typeof arraySerializer;
declare const types$1_parseType: typeof parseType;
declare const types$1_parsers: typeof parsers;
declare const types$1_serializers: typeof serializers;
declare const types$1_types: typeof types;
declare namespace types$1 {
export { types$1_ABSTIME as ABSTIME, types$1_ACLITEM as ACLITEM, types$1_BIT as BIT, types$1_BOOL as BOOL, types$1_BPCHAR as BPCHAR, types$1_BYTEA as BYTEA, types$1_CHAR as CHAR, types$1_CID as CID, types$1_CIDR as CIDR, types$1_CIRCLE as CIRCLE, types$1_DATE as DATE, types$1_FLOAT4 as FLOAT4, types$1_FLOAT8 as FLOAT8, types$1_GTSVECTOR as GTSVECTOR, types$1_INET as INET, types$1_INT2 as INT2, types$1_INT4 as INT4, types$1_INT8 as INT8, types$1_INTERVAL as INTERVAL, types$1_JSON as JSON, types$1_JSONB as JSONB, types$1_MACADDR as MACADDR, types$1_MACADDR8 as MACADDR8, types$1_MONEY as MONEY, types$1_NUMERIC as NUMERIC, types$1_OID as OID, types$1_PATH as PATH, types$1_PG_DEPENDENCIES as PG_DEPENDENCIES, types$1_PG_LSN as PG_LSN, types$1_PG_NDISTINCT as PG_NDISTINCT, types$1_PG_NODE_TREE as PG_NODE_TREE, types$1_POLYGON as POLYGON, type types$1_Parser as Parser, types$1_REFCURSOR as REFCURSOR, types$1_REGCLASS as REGCLASS, types$1_REGCONFIG as REGCONFIG, types$1_REGDICTIONARY as REGDICTIONARY, types$1_REGNAMESPACE as REGNAMESPACE, types$1_REGOPER as REGOPER, types$1_REGOPERATOR as REGOPERATOR, types$1_REGPROC as REGPROC, types$1_REGPROCEDURE as REGPROCEDURE, types$1_REGROLE as REGROLE, types$1_REGTYPE as REGTYPE, types$1_RELTIME as RELTIME, types$1_SMGR as SMGR, type types$1_Serializer as Serializer, types$1_TEXT as TEXT, types$1_TID as TID, types$1_TIME as TIME, types$1_TIMESTAMP as TIMESTAMP, types$1_TIMESTAMPTZ as TIMESTAMPTZ, types$1_TIMETZ as TIMETZ, types$1_TINTERVAL as TINTERVAL, types$1_TSQUERY as TSQUERY, types$1_TSVECTOR as TSVECTOR, types$1_TXID_SNAPSHOT as TXID_SNAPSHOT, type types$1_TypeHandler as TypeHandler, type types$1_TypeHandlers as TypeHandlers, types$1_UUID as UUID, types$1_VARBIT as VARBIT, types$1_VARCHAR as VARCHAR, types$1_XID as XID, types$1_XML as XML, types$1_arrayParser as arrayParser, types$1_arraySerializer as arraySerializer, types$1_parseType as parseType, types$1_parsers as parsers, types$1_serializers as serializers, types$1_types as types };
}
declare abstract class BasePGlite implements Pick<PGliteInterface, 'query' | 'sql' | 'exec' | 'transaction'> {
#private;
serializers: Record<number | string, Serializer>;
parsers: Record<number | string, Parser>;
abstract debug: DebugLevel;
/**
* Execute a postgres wire protocol message
* @param message The postgres wire protocol message to execute
* @returns The result of the query
*/
abstract execProtocol(message: Uint8Array, { syncToFs, onNotice }: ExecProtocolOptions): Promise<ExecProtocolResult>;
/**
* Execute a postgres wire protocol message
* @param message The postgres wire protocol message to execute
* @returns The parsed results of the query
*/
abstract execProtocolStream(message: Uint8Array, { syncToFs, onNotice }: ExecProtocolOptions): Promise<BackendMessage[]>;
/**
* Execute a postgres wire protocol message directly without wrapping the response.
* Only use if `execProtocol()` doesn't suite your needs.
*
* **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,
* transactions, and notification listeners. Only use if you need to bypass these wrappers and
* don't intend to use the above features.
*
* @param message The postgres wire protocol message to execute
* @returns The direct message data response produced by Postgres
*/
abstract execProtocolRaw(message: Uint8Array, { syncToFs }: ExecProtocolOptions): Promise<Uint8Array>;
/**
* Execute a postgres wire protocol message directly without wrapping the response.
* Only use if `execProtocol()` doesn't suite your needs.
*
* **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,
* transactions, and notification listeners. Only use if you need to bypass these wrappers and
* don't intend to use the above features.
*
* @param message The postgres wire protocol message to execute
* @param options.onRawData Callback to receive streaming data
*/
abstract execProtocolRawStream(message: Uint8Array, { syncToFs, onRawData }: ExecProtocolOptionsStream): Promise<void>;
/**
* Sync the database to the filesystem
* @returns Promise that resolves when the database is synced to the filesystem
*/
abstract syncToFs(): Promise<void>;
/**
* Handle a file attached to the current query
* @param file The file to handle
*/
abstract _handleBlob(blob?: File | Blob): Promise<void>;
/**
* Get the written file
*/
abstract _getWrittenBlob(): Promise<File | Blob | undefined>;
/**
* Cleanup the current file
*/
abstract _cleanupBlob(): Promise<void>;
abstract _checkReady(): Promise<void>;
abstract _runExclusiveQuery<T>(fn: () => Promise<T>): Promise<T>;
abstract _runExclusiveTransaction<T>(fn: () => Promise<T>): Promise<T>;
/**
* Listen for notifications on a channel
*/
abstract listen(channel: string, callback: (payload: string) => void, tx?: Transaction): Promise<(tx?: Transaction) => Promise<void>>;
/**
* Initialize the array types
* The oid if the type of an element and the typarray is the oid of the type of the
* array.
* We extract these from the database then create the serializers/parsers for
* each type.
* This should be called at the end of #init() in the implementing class.
*/
_initArrayTypes({ force }?: {
force?: boolean | undefined;
}): Promise<void>;
/**
* Re-syncs the array types from the database
* This is useful if you add a new type to the database and want to use it, otherwise pglite won't recognize it.
*/
refreshArrayTypes(): Promise<void>;
/**
* Execute a single SQL statement
* This uses the "Extended Query" postgres wire protocol message.
* @param query The query to execute
* @param params Optional parameters for the query
* @returns The result of the query
*/
query<T>(query: string, params?: any[], options?: QueryOptions): Promise<Results<T>>;
/**
* Execute a single SQL statement like with {@link PGlite.query}, but with a
* templated statement where template values will be treated as parameters.
*
* You can use helpers from `/template` to further format the query with
* identifiers, raw SQL, and nested statements.
*
* This uses the "Extended Query" postgres wire protocol message.
*
* @param query The query to execute with parameters as template values
* @returns The result of the query
*
* @example
* ```ts
* const results = await db.sql`SELECT * FROM ${identifier`foo`} WHERE id = ${id}`
* ```
*/
sql<T>(sqlStrings: TemplateStringsArray, ...params: any[]): Promise<Results<T>>;
/**
* Execute a SQL query, this can have multiple statements.
* This uses the "Simple Query" postgres wire protocol message.
* @param query The query to execute
* @returns The result of the query
*/
exec(query: string, options?: QueryOptions): Promise<Array<Results>>;
/**
* Describe a query
* @param query The query to describe
* @returns A description of the result types for the query
*/
describeQuery(query: string, options?: QueryOptions): Promise<DescribeQueryResult>;
/**
* Execute a transaction
* @param callback A callback function that takes a transaction object
* @returns The result of the transaction
*/
transaction<T>(callback: (tx: Transaction) => Promise<T>): Promise<T>;
/**
* Run a function exclusively, no other transactions or queries will be allowed
* while the function is running.
* This is useful when working with the execProtocol methods as they are not blocked,
* and do not block the locks used by transactions and queries.
* @param fn The function to run
* @returns The result of the function
*/
runExclusive<T>(fn: () => Promise<T>): Promise<T>;
}
declare class PGlite extends BasePGlite implements PGliteInterface, AsyncDisposable {
#private;
fs?: Filesystem;
protected mod?: PostgresMod;
private readonly POSTGRES_MAIN_LONGJMP;
get ENV(): any;
readonly dataDir?: string;
readonly waitReady: Promise<void>;
readonly debug: DebugLevel;
static readonly paths: {
readonly PG_ROOT: "/pglite";
readonly PGDATA: string;
readonly ICU_DATA_PATH: string;
readonly INITDB_EXE_PATH: string;
readonly POSTGRES_EXE_PATH: string;
};
static readonly DEFAULT_RECV_BUF_SIZE: number;
static readonly MAX_BUFFER_SIZE: number;
externalCommandStreamFd: number | null;
static readonly defaultStartParams: string[];
/**
* Create a new PGlite instance
* @param dataDir The directory to store the database files
* Prefix with idb:// to use indexeddb filesystem in the browser
* Use memory:// to use in-memory filesystem
* @param options PGlite options
*/
constructor(dataDir?: string, options?: PGliteOptions);
/**
* Create a new PGlite instance
* @param options PGlite options including the data directory
*/
constructor(options?: PGliteOptions);
/**
* Create a new PGlite instance with extensions on the Typescript interface
* (The main constructor does enable extensions, however due to the limitations
* of Typescript, the extensions are not available on the instance interface)
* @param options PGlite options including the data directory
* @returns A promise that resolves to the PGlite instance when it's ready.
*/
static create<O extends PGliteOptions>(options?: O): Promise<PGlite & PGliteInterfaceExtensions<O['extensions']>>;
/**
* Create a new PGlite instance with extensions on the Typescript interface
* (The main constructor does enable extensions, however due to the limitations
* of Typescript, the extensions are not available on the instance interface)
* @param dataDir The directory to store the database files
* Prefix with idb:// to use indexeddb filesystem in the browser
* Use memory:// to use in-memory filesystem
* @param options PGlite options
* @returns A promise that resolves to the PGlite instance when it's ready.
*/
static create<O extends PGliteOptions>(dataDir?: string, options?: O): Promise<PGlite & PGliteInterfaceExtensions<O['extensions']>>;
handleExternalCmd(cmd: string, mode: string): number;
/**
* The Postgres Emscripten Module
*/
get Module(): PostgresMod;
/**
* The ready state of the database
*/
get ready(): boolean;
/**
* The closed state of the database
*/
get closed(): boolean;
/**
* Close the database
* @returns A promise that resolves when the database is closed
*/
close(): Promise<void>;
/**
* Close the database when the object exits scope
* Stage 3 ECMAScript Explicit Resource Management
* https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management
*/
[Symbol.asyncDispose](): Promise<void>;
/**
* Handle a file attached to the current query
* @param file The file to handle
*/
_handleBlob(blob?: File | Blob): Promise<void>;
/**
* Cleanup the current file
*/
_cleanupBlob(): Promise<void>;
/**
* Get the written blob from the current query
* @returns The written blob
*/
_getWrittenBlob(): Promise<Blob | undefined>;
/**
* Wait for the database to be ready
*/
_checkReady(): Promise<void>;
/**
* Execute a postgres wire protocol synchronously
* @param message The postgres wire protocol message to execute
* @returns The direct message data response produced by Postgres
*/
execProtocolRawSync(message: Uint8Array): Uint8Array;
/**
* Execute a postgres wire protocol message directly without wrapping the response.
* Only use if `execProtocol()` doesn't suite your needs.
*
* **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,
* transactions, and notification listeners. Only use if you need to bypass these wrappers and
* don't intend to use the above features.
*
* @param message The postgres wire protocol message to execute
* @returns The direct message data response produced by Postgres
*/
execProtocolRaw(message: Uint8Array, { syncToFs }?: ExecProtocolOptions): Promise<Uint8Array>;
/**
* Execute a postgres wire protocol message directly without wrapping the response.
* Only use if `execProtocol()` doesn't suite your needs.
*
* **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,
* transactions, and notification listeners. Only use if you need to bypass these wrappers and
* don't intend to use the above features.
*
* @param message The postgres wire protocol message to execute
* @param options.onRawData Callback to receive results as streaming data
*/
execProtocolRawStream(message: Uint8Array, { syncToFs, onRawData }: ExecProtocolOptionsStream): Promise<void>;
/**
* Execute a postgres wire protocol message
* @param message The postgres wire protocol message to execute
* @returns The result of the query
*/
execProtocol(message: Uint8Array, { syncToFs, throwOnError, onNotice, }?: ExecProtocolOptions): Promise<ExecProtocolResult>;
/**
* Execute a postgres wire protocol message
* @param message The postgres wire protocol message to execute
* @returns The parsed results of the query
*/
execProtocolStream(message: Uint8Array, { syncToFs, throwOnError, onNotice }?: ExecProtocolOptions): Promise<BackendMessage[]>;
/**
* Check if the database is in a transaction
* @returns True if the database is in a transaction, false otherwise
*/
isInTransaction(): boolean;
/**
* Perform any sync operations implemented by the filesystem, this is
* run after every query to ensure that the filesystem is synced.
*/
syncToFs(): Promise<void>;
/**
* Listen for a notification
* @param channel The channel to listen on
* @param callback The callback to call when a notification is received
*/
listen(channel: string, callback: (payload: string) => void, tx?: Transaction): Promise<(tx?: Transaction) => Promise<void>>;
/**
* Stop listening for a notification
* @param channel The channel to stop listening on
* @param callback The callback to remove
*/
unlisten(channel: string, callback?: (payload: string) => void, tx?: Transaction): Promise<void>;
/**
* Listen to notifications
* @param callback The callback to call when a notification is received
*/
onNotification(callback: (channel: string, payload: string) => void): () => void;
/**
* Stop listening to notifications
* @param callback The callback to remove
*/
offNotification(callback: (channel: string, payload: string) => void): void;
/**
* Dump the PGDATA dir from the filesystem to a gzipped tarball.
* @param compression The compression options to use - 'gzip', 'auto', 'none'
* @returns The tarball as a File object where available, and fallback to a Blob
*/
dumpDataDir(compression?: DumpTarCompressionOptions): Promise<File | Blob>;
/**
* Run a function in a mutex that's exclusive to queries
* @param fn The query to run
* @returns The result of the query
*/
_runExclusiveQuery<T>(fn: () => Promise<T>): Promise<T>;
/**
* Run a function in a mutex that's exclusive to transactions
* @param fn The function to run
* @returns The result of the function
*/
_runExclusiveTransaction<T>(fn: () => Promise<T>): Promise<T>;
clone(): Promise<PGliteInterface>;
_runExclusiveListen<T>(fn: () => Promise<T>): Promise<T>;
callMain(args: string[]): number;
copyToFS(filePath: string, data: Uint8Array, mode?: number): void;
}
export { type FsType as A, type BackendMessage as B, type Filesystem as C, type DebugLevel as D, EmscriptenBuiltinFilesystem as E, type FilesystemType as F, ERRNO_CODES as G, type InitializedExtensions as I, type Mode as M, type Parser as P, type QueryOptions as Q, type Results as R, type SerializerOptions as S, type Transaction as T, type BufferParameter as a, PGlite as b, type PostgresMod as c, type PGliteInterface as d, type RowMode as e, type ParserOptions as f, type ExecProtocolOptions as g, type ExecProtocolOptionsStream as h, type ExtensionSetupResult as i, type ExtensionSetup as j, type Extension as k, type ExtensionNamespace as l, messages as m, type Extensions as n, type ExecProtocolResult as o, postgresMod as p, type DumpDataDirResult as q, type PGliteOptions as r, type PGliteInterfaceExtensions as s, types$1 as t, type Row as u, type DescribeQueryResult as v, BaseFilesystem as w, type FsStats as x, BasePGlite as y, type DumpTarCompressionOptions as z };
declare const Modes: {
readonly text: 0;
readonly binary: 1;
};
type Mode = (typeof Modes)[keyof typeof Modes];
type BufferParameter = ArrayBuffer | ArrayBufferView;
type MessageName = 'parseComplete' | 'bindComplete' | 'closeComplete' | 'noData' | 'portalSuspended' | 'replicationStart' | 'emptyQuery' | 'copyDone' | 'copyData' | 'rowDescription' | 'parameterDescription' | 'parameterStatus' | 'backendKeyData' | 'notification' | 'readyForQuery' | 'commandComplete' | 'dataRow' | 'copyInResponse' | 'copyOutResponse' | 'authenticationOk' | 'authenticationMD5Password' | 'authenticationCleartextPassword' | 'authenticationSASL' | 'authenticationSASLContinue' | 'authenticationSASLFinal' | 'error' | 'notice';
type BackendMessage = {
name: MessageName;
length: number;
};
declare const parseComplete: BackendMessage;
declare const bindComplete: BackendMessage;
declare const closeComplete: BackendMessage;
declare const noData: BackendMessage;
declare const portalSuspended: BackendMessage;
declare const replicationStart: BackendMessage;
declare const emptyQuery: BackendMessage;
declare const copyDone: BackendMessage;
declare class AuthenticationOk implements BackendMessage {
readonly length: number;
readonly name = "authenticationOk";
constructor(length: number);
}
declare class AuthenticationCleartextPassword implements BackendMessage {
readonly length: number;
readonly name = "authenticationCleartextPassword";
constructor(length: number);
}
declare class AuthenticationMD5Password implements BackendMessage {
readonly length: number;
readonly salt: Uint8Array;
readonly name = "authenticationMD5Password";
constructor(length: number, salt: Uint8Array);
}
declare class AuthenticationSASL implements BackendMessage {
readonly length: number;
readonly mechanisms: string[];
readonly name = "authenticationSASL";
constructor(length: number, mechanisms: string[]);
}
declare class AuthenticationSASLContinue implements BackendMessage {
readonly length: number;
readonly data: string;
readonly name = "authenticationSASLContinue";
constructor(length: number, data: string);
}
declare class AuthenticationSASLFinal implements BackendMessage {
readonly length: number;
readonly data: string;
readonly name = "authenticationSASLFinal";
constructor(length: number, data: string);
}
type AuthenticationMessage = AuthenticationOk | AuthenticationCleartextPassword | AuthenticationMD5Password | AuthenticationSASL | AuthenticationSASLContinue | AuthenticationSASLFinal;
interface NoticeOrError {
message: string | undefined;
severity: string | undefined;
code: string | undefined;
detail: string | undefined;
hint: string | undefined;
position: string | undefined;
internalPosition: string | undefined;
internalQuery: string | undefined;
where: string | undefined;
schema: string | undefined;
table: string | undefined;
column: string | undefined;
dataType: string | undefined;
constraint: string | undefined;
file: string | undefined;
line: string | undefined;
routine: string | undefined;
}
declare class DatabaseError extends Error implements NoticeOrError {
readonly length: number;
readonly name: MessageName;
severity: string | undefined;
code: string | undefined;
detail: string | undefined;
hint: string | undefined;
position: string | undefined;
internalPosition: string | undefined;
internalQuery: string | undefined;
where: string | undefined;
schema: string | undefined;
table: string | undefined;
column: string | undefined;
dataType: string | undefined;
constraint: string | undefined;
file: string | undefined;
line: string | undefined;
routine: string | undefined;
constructor(message: string, length: number, name: MessageName);
}
declare class CopyDataMessage implements BackendMessage {
readonly length: number;
readonly chunk: Uint8Array;
readonly name = "copyData";
constructor(length: number, chunk: Uint8Array);
}
declare class CopyResponse implements BackendMessage {
readonly length: number;
readonly name: MessageName;
readonly binary: boolean;
readonly columnTypes: number[];
constructor(length: number, name: MessageName, binary: boolean, columnCount: number);
}
declare class Field {
readonly name: string;
readonly tableID: number;
readonly columnID: number;
readonly dataTypeID: number;
readonly dataTypeSize: number;
readonly dataTypeModifier: number;
readonly format: Mode;
constructor(name: string, tableID: number, columnID: number, dataTypeID: number, dataTypeSize: number, dataTypeModifier: number, format: Mode);
}
declare class RowDescriptionMessage implements BackendMessage {
readonly length: number;
readonly fieldCount: number;
readonly name: MessageName;
readonly fields: Field[];
constructor(length: number, fieldCount: number);
}
declare class ParameterDescriptionMessage implements BackendMessage {
readonly length: number;
readonly parameterCount: number;
readonly name: MessageName;
readonly dataTypeIDs: number[];
constructor(length: number, parameterCount: number);
}
declare class ParameterStatusMessage implements BackendMessage {
readonly length: number;
readonly parameterName: string;
readonly parameterValue: string;
readonly name: MessageName;
constructor(length: number, parameterName: string, parameterValue: string);
}
declare class BackendKeyDataMessage implements BackendMessage {
readonly length: number;
readonly processID: number;
readonly secretKey: number;
readonly name: MessageName;
constructor(length: number, processID: number, secretKey: number);
}
declare class NotificationResponseMessage implements BackendMessage {
readonly length: number;
readonly processId: number;
readonly channel: string;
readonly payload: string;
readonly name: MessageName;
constructor(length: number, processId: number, channel: string, payload: string);
}
declare class ReadyForQueryMessage implements BackendMessage {
readonly length: number;
readonly status: string;
readonly name: MessageName;
constructor(length: number, status: string);
}
declare class CommandCompleteMessage implements BackendMessage {
readonly length: number;
readonly text: string;
readonly name: MessageName;
constructor(length: number, text: string);
}
declare class DataRowMessage implements BackendMessage {
length: number;
fields: (string | null)[];
readonly fieldCount: number;
readonly name: MessageName;
constructor(length: number, fields: (string | null)[]);
}
declare class NoticeMessage implements BackendMessage, NoticeOrError {
readonly length: number;
readonly message: string | undefined;
constructor(length: number, message: string | undefined);
readonly name = "notice";
severity: string | undefined;
code: string | undefined;
detail: string | undefined;
hint: string | undefined;
position: string | undefined;
internalPosition: string | undefined;
internalQuery: string | undefined;
where: string | undefined;
schema: string | undefined;
table: string | undefined;
column: string | undefined;
dataType: string | undefined;
constraint: string | undefined;
file: string | undefined;
line: string | undefined;
routine: string | undefined;
}
type messages_AuthenticationCleartextPassword = AuthenticationCleartextPassword;
declare const messages_AuthenticationCleartextPassword: typeof AuthenticationCleartextPassword;
type messages_AuthenticationMD5Password = AuthenticationMD5Password;
declare const messages_AuthenticationMD5Password: typeof AuthenticationMD5Password;
type messages_AuthenticationMessage = AuthenticationMessage;
type messages_AuthenticationOk = AuthenticationOk;
declare const messages_AuthenticationOk: typeof AuthenticationOk;
type messages_AuthenticationSASL = AuthenticationSASL;
declare const messages_AuthenticationSASL: typeof AuthenticationSASL;
type messages_AuthenticationSASLContinue = AuthenticationSASLContinue;
declare const messages_AuthenticationSASLContinue: typeof AuthenticationSASLContinue;
type messages_AuthenticationSASLFinal = AuthenticationSASLFinal;
declare const messages_AuthenticationSASLFinal: typeof AuthenticationSASLFinal;
type messages_BackendKeyDataMessage = BackendKeyDataMessage;
declare const messages_BackendKeyDataMessage: typeof BackendKeyDataMessage;
type messages_BackendMessage = BackendMessage;
type messages_CommandCompleteMessage = CommandCompleteMessage;
declare const messages_CommandCompleteMessage: typeof CommandCompleteMessage;
type messages_CopyDataMessage = CopyDataMessage;
declare const messages_CopyDataMessage: typeof CopyDataMessage;
type messages_CopyResponse = CopyResponse;
declare const messages_CopyResponse: typeof CopyResponse;
type messages_DataRowMessage = DataRowMessage;
declare const messages_DataRowMessage: typeof DataRowMessage;
type messages_DatabaseError = DatabaseError;
declare const messages_DatabaseError: typeof DatabaseError;
type messages_Field = Field;
declare const messages_Field: typeof Field;
type messages_MessageName = MessageName;
type messages_NoticeMessage = NoticeMessage;
declare const messages_NoticeMessage: typeof NoticeMessage;
type messages_NotificationResponseMessage = NotificationResponseMessage;
declare const messages_NotificationResponseMessage: typeof NotificationResponseMessage;
type messages_ParameterDescriptionMessage = ParameterDescriptionMessage;
declare const messages_ParameterDescriptionMessage: typeof ParameterDescriptionMessage;
type messages_ParameterStatusMessage = ParameterStatusMessage;
declare const messages_ParameterStatusMessage: typeof ParameterStatusMessage;
type messages_ReadyForQueryMessage = ReadyForQueryMessage;
declare const messages_ReadyForQueryMessage: typeof ReadyForQueryMessage;
type messages_RowDescriptionMessage = RowDescriptionMessage;
declare const messages_RowDescriptionMessage: typeof RowDescriptionMessage;
declare const messages_bindComplete: typeof bindComplete;
declare const messages_closeComplete: typeof closeComplete;
declare const messages_copyDone: typeof copyDone;
declare const messages_emptyQuery: typeof emptyQuery;
declare const messages_noData: typeof noData;
declare const messages_parseComplete: typeof parseComplete;
declare const messages_portalSuspended: typeof portalSuspended;
declare const messages_replicationStart: typeof replicationStart;
declare namespace messages {
export { messages_AuthenticationCleartextPassword as AuthenticationCleartextPassword, messages_AuthenticationMD5Password as AuthenticationMD5Password, type messages_AuthenticationMessage as AuthenticationMessage, messages_AuthenticationOk as AuthenticationOk, messages_AuthenticationSASL as AuthenticationSASL, messages_AuthenticationSASLContinue as AuthenticationSASLContinue, messages_AuthenticationSASLFinal as AuthenticationSASLFinal, messages_BackendKeyDataMessage as BackendKeyDataMessage, type messages_BackendMessage as BackendMessage, messages_CommandCompleteMessage as CommandCompleteMessage, messages_CopyDataMessage as CopyDataMessage, messages_CopyResponse as CopyResponse, messages_DataRowMessage as DataRowMessage, messages_DatabaseError as DatabaseError, messages_Field as Field, type messages_MessageName as MessageName, messages_NoticeMessage as NoticeMessage, messages_NotificationResponseMessage as NotificationResponseMessage, messages_ParameterDescriptionMessage as ParameterDescriptionMessage, messages_ParameterStatusMessage as ParameterStatusMessage, messages_ReadyForQueryMessage as ReadyForQueryMessage, messages_RowDescriptionMessage as RowDescriptionMessage, messages_bindComplete as bindComplete, messages_closeComplete as closeComplete, messages_copyDone as copyDone, messages_emptyQuery as emptyQuery, messages_noData as noData, messages_parseComplete as parseComplete, messages_portalSuspended as portalSuspended, messages_replicationStart as replicationStart };
}
type IDBFS = Emscripten.FileSystemType & {
quit: () => void;
dbs: Record<string, IDBDatabase>;
};
type FS = typeof FS & {
filesystems: {
MEMFS: Emscripten.FileSystemType;
NODEFS: Emscripten.FileSystemType;
IDBFS: IDBFS;
};
quit: () => void;
};
interface PostgresMod extends Omit<EmscriptenModule, 'preInit' | 'preRun' | 'postRun'> {
preInit: Array<{
(mod: PostgresMod): void;
}>;
preRun: Array<{
(mod: PostgresMod): void;
}>;
postRun: Array<{
(mod: PostgresMod): void;
}>;
thisProgram: string;
stdin: (() => number | null) | null;
FS: FS;
wasmMemory: WebAssembly.Memory;
PROXYFS: Emscripten.FileSystemType;
WASM_PREFIX: string;
pg_extensions: Record<string, Promise<Blob | null>>;
UTF8ToString: (ptr: number, maxBytesToRead?: number) => string;
stringToUTF8OnStack: (s: string) => number;
_pgl_set_system_fn: (system_fn: number) => void;
_pgl_set_popen_fn: (popen_fn: number) => void;
_pgl_set_pclose_fn: (pclose_fn: number) => void;
_pgl_set_rw_cbs: (read_cb: number, write_cb: number) => void;
_pgl_set_pipe_fn: (pipe_fn: number) => number;
_pgl_freopen: (filepath: number, mode: number, stream: number) => number;
_pgl_pq_flush: () => void;
_fopen: (path: number, mode: number) => number;
_fclose: (stream: number) => number;
_fflush: (stream: number) => void;
_pgl_proc_exit: (code: number) => number;
addFunction: (cb: (ptr: any, length: number) => void, signature: string) => number;
removeFunction: (f: number) => void;
callMain: (args?: string[]) => number;
_PostgresMainLoopOnce: () => void;
_PostgresMainLongJmp: () => void;
_PostgresSendReadyForQueryIfNecessary: () => void;
_ProcessStartupPacket: (Port: number, ssl_done: boolean, gss_done: boolean) => number;
_IsTransactionBlock: () => number;
_pgl_setPGliteActive: (newValue: number) => number;
_pgl_startPGlite: () => void;
_pgl_getMyProcPort: () => number;
_pgl_sendConnData: () => void;
ENV: any;
PGLITE_ENV: any;
_emscripten_force_exit: (status: number) => void;
_pgl_run_atexit_funcs: () => void;
_pq_buffer_remaining_data: () => number;
}
type PostgresFactory<T extends PostgresMod = PostgresMod> = (moduleOverrides?: Partial<T>) => Promise<T>;
declare const _default: PostgresFactory<PostgresMod>;
type postgresMod_FS = FS;
type postgresMod_PostgresMod = PostgresMod;
declare namespace postgresMod {
export { type postgresMod_FS as FS, type postgresMod_PostgresMod as PostgresMod, _default as default };
}
type DumpTarCompressionOptions = 'none' | 'gzip' | 'auto';
type FsType = 'nodefs' | 'idbfs' | 'memoryfs' | 'opfs-ahp';
/**
* Filesystem interface.
* All virtual filesystems that are compatible with PGlite must implement
* this interface.
*/
interface Filesystem {
/**
* Initiate the filesystem and return the options to pass to the emscripten module.
*/
init(pg: PGlite, emscriptenOptions: Partial<PostgresMod>): Promise<{
emscriptenOpts: Partial<PostgresMod>;
}>;
/**
* Sync the filesystem to any underlying storage.
*/
syncToFs(relaxedDurability?: boolean): Promise<void>;
/**
* Sync the filesystem from any underlying storage.
*/
initialSyncFs(): Promise<void>;
/**
* Dump the PGDATA dir from the filesystem to a gzipped tarball.
*/
dumpTar(dbname: string, compression?: DumpTarCompressionOptions): Promise<File | Blob>;
/**
* Close the filesystem.
*/
closeFs(): Promise<void>;
}
/**
* Base class for all emscripten built-in filesystems.
*/
declare class EmscriptenBuiltinFilesystem implements Filesystem {
protected dataDir?: string;
protected pg?: PGlite;
constructor(dataDir?: string);
init(pg: PGlite, emscriptenOptions: Partial<PostgresMod>): Promise<{
emscriptenOpts: Partial<PostgresMod>;
}>;
syncToFs(_relaxedDurability?: boolean): Promise<void>;
initialSyncFs(): Promise<void>;
closeFs(): Promise<void>;
dumpTar(dbname: string, compression?: DumpTarCompressionOptions): Promise<Blob | File>;
}
/**
* Abstract base class for all custom virtual filesystems.
* Each custom filesystem needs to implement an interface similar to the NodeJS FS API.
*/
declare abstract class BaseFilesystem implements Filesystem {
protected dataDir?: string;
protected pg?: PGlite;
readonly debug: boolean;
constructor(dataDir?: string, { debug }?: {
debug?: boolean;
});
syncToFs(_relaxedDurability?: boolean): Promise<void>;
initialSyncFs(): Promise<void>;
closeFs(): Promise<void>;
dumpTar(dbname: string, compression?: DumpTarCompressionOptions): Promise<Blob | File>;
init(pg: PGlite, emscriptenOptions: Partial<PostgresMod>): Promise<{
emscriptenOpts: Partial<PostgresMod>;
}>;
abstract chmod(path: string, mode: number): void;
abstract close(fd: number): void;
abstract fstat(fd: number): FsStats;
abstract lstat(path: string): FsStats;
abstract mkdir(path: string, options?: {
recursive?: boolean;
mode?: number;
}): void;
abstract open(path: string, flags?: string, mode?: number): number;
abstract readdir(path: string): string[];
abstract read(fd: number, buffer: Uint8Array, // Buffer to read into
offset: number, // Offset in buffer to start writing to
length: number, // Number of bytes to read
position: number): number;
abstract rename(oldPath: string, newPath: string): void;
abstract rmdir(path: string): void;
abstract truncate(path: string, len: number): void;
abstract unlink(path: string): void;
abstract utimes(path: string, atime: number, mtime: number): void;
abstract writeFile(path: string, data: string | Uint8Array, options?: {
encoding?: string;
mode?: number;
flag?: string;
}): void;
abstract write(fd: number, buffer: Uint8Array, // Buffer to read from
offset: number, // Offset in buffer to start reading from
length: number, // Number of bytes to write
position: number): number;
}
type FsStats = {
dev: number;
ino: number;
mode: number;
nlink: number;
uid: number;
gid: number;
rdev: number;
size: number;
blksize: number;
blocks: number;
atime: number;
mtime: number;
ctime: number;
};
declare const ERRNO_CODES: {
readonly EBADF: 8;
readonly EBADFD: 127;
readonly EEXIST: 20;
readonly EINVAL: 28;
readonly EISDIR: 31;
readonly ENODEV: 43;
readonly ENOENT: 44;
readonly ENOTDIR: 54;
readonly ENOTEMPTY: 55;
};
type FilesystemType = 'nodefs' | 'idbfs' | 'memoryfs';
type DebugLevel = 0 | 1 | 2 | 3 | 4 | 5;
type RowMode = 'array' | 'object';
interface ParserOptions {
[pgType: number]: (value: string) => any;
}
interface SerializerOptions {
[pgType: number]: (value: any) => string;
}
interface QueryOptions {
rowMode?: RowMode;
parsers?: ParserOptions;
serializers?: SerializerOptions;
blob?: Blob | File;
onNotice?: (notice: NoticeMessage) => void;
paramTypes?: number[];
}
interface ExecProtocolOptions {
syncToFs?: boolean;
throwOnError?: boolean;
onNotice?: (notice: NoticeMessage) => void;
}
interface ExecProtocolOptionsStream {
syncToFs?: boolean;
onRawData: (data: Uint8Array) => void;
}
interface ExtensionSetupResult<TNamespace = any> {
emscriptenOpts?: any;
namespaceObj?: TNamespace;
bundlePath?: URL;
sharedPreloadLibraries?: string[];
init?: () => Promise<void>;
close?: () => Promise<void>;
}
type ExtensionSetup<TNamespace = any> = (pg: PGliteInterface, emscriptenOpts: any, clientOnly?: boolean) => Promise<ExtensionSetupResult<TNamespace>>;
interface Extension<TNamespace = any> {
name: string;
setup: ExtensionSetup<TNamespace>;
}
type ExtensionNamespace<T> = T extends Extension<infer TNamespace> ? TNamespace : any;
type Extensions = {
[namespace: string]: Extension | URL;
};
type InitializedExtensions<TExtensions extends Extensions = Extensions> = {
[K in keyof TExtensions]: ExtensionNamespace<TExtensions[K]>;
};
interface ExecProtocolResult {
messages: BackendMessage[];
data: Uint8Array;
}
interface DumpDataDirResult {
tarball: Uint8Array;
extension: '.tar' | '.tgz';
filename: string;
}
interface PGliteOptions<TExtensions extends Extensions = Extensions> {
noInitDb?: boolean;
dataDir?: string;
username?: string;
database?: string;
fs?: Filesystem;
debug?: DebugLevel;
relaxedDurability?: boolean;
extensions?: TExtensions;
loadDataDir?: Blob | File;
icuDataDir?: Blob | File;
initialMemory?: number;
pgliteWasmModule?: WebAssembly.Module;
initdbWasmModule?: WebAssembly.Module;
fsBundle?: Blob | File;
parsers?: ParserOptions;
serializers?: SerializerOptions;
startParams?: string[];
initDbStartParams?: string[];
postgresqlconf?: string[] | string;
}
type PGliteInterface<T extends Extensions = Extensions> = InitializedExtensions<T> & {
readonly waitReady: Promise<void>;
readonly debug: DebugLevel;
readonly ready: boolean;
readonly closed: boolean;
close(): Promise<void>;
query<T>(query: string, params?: any[], options?: QueryOptions): Promise<Results<T>>;
sql<T>(sqlStrings: TemplateStringsArray, ...params: any[]): Promise<Results<T>>;
exec(query: string, options?: QueryOptions): Promise<Array<Results>>;
describeQuery(query: string): Promise<DescribeQueryResult>;
transaction<T>(callback: (tx: Transaction) => Promise<T>): Promise<T>;
execProtocolRaw(message: Uint8Array, options?: ExecProtocolOptions): Promise<Uint8Array>;
execProtocolRawStream(message: Uint8Array, options?: ExecProtocolOptionsStream): Promise<void>;
execProtocol(message: Uint8Array, options?: ExecProtocolOptions): Promise<ExecProtocolResult>;
runExclusive<T>(fn: () => Promise<T>): Promise<T>;
listen(channel: string, callback: (payload: string) => void, tx?: Transaction): Promise<(tx?: Transaction) => Promise<void>>;
unlisten(channel: string, callback?: (payload: string) => void, tx?: Transaction): Promise<void>;
onNotification(callback: (channel: string, payload: string) => void): () => void;
offNotification(callback: (channel: string, payload: string) => void): void;
dumpDataDir(compression?: DumpTarCompressionOptions): Promise<File | Blob>;
refreshArrayTypes(): Promise<void>;
};
type PGliteInterfaceExtensions<E> = E extends Extensions ? {
[K in keyof E]: E[K] extends Extension ? Awaited<ReturnType<E[K]['setup']>>['namespaceObj'] extends infer N ? N extends undefined | null | void ? never : N : never : never;
} : Record<string, never>;
type Row<T = {
[key: string]: any;
}> = T;
type Results<T = {
[key: string]: any;
}> = {
rows: Row<T>[];
affectedRows?: number;
fields: {
name: string;
dataTypeID: number;
}[];
blob?: Blob;
};
interface Transaction {
query<T>(query: string, params?: any[], options?: QueryOptions): Promise<Results<T>>;
sql<T>(sqlStrings: TemplateStringsArray, ...params: any[]): Promise<Results<T>>;
exec(query: string, options?: QueryOptions): Promise<Array<Results>>;
rollback(): Promise<void>;
listen(channel: string, callback: (payload: string) => void): Promise<(tx?: Transaction) => Promise<void>>;
get closed(): boolean;
}
type DescribeQueryResult = {
queryParams: {
dataTypeID: number;
serializer: Serializer;
}[];
resultFields: {
name: string;
dataTypeID: number;
parser: Parser;
}[];
};
declare const BOOL = 16;
declare const BYTEA = 17;
declare const CHAR = 18;
declare const INT8 = 20;
declare const INT2 = 21;
declare const INT4 = 23;
declare const REGPROC = 24;
declare const TEXT = 25;
declare const OID = 26;
declare const TID = 27;
declare const XID = 28;
declare const CID = 29;
declare const JSON = 114;
declare const XML = 142;
declare const PG_NODE_TREE = 194;
declare const SMGR = 210;
declare const PATH = 602;
declare const POLYGON = 604;
declare const CIDR = 650;
declare const FLOAT4 = 700;
declare const FLOAT8 = 701;
declare const ABSTIME = 702;
declare const RELTIME = 703;
declare const TINTERVAL = 704;
declare const CIRCLE = 718;
declare const MACADDR8 = 774;
declare const MONEY = 790;
declare const MACADDR = 829;
declare const INET = 869;
declare const ACLITEM = 1033;
declare const BPCHAR = 1042;
declare const VARCHAR = 1043;
declare const DATE = 1082;
declare const TIME = 1083;
declare const TIMESTAMP = 1114;
declare const TIMESTAMPTZ = 1184;
declare const INTERVAL = 1186;
declare const TIMETZ = 1266;
declare const BIT = 1560;
declare const VARBIT = 1562;
declare const NUMERIC = 1700;
declare const REFCURSOR = 1790;
declare const REGPROCEDURE = 2202;
declare const REGOPER = 2203;
declare const REGOPERATOR = 2204;
declare const REGCLASS = 2205;
declare const REGTYPE = 2206;
declare const UUID = 2950;
declare const TXID_SNAPSHOT = 2970;
declare const PG_LSN = 3220;
declare const PG_NDISTINCT = 3361;
declare const PG_DEPENDENCIES = 3402;
declare const TSVECTOR = 3614;
declare const TSQUERY = 3615;
declare const GTSVECTOR = 3642;
declare const REGCONFIG = 3734;
declare const REGDICTIONARY = 3769;
declare const JSONB = 3802;
declare const REGNAMESPACE = 4089;
declare const REGROLE = 4096;
declare const types: {
string: {
to: number;
from: number[];
serialize: (x: string | number | Date) => string;
parse: (x: string) => string;
};
number: {
to: number;
from: number[];
serialize: (x: number) => string;
parse: (x: string) => number;
};
bigint: {
to: number;
from: number[];
serialize: (x: bigint) => string;
parse: (x: string) => number | bigint;
};
json: {
to: number;
from: number[];
serialize: (x: any) => string;
parse: (x: string) => any;
};
boolean: {
to: number;
from: number[];
serialize: (x: boolean | number | string) => "t" | "f";
parse: (x: string) => x is "t";
};
date: {
to: number;
from: number[];
serialize: (x: Date | string | number) => string;
parse: (x: string | number) => Date;
};
bytea: {
to: number;
from: number[];
serialize: (x: Uint8Array) => string;
parse: (x: string) => Uint8Array;
};
};
type Parser = (x: string, typeId?: number) => any;
type Serializer = (x: any) => string;
type TypeHandler = {
to: number;
from: number | number[];
serialize: Serializer;
parse: Parser;
};
type TypeHandlers = {
[key: string]: TypeHandler;
};
declare const parsers: {
[key: string]: (x: string, typeId?: number) => any;
[key: number]: (x: string, typeId?: number) => any;
};
declare const serializers: {
[key: string]: Serializer;
[key: number]: Serializer;
};
declare function parseType(x: string | null, type: number, parsers?: ParserOptions): any;
declare function arraySerializer(xs: any, serializer: Serializer | undefined, typarray: number): string;
declare function arrayParser(x: string, parser: Parser, typarray: number): any;
declare const types$1_ABSTIME: typeof ABSTIME;
declare const types$1_ACLITEM: typeof ACLITEM;
declare const types$1_BIT: typeof BIT;
declare const types$1_BOOL: typeof BOOL;
declare const types$1_BPCHAR: typeof BPCHAR;
declare const types$1_BYTEA: typeof BYTEA;
declare const types$1_CHAR: typeof CHAR;
declare const types$1_CID: typeof CID;
declare const types$1_CIDR: typeof CIDR;
declare const types$1_CIRCLE: typeof CIRCLE;
declare const types$1_DATE: typeof DATE;
declare const types$1_FLOAT4: typeof FLOAT4;
declare const types$1_FLOAT8: typeof FLOAT8;
declare const types$1_GTSVECTOR: typeof GTSVECTOR;
declare const types$1_INET: typeof INET;
declare const types$1_INT2: typeof INT2;
declare const types$1_INT4: typeof INT4;
declare const types$1_INT8: typeof INT8;
declare const types$1_INTERVAL: typeof INTERVAL;
declare const types$1_JSON: typeof JSON;
declare const types$1_JSONB: typeof JSONB;
declare const types$1_MACADDR: typeof MACADDR;
declare const types$1_MACADDR8: typeof MACADDR8;
declare const types$1_MONEY: typeof MONEY;
declare const types$1_NUMERIC: typeof NUMERIC;
declare const types$1_OID: typeof OID;
declare const types$1_PATH: typeof PATH;
declare const types$1_PG_DEPENDENCIES: typeof PG_DEPENDENCIES;
declare const types$1_PG_LSN: typeof PG_LSN;
declare const types$1_PG_NDISTINCT: typeof PG_NDISTINCT;
declare const types$1_PG_NODE_TREE: typeof PG_NODE_TREE;
declare const types$1_POLYGON: typeof POLYGON;
type types$1_Parser = Parser;
declare const types$1_REFCURSOR: typeof REFCURSOR;
declare const types$1_REGCLASS: typeof REGCLASS;
declare const types$1_REGCONFIG: typeof REGCONFIG;
declare const types$1_REGDICTIONARY: typeof REGDICTIONARY;
declare const types$1_REGNAMESPACE: typeof REGNAMESPACE;
declare const types$1_REGOPER: typeof REGOPER;
declare const types$1_REGOPERATOR: typeof REGOPERATOR;
declare const types$1_REGPROC: typeof REGPROC;
declare const types$1_REGPROCEDURE: typeof REGPROCEDURE;
declare const types$1_REGROLE: typeof REGROLE;
declare const types$1_REGTYPE: typeof REGTYPE;
declare const types$1_RELTIME: typeof RELTIME;
declare const types$1_SMGR: typeof SMGR;
type types$1_Serializer = Serializer;
declare const types$1_TEXT: typeof TEXT;
declare const types$1_TID: typeof TID;
declare const types$1_TIME: typeof TIME;
declare const types$1_TIMESTAMP: typeof TIMESTAMP;
declare const types$1_TIMESTAMPTZ: typeof TIMESTAMPTZ;
declare const types$1_TIMETZ: typeof TIMETZ;
declare const types$1_TINTERVAL: typeof TINTERVAL;
declare const types$1_TSQUERY: typeof TSQUERY;
declare const types$1_TSVECTOR: typeof TSVECTOR;
declare const types$1_TXID_SNAPSHOT: typeof TXID_SNAPSHOT;
type types$1_TypeHandler = TypeHandler;
type types$1_TypeHandlers = TypeHandlers;
declare const types$1_UUID: typeof UUID;
declare const types$1_VARBIT: typeof VARBIT;
declare const types$1_VARCHAR: typeof VARCHAR;
declare const types$1_XID: typeof XID;
declare const types$1_XML: typeof XML;
declare const types$1_arrayParser: typeof arrayParser;
declare const types$1_arraySerializer: typeof arraySerializer;
declare const types$1_parseType: typeof parseType;
declare const types$1_parsers: typeof parsers;
declare const types$1_serializers: typeof serializers;
declare const types$1_types: typeof types;
declare namespace types$1 {
export { types$1_ABSTIME as ABSTIME, types$1_ACLITEM as ACLITEM, types$1_BIT as BIT, types$1_BOOL as BOOL, types$1_BPCHAR as BPCHAR, types$1_BYTEA as BYTEA, types$1_CHAR as CHAR, types$1_CID as CID, types$1_CIDR as CIDR, types$1_CIRCLE as CIRCLE, types$1_DATE as DATE, types$1_FLOAT4 as FLOAT4, types$1_FLOAT8 as FLOAT8, types$1_GTSVECTOR as GTSVECTOR, types$1_INET as INET, types$1_INT2 as INT2, types$1_INT4 as INT4, types$1_INT8 as INT8, types$1_INTERVAL as INTERVAL, types$1_JSON as JSON, types$1_JSONB as JSONB, types$1_MACADDR as MACADDR, types$1_MACADDR8 as MACADDR8, types$1_MONEY as MONEY, types$1_NUMERIC as NUMERIC, types$1_OID as OID, types$1_PATH as PATH, types$1_PG_DEPENDENCIES as PG_DEPENDENCIES, types$1_PG_LSN as PG_LSN, types$1_PG_NDISTINCT as PG_NDISTINCT, types$1_PG_NODE_TREE as PG_NODE_TREE, types$1_POLYGON as POLYGON, type types$1_Parser as Parser, types$1_REFCURSOR as REFCURSOR, types$1_REGCLASS as REGCLASS, types$1_REGCONFIG as REGCONFIG, types$1_REGDICTIONARY as REGDICTIONARY, types$1_REGNAMESPACE as REGNAMESPACE, types$1_REGOPER as REGOPER, types$1_REGOPERATOR as REGOPERATOR, types$1_REGPROC as REGPROC, types$1_REGPROCEDURE as REGPROCEDURE, types$1_REGROLE as REGROLE, types$1_REGTYPE as REGTYPE, types$1_RELTIME as RELTIME, types$1_SMGR as SMGR, type types$1_Serializer as Serializer, types$1_TEXT as TEXT, types$1_TID as TID, types$1_TIME as TIME, types$1_TIMESTAMP as TIMESTAMP, types$1_TIMESTAMPTZ as TIMESTAMPTZ, types$1_TIMETZ as TIMETZ, types$1_TINTERVAL as TINTERVAL, types$1_TSQUERY as TSQUERY, types$1_TSVECTOR as TSVECTOR, types$1_TXID_SNAPSHOT as TXID_SNAPSHOT, type types$1_TypeHandler as TypeHandler, type types$1_TypeHandlers as TypeHandlers, types$1_UUID as UUID, types$1_VARBIT as VARBIT, types$1_VARCHAR as VARCHAR, types$1_XID as XID, types$1_XML as XML, types$1_arrayParser as arrayParser, types$1_arraySerializer as arraySerializer, types$1_parseType as parseType, types$1_parsers as parsers, types$1_serializers as serializers, types$1_types as types };
}
declare abstract class BasePGlite implements Pick<PGliteInterface, 'query' | 'sql' | 'exec' | 'transaction'> {
#private;
serializers: Record<number | string, Serializer>;
parsers: Record<number | string, Parser>;
abstract debug: DebugLevel;
/**
* Execute a postgres wire protocol message
* @param message The postgres wire protocol message to execute
* @returns The result of the query
*/
abstract execProtocol(message: Uint8Array, { syncToFs, onNotice }: ExecProtocolOptions): Promise<ExecProtocolResult>;
/**
* Execute a postgres wire protocol message
* @param message The postgres wire protocol message to execute
* @returns The parsed results of the query
*/
abstract execProtocolStream(message: Uint8Array, { syncToFs, onNotice }: ExecProtocolOptions): Promise<BackendMessage[]>;
/**
* Execute a postgres wire protocol message directly without wrapping the response.
* Only use if `execProtocol()` doesn't suite your needs.
*
* **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,
* transactions, and notification listeners. Only use if you need to bypass these wrappers and
* don't intend to use the above features.
*
* @param message The postgres wire protocol message to execute
* @returns The direct message data response produced by Postgres
*/
abstract execProtocolRaw(message: Uint8Array, { syncToFs }: ExecProtocolOptions): Promise<Uint8Array>;
/**
* Execute a postgres wire protocol message directly without wrapping the response.
* Only use if `execProtocol()` doesn't suite your needs.
*
* **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,
* transactions, and notification listeners. Only use if you need to bypass these wrappers and
* don't intend to use the above features.
*
* @param message The postgres wire protocol message to execute
* @param options.onRawData Callback to receive streaming data
*/
abstract execProtocolRawStream(message: Uint8Array, { syncToFs, onRawData }: ExecProtocolOptionsStream): Promise<void>;
/**
* Sync the database to the filesystem
* @returns Promise that resolves when the database is synced to the filesystem
*/
abstract syncToFs(): Promise<void>;
/**
* Handle a file attached to the current query
* @param file The file to handle
*/
abstract _handleBlob(blob?: File | Blob): Promise<void>;
/**
* Get the written file
*/
abstract _getWrittenBlob(): Promise<File | Blob | undefined>;
/**
* Cleanup the current file
*/
abstract _cleanupBlob(): Promise<void>;
abstract _checkReady(): Promise<void>;
abstract _runExclusiveQuery<T>(fn: () => Promise<T>): Promise<T>;
abstract _runExclusiveTransaction<T>(fn: () => Promise<T>): Promise<T>;
/**
* Listen for notifications on a channel
*/
abstract listen(channel: string, callback: (payload: string) => void, tx?: Transaction): Promise<(tx?: Transaction) => Promise<void>>;
/**
* Initialize the array types
* The oid if the type of an element and the typarray is the oid of the type of the
* array.
* We extract these from the database then create the serializers/parsers for
* each type.
* This should be called at the end of #init() in the implementing class.
*/
_initArrayTypes({ force }?: {
force?: boolean | undefined;
}): Promise<void>;
/**
* Re-syncs the array types from the database
* This is useful if you add a new type to the database and want to use it, otherwise pglite won't recognize it.
*/
refreshArrayTypes(): Promise<void>;
/**
* Execute a single SQL statement
* This uses the "Extended Query" postgres wire protocol message.
* @param query The query to execute
* @param params Optional parameters for the query
* @returns The result of the query
*/
query<T>(query: string, params?: any[], options?: QueryOptions): Promise<Results<T>>;
/**
* Execute a single SQL statement like with {@link PGlite.query}, but with a
* templated statement where template values will be treated as parameters.
*
* You can use helpers from `/template` to further format the query with
* identifiers, raw SQL, and nested statements.
*
* This uses the "Extended Query" postgres wire protocol message.
*
* @param query The query to execute with parameters as template values
* @returns The result of the query
*
* @example
* ```ts
* const results = await db.sql`SELECT * FROM ${identifier`foo`} WHERE id = ${id}`
* ```
*/
sql<T>(sqlStrings: TemplateStringsArray, ...params: any[]): Promise<Results<T>>;
/**
* Execute a SQL query, this can have multiple statements.
* This uses the "Simple Query" postgres wire protocol message.
* @param query The query to execute
* @returns The result of the query
*/
exec(query: string, options?: QueryOptions): Promise<Array<Results>>;
/**
* Describe a query
* @param query The query to describe
* @returns A description of the result types for the query
*/
describeQuery(query: string, options?: QueryOptions): Promise<DescribeQueryResult>;
/**
* Execute a transaction
* @param callback A callback function that takes a transaction object
* @returns The result of the transaction
*/
transaction<T>(callback: (tx: Transaction) => Promise<T>): Promise<T>;
/**
* Run a function exclusively, no other transactions or queries will be allowed
* while the function is running.
* This is useful when working with the execProtocol methods as they are not blocked,
* and do not block the locks used by transactions and queries.
* @param fn The function to run
* @returns The result of the function
*/
runExclusive<T>(fn: () => Promise<T>): Promise<T>;
}
declare class PGlite extends BasePGlite implements PGliteInterface, AsyncDisposable {
#private;
fs?: Filesystem;
protected mod?: PostgresMod;
private readonly POSTGRES_MAIN_LONGJMP;
get ENV(): any;
readonly dataDir?: string;
readonly waitReady: Promise<void>;
readonly debug: DebugLevel;
static readonly paths: {
readonly PG_ROOT: "/pglite";
readonly PGDATA: string;
readonly ICU_DATA_PATH: string;
readonly INITDB_EXE_PATH: string;
readonly POSTGRES_EXE_PATH: string;
};
static readonly DEFAULT_RECV_BUF_SIZE: number;
static readonly MAX_BUFFER_SIZE: number;
externalCommandStreamFd: number | null;
static readonly defaultStartParams: string[];
/**
* Create a new PGlite instance
* @param dataDir The directory to store the database files
* Prefix with idb:// to use indexeddb filesystem in the browser
* Use memory:// to use in-memory filesystem
* @param options PGlite options
*/
constructor(dataDir?: string, options?: PGliteOptions);
/**
* Create a new PGlite instance
* @param options PGlite options including the data directory
*/
constructor(options?: PGliteOptions);
/**
* Create a new PGlite instance with extensions on the Typescript interface
* (The main constructor does enable extensions, however due to the limitations
* of Typescript, the extensions are not available on the instance interface)
* @param options PGlite options including the data directory
* @returns A promise that resolves to the PGlite instance when it's ready.
*/
static create<O extends PGliteOptions>(options?: O): Promise<PGlite & PGliteInterfaceExtensions<O['extensions']>>;
/**
* Create a new PGlite instance with extensions on the Typescript interface
* (The main constructor does enable extensions, however due to the limitations
* of Typescript, the extensions are not available on the instance interface)
* @param dataDir The directory to store the database files
* Prefix with idb:// to use indexeddb filesystem in the browser
* Use memory:// to use in-memory filesystem
* @param options PGlite options
* @returns A promise that resolves to the PGlite instance when it's ready.
*/
static create<O extends PGliteOptions>(dataDir?: string, options?: O): Promise<PGlite & PGliteInterfaceExtensions<O['extensions']>>;
handleExternalCmd(cmd: string, mode: string): number;
/**
* The Postgres Emscripten Module
*/
get Module(): PostgresMod;
/**
* The ready state of the database
*/
get ready(): boolean;
/**
* The closed state of the database
*/
get closed(): boolean;
/**
* Close the database
* @returns A promise that resolves when the database is closed
*/
close(): Promise<void>;
/**
* Close the database when the object exits scope
* Stage 3 ECMAScript Explicit Resource Management
* https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management
*/
[Symbol.asyncDispose](): Promise<void>;
/**
* Handle a file attached to the current query
* @param file The file to handle
*/
_handleBlob(blob?: File | Blob): Promise<void>;
/**
* Cleanup the current file
*/
_cleanupBlob(): Promise<void>;
/**
* Get the written blob from the current query
* @returns The written blob
*/
_getWrittenBlob(): Promise<Blob | undefined>;
/**
* Wait for the database to be ready
*/
_checkReady(): Promise<void>;
/**
* Execute a postgres wire protocol synchronously
* @param message The postgres wire protocol message to execute
* @returns The direct message data response produced by Postgres
*/
execProtocolRawSync(message: Uint8Array): Uint8Array;
/**
* Execute a postgres wire protocol message directly without wrapping the response.
* Only use if `execProtocol()` doesn't suite your needs.
*
* **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,
* transactions, and notification listeners. Only use if you need to bypass these wrappers and
* don't intend to use the above features.
*
* @param message The postgres wire protocol message to execute
* @returns The direct message data response produced by Postgres
*/
execProtocolRaw(message: Uint8Array, { syncToFs }?: ExecProtocolOptions): Promise<Uint8Array>;
/**
* Execute a postgres wire protocol message directly without wrapping the response.
* Only use if `execProtocol()` doesn't suite your needs.
*
* **Warning:** This bypasses PGlite's protocol wrappers that manage error/notice messages,
* transactions, and notification listeners. Only use if you need to bypass these wrappers and
* don't intend to use the above features.
*
* @param message The postgres wire protocol message to execute
* @param options.onRawData Callback to receive results as streaming data
*/
execProtocolRawStream(message: Uint8Array, { syncToFs, onRawData }: ExecProtocolOptionsStream): Promise<void>;
/**
* Execute a postgres wire protocol message
* @param message The postgres wire protocol message to execute
* @returns The result of the query
*/
execProtocol(message: Uint8Array, { syncToFs, throwOnError, onNotice, }?: ExecProtocolOptions): Promise<ExecProtocolResult>;
/**
* Execute a postgres wire protocol message
* @param message The postgres wire protocol message to execute
* @returns The parsed results of the query
*/
execProtocolStream(message: Uint8Array, { syncToFs, throwOnError, onNotice }?: ExecProtocolOptions): Promise<BackendMessage[]>;
/**
* Check if the database is in a transaction
* @returns True if the database is in a transaction, false otherwise
*/
isInTransaction(): boolean;
/**
* Perform any sync operations implemented by the filesystem, this is
* run after every query to ensure that the filesystem is synced.
*/
syncToFs(): Promise<void>;
/**
* Listen for a notification
* @param channel The channel to listen on
* @param callback The callback to call when a notification is received
*/
listen(channel: string, callback: (payload: string) => void, tx?: Transaction): Promise<(tx?: Transaction) => Promise<void>>;
/**
* Stop listening for a notification
* @param channel The channel to stop listening on
* @param callback The callback to remove
*/
unlisten(channel: string, callback?: (payload: string) => void, tx?: Transaction): Promise<void>;
/**
* Listen to notifications
* @param callback The callback to call when a notification is received
*/
onNotification(callback: (channel: string, payload: string) => void): () => void;
/**
* Stop listening to notifications
* @param callback The callback to remove
*/
offNotification(callback: (channel: string, payload: string) => void): void;
/**
* Dump the PGDATA dir from the filesystem to a gzipped tarball.
* @param compression The compression options to use - 'gzip', 'auto', 'none'
* @returns The tarball as a File object where available, and fallback to a Blob
*/
dumpDataDir(compression?: DumpTarCompressionOptions): Promise<File | Blob>;
/**
* Run a function in a mutex that's exclusive to queries
* @param fn The query to run
* @returns The result of the query
*/
_runExclusiveQuery<T>(fn: () => Promise<T>): Promise<T>;
/**
* Run a function in a mutex that's exclusive to transactions
* @param fn The function to run
* @returns The result of the function
*/
_runExclusiveTransaction<T>(fn: () => Promise<T>): Promise<T>;
clone(): Promise<PGliteInterface>;
_runExclusiveListen<T>(fn: () => Promise<T>): Promise<T>;
callMain(args: string[]): number;
copyToFS(filePath: string, data: Uint8Array, mode?: number): void;
}
export { type FsType as A, type BackendMessage as B, type Filesystem as C, type DebugLevel as D, EmscriptenBuiltinFilesystem as E, type FilesystemType as F, ERRNO_CODES as G, type InitializedExtensions as I, type Mode as M, type Parser as P, type QueryOptions as Q, type Results as R, type SerializerOptions as S, type Transaction as T, type BufferParameter as a, PGlite as b, type PostgresMod as c, type PGliteInterface as d, type RowMode as e, type ParserOptions as f, type ExecProtocolOptions as g, type ExecProtocolOptionsStream as h, type ExtensionSetupResult as i, type ExtensionSetup as j, type Extension as k, type ExtensionNamespace as l, messages as m, type Extensions as n, type ExecProtocolResult as o, postgresMod as p, type DumpDataDirResult as q, type PGliteOptions as r, type PGliteInterfaceExtensions as s, types$1 as t, type Row as u, type DescribeQueryResult as v, BaseFilesystem as w, type FsStats as x, BasePGlite as y, type DumpTarCompressionOptions as z };

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display