zen-code 4.10.1 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app.js +151 -2699
- package/dist/chunk-069q9hkz.js +1 -0
- package/dist/chunk-06trk066.js +1 -0
- package/dist/chunk-0kfw8bwn.js +2 -0
- package/dist/chunk-0mq8786q.js +281 -0
- package/dist/chunk-0qz8rr2k.js +1 -0
- package/dist/chunk-1d47g6nc.js +2 -0
- package/dist/chunk-1gssqf6g.js +88 -0
- package/dist/chunk-1rcc9xzn.js +79 -0
- package/dist/chunk-2bjeg40f.js +1 -0
- package/dist/chunk-2gd8vzrf.js +2 -0
- package/dist/chunk-2gprcgep.js +6 -0
- package/dist/chunk-3k3c686f.js +1 -0
- package/dist/chunk-43h0n2td.js +1 -0
- package/dist/chunk-492hjs9k.js +26 -0
- package/dist/chunk-4eaqmt3c.js +16 -0
- package/dist/chunk-4fs853nh.js +2 -0
- package/dist/chunk-5fe27s34.js +2 -0
- package/dist/chunk-5hqvapp1.js +7 -0
- package/dist/chunk-6b3vfr39.js +2 -0
- package/dist/chunk-6j695pam.js +5 -0
- package/dist/chunk-6saqxa3z.js +2 -0
- package/dist/chunk-78ksrp8v.js +41 -0
- package/dist/chunk-7cx9kda0.js +228 -0
- package/dist/chunk-7qba2raw.js +2 -0
- package/dist/chunk-81b2s97q.js +1 -0
- package/dist/chunk-88w3txtb.js +160 -0
- package/dist/chunk-8ygdre0g.js +1 -0
- package/dist/chunk-9011y634.js +6 -0
- package/dist/chunk-9zcr1qh6.js +1 -0
- package/dist/chunk-a0nr8jva.js +2 -0
- package/dist/chunk-agevsn2e.js +1 -0
- package/dist/chunk-akc3s5aw.js +6 -0
- package/dist/chunk-b0beqmg2.js +2 -0
- package/dist/chunk-b175s7dm.js +1 -0
- package/dist/chunk-bk32cwxa.js +5 -0
- package/dist/chunk-bn077sjq.js +213 -0
- package/dist/chunk-c9yrpb3g.js +18 -0
- package/dist/chunk-cb0f54ar.js +3 -0
- package/dist/chunk-ctqtahz4.js +1 -0
- package/dist/chunk-d2sr8fnm.js +3 -0
- package/dist/chunk-d5gzkkgg.js +1 -0
- package/dist/chunk-dh2f4xyb.js +3 -0
- package/dist/chunk-dr32dt9y.js +1 -0
- package/dist/chunk-dv1vt080.js +1 -0
- package/dist/chunk-dz9sqfph.js +2 -0
- package/dist/chunk-e7mbewmw.js +1 -0
- package/dist/chunk-em03xqy9.js +1 -0
- package/dist/chunk-fkt5b511.js +1 -0
- package/dist/chunk-gphssgy6.js +2 -0
- package/dist/chunk-h2hk7vx4.js +1 -0
- package/dist/chunk-h7ypcqp3.js +279 -0
- package/dist/chunk-j8tq0e8m.js +2 -0
- package/dist/chunk-jd1razfg.js +91 -0
- package/dist/chunk-jhxvctg5.js +8 -0
- package/dist/chunk-kada5fyh.js +1 -0
- package/dist/chunk-kgc6ws03.js +1 -0
- package/dist/chunk-mk8ggmt8.js +17 -0
- package/dist/chunk-mv5m8bf4.js +140 -0
- package/dist/chunk-mv8a5svx.js +1 -0
- package/dist/chunk-n61yv4t5.js +2 -0
- package/dist/chunk-nt2yp4jh.js +1 -0
- package/dist/chunk-p7ew4trx.js +1 -0
- package/dist/chunk-pgnhcznr.js +4 -0
- package/dist/chunk-q8cfxky4.js +8 -0
- package/dist/chunk-q8zsxwd8.js +81 -0
- package/dist/chunk-qfa5v4n5.js +1 -0
- package/dist/chunk-qhzztj83.js +1 -0
- package/dist/chunk-snmkgfbe.js +15 -0
- package/dist/chunk-ss4bh5wb.js +2 -0
- package/dist/chunk-sv0k2v66.js +1 -0
- package/dist/chunk-tbav8trq.js +23 -0
- package/dist/chunk-tmyzfvsy.js +1 -0
- package/dist/chunk-ts4jreym.js +7 -0
- package/dist/chunk-tws3wcnm.js +2 -0
- package/dist/chunk-v0e9bsvt.js +89 -0
- package/dist/chunk-vwj4n000.js +4 -0
- package/dist/chunk-wd6s7gg7.js +175 -0
- package/dist/chunk-y524zd2h.js +54 -0
- package/dist/chunk-yb71zqvt.js +2 -0
- package/dist/chunk-yejgw2hm.js +112 -0
- package/dist/chunk-yfjs6pf8.js +3 -0
- package/dist/chunk-zhqdp4ak.js +2 -0
- package/dist/chunk-zkd3m39v.js +1 -0
- package/dist/cli.js +1 -3116
- package/dist/nonInteractive.js +180 -1950
- package/dist/zen-core.js +644 -0
- package/dist/zen-keyboard.js +3 -358
- package/package.json +5 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as i,d as u}from"./chunk-a0nr8jva.js";import"./chunk-vwj4n000.js";import"./chunk-4fs853nh.js";function l(e,t){let r=t?"query":"prepare",a=(o,n)=>e[r](o,n);return{db:e,query:(o,n,s)=>{let c=a(n,s);if(c.columnNames.length>0)return{rows:c.all()};else{let{changes:m,lastInsertRowid:p}=c.run();return{numAffectedRows:i(m),insertId:i(p),rows:[]}}},close:()=>e.close(),iterator:(o,n,s)=>f(a(n),s)}}async function*f(e,t){if(!("iterate"in e))throw Error("Streaming not supported, please upgrade to Bun@1.1.31 or later");for(let r of e.iterate(...t||[]))yield r}import w from"bun:sqlite";var y=class extends u{constructor(e){let{url:t=":memory:",cacheStatment:r=!1,onCreateConnection:a,dbOptions:o={create:!0}}=e||{};super(()=>l(new w(t,o),r),a)}};export{y as BunSqliteDialect};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{H as a}from"./chunk-5fe27s34.js";import{K as f,M as r,N as l,O as n}from"./chunk-5hqvapp1.js";import{U as x,fa as P}from"./chunk-h7ypcqp3.js";import{Wl as g}from"./chunk-4fs853nh.js";var t=g(x(),1);function _({enabled:o=!0}={}){let i=a();return r({queryKey:n.config.detail(),queryFn:()=>i.config.get.query(),enabled:o,staleTime:300000,gcTime:600000})}function v(){let o=a(),i=f();return l({mutationFn:(e)=>o.config.update.mutate(e),onSuccess:(e)=>{i.setQueryData(n.config.detail(),e),i.invalidateQueries({queryKey:n.providers.all}),i.invalidateQueries({queryKey:n.models.all})}})}var h=g(P(),1),C=t.createContext(void 0),B=()=>{let o=t.useContext(C);if(o===void 0)throw Error("useSettings must be used within a SettingsProvider");return o},N=({children:o})=>{let i=a(),{data:e}=_(),d=v(),s=e?.provider_id,{data:c=[]}=r({queryKey:n.models.available(s),queryFn:()=>i.models.list.query({providerId:s}),staleTime:1800000,retry:1,enabled:!!s}),u=t.useMemo(()=>{return{provider_id:e?.provider_id||"openai",provider_type:e?.provider_type||"openai",model_id:e?.model_id||c[0]?.id||"default",mcp_config:e?.mcp_config,enable_thinking:e?.enable_thinking??!0,streaming:e?.streaming??!1,active_agent:e?.active_agent||"",cwd:process.cwd()}},[e?.provider_id,e?.provider_type,e?.model_id,e?.mcp_config,e?.enable_thinking,e?.streaming,e?.active_agent,e?.providers,c]),p=t.useMemo(()=>e?.compact_mode??!1,[e?.compact_mode]),A=async()=>{await d.mutateAsync({compact_mode:!p})},m=t.useMemo(()=>e?.show_detailed_info??!1,[e?.show_detailed_info]),S=async()=>{await d.mutateAsync({show_detailed_info:!m})},M=async(w)=>{await d.mutateAsync(w)};return h.jsxDEV(C.Provider,{value:{config:e||null,updateConfig:M,extraParams:u,AVAILABLE_MODELS:c,compactMode:p,toggleCompactMode:A,showDetailedInfo:m,toggleDetailedInfo:S},children:o},void 0,!1,void 0,this)};
|
|
2
|
+
export{B as E,N as F};
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import{Ag as VO,Cg as SO,Dg as s$,ug as u}from"./chunk-88w3txtb.js";import"./chunk-v0e9bsvt.js";import"./chunk-jhxvctg5.js";import"./chunk-bk32cwxa.js";import"./chunk-qfa5v4n5.js";import"./chunk-78ksrp8v.js";import"./chunk-yb71zqvt.js";import{$l as W,Wl as vG,Yl as R}from"./chunk-4fs853nh.js";var L$=R((wO)=>{wO.parse=function($,E){return new W$($,E).parse()};class W${constructor($,E){this.source=$,this.transform=E||kO,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var $=this.source[this.position++];if($==="\\")return{value:this.source[this.position++],escaped:!0};return{value:$,escaped:!1}}record($){this.recorded.push($)}newEntry($){var E;if(this.recorded.length>0||$){if(E=this.recorded.join(""),E==="NULL"&&!$)E=null;if(E!==null)E=this.transform(E);this.entries.push(E),this.recorded=[]}}consumeDimensions(){if(this.source[0]==="[")while(!this.isEof()){var $=this.nextCharacter();if($.value==="=")break}}parse($){var E,_,O;this.consumeDimensions();while(!this.isEof())if(E=this.nextCharacter(),E.value==="{"&&!O){if(this.dimension++,this.dimension>1)_=new W$(this.source.substr(this.position-1),this.transform),this.entries.push(_.parse(!0)),this.position+=_.position-2}else if(E.value==="}"&&!O){if(this.dimension--,!this.dimension){if(this.newEntry(),$)return this.entries}}else if(E.value==='"'&&!E.escaped){if(O)this.newEntry(!0);O=!O}else if(E.value===","&&!O)this.newEntry();else this.record(E.value);if(this.dimension!==0)throw Error("array dimension not balanced");return this.entries}}function kO($){return $}});var Q$=R((nG,e$)=>{var hO=L$();e$.exports={create:function($,E){return{parse:function(){return hO.parse($,E)}}}}});var _E=R((iG,EE)=>{var bO=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,yO=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,vO=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,pO=/^-?infinity$/;EE.exports=function(E){if(pO.test(E))return Number(E.replace("i","I"));var _=bO.exec(E);if(!_)return mO(E)||null;var O=!!_[8],G=parseInt(_[1],10);if(O)G=$E(G);var X=parseInt(_[2],10)-1,U=_[3],J=parseInt(_[4],10),Z=parseInt(_[5],10),H=parseInt(_[6],10),Y=_[7];Y=Y?1000*parseFloat(Y):0;var T,K=fO(E);if(K!=null){if(T=new Date(Date.UTC(G,X,U,J,Z,H,Y)),j$(G))T.setUTCFullYear(G);if(K!==0)T.setTime(T.getTime()-K)}else if(T=new Date(G,X,U,J,Z,H,Y),j$(G))T.setFullYear(G);return T};function mO($){var E=yO.exec($);if(!E)return;var _=parseInt(E[1],10),O=!!E[4];if(O)_=$E(_);var G=parseInt(E[2],10)-1,X=E[3],U=new Date(_,G,X);if(j$(_))U.setFullYear(_);return U}function fO($){if($.endsWith("+00"))return 0;var E=vO.exec($.split(" ")[1]);if(!E)return;var _=E[1];if(_==="Z")return 0;var O=_==="-"?-1:1,G=parseInt(E[2],10)*3600+parseInt(E[3]||0,10)*60+parseInt(E[4]||0,10);return G*O*1000}function $E($){return-($-1)}function j$($){return $>=0&&$<100}});var GE=R((sG,OE)=>{OE.exports=uO;var dO=Object.prototype.hasOwnProperty;function uO($){for(var E=1;E<arguments.length;E++){var _=arguments[E];for(var O in _)if(dO.call(_,O))$[O]=_[O]}return $}});var JE=R((tG,UE)=>{var gO=GE();UE.exports=x;function x($){if(!(this instanceof x))return new x($);gO(this,E0($))}var cO=["seconds","minutes","hours","days","months","years"];x.prototype.toPostgres=function(){var $=cO.filter(this.hasOwnProperty,this);if(this.milliseconds&&$.indexOf("seconds")<0)$.push("seconds");if($.length===0)return"0";return $.map(function(E){var _=this[E]||0;if(E==="seconds"&&this.milliseconds)_=(_+this.milliseconds/1000).toFixed(6).replace(/\.?0+$/,"");return _+" "+E},this).join(" ")};var lO={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},oO=["years","months","days"],nO=["hours","minutes","seconds"];x.prototype.toISOString=x.prototype.toISO=function(){var $=oO.map(_,this).join(""),E=nO.map(_,this).join("");return"P"+$+"T"+E;function _(O){var G=this[O]||0;if(O==="seconds"&&this.milliseconds)G=(G+this.milliseconds/1000).toFixed(6).replace(/0+$/,"");return G+lO[O]}};var N$="([+-]?\\d+)",iO=N$+"\\s+years?",sO=N$+"\\s+mons?",tO=N$+"\\s+days?",aO="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",rO=new RegExp([iO,sO,tO,aO].map(function($){return"("+$+")?"}).join("\\s*")),XE={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},eO=["hours","minutes","seconds","milliseconds"];function $0($){var E=$+"000000".slice($.length);return parseInt(E,10)/1000}function E0($){if(!$)return{};var E=rO.exec($),_=E[8]==="-";return Object.keys(XE).reduce(function(O,G){var X=XE[G],U=E[X];if(!U)return O;if(U=G==="milliseconds"?$0(U):parseInt(U,10),!U)return O;if(_&&~eO.indexOf(G))U*=-1;return O[G]=U,O},{})}});var TE=R((aG,HE)=>{var ZE=Buffer.from||Buffer;HE.exports=function(E){if(/^\\x/.test(E))return ZE(E.substr(2),"hex");var _="",O=0;while(O<E.length)if(E[O]!=="\\")_+=E[O],++O;else if(/[0-7]{3}/.test(E.substr(O+1,3)))_+=String.fromCharCode(parseInt(E.substr(O+1,3),8)),O+=4;else{var G=1;while(O+G<E.length&&E[O+G]==="\\")G++;for(var X=0;X<Math.floor(G/2);++X)_+="\\";O+=Math.floor(G/2)*2}return ZE(_,"binary")}});var jE=R((rG,QE)=>{var c=L$(),l=Q$(),$$=_E(),RE=JE(),KE=TE();function E$($){return function(_){if(_===null)return _;return $(_)}}function WE($){if($===null)return $;return $==="TRUE"||$==="t"||$==="true"||$==="y"||$==="yes"||$==="on"||$==="1"}function _0($){if(!$)return null;return c.parse($,WE)}function O0($){return parseInt($,10)}function F$($){if(!$)return null;return c.parse($,E$(O0))}function G0($){if(!$)return null;return c.parse($,E$(function(E){return LE(E).trim()}))}var X0=function($){if(!$)return null;var E=l.create($,function(_){if(_!==null)_=D$(_);return _});return E.parse()},z$=function($){if(!$)return null;var E=l.create($,function(_){if(_!==null)_=parseFloat(_);return _});return E.parse()},V=function($){if(!$)return null;var E=l.create($);return E.parse()},P$=function($){if(!$)return null;var E=l.create($,function(_){if(_!==null)_=$$(_);return _});return E.parse()},U0=function($){if(!$)return null;var E=l.create($,function(_){if(_!==null)_=RE(_);return _});return E.parse()},J0=function($){if(!$)return null;return c.parse($,E$(KE))},A$=function($){return parseInt($,10)},LE=function($){var E=String($);if(/^\d+$/.test(E))return E;return $},YE=function($){if(!$)return null;return c.parse($,E$(JSON.parse))},D$=function($){if($[0]!=="(")return null;return $=$.substring(1,$.length-1).split(","),{x:parseFloat($[0]),y:parseFloat($[1])}},Z0=function($){if($[0]!=="<"&&$[1]!=="(")return null;var E="(",_="",O=!1;for(var G=2;G<$.length-1;G++){if(!O)E+=$[G];if($[G]===")"){O=!0;continue}else if(!O)continue;if($[G]===",")continue;_+=$[G]}var X=D$(E);return X.radius=parseFloat(_),X},H0=function($){$(20,LE),$(21,A$),$(23,A$),$(26,A$),$(700,parseFloat),$(701,parseFloat),$(16,WE),$(1082,$$),$(1114,$$),$(1184,$$),$(600,D$),$(651,V),$(718,Z0),$(1000,_0),$(1001,J0),$(1005,F$),$(1007,F$),$(1028,F$),$(1016,G0),$(1017,X0),$(1021,z$),$(1022,z$),$(1231,z$),$(1014,V),$(1015,V),$(1008,V),$(1009,V),$(1040,V),$(1041,V),$(1115,P$),$(1182,P$),$(1185,P$),$(1186,RE),$(1187,U0),$(17,KE),$(114,JSON.parse.bind(JSON)),$(3802,JSON.parse.bind(JSON)),$(199,YE),$(3807,YE),$(3907,V),$(2951,V),$(791,V),$(1183,V),$(1270,V)};QE.exports={init:H0}});var FE=R((eG,NE)=>{var P=1e6;function T0($){var E=$.readInt32BE(0),_=$.readUInt32BE(4),O="";if(E<0)E=~E+(_===0),_=~_+1>>>0,O="-";var G="",X,U,J,Z,H,Y;{if(X=E%P,E=E/P>>>0,U=4294967296*X+_,_=U/P>>>0,J=""+(U-P*_),_===0&&E===0)return O+J+G;Z="",H=6-J.length;for(Y=0;Y<H;Y++)Z+="0";G=Z+J+G}{if(X=E%P,E=E/P>>>0,U=4294967296*X+_,_=U/P>>>0,J=""+(U-P*_),_===0&&E===0)return O+J+G;Z="",H=6-J.length;for(Y=0;Y<H;Y++)Z+="0";G=Z+J+G}{if(X=E%P,E=E/P>>>0,U=4294967296*X+_,_=U/P>>>0,J=""+(U-P*_),_===0&&E===0)return O+J+G;Z="",H=6-J.length;for(Y=0;Y<H;Y++)Z+="0";G=Z+J+G}return X=E%P,U=4294967296*X+_,J=""+U%P,O+J+G}NE.exports=T0});var ME=R(($8,DE)=>{var Y0=FE(),j=function($,E,_,O,G){_=_||0,O=O||!1,G=G||function(Q,C,K$){return Q*Math.pow(2,K$)+C};var X=_>>3,U=function(Q){if(O)return~Q&255;return Q},J=255,Z=8-_%8;if(E<Z)J=255<<8-E&255,Z=E;if(_)J=J>>_%8;var H=0;if(_%8+E>=8)H=G(0,U($[X])&J,Z);var Y=E+_>>3;for(var T=X+1;T<Y;T++)H=G(H,U($[T]),8);var K=(E+_)%8;if(K>0)H=G(H,U($[Y])>>8-K,K);return H},AE=function($,E,_){var O=Math.pow(2,_-1)-1,G=j($,1),X=j($,_,1);if(X===0)return 0;var U=1,J=function(H,Y,T){if(H===0)H=1;for(var K=1;K<=T;K++)if(U/=2,(Y&1<<T-K)>0)H+=U;return H},Z=j($,E,_+1,!1,J);if(X==Math.pow(2,_+1)-1){if(Z===0)return G===0?1/0:-1/0;return NaN}return(G===0?1:-1)*Math.pow(2,X-O)*Z},R0=function($){if(j($,1)==1)return-1*(j($,15,1,!0)+1);return j($,15,1)},zE=function($){if(j($,1)==1)return-1*(j($,31,1,!0)+1);return j($,31,1)},K0=function($){return AE($,23,8)},W0=function($){return AE($,52,11)},L0=function($){var E=j($,16,32);if(E==49152)return NaN;var _=Math.pow(1e4,j($,16,16)),O=0,G=[],X=j($,16);for(var U=0;U<X;U++)O+=j($,16,64+16*U)*_,_/=1e4;var J=Math.pow(10,j($,16,48));return(E===0?1:-1)*Math.round(O*J)/J},PE=function($,E){var _=j(E,1),O=j(E,63,1),G=new Date((_===0?1:-1)*O/1000+946684800000);if(!$)G.setTime(G.getTime()+G.getTimezoneOffset()*60000);return G.usec=O%1000,G.getMicroSeconds=function(){return this.usec},G.setMicroSeconds=function(X){this.usec=X},G.getUTCMicroSeconds=function(){return this.usec},G},o=function($){var E=j($,32),_=j($,32,32),O=j($,32,64),G=96,X=[];for(var U=0;U<E;U++)X[U]=j($,32,G),G+=32,G+=32;var J=function(H){var Y=j($,32,G);if(G+=32,Y==4294967295)return null;var T;if(H==23||H==20)return T=j($,Y*8,G),G+=Y*8,T;else if(H==25)return T=$.toString(this.encoding,G>>3,(G+=Y<<3)>>3),T;else console.log("ERROR: ElementType not implemented: "+H)},Z=function(H,Y){var T=[],K;if(H.length>1){var Q=H.shift();for(K=0;K<Q;K++)T[K]=Z(H,Y);H.unshift(Q)}else for(K=0;K<H[0];K++)T[K]=J(Y);return T};return Z(X,O)},Q0=function($){return $.toString("utf8")},j0=function($){if($===null)return null;return j($,8)>0},N0=function($){$(20,Y0),$(21,R0),$(23,zE),$(26,zE),$(1700,L0),$(700,K0),$(701,W0),$(16,j0),$(1114,PE.bind(null,!1)),$(1184,PE.bind(null,!0)),$(1000,o),$(1007,o),$(1016,o),$(1008,o),$(1009,o),$(25,Q0)};DE.exports={init:N0}});var SE=R((E8,VE)=>{VE.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}});var i=R((V0)=>{var F0=jE(),z0=ME(),P0=Q$(),A0=SE();V0.getTypeParser=D0;V0.setTypeParser=M0;V0.arrayParser=P0;V0.builtins=A0;var n={text:{},binary:{}};function CE($){return String($)}function D0($,E){if(E=E||"text",!n[E])return CE;return n[E][$]||CE}function M0($,E,_){if(typeof E=="function")_=E,E="text";n[E][$]=_}F0.init(function($,E){n.text[$]=E});z0.init(function($,E){n.binary[$]=E})});var s=R((O8,M$)=>{var IE;try{IE=process.platform==="win32"?process.env.USERNAME:process.env.USER}catch{}M$.exports={host:"localhost",user:IE,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:30000,client_encoding:"",ssl:!1,application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,connect_timeout:0,keepalives:1,keepalives_idle:0};var h=i(),B0=h.getTypeParser(20,"text"),k0=h.getTypeParser(1016,"text");M$.exports.__defineSetter__("parseInt8",function($){h.setTypeParser(20,"text",$?h.getTypeParser(23,"text"):B0),h.setTypeParser(1016,"text",$?h.getTypeParser(1007,"text"):k0)})});var b=R((G8,kE)=>{var w0=s(),qE=W("util"),{isDate:x0}=qE.types||qE;function h0($){return'"'+$.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")+'"'}function BE($){let E="{";for(let _=0;_<$.length;_++){if(_>0)E=E+",";if($[_]===null||typeof $[_]>"u")E=E+"NULL";else if(Array.isArray($[_]))E=E+BE($[_]);else if(ArrayBuffer.isView($[_])){let O=$[_];if(!(O instanceof Buffer)){let G=Buffer.from(O.buffer,O.byteOffset,O.byteLength);if(G.length===O.byteLength)O=G;else O=G.slice(O.byteOffset,O.byteOffset+O.byteLength)}E+="\\\\x"+O.toString("hex")}else E+=h0(_$($[_]))}return E=E+"}",E}var _$=function($,E){if($==null)return null;if(typeof $==="object"){if($ instanceof Buffer)return $;if(ArrayBuffer.isView($)){let _=Buffer.from($.buffer,$.byteOffset,$.byteLength);if(_.length===$.byteLength)return _;return _.slice($.byteOffset,$.byteOffset+$.byteLength)}if(x0($))if(w0.parseInputDatesAsUTC)return v0($);else return y0($);if(Array.isArray($))return BE($);return b0($,E)}return $.toString()};function b0($,E){if($&&typeof $.toPostgres==="function"){if(E=E||[],E.indexOf($)!==-1)throw Error('circular reference detected while preparing "'+$+'" for query');return E.push($),_$($.toPostgres(_$),E)}return JSON.stringify($)}function y0($){let E=-$.getTimezoneOffset(),_=$.getFullYear(),O=_<1;if(O)_=Math.abs(_)+1;let G=String(_).padStart(4,"0")+"-"+String($.getMonth()+1).padStart(2,"0")+"-"+String($.getDate()).padStart(2,"0")+"T"+String($.getHours()).padStart(2,"0")+":"+String($.getMinutes()).padStart(2,"0")+":"+String($.getSeconds()).padStart(2,"0")+"."+String($.getMilliseconds()).padStart(3,"0");if(E<0)G+="-",E*=-1;else G+="+";if(G+=String(Math.floor(E/60)).padStart(2,"0")+":"+String(E%60).padStart(2,"0"),O)G+=" BC";return G}function v0($){let E=$.getUTCFullYear(),_=E<1;if(_)E=Math.abs(E)+1;let O=String(E).padStart(4,"0")+"-"+String($.getUTCMonth()+1).padStart(2,"0")+"-"+String($.getUTCDate()).padStart(2,"0")+"T"+String($.getUTCHours()).padStart(2,"0")+":"+String($.getUTCMinutes()).padStart(2,"0")+":"+String($.getUTCSeconds()).padStart(2,"0")+"."+String($.getUTCMilliseconds()).padStart(3,"0");if(O+="+00:00",_)O+=" BC";return O}function p0($,E,_){if($=typeof $==="string"?{text:$}:$,E)if(typeof E==="function")$.callback=E;else $.values=E;if(_)$.callback=_;return $}var m0=function($){return'"'+$.replace(/"/g,'""')+'"'},f0=function($){let E=!1,_="'";if($==null)return"''";if(typeof $!=="string")return"''";for(let O=0;O<$.length;O++){let G=$[O];if(G==="'")_+=G+G;else if(G==="\\")_+=G+G,E=!0;else _+=G}if(_+="'",E===!0)_=" E"+_;return _};kE.exports={prepareValue:function(E){return _$(E)},normalizeQueryConfig:p0,escapeIdentifier:m0,escapeLiteral:f0}});var xE=R((X8,wE)=>{var y=W("crypto");function V$($){return y.createHash("md5").update($,"utf-8").digest("hex")}function d0($,E,_){let O=V$(E+$);return"md5"+V$(Buffer.concat([Buffer.from(O),_]))}function u0($){return y.createHash("sha256").update($).digest()}function g0($,E){return $=$.replace(/(\D)-/,"$1"),y.createHash($).update(E).digest()}function c0($,E){return y.createHmac("sha256",$).update(E).digest()}async function l0($,E,_){return y.pbkdf2Sync($,E,_,32,"sha256")}wE.exports={postgresMd5PasswordHash:d0,randomBytes:y.randomBytes,deriveKey:l0,sha256:u0,hashByName:g0,hmacSha256:c0,md5:V$}});var vE=R((U8,yE)=>{var hE=W("crypto");yE.exports={postgresMd5PasswordHash:n0,randomBytes:o0,deriveKey:a0,sha256:i0,hashByName:s0,hmacSha256:t0,md5:S$};var bE=hE.webcrypto||globalThis.crypto,k=bE.subtle,C$=new TextEncoder;function o0($){return bE.getRandomValues(Buffer.alloc($))}async function S$($){try{return hE.createHash("md5").update($,"utf-8").digest("hex")}catch(E){let _=typeof $==="string"?C$.encode($):$,O=await k.digest("MD5",_);return Array.from(new Uint8Array(O)).map((G)=>G.toString(16).padStart(2,"0")).join("")}}async function n0($,E,_){let O=await S$(E+$);return"md5"+await S$(Buffer.concat([Buffer.from(O),_]))}async function i0($){return await k.digest("SHA-256",$)}async function s0($,E){return await k.digest($,E)}async function t0($,E){let _=await k.importKey("raw",$,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return await k.sign("HMAC",_,C$.encode(E))}async function a0($,E,_){let O=await k.importKey("raw",C$.encode($),"PBKDF2",!1,["deriveBits"]),G={name:"PBKDF2",hash:"SHA-256",salt:E,iterations:_};return await k.deriveBits(G,O,256,["deriveBits"])}});var q$=R((J8,I$)=>{var r0=parseInt(process.versions&&process.versions.node&&process.versions.node.split(".")[0])<15;if(r0)I$.exports=xE();else I$.exports=vE()});var fE=R((Z8,mE)=>{function w($,E){return Error("SASL channel binding: "+$+" when parsing public certificate "+E.toString("base64"))}function B$($,E){let _=$[E++];if(_<128)return{length:_,index:E};let O=_&127;if(O>4)throw w("bad length",$);_=0;for(let G=0;G<O;G++)_=_<<8|$[E++];return{length:_,index:E}}function pE($,E){if($[E++]!==6)throw w("non-OID data",$);let{length:_,index:O}=B$($,E);E=O;let G=E+_,X=$[E++],U=(X/40>>0)+"."+X%40;while(E<G){let J=0;while(E<G){let Z=$[E++];if(J=J<<7|Z&127,Z<128)break}U+="."+J}return{oid:U,index:E}}function t($,E){if($[E++]!==48)throw w("non-sequence data",$);return B$($,E)}function e0($,E){if(E===void 0)E=0;E=t($,E).index;let{length:_,index:O}=t($,E);E=O+_,E=t($,E).index;let{oid:G,index:X}=pE($,E);switch(G){case"1.2.840.113549.1.1.4":return"MD5";case"1.2.840.113549.1.1.5":return"SHA-1";case"1.2.840.113549.1.1.11":return"SHA-256";case"1.2.840.113549.1.1.12":return"SHA-384";case"1.2.840.113549.1.1.13":return"SHA-512";case"1.2.840.113549.1.1.14":return"SHA-224";case"1.2.840.113549.1.1.15":return"SHA512-224";case"1.2.840.113549.1.1.16":return"SHA512-256";case"1.2.840.10045.4.1":return"SHA-1";case"1.2.840.10045.4.3.1":return"SHA-224";case"1.2.840.10045.4.3.2":return"SHA-256";case"1.2.840.10045.4.3.3":return"SHA-384";case"1.2.840.10045.4.3.4":return"SHA-512";case"1.2.840.113549.1.1.10":{if(E=X,E=t($,E).index,$[E++]!==160)throw w("non-tag data",$);E=B$($,E).index,E=t($,E).index;let{oid:U}=pE($,E);switch(U){case"1.2.840.113549.2.5":return"MD5";case"1.3.14.3.2.26":return"SHA-1";case"2.16.840.1.101.3.4.2.1":return"SHA-256";case"2.16.840.1.101.3.4.2.2":return"SHA-384";case"2.16.840.1.101.3.4.2.3":return"SHA-512"}throw w("unknown hash OID "+U,$)}case"1.3.101.110":case"1.3.101.112":return"SHA-512";case"1.3.101.111":case"1.3.101.113":throw w("Ed448 certificate channel binding is not currently supported by Postgres")}throw w("unknown OID "+G,$)}mE.exports={signatureAlgorithmHashFromCertificate:e0}});var cE=R((H8,gE)=>{var q=q$(),{signatureAlgorithmHashFromCertificate:$1}=fE();function E1($,E){let _=["SCRAM-SHA-256"];if(E)_.unshift("SCRAM-SHA-256-PLUS");let O=_.find((U)=>$.includes(U));if(!O)throw Error("SASL: Only mechanism(s) "+_.join(" and ")+" are supported");if(O==="SCRAM-SHA-256-PLUS"&&typeof E.getPeerCertificate!=="function")throw Error("SASL: Mechanism SCRAM-SHA-256-PLUS requires a certificate");let G=q.randomBytes(18).toString("base64");return{mechanism:O,clientNonce:G,response:(O==="SCRAM-SHA-256-PLUS"?"p=tls-server-end-point":E?"y":"n")+",,n=*,r="+G,message:"SASLInitialResponse"}}async function _1($,E,_,O){if($.message!=="SASLInitialResponse")throw Error("SASL: Last message was not SASLInitialResponse");if(typeof E!=="string")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(E==="")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string");if(typeof _!=="string")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let G=X1(_);if(!G.nonce.startsWith($.clientNonce))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");else if(G.nonce.length===$.clientNonce.length)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short");let X="n=*,r="+$.clientNonce,U="r="+G.nonce+",s="+G.salt+",i="+G.iteration,J=O?"eSws":"biws";if($.mechanism==="SCRAM-SHA-256-PLUS"){let t$=O.getPeerCertificate().raw,e=$1(t$);if(e==="MD5"||e==="SHA-1")e="SHA-256";let BO=await q.hashByName(e,t$);J=Buffer.concat([Buffer.from("p=tls-server-end-point,,"),Buffer.from(BO)]).toString("base64")}let Z="c="+J+",r="+G.nonce,H=X+","+U+","+Z,Y=Buffer.from(G.salt,"base64"),T=await q.deriveKey(E,Y,G.iteration),K=await q.hmacSha256(T,"Client Key"),Q=await q.sha256(K),C=await q.hmacSha256(Q,H),K$=J1(Buffer.from(K),Buffer.from(C)).toString("base64"),IO=await q.hmacSha256(T,"Server Key"),qO=await q.hmacSha256(IO,H);$.message="SASLResponse",$.serverSignature=Buffer.from(qO).toString("base64"),$.response=Z+",p="+K$}function O1($,E){if($.message!=="SASLResponse")throw Error("SASL: Last message was not SASLResponse");if(typeof E!=="string")throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:_}=U1(E);if(_!==$.serverSignature)throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}function G1($){if(typeof $!=="string")throw TypeError("SASL: text must be a string");return $.split("").map((E,_)=>$.charCodeAt(_)).every((E)=>E>=33&&E<=43||E>=45&&E<=126)}function dE($){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test($)}function uE($){if(typeof $!=="string")throw TypeError("SASL: attribute pairs text must be a string");return new Map($.split(",").map((E)=>{if(!/^.=/.test(E))throw Error("SASL: Invalid attribute pair entry");let _=E[0],O=E.substring(2);return[_,O]}))}function X1($){let E=uE($),_=E.get("r");if(!_)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");else if(!G1(_))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters");let O=E.get("s");if(!O)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");else if(!dE(O))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64");let G=E.get("i");if(!G)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");else if(!/^[1-9][0-9]*$/.test(G))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count");let X=parseInt(G,10);return{nonce:_,salt:O,iteration:X}}function U1($){let _=uE($).get("v");if(!_)throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");else if(!dE(_))throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64");return{serverSignature:_}}function J1($,E){if(!Buffer.isBuffer($))throw TypeError("first argument must be a Buffer");if(!Buffer.isBuffer(E))throw TypeError("second argument must be a Buffer");if($.length!==E.length)throw Error("Buffer lengths must match");if($.length===0)throw Error("Buffers cannot be empty");return Buffer.from($.map((_,O)=>$[O]^E[O]))}gE.exports={startSession:E1,continueSession:_1,finalizeSession:O1}});var G$=R((T8,lE)=>{var Z1=i();function O$($){this._types=$||Z1,this.text={},this.binary={}}O$.prototype.getOverrides=function($){switch($){case"text":return this.text;case"binary":return this.binary;default:return{}}};O$.prototype.setTypeParser=function($,E,_){if(typeof E==="function")_=E,E="text";this.getOverrides(E)[$]=_};O$.prototype.getTypeParser=function($,E){return E=E||"text",this.getOverrides(E)[$]||this._types.getTypeParser($,E)};lE.exports=O$});var iE=R((Y8,nE)=>{function v($,E={}){if($.charAt(0)==="/"){let Z=$.split(" ");return{host:Z[0],database:Z[1]}}let _={},O,G=!1;if(/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test($))$=encodeURI($).replace(/%25(\d\d)/g,"%$1");try{try{O=new URL($,"postgres://base")}catch(Z){O=new URL($.replace("@/","@___DUMMY___/"),"postgres://base"),G=!0}}catch(Z){throw Z.input&&(Z.input="*****REDACTED*****"),Z}for(let Z of O.searchParams.entries())_[Z[0]]=Z[1];if(_.user=_.user||decodeURIComponent(O.username),_.password=_.password||decodeURIComponent(O.password),O.protocol=="socket:")return _.host=decodeURI(O.pathname),_.database=O.searchParams.get("db"),_.client_encoding=O.searchParams.get("encoding"),_;let X=G?"":O.hostname;if(!_.host)_.host=decodeURIComponent(X);else if(X&&/^%2f/i.test(X))O.pathname=X+O.pathname;if(!_.port)_.port=O.port;let U=O.pathname.slice(1)||null;if(_.database=U?decodeURI(U):null,_.ssl==="true"||_.ssl==="1")_.ssl=!0;if(_.ssl==="0")_.ssl=!1;if(_.sslcert||_.sslkey||_.sslrootcert||_.sslmode)_.ssl={};let J=_.sslcert||_.sslkey||_.sslrootcert?W("fs"):null;if(_.sslcert)_.ssl.cert=J.readFileSync(_.sslcert).toString();if(_.sslkey)_.ssl.key=J.readFileSync(_.sslkey).toString();if(_.sslrootcert)_.ssl.ca=J.readFileSync(_.sslrootcert).toString();if(E.useLibpqCompat&&_.uselibpqcompat)throw Error("Both useLibpqCompat and uselibpqcompat are set. Please use only one of them.");if(_.uselibpqcompat==="true"||E.useLibpqCompat)switch(_.sslmode){case"disable":{_.ssl=!1;break}case"prefer":{_.ssl.rejectUnauthorized=!1;break}case"require":{if(_.sslrootcert)_.ssl.checkServerIdentity=function(){};else _.ssl.rejectUnauthorized=!1;break}case"verify-ca":{if(!_.ssl.ca)throw Error("SECURITY WARNING: Using sslmode=verify-ca requires specifying a CA with sslrootcert. If a public CA is used, verify-ca allows connections to a server that somebody else may have registered with the CA, making you vulnerable to Man-in-the-Middle attacks. Either specify a custom CA certificate with sslrootcert parameter or use sslmode=verify-full for proper security.");_.ssl.checkServerIdentity=function(){};break}case"verify-full":break}else switch(_.sslmode){case"disable":{_.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":{if(_.sslmode!=="verify-full")k$(_.sslmode);break}case"no-verify":{_.ssl.rejectUnauthorized=!1;break}}return _}function H1($){return Object.entries($).reduce((_,[O,G])=>{if(G!==void 0&&G!==null)_[O]=G;return _},{})}function oE($){return Object.entries($).reduce((_,[O,G])=>{if(O==="ssl"){let X=G;if(typeof X==="boolean")_[O]=X;if(typeof X==="object")_[O]=H1(X)}else if(G!==void 0&&G!==null)if(O==="port"){if(G!==""){let X=parseInt(G,10);if(isNaN(X))throw Error(`Invalid ${O}: ${G}`);_[O]=X}}else _[O]=G;return _},{})}function T1($){return oE(v($))}function k$($){if(!k$.warned&&typeof process<"u"&&process.emitWarning)k$.warned=!0,process.emitWarning(`SECURITY WARNING: The SSL modes 'prefer', 'require', and 'verify-ca' are treated as aliases for 'verify-full'.
|
|
2
|
+
In the next major version (pg-connection-string v3.0.0 and pg v9.0.0), these modes will adopt standard libpq semantics, which have weaker security guarantees.
|
|
3
|
+
|
|
4
|
+
To prepare for this change:
|
|
5
|
+
- If you want the current behavior, explicitly use 'sslmode=verify-full'
|
|
6
|
+
- If you want libpq compatibility now, use 'uselibpqcompat=true&sslmode=${$}'
|
|
7
|
+
|
|
8
|
+
See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode definitions.`)}nE.exports=v;v.parse=v;v.toClientConfig=oE;v.parseIntoClientConfig=T1});var w$=R((R8,rE)=>{var Y1=W("dns"),tE=s(),sE=iE().parse,z=function($,E,_){if(E[$])return E[$];if(_===void 0)_=process.env["PG"+$.toUpperCase()];else if(_===!1);else _=process.env[_];return _||tE[$]},R1=function(){switch(process.env.PGSSLMODE){case"disable":return!1;case"prefer":case"require":case"verify-ca":case"verify-full":return!0;case"no-verify":return{rejectUnauthorized:!1}}return tE.ssl},p=function($){return"'"+(""+$).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},S=function($,E,_){let O=E[_];if(O!==void 0&&O!==null)$.push(_+"="+p(O))};class aE{constructor($){if($=typeof $==="string"?sE($):$||{},$.connectionString)$=Object.assign({},$,sE($.connectionString));if(this.user=z("user",$),this.database=z("database",$),this.database===void 0)this.database=this.user;if(this.port=parseInt(z("port",$),10),this.host=z("host",$),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:z("password",$)}),this.binary=z("binary",$),this.options=z("options",$),this.ssl=typeof $.ssl>"u"?R1():$.ssl,typeof this.ssl==="string"){if(this.ssl==="true")this.ssl=!0}if(this.ssl==="no-verify")this.ssl={rejectUnauthorized:!1};if(this.ssl&&this.ssl.key)Object.defineProperty(this.ssl,"key",{enumerable:!1});if(this.client_encoding=z("client_encoding",$),this.replication=z("replication",$),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=z("application_name",$,"PGAPPNAME"),this.fallback_application_name=z("fallback_application_name",$,!1),this.statement_timeout=z("statement_timeout",$,!1),this.lock_timeout=z("lock_timeout",$,!1),this.idle_in_transaction_session_timeout=z("idle_in_transaction_session_timeout",$,!1),this.query_timeout=z("query_timeout",$,!1),$.connectionTimeoutMillis===void 0)this.connect_timeout=process.env.PGCONNECT_TIMEOUT||0;else this.connect_timeout=Math.floor($.connectionTimeoutMillis/1000);if($.keepAlive===!1)this.keepalives=0;else if($.keepAlive===!0)this.keepalives=1;if(typeof $.keepAliveInitialDelayMillis==="number")this.keepalives_idle=Math.floor($.keepAliveInitialDelayMillis/1000)}getLibpqConnectionString($){let E=[];S(E,this,"user"),S(E,this,"password"),S(E,this,"port"),S(E,this,"application_name"),S(E,this,"fallback_application_name"),S(E,this,"connect_timeout"),S(E,this,"options");let _=typeof this.ssl==="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(S(E,_,"sslmode"),S(E,_,"sslca"),S(E,_,"sslkey"),S(E,_,"sslcert"),S(E,_,"sslrootcert"),this.database)E.push("dbname="+p(this.database));if(this.replication)E.push("replication="+p(this.replication));if(this.host)E.push("host="+p(this.host));if(this.isDomainSocket)return $(null,E.join(" "));if(this.client_encoding)E.push("client_encoding="+p(this.client_encoding));Y1.lookup(this.host,function(O,G){if(O)return $(O,null);return E.push("hostaddr="+p(G)),$(null,E.join(" "))})}}rE.exports=aE});var x$=R((K8,E_)=>{var K1=i(),eE=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/;class $_{constructor($,E){if(this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=E,this.RowCtor=null,this.rowAsArray=$==="array",this.rowAsArray)this.parseRow=this._parseRowAsArray;this._prebuiltEmptyResultObject=null}addCommandComplete($){let E;if($.text)E=eE.exec($.text);else E=eE.exec($.command);if(E){if(this.command=E[1],E[3])this.oid=parseInt(E[2],10),this.rowCount=parseInt(E[3],10);else if(E[2])this.rowCount=parseInt(E[2],10)}}_parseRowAsArray($){let E=Array($.length);for(let _=0,O=$.length;_<O;_++){let G=$[_];if(G!==null)E[_]=this._parsers[_](G);else E[_]=null}return E}parseRow($){let E={...this._prebuiltEmptyResultObject};for(let _=0,O=$.length;_<O;_++){let G=$[_],X=this.fields[_].name;if(G!==null){let U=this.fields[_].format==="binary"?Buffer.from(G):G;E[X]=this._parsers[_](U)}else E[X]=null}return E}addRow($){this.rows.push($)}addFields($){if(this.fields=$,this.fields.length)this._parsers=Array($.length);let E={};for(let _=0;_<$.length;_++){let O=$[_];if(E[O.name]=null,this._types)this._parsers[_]=this._types.getTypeParser(O.dataTypeID,O.format||"text");else this._parsers[_]=K1.getTypeParser(O.dataTypeID,O.format||"text")}this._prebuiltEmptyResultObject={...E}}}E_.exports=$_});var U_=R((W8,X_)=>{var{EventEmitter:W1}=W("events"),__=x$(),O_=b();class G_ extends W1{constructor($,E,_){super();if($=O_.normalizeQueryConfig($,E,_),this.text=$.text,this.values=$.values,this.rows=$.rows,this.types=$.types,this.name=$.name,this.queryMode=$.queryMode,this.binary=$.binary,this.portal=$.portal||"",this.callback=$.callback,this._rowMode=$.rowMode,process.domain&&$.callback)this.callback=process.domain.bind($.callback);this._result=new __(this._rowMode,this.types),this._results=this._result,this._canceledDueToError=!1}requiresPreparation(){if(this.queryMode==="extended")return!0;if(this.name)return!0;if(this.rows)return!0;if(!this.text)return!1;if(!this.values)return!1;return this.values.length>0}_checkForMultirow(){if(this._result.command){if(!Array.isArray(this._results))this._results=[this._result];this._result=new __(this._rowMode,this._result._types),this._results.push(this._result)}}handleRowDescription($){this._checkForMultirow(),this._result.addFields($.fields),this._accumulateRows=this.callback||!this.listeners("row").length}handleDataRow($){let E;if(this._canceledDueToError)return;try{E=this._result.parseRow($.fields)}catch(_){this._canceledDueToError=_;return}if(this.emit("row",E,this._result),this._accumulateRows)this._result.addRow(E)}handleCommandComplete($,E){if(this._checkForMultirow(),this._result.addCommandComplete($),this.rows)E.sync()}handleEmptyQuery($){if(this.rows)$.sync()}handleError($,E){if(this._canceledDueToError)$=this._canceledDueToError,this._canceledDueToError=!1;if(this.callback)return this.callback($);this.emit("error",$)}handleReadyForQuery($){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,$);if(this.callback)try{this.callback(null,this._results)}catch(E){process.nextTick(()=>{throw E})}this.emit("end",this._results)}submit($){if(typeof this.text!=="string"&&typeof this.name!=="string")return Error("A query must have either text or a name. Supplying neither is unsupported.");let E=$.parsedStatements[this.name];if(this.text&&E&&this.text!==E)return Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);if(this.values&&!Array.isArray(this.values))return Error("Query values must be an array");if(this.requiresPreparation()){$.stream.cork&&$.stream.cork();try{this.prepare($)}finally{$.stream.uncork&&$.stream.uncork()}}else $.query(this.text);return null}hasBeenParsed($){return this.name&&$.parsedStatements[this.name]}handlePortalSuspended($){this._getRows($,this.rows)}_getRows($,E){if($.execute({portal:this.portal,rows:E}),!E)$.sync();else $.flush()}prepare($){if(!this.hasBeenParsed($))$.parse({text:this.text,name:this.name,types:this.types});try{$.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:O_.prepareValue})}catch(E){this.handleError(E,$);return}$.describe({type:"P",name:this.portal||""}),this._getRows($,this.rows)}handleCopyInResponse($){$.sendCopyFail("No source stream defined")}handleCopyData($,E){}}X_.exports=G_});var h$=R((P_)=>{Object.defineProperty(P_,"__esModule",{value:!0});P_.NoticeMessage=P_.DataRowMessage=P_.CommandCompleteMessage=P_.ReadyForQueryMessage=P_.NotificationResponseMessage=P_.BackendKeyDataMessage=P_.AuthenticationMD5Password=P_.ParameterStatusMessage=P_.ParameterDescriptionMessage=P_.RowDescriptionMessage=P_.Field=P_.CopyResponse=P_.CopyDataMessage=P_.DatabaseError=P_.copyDone=P_.emptyQuery=P_.replicationStart=P_.portalSuspended=P_.noData=P_.closeComplete=P_.bindComplete=P_.parseComplete=void 0;P_.parseComplete={name:"parseComplete",length:5};P_.bindComplete={name:"bindComplete",length:5};P_.closeComplete={name:"closeComplete",length:5};P_.noData={name:"noData",length:5};P_.portalSuspended={name:"portalSuspended",length:5};P_.replicationStart={name:"replicationStart",length:4};P_.emptyQuery={name:"emptyQuery",length:4};P_.copyDone={name:"copyDone",length:4};class J_ extends Error{constructor($,E,_){super($);this.length=E,this.name=_}}P_.DatabaseError=J_;class Z_{constructor($,E){this.length=$,this.chunk=E,this.name="copyData"}}P_.CopyDataMessage=Z_;class H_{constructor($,E,_,O){this.length=$,this.name=E,this.binary=_,this.columnTypes=Array(O)}}P_.CopyResponse=H_;class T_{constructor($,E,_,O,G,X,U){this.name=$,this.tableID=E,this.columnID=_,this.dataTypeID=O,this.dataTypeSize=G,this.dataTypeModifier=X,this.format=U}}P_.Field=T_;class Y_{constructor($,E){this.length=$,this.fieldCount=E,this.name="rowDescription",this.fields=Array(this.fieldCount)}}P_.RowDescriptionMessage=Y_;class R_{constructor($,E){this.length=$,this.parameterCount=E,this.name="parameterDescription",this.dataTypeIDs=Array(this.parameterCount)}}P_.ParameterDescriptionMessage=R_;class K_{constructor($,E,_){this.length=$,this.parameterName=E,this.parameterValue=_,this.name="parameterStatus"}}P_.ParameterStatusMessage=K_;class W_{constructor($,E){this.length=$,this.salt=E,this.name="authenticationMD5Password"}}P_.AuthenticationMD5Password=W_;class L_{constructor($,E,_){this.length=$,this.processID=E,this.secretKey=_,this.name="backendKeyData"}}P_.BackendKeyDataMessage=L_;class Q_{constructor($,E,_,O){this.length=$,this.processId=E,this.channel=_,this.payload=O,this.name="notification"}}P_.NotificationResponseMessage=Q_;class j_{constructor($,E){this.length=$,this.status=E,this.name="readyForQuery"}}P_.ReadyForQueryMessage=j_;class N_{constructor($,E){this.length=$,this.text=E,this.name="commandComplete"}}P_.CommandCompleteMessage=N_;class F_{constructor($,E){this.length=$,this.fields=E,this.name="dataRow",this.fieldCount=E.length}}P_.DataRowMessage=F_;class z_{constructor($,E){this.length=$,this.message=E,this.name="notice"}}P_.NoticeMessage=z_});var S_=R((M_)=>{Object.defineProperty(M_,"__esModule",{value:!0});M_.Writer=void 0;class D_{constructor($=256){this.size=$,this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe($)}ensure($){if(this.buffer.length-this.offset<$){let _=this.buffer,O=_.length+(_.length>>1)+$;this.buffer=Buffer.allocUnsafe(O),_.copy(this.buffer)}}addInt32($){return this.ensure(4),this.buffer[this.offset++]=$>>>24&255,this.buffer[this.offset++]=$>>>16&255,this.buffer[this.offset++]=$>>>8&255,this.buffer[this.offset++]=$>>>0&255,this}addInt16($){return this.ensure(2),this.buffer[this.offset++]=$>>>8&255,this.buffer[this.offset++]=$>>>0&255,this}addCString($){if(!$)this.ensure(1);else{let E=Buffer.byteLength($);this.ensure(E+1),this.buffer.write($,this.offset,"utf-8"),this.offset+=E}return this.buffer[this.offset++]=0,this}addString($=""){let E=Buffer.byteLength($);return this.ensure(E),this.buffer.write($,this.offset),this.offset+=E,this}add($){return this.ensure($.length),$.copy(this.buffer,this.offset),this.offset+=$.length,this}join($){if($){this.buffer[this.headerPosition]=$;let E=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(E,this.headerPosition+1)}return this.buffer.slice($?0:5,this.offset)}flush($){let E=this.join($);return this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(this.size),E}}M_.Writer=D_});var B_=R((I_)=>{Object.defineProperty(I_,"__esModule",{value:!0});I_.serialize=void 0;var b$=S_(),L=new b$.Writer,y1=($)=>{L.addInt16(3).addInt16(0);for(let O of Object.keys($))L.addCString(O).addCString($[O]);L.addCString("client_encoding").addCString("UTF8");let E=L.addCString("").flush(),_=E.length+4;return new b$.Writer().addInt32(_).add(E).flush()},v1=()=>{let $=Buffer.allocUnsafe(8);return $.writeInt32BE(8,0),$.writeInt32BE(80877103,4),$},p1=($)=>{return L.addCString($).flush(112)},m1=function($,E){return L.addCString($).addInt32(Buffer.byteLength(E)).addString(E),L.flush(112)},f1=function($){return L.addString($).flush(112)},d1=($)=>{return L.addCString($).flush(81)},C_=[],u1=($)=>{let E=$.name||"";if(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 _=$.types||C_,O=_.length,G=L.addCString(E).addCString($.text).addInt16(O);for(let X=0;X<O;X++)G.addInt32(_[X]);return L.flush(80)},m=new b$.Writer,g1=function($,E){for(let _=0;_<$.length;_++){let O=E?E($[_],_):$[_];if(O==null)L.addInt16(0),m.addInt32(-1);else if(O instanceof Buffer)L.addInt16(1),m.addInt32(O.length),m.add(O);else L.addInt16(0),m.addInt32(Buffer.byteLength(O)),m.addString(O)}},c1=($={})=>{let E=$.portal||"",_=$.statement||"",O=$.binary||!1,G=$.values||C_,X=G.length;return L.addCString(E).addCString(_),L.addInt16(X),g1(G,$.valueMapper),L.addInt16(X),L.add(m.flush()),L.addInt16(1),L.addInt16(O?1:0),L.flush(66)},l1=Buffer.from([69,0,0,0,9,0,0,0,0,0]),o1=($)=>{if(!$||!$.portal&&!$.rows)return l1;let E=$.portal||"",_=$.rows||0,O=Buffer.byteLength(E),G=4+O+1+4,X=Buffer.allocUnsafe(1+G);return X[0]=69,X.writeInt32BE(G,1),X.write(E,5,"utf-8"),X[O+5]=0,X.writeUInt32BE(_,X.length-4),X},n1=($,E)=>{let _=Buffer.allocUnsafe(16);return _.writeInt32BE(16,0),_.writeInt16BE(1234,4),_.writeInt16BE(5678,6),_.writeInt32BE($,8),_.writeInt32BE(E,12),_},y$=($,E)=>{let O=4+Buffer.byteLength(E)+1,G=Buffer.allocUnsafe(1+O);return G[0]=$,G.writeInt32BE(O,1),G.write(E,5,"utf-8"),G[O]=0,G},i1=L.addCString("P").flush(68),s1=L.addCString("S").flush(68),t1=($)=>{return $.name?y$(68,`${$.type}${$.name||""}`):$.type==="P"?i1:s1},a1=($)=>{let E=`${$.type}${$.name||""}`;return y$(67,E)},r1=($)=>{return L.add($).flush(100)},e1=($)=>{return y$(102,$)},X$=($)=>Buffer.from([$,0,0,0,4]),$4=X$(72),E4=X$(83),_4=X$(88),O4=X$(99),G4={startup:y1,password:p1,requestSsl:v1,sendSASLInitialResponseMessage:m1,sendSCRAMClientFinalMessage:f1,query:d1,parse:u1,bind:c1,execute:o1,describe:t1,close:a1,flush:()=>$4,sync:()=>E4,end:()=>_4,copyData:r1,copyDone:()=>O4,copyFail:e1,cancel:n1};I_.serialize=G4});var h_=R((w_)=>{Object.defineProperty(w_,"__esModule",{value:!0});w_.BufferReader=void 0;var X4=Buffer.allocUnsafe(0);class k_{constructor($=0){this.offset=$,this.buffer=X4,this.encoding="utf-8"}setBuffer($,E){this.offset=$,this.buffer=E}int16(){let $=this.buffer.readInt16BE(this.offset);return this.offset+=2,$}byte(){let $=this.buffer[this.offset];return this.offset++,$}int32(){let $=this.buffer.readInt32BE(this.offset);return this.offset+=4,$}uint32(){let $=this.buffer.readUInt32BE(this.offset);return this.offset+=4,$}string($){let E=this.buffer.toString(this.encoding,this.offset,this.offset+$);return this.offset+=$,E}cstring(){let $=this.offset,E=$;while(this.buffer[E++]!==0);return this.offset=E,this.buffer.toString(this.encoding,$,E-1)}bytes($){let E=this.buffer.slice(this.offset,this.offset+$);return this.offset+=$,E}}w_.BufferReader=k_});var d_=R((m_)=>{Object.defineProperty(m_,"__esModule",{value:!0});m_.Parser=void 0;var N=h$(),U4=h_(),p$=1,J4=4,b_=p$+J4,D=-1,v$=Buffer.allocUnsafe(0);class v_{constructor($){if(this.buffer=v$,this.bufferLength=0,this.bufferOffset=0,this.reader=new U4.BufferReader,($===null||$===void 0?void 0:$.mode)==="binary")throw Error("Binary mode not supported yet");this.mode=($===null||$===void 0?void 0:$.mode)||"text"}parse($,E){this.mergeBuffer($);let _=this.bufferOffset+this.bufferLength,O=this.bufferOffset;while(O+b_<=_){let G=this.buffer[O],X=this.buffer.readUInt32BE(O+p$),U=p$+X;if(U+O<=_){let J=this.handlePacket(O+b_,G,X,this.buffer);E(J),O+=U}else break}if(O===_)this.buffer=v$,this.bufferLength=0,this.bufferOffset=0;else this.bufferLength=_-O,this.bufferOffset=O}mergeBuffer($){if(this.bufferLength>0){let E=this.bufferLength+$.byteLength;if(E+this.bufferOffset>this.buffer.byteLength){let O;if(E<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)O=this.buffer;else{let G=this.buffer.byteLength*2;while(E>=G)G*=2;O=Buffer.allocUnsafe(G)}this.buffer.copy(O,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=O,this.bufferOffset=0}$.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=E}else this.buffer=$,this.bufferOffset=0,this.bufferLength=$.byteLength}handlePacket($,E,_,O){let{reader:G}=this;G.setBuffer($,O);let X;switch(E){case 50:X=N.bindComplete;break;case 49:X=N.parseComplete;break;case 51:X=N.closeComplete;break;case 110:X=N.noData;break;case 115:X=N.portalSuspended;break;case 99:X=N.copyDone;break;case 87:X=N.replicationStart;break;case 73:X=N.emptyQuery;break;case 68:X=j4(G);break;case 67:X=H4(G);break;case 90:X=Z4(G);break;case 65:X=K4(G);break;case 82:X=z4(G,_);break;case 83:X=N4(G);break;case 75:X=F4(G);break;case 69:X=y_(G,"error");break;case 78:X=y_(G,"notice");break;case 84:X=W4(G);break;case 116:X=Q4(G);break;case 71:X=Y4(G);break;case 72:X=R4(G);break;case 100:X=T4(G,_);break;default:return new N.DatabaseError("received invalid response: "+E.toString(16),_,"error")}return G.setBuffer(0,v$),X.length=_,X}}m_.Parser=v_;var Z4=($)=>{let E=$.string(1);return new N.ReadyForQueryMessage(D,E)},H4=($)=>{let E=$.cstring();return new N.CommandCompleteMessage(D,E)},T4=($,E)=>{let _=$.bytes(E-4);return new N.CopyDataMessage(D,_)},Y4=($)=>p_($,"copyInResponse"),R4=($)=>p_($,"copyOutResponse"),p_=($,E)=>{let _=$.byte()!==0,O=$.int16(),G=new N.CopyResponse(D,E,_,O);for(let X=0;X<O;X++)G.columnTypes[X]=$.int16();return G},K4=($)=>{let E=$.int32(),_=$.cstring(),O=$.cstring();return new N.NotificationResponseMessage(D,E,_,O)},W4=($)=>{let E=$.int16(),_=new N.RowDescriptionMessage(D,E);for(let O=0;O<E;O++)_.fields[O]=L4($);return _},L4=($)=>{let E=$.cstring(),_=$.uint32(),O=$.int16(),G=$.uint32(),X=$.int16(),U=$.int32(),J=$.int16()===0?"text":"binary";return new N.Field(E,_,O,G,X,U,J)},Q4=($)=>{let E=$.int16(),_=new N.ParameterDescriptionMessage(D,E);for(let O=0;O<E;O++)_.dataTypeIDs[O]=$.int32();return _},j4=($)=>{let E=$.int16(),_=Array(E);for(let O=0;O<E;O++){let G=$.int32();_[O]=G===-1?null:$.string(G)}return new N.DataRowMessage(D,_)},N4=($)=>{let E=$.cstring(),_=$.cstring();return new N.ParameterStatusMessage(D,E,_)},F4=($)=>{let E=$.int32(),_=$.int32();return new N.BackendKeyDataMessage(D,E,_)},z4=($,E)=>{let _=$.int32(),O={name:"authenticationOk",length:E};switch(_){case 0:break;case 3:if(O.length===8)O.name="authenticationCleartextPassword";break;case 5:if(O.length===12){O.name="authenticationMD5Password";let G=$.bytes(4);return new N.AuthenticationMD5Password(D,G)}break;case 10:{O.name="authenticationSASL",O.mechanisms=[];let G;do if(G=$.cstring(),G)O.mechanisms.push(G);while(G)}break;case 11:O.name="authenticationSASLContinue",O.data=$.string(E-8);break;case 12:O.name="authenticationSASLFinal",O.data=$.string(E-8);break;default:throw Error("Unknown authenticationOk message type "+_)}return O},y_=($,E)=>{let _={},O=$.string(1);while(O!=="\x00")_[O]=$.cstring(),O=$.string(1);let G=_.M,X=E==="notice"?new N.NoticeMessage(D,G):new N.DatabaseError(G,D,E);return X.severity=_.S,X.code=_.C,X.detail=_.D,X.hint=_.H,X.position=_.P,X.internalPosition=_.p,X.internalQuery=_.q,X.where=_.W,X.schema=_.s,X.table=_.t,X.column=_.c,X.dataType=_.d,X.constraint=_.n,X.file=_.F,X.line=_.L,X.routine=_.R,X}});var m$=R((U$)=>{Object.defineProperty(U$,"__esModule",{value:!0});U$.DatabaseError=U$.serialize=U$.parse=void 0;var P4=h$();Object.defineProperty(U$,"DatabaseError",{enumerable:!0,get:function(){return P4.DatabaseError}});var A4=B_();Object.defineProperty(U$,"serialize",{enumerable:!0,get:function(){return A4.serialize}});var D4=d_();function M4($,E){let _=new D4.Parser;return $.on("data",(O)=>_.parse(O,E)),new Promise((O)=>$.on("end",()=>O()))}U$.parse=M4});var g_=R((u_)=>{Object.defineProperty(u_,"__esModule",{value:!0});u_.default={}});var l_=R((D8,c_)=>{var{getStream:I4,getSecureStream:q4}=x4();c_.exports={getStream:I4,getSecureStream:q4};function B4(){function $(_){return new(W("net")).Socket}function E(_){return W("tls").connect(_)}return{getStream:$,getSecureStream:E}}function k4(){function $(_){let{CloudflareSocket:O}=g_();return new O(_)}function E(_){return _.socket.startTls(_),_.socket}return{getStream:$,getSecureStream:E}}function w4(){if(typeof navigator==="object"&&navigator!==null&&typeof navigator.userAgent==="string")return navigator.userAgent==="Cloudflare-Workers";if(typeof Response==="function"){let $=new Response(null,{cf:{thing:!0}});if(typeof $.cf==="object"&&$.cf!==null&&$.cf.thing)return!0}return!1}function x4(){if(w4())return k4();return B4()}});var f$=R((M8,n_)=>{var h4=W("events").EventEmitter,{parse:b4,serialize:F}=m$(),{getStream:y4,getSecureStream:v4}=l_(),p4=F.flush(),m4=F.sync(),f4=F.end();class o_ extends h4{constructor($){super();if($=$||{},this.stream=$.stream||y4($.ssl),typeof this.stream==="function")this.stream=this.stream($);this._keepAlive=$.keepAlive,this._keepAliveInitialDelayMillis=$.keepAliveInitialDelayMillis,this.parsedStatements={},this.ssl=$.ssl||!1,this._ending=!1,this._emitMessage=!1;let E=this;this.on("newListener",function(_){if(_==="message")E._emitMessage=!0})}connect($,E){let _=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect($,E),this.stream.once("connect",function(){if(_._keepAlive)_.stream.setKeepAlive(!0,_._keepAliveInitialDelayMillis);_.emit("connect")});let O=function(G){if(_._ending&&(G.code==="ECONNRESET"||G.code==="EPIPE"))return;_.emit("error",G)};if(this.stream.on("error",O),this.stream.on("close",function(){_.emit("end")}),!this.ssl)return this.attachListeners(this.stream);this.stream.once("data",function(G){switch(G.toString("utf8")){case"S":break;case"N":return _.stream.end(),_.emit("error",Error("The server does not support SSL connections"));default:return _.stream.end(),_.emit("error",Error("There was an error establishing an SSL connection"))}let U={socket:_.stream};if(_.ssl!==!0){if(Object.assign(U,_.ssl),"key"in _.ssl)U.key=_.ssl.key}let J=W("net");if(J.isIP&&J.isIP(E)===0)U.servername=E;try{_.stream=v4(U)}catch(Z){return _.emit("error",Z)}_.attachListeners(_.stream),_.stream.on("error",O),_.emit("sslconnect")})}attachListeners($){b4($,(E)=>{let _=E.name==="error"?"errorMessage":E.name;if(this._emitMessage)this.emit("message",E);this.emit(_,E)})}requestSsl(){this.stream.write(F.requestSsl())}startup($){this.stream.write(F.startup($))}cancel($,E){this._send(F.cancel($,E))}password($){this._send(F.password($))}sendSASLInitialResponseMessage($,E){this._send(F.sendSASLInitialResponseMessage($,E))}sendSCRAMClientFinalMessage($){this._send(F.sendSCRAMClientFinalMessage($))}_send($){if(!this.stream.writable)return!1;return this.stream.write($)}query($){this._send(F.query($))}parse($){this._send(F.parse($))}bind($){this._send(F.bind($))}execute($){this._send(F.execute($))}flush(){if(this.stream.writable)this.stream.write(p4)}sync(){this._ending=!0,this._send(m4)}ref(){this.stream.ref()}unref(){this.stream.unref()}end(){if(this._ending=!0,!this._connecting||!this.stream.writable){this.stream.end();return}return this.stream.write(f4,()=>{this.stream.end()})}close($){this._send(F.close($))}describe($){this._send(F.describe($))}sendCopyFromChunk($){this._send(F.copyData($))}endCopyFrom(){this._send(F.copyDone())}sendCopyFail($){this._send(F.copyFail($))}}n_.exports=o_});var a_=R((V8,t_)=>{var{Transform:d4}=W("stream"),{StringDecoder:u4}=W("string_decoder"),B=Symbol("last"),J$=Symbol("decoder");function g4($,E,_){let O;if(this.overflow){if(O=this[J$].write($).split(this.matcher),O.length===1)return _();O.shift(),this.overflow=!1}else this[B]+=this[J$].write($),O=this[B].split(this.matcher);this[B]=O.pop();for(let G=0;G<O.length;G++)try{s_(this,this.mapper(O[G]))}catch(X){return _(X)}if(this.overflow=this[B].length>this.maxLength,this.overflow&&!this.skipOverflow){_(Error("maximum buffer reached"));return}_()}function c4($){if(this[B]+=this[J$].end(),this[B])try{s_(this,this.mapper(this[B]))}catch(E){return $(E)}$()}function s_($,E){if(E!==void 0)$.push(E)}function i_($){return $}function l4($,E,_){switch($=$||/\r?\n/,E=E||i_,_=_||{},arguments.length){case 1:if(typeof $==="function")E=$,$=/\r?\n/;else if(typeof $==="object"&&!($ instanceof RegExp)&&!$[Symbol.split])_=$,$=/\r?\n/;break;case 2:if(typeof $==="function")_=E,E=$,$=/\r?\n/;else if(typeof E==="object")_=E,E=i_}_=Object.assign({},_),_.autoDestroy=!0,_.transform=g4,_.flush=c4,_.readableObjectMode=!0;let O=new d4(_);return O[B]="",O[J$]=new u4("utf8"),O.matcher=$,O.mapper=E,O.maxLength=_.maxLength,O.skipOverflow=_.skipOverflow||!1,O.overflow=!1,O._destroy=function(G,X){this._writableState.errorEmitted=!1,X(G)},O}t_.exports=l4});var $O=R((GG,I)=>{var r_=W("path"),o4=W("stream").Stream,n4=a_(),e_=W("util"),i4=5432,Z$=process.platform==="win32",a=process.stderr,s4=56,t4=7,a4=61440,r4=32768;function e4($){return($&a4)==r4}var f=["host","port","database","user","password"],d$=f.length,$G=f[d$-1];function u$(){var $=a instanceof o4&&a.writable===!0;if($){var E=Array.prototype.slice.call(arguments).concat(`
|
|
9
|
+
`);a.write(e_.format.apply(e_,E))}}Object.defineProperty(GG,"isWin",{get:function(){return Z$},set:function($){Z$=$}});GG.warnTo=function($){var E=a;return a=$,E};GG.getFileName=function($){var E=$||process.env,_=E.PGPASSFILE||(Z$?r_.join(E.APPDATA||"./","postgresql","pgpass.conf"):r_.join(E.HOME||"./",".pgpass"));return _};GG.usePgPass=function($,E){if(Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD"))return!1;if(Z$)return!0;if(E=E||"<unkn>",!e4($.mode))return u$('WARNING: password file "%s" is not a plain file',E),!1;if($.mode&(s4|t4))return u$('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',E),!1;return!0};var EG=GG.match=function($,E){return f.slice(0,-1).reduce(function(_,O,G){if(G==1){if(Number($[O]||i4)===Number(E[O]))return _&&!0}return _&&(E[O]==="*"||E[O]===$[O])},!0)};GG.getPassword=function($,E,_){var O,G=E.pipe(n4());function X(Z){var H=_G(Z);if(H&&OG(H)&&EG($,H))O=H[$G],G.end()}var U=function(){E.destroy(),_(O)},J=function(Z){E.destroy(),u$("WARNING: error on reading file: %s",Z),_(void 0)};E.on("error",J),G.on("data",X).on("end",U).on("error",J)};var _G=GG.parseLine=function($){if($.length<11||$.match(/^\s+#/))return null;var E="",_="",O=0,G=0,X=0,U={},J=!1,Z=function(Y,T,K){var Q=$.substring(T,K);if(!Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE"))Q=Q.replace(/\\([:\\])/g,"$1");U[f[Y]]=Q};for(var H=0;H<$.length-1;H+=1){if(E=$.charAt(H+1),_=$.charAt(H),J=O==d$-1,J){Z(O,G);break}if(H>=0&&E==":"&&_!=="\\")Z(O,G,H+1),G=H+2,O+=1}return U=Object.keys(U).length===d$?U:null,U},OG=GG.isValidEntry=function($){var E={0:function(U){return U.length>0},1:function(U){if(U==="*")return!0;return U=Number(U),isFinite(U)&&U>0&&U<9007199254740992&&Math.floor(U)===U},2:function(U){return U.length>0},3:function(U){return U.length>0},4:function(U){return U.length>0}};for(var _=0;_<f.length;_+=1){var O=E[_],G=$[f[_]]||"",X=O(G);if(!X)return!1}return!0}});var _O=R((B8,g$)=>{var q8=W("path"),EO=W("fs"),H$=$O();g$.exports=function($,E){var _=H$.getFileName();EO.stat(_,function(O,G){if(O||!H$.usePgPass(G,_))return E(void 0);var X=EO.createReadStream(_);H$.getPassword($,X,E)})};g$.exports.warnTo=H$.warnTo});var JO=R((k8,UO)=>{var HG=W("events").EventEmitter,OO=b(),T$=W("util"),c$=cE(),TG=G$(),YG=w$(),XO=U_(),RG=s(),KG=f$(),WG=q$(),GO=T$.deprecate(()=>{},"Client.activeQuery is deprecated and will be removed in a future version."),LG=T$.deprecate(()=>{},"Client.queryQueue is deprecated and will be removed in a future version."),QG=T$.deprecate(()=>{},"pgpass support is deprecated and will be removed in a future version. You can provide an async function as the password property to the Client/Pool constructor that returns a password instead. Within this funciton you can call the pgpass module in your own code."),jG=T$.deprecate(()=>{},"Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in a future version.");class l$ extends HG{constructor($){super();this.connectionParameters=new YG($),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;let E=$||{};if(E.Promise)jG();if(this._Promise=E.Promise||global.Promise,this._types=new TG(E.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this._activeQuery=null,this.enableChannelBinding=Boolean(E.enableChannelBinding),this.connection=E.connection||new KG({stream:E.stream,ssl:this.connectionParameters.ssl,keepAlive:E.keepAlive||!1,keepAliveInitialDelayMillis:E.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this._queryQueue=[],this.binary=E.binary||RG.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.ssl&&this.ssl.key)Object.defineProperty(this.ssl,"key",{enumerable:!1});this._connectionTimeoutMillis=E.connectionTimeoutMillis||0}get activeQuery(){return GO(),this._activeQuery}set activeQuery($){GO(),this._activeQuery=$}_getActiveQuery(){return this._activeQuery}_errorAllQueries($){let E=(O)=>{process.nextTick(()=>{O.handleError($,this.connection)})},_=this._getActiveQuery();if(_)E(_),this._activeQuery=null;this._queryQueue.forEach(E),this._queryQueue.length=0}_connect($){let E=this,_=this.connection;if(this._connectionCallback=$,this._connecting||this._connected){let O=Error("Client has already been connected. You cannot reuse a client.");process.nextTick(()=>{$(O)});return}if(this._connecting=!0,this._connectionTimeoutMillis>0){if(this.connectionTimeoutHandle=setTimeout(()=>{_._ending=!0,_.stream.destroy(Error("timeout expired"))},this._connectionTimeoutMillis),this.connectionTimeoutHandle.unref)this.connectionTimeoutHandle.unref()}if(this.host&&this.host.indexOf("/")===0)_.connect(this.host+"/.s.PGSQL."+this.port);else _.connect(this.port,this.host);_.on("connect",function(){if(E.ssl)_.requestSsl();else _.startup(E.getStartupConf())}),_.on("sslconnect",function(){_.startup(E.getStartupConf())}),this._attachListeners(_),_.once("end",()=>{let O=this._ending?Error("Connection terminated"):Error("Connection terminated unexpectedly");if(clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(O),this._ended=!0,!this._ending){if(this._connecting&&!this._connectionError)if(this._connectionCallback)this._connectionCallback(O);else this._handleErrorEvent(O);else if(!this._connectionError)this._handleErrorEvent(O)}process.nextTick(()=>{this.emit("end")})})}connect($){if($){this._connect($);return}return new this._Promise((E,_)=>{this._connect((O)=>{if(O)_(O);else E(this)})})}_attachListeners($){$.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),$.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),$.on("authenticationSASL",this._handleAuthSASL.bind(this)),$.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),$.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),$.on("backendKeyData",this._handleBackendKeyData.bind(this)),$.on("error",this._handleErrorEvent.bind(this)),$.on("errorMessage",this._handleErrorMessage.bind(this)),$.on("readyForQuery",this._handleReadyForQuery.bind(this)),$.on("notice",this._handleNotice.bind(this)),$.on("rowDescription",this._handleRowDescription.bind(this)),$.on("dataRow",this._handleDataRow.bind(this)),$.on("portalSuspended",this._handlePortalSuspended.bind(this)),$.on("emptyQuery",this._handleEmptyQuery.bind(this)),$.on("commandComplete",this._handleCommandComplete.bind(this)),$.on("parseComplete",this._handleParseComplete.bind(this)),$.on("copyInResponse",this._handleCopyInResponse.bind(this)),$.on("copyData",this._handleCopyData.bind(this)),$.on("notification",this._handleNotification.bind(this))}_getPassword($){let E=this.connection;if(typeof this.password==="function")this._Promise.resolve().then(()=>this.password()).then((_)=>{if(_!==void 0){if(typeof _!=="string"){E.emit("error",TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=_}else this.connectionParameters.password=this.password=null;$()}).catch((_)=>{E.emit("error",_)});else if(this.password!==null)$();else try{_O()(this.connectionParameters,(O)=>{if(O!==void 0)QG(),this.connectionParameters.password=this.password=O;$()})}catch(_){this.emit("error",_)}}_handleAuthCleartextPassword($){this._getPassword(()=>{this.connection.password(this.password)})}_handleAuthMD5Password($){this._getPassword(async()=>{try{let E=await WG.postgresMd5PasswordHash(this.user,this.password,$.salt);this.connection.password(E)}catch(E){this.emit("error",E)}})}_handleAuthSASL($){this._getPassword(()=>{try{this.saslSession=c$.startSession($.mechanisms,this.enableChannelBinding&&this.connection.stream),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(E){this.connection.emit("error",E)}})}async _handleAuthSASLContinue($){try{await c$.continueSession(this.saslSession,this.password,$.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(E){this.connection.emit("error",E)}}_handleAuthSASLFinal($){try{c$.finalizeSession(this.saslSession,$.data),this.saslSession=null}catch(E){this.connection.emit("error",E)}}_handleBackendKeyData($){this.processID=$.processID,this.secretKey=$.secretKey}_handleReadyForQuery($){if(this._connecting){if(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)this._connectionCallback(null,this),this._connectionCallback=null;this.emit("connect")}let E=this._getActiveQuery();if(this._activeQuery=null,this.readyForQuery=!0,E)E.handleReadyForQuery(this.connection);this._pulseQueryQueue()}_handleErrorWhileConnecting($){if(this._connectionError)return;if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback($);this.emit("error",$)}_handleErrorEvent($){if(this._connecting)return this._handleErrorWhileConnecting($);this._queryable=!1,this._errorAllQueries($),this.emit("error",$)}_handleErrorMessage($){if(this._connecting)return this._handleErrorWhileConnecting($);let E=this._getActiveQuery();if(!E){this._handleErrorEvent($);return}this._activeQuery=null,E.handleError($,this.connection)}_handleRowDescription($){let E=this._getActiveQuery();if(E==null){let _=Error("Received unexpected rowDescription message from backend.");this._handleErrorEvent(_);return}E.handleRowDescription($)}_handleDataRow($){let E=this._getActiveQuery();if(E==null){let _=Error("Received unexpected dataRow message from backend.");this._handleErrorEvent(_);return}E.handleDataRow($)}_handlePortalSuspended($){let E=this._getActiveQuery();if(E==null){let _=Error("Received unexpected portalSuspended message from backend.");this._handleErrorEvent(_);return}E.handlePortalSuspended(this.connection)}_handleEmptyQuery($){let E=this._getActiveQuery();if(E==null){let _=Error("Received unexpected emptyQuery message from backend.");this._handleErrorEvent(_);return}E.handleEmptyQuery(this.connection)}_handleCommandComplete($){let E=this._getActiveQuery();if(E==null){let _=Error("Received unexpected commandComplete message from backend.");this._handleErrorEvent(_);return}E.handleCommandComplete($,this.connection)}_handleParseComplete(){let $=this._getActiveQuery();if($==null){let E=Error("Received unexpected parseComplete message from backend.");this._handleErrorEvent(E);return}if($.name)this.connection.parsedStatements[$.name]=$.text}_handleCopyInResponse($){let E=this._getActiveQuery();if(E==null){let _=Error("Received unexpected copyInResponse message from backend.");this._handleErrorEvent(_);return}E.handleCopyInResponse(this.connection)}_handleCopyData($){let E=this._getActiveQuery();if(E==null){let _=Error("Received unexpected copyData message from backend.");this._handleErrorEvent(_);return}E.handleCopyData($,this.connection)}_handleNotification($){this.emit("notification",$)}_handleNotice($){this.emit("notice",$)}getStartupConf(){let $=this.connectionParameters,E={user:$.user,database:$.database},_=$.application_name||$.fallback_application_name;if(_)E.application_name=_;if($.replication)E.replication=""+$.replication;if($.statement_timeout)E.statement_timeout=String(parseInt($.statement_timeout,10));if($.lock_timeout)E.lock_timeout=String(parseInt($.lock_timeout,10));if($.idle_in_transaction_session_timeout)E.idle_in_transaction_session_timeout=String(parseInt($.idle_in_transaction_session_timeout,10));if($.options)E.options=$.options;return E}cancel($,E){if($.activeQuery===E){let _=this.connection;if(this.host&&this.host.indexOf("/")===0)_.connect(this.host+"/.s.PGSQL."+this.port);else _.connect(this.port,this.host);_.on("connect",function(){_.cancel($.processID,$.secretKey)})}else if($._queryQueue.indexOf(E)!==-1)$._queryQueue.splice($._queryQueue.indexOf(E),1)}setTypeParser($,E,_){return this._types.setTypeParser($,E,_)}getTypeParser($,E){return this._types.getTypeParser($,E)}escapeIdentifier($){return OO.escapeIdentifier($)}escapeLiteral($){return OO.escapeLiteral($)}_pulseQueryQueue(){if(this.readyForQuery===!0){this._activeQuery=this._queryQueue.shift();let $=this._getActiveQuery();if($){this.readyForQuery=!1,this.hasExecuted=!0;let E=$.submit(this.connection);if(E)process.nextTick(()=>{$.handleError(E,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else if(this.hasExecuted)this._activeQuery=null,this.emit("drain")}}query($,E,_){let O,G,X,U,J;if($===null||$===void 0)throw TypeError("Client was passed a null or undefined query");else if(typeof $.submit==="function"){if(X=$.query_timeout||this.connectionParameters.query_timeout,G=O=$,typeof E==="function")O.callback=O.callback||E}else if(X=$.query_timeout||this.connectionParameters.query_timeout,O=new XO($,E,_),!O.callback)G=new this._Promise((Z,H)=>{O.callback=(Y,T)=>Y?H(Y):Z(T)}).catch((Z)=>{throw Error.captureStackTrace(Z),Z});if(X)J=O.callback,U=setTimeout(()=>{let Z=Error("Query read timeout");process.nextTick(()=>{O.handleError(Z,this.connection)}),J(Z),O.callback=()=>{};let H=this._queryQueue.indexOf(O);if(H>-1)this._queryQueue.splice(H,1);this._pulseQueryQueue()},X),O.callback=(Z,H)=>{clearTimeout(U),J(Z,H)};if(this.binary&&!O.binary)O.binary=!0;if(O._result&&!O._result._types)O._result._types=this._types;if(!this._queryable)return process.nextTick(()=>{O.handleError(Error("Client has encountered a connection error and is not queryable"),this.connection)}),G;if(this._ending)return process.nextTick(()=>{O.handleError(Error("Client was closed and is not queryable"),this.connection)}),G;return this._queryQueue.push(O),this._pulseQueryQueue(),G}ref(){this.connection.ref()}unref(){this.connection.unref()}end($){if(this._ending=!0,!this.connection._connecting||this._ended)if($)$();else return this._Promise.resolve();if(this._getActiveQuery()||!this._queryable)this.connection.stream.destroy();else this.connection.end();if($)this.connection.once("end",$);else return new this._Promise((E)=>{this.connection.once("end",E)})}get queryQueue(){return LG(),this._queryQueue}}l$.Query=XO;UO.exports=l$});var KO=R((w8,RO)=>{var NG=W("events").EventEmitter,ZO=function(){},HO=($,E)=>{let _=$.findIndex(E);return _===-1?void 0:$.splice(_,1)[0]};class TO{constructor($,E,_){this.client=$,this.idleListener=E,this.timeoutId=_}}class r{constructor($){this.callback=$}}function FG(){throw Error("Release called on client which has already been released to the pool.")}function Y$($,E){if(E)return{callback:E,result:void 0};let _,O,G=function(U,J){U?_(U):O(J)},X=new $(function(U,J){O=U,_=J}).catch((U)=>{throw Error.captureStackTrace(U),U});return{callback:G,result:X}}function zG($,E){return function _(O){O.client=E,E.removeListener("error",_),E.on("error",()=>{$.log("additional client error after disconnection due to error",O)}),$._remove(E),$.emit("error",O,E)}}class YO extends NG{constructor($,E){super();if(this.options=Object.assign({},$),$!=null&&"password"in $)Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:$.password});if($!=null&&$.ssl&&$.ssl.key)Object.defineProperty(this.options.ssl,"key",{enumerable:!1});if(this.options.max=this.options.max||this.options.poolSize||10,this.options.min=this.options.min||0,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||E||o$().Client,this.Promise=this.options.Promise||global.Promise,typeof this.options.idleTimeoutMillis>"u")this.options.idleTimeoutMillis=1e4;this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_isFull(){return this._clients.length>=this.options.max}_isAboveMin(){return this._clients.length>this.options.min}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){if(this.log("pulse queue on ending"),this._idle.length)this._idle.slice().map((E)=>{this._remove(E.client)});if(!this._clients.length)this.ended=!0,this._endCallback();return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let $=this._pendingQueue.shift();if(this._idle.length){let E=this._idle.pop();clearTimeout(E.timeoutId);let _=E.client;_.ref&&_.ref();let O=E.idleListener;return this._acquireClient(_,$,O,!1)}if(!this._isFull())return this.newClient($);throw Error("unexpected condition")}_remove($,E){let _=HO(this._idle,(G)=>G.client===$);if(_!==void 0)clearTimeout(_.timeoutId);this._clients=this._clients.filter((G)=>G!==$);let O=this;$.end(()=>{if(O.emit("remove",$),typeof E==="function")E()})}connect($){if(this.ending){let O=Error("Cannot use a pool after calling end on the pool");return $?$(O):this.Promise.reject(O)}let E=Y$(this.Promise,$),_=E.result;if(this._isFull()||this._idle.length){if(this._idle.length)process.nextTick(()=>this._pulseQueue());if(!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new r(E.callback)),_;let O=(U,J,Z)=>{clearTimeout(X),E.callback(U,J,Z)},G=new r(O),X=setTimeout(()=>{HO(this._pendingQueue,(U)=>U.callback===O),G.timedOut=!0,E.callback(Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);if(X.unref)X.unref();return this._pendingQueue.push(G),_}return this.newClient(new r(E.callback)),_}newClient($){let E=new this.Client(this.options);this._clients.push(E);let _=zG(this,E);this.log("checking client timeout");let O,G=!1;if(this.options.connectionTimeoutMillis)O=setTimeout(()=>{this.log("ending client due to timeout"),G=!0,E.connection?E.connection.stream.destroy():E.end()},this.options.connectionTimeoutMillis);this.log("connecting new client"),E.connect((X)=>{if(O)clearTimeout(O);if(E.on("error",_),X){if(this.log("client failed to connect",X),this._clients=this._clients.filter((U)=>U!==E),G)X=Error("Connection terminated due to connection timeout",{cause:X});if(this._pulseQueue(),!$.timedOut)$.callback(X,void 0,ZO)}else{if(this.log("new client connected"),this.options.maxLifetimeSeconds!==0){let U=setTimeout(()=>{if(this.log("ending client due to expired lifetime"),this._expired.add(E),this._idle.findIndex((Z)=>Z.client===E)!==-1)this._acquireClient(E,new r((Z,H,Y)=>Y()),_,!1)},this.options.maxLifetimeSeconds*1000);U.unref(),E.once("end",()=>clearTimeout(U))}return this._acquireClient(E,$,_,!0)}})}_acquireClient($,E,_,O){if(O)this.emit("connect",$);if(this.emit("acquire",$),$.release=this._releaseOnce($,_),$.removeListener("error",_),!E.timedOut)if(O&&this.options.verify)this.options.verify($,(G)=>{if(G)return $.release(G),E.callback(G,void 0,ZO);E.callback(void 0,$,$.release)});else E.callback(void 0,$,$.release);else if(O&&this.options.verify)this.options.verify($,$.release);else $.release()}_releaseOnce($,E){let _=!1;return(O)=>{if(_)FG();_=!0,this._release($,E,O)}}_release($,E,_){if($.on("error",E),$._poolUseCount=($._poolUseCount||0)+1,this.emit("release",_,$),_||this.ending||!$._queryable||$._ending||$._poolUseCount>=this.options.maxUses){if($._poolUseCount>=this.options.maxUses)this.log("remove expended client");return this._remove($,this._pulseQueue.bind(this))}if(this._expired.has($))return this.log("remove expired client"),this._expired.delete($),this._remove($,this._pulseQueue.bind(this));let G;if(this.options.idleTimeoutMillis&&this._isAboveMin()){if(G=setTimeout(()=>{if(this._isAboveMin())this.log("remove idle client"),this._remove($,this._pulseQueue.bind(this))},this.options.idleTimeoutMillis),this.options.allowExitOnIdle)G.unref()}if(this.options.allowExitOnIdle)$.unref();this._idle.push(new TO($,E,G)),this._pulseQueue()}query($,E,_){if(typeof $==="function"){let G=Y$(this.Promise,$);return setImmediate(function(){return G.callback(Error("Passing a function as the first parameter to pool.query is not supported"))}),G.result}if(typeof E==="function")_=E,E=void 0;let O=Y$(this.Promise,_);return _=O.callback,this.connect((G,X)=>{if(G)return _(G);let U=!1,J=(Z)=>{if(U)return;U=!0,X.release(Z),_(Z)};X.once("error",J),this.log("dispatching query");try{X.query($,E,(Z,H)=>{if(this.log("query dispatched"),X.removeListener("error",J),U)return;if(U=!0,X.release(Z),Z)return _(Z);return _(void 0,H)})}catch(Z){return X.release(Z),_(Z)}}),O.result}end($){if(this.log("ending"),this.ending){let _=Error("Called end on pool more than once");return $?$(_):this.Promise.reject(_)}this.ending=!0;let E=Y$(this.Promise,$);return this._endCallback=E.callback,this._pulseQueue(),E.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce(($,E)=>$+(this._expired.has(E)?1:0),0)}get totalCount(){return this._clients.length}}RO.exports=YO});var QO=R((x8,LO)=>{var WO=W("events").EventEmitter,PG=W("util"),n$=b(),d=LO.exports=function($,E,_){WO.call(this),$=n$.normalizeQueryConfig($,E,_),this.text=$.text,this.values=$.values,this.name=$.name,this.queryMode=$.queryMode,this.callback=$.callback,this.state="new",this._arrayMode=$.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(O){if(O==="row")this._emitRowEvents=!0}.bind(this))};PG.inherits(d,WO);var AG={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};d.prototype.handleError=function($){let E=this.native.pq.resultErrorFields();if(E)for(let _ in E){let O=AG[_]||_;$[O]=E[_]}if(this.callback)this.callback($);else this.emit("error",$);this.state="error"};d.prototype.then=function($,E){return this._getPromise().then($,E)};d.prototype.catch=function($){return this._getPromise().catch($)};d.prototype._getPromise=function(){if(this._promise)return this._promise;return this._promise=new Promise(function($,E){this._once("end",$),this._once("error",E)}.bind(this)),this._promise};d.prototype.submit=function($){this.state="running";let E=this;this.native=$.native,$.native.arrayMode=this._arrayMode;let _=function(O,G,X){if($.native.arrayMode=!1,setImmediate(function(){E.emit("_done")}),O)return E.handleError(O);if(E._emitRowEvents)if(X.length>1)G.forEach((U,J)=>{U.forEach((Z)=>{E.emit("row",Z,X[J])})});else G.forEach(function(U){E.emit("row",U,X)});if(E.state="end",E.emit("end",X),E.callback)E.callback(null,X)};if(process.domain)_=process.domain.bind(_);if(this.name){if(this.name.length>63)console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries");let O=(this.values||[]).map(n$.prepareValue);if($.namedQueries[this.name]){if(this.text&&$.namedQueries[this.name]!==this.text){let G=Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return _(G)}return $.native.execute(this.name,O,_)}return $.native.prepare(this.name,this.text,O.length,function(G){if(G)return _(G);return $.namedQueries[E.name]=E.text,E.native.execute(E.name,O,_)})}else if(this.values){if(!Array.isArray(this.values)){let G=Error("Query values must be an array");return _(G)}let O=this.values.map(n$.prepareValue);$.native.query(this.text,O,_)}else if(this.queryMode==="extended")$.native.query(this.text,[],_);else $.native.query(this.text,_)}});var i$=R((h8,zO)=>{var jO;try{jO=(()=>{throw new Error("Cannot require module "+"pg-native");})()}catch($){throw $}var DG=G$(),NO=W("events").EventEmitter,MG=W("util"),VG=w$(),FO=QO(),A=zO.exports=function($){NO.call(this),$=$||{},this._Promise=$.Promise||global.Promise,this._types=new DG($.types),this.native=new jO({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;let E=this.connectionParameters=new VG($);if($.nativeConnectionString)E.nativeConnectionString=$.nativeConnectionString;this.user=E.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:E.password}),this.database=E.database,this.host=E.host,this.port=E.port,this.namedQueries={}};A.Query=FO;MG.inherits(A,NO);A.prototype._errorAllQueries=function($){let E=(_)=>{process.nextTick(()=>{_.native=this.native,_.handleError($)})};if(this._hasActiveQuery())E(this._activeQuery),this._activeQuery=null;this._queryQueue.forEach(E),this._queryQueue.length=0};A.prototype._connect=function($){let E=this;if(this._connecting){process.nextTick(()=>$(Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(_,O){if(E.connectionParameters.nativeConnectionString)O=E.connectionParameters.nativeConnectionString;if(_)return $(_);E.native.connect(O,function(G){if(G)return E.native.end(),$(G);E._connected=!0,E.native.on("error",function(X){E._queryable=!1,E._errorAllQueries(X),E.emit("error",X)}),E.native.on("notification",function(X){E.emit("notification",{channel:X.relname,payload:X.extra})}),E.emit("connect"),E._pulseQueryQueue(!0),$(null,this)})})};A.prototype.connect=function($){if($){this._connect($);return}return new this._Promise((E,_)=>{this._connect((O)=>{if(O)_(O);else E(this)})})};A.prototype.query=function($,E,_){let O,G,X,U,J;if($===null||$===void 0)throw TypeError("Client was passed a null or undefined query");else if(typeof $.submit==="function"){if(X=$.query_timeout||this.connectionParameters.query_timeout,G=O=$,typeof E==="function")$.callback=E}else if(X=$.query_timeout||this.connectionParameters.query_timeout,O=new FO($,E,_),!O.callback){let Z,H;G=new this._Promise((Y,T)=>{Z=Y,H=T}).catch((Y)=>{throw Error.captureStackTrace(Y),Y}),O.callback=(Y,T)=>Y?H(Y):Z(T)}if(X)J=O.callback,U=setTimeout(()=>{let Z=Error("Query read timeout");process.nextTick(()=>{O.handleError(Z,this.connection)}),J(Z),O.callback=()=>{};let H=this._queryQueue.indexOf(O);if(H>-1)this._queryQueue.splice(H,1);this._pulseQueryQueue()},X),O.callback=(Z,H)=>{clearTimeout(U),J(Z,H)};if(!this._queryable)return O.native=this.native,process.nextTick(()=>{O.handleError(Error("Client has encountered a connection error and is not queryable"))}),G;if(this._ending)return O.native=this.native,process.nextTick(()=>{O.handleError(Error("Client was closed and is not queryable"))}),G;return this._queryQueue.push(O),this._pulseQueryQueue(),G};A.prototype.end=function($){let E=this;if(this._ending=!0,!this._connected)this.once("connect",this.end.bind(this,$));let _;if(!$)_=new this._Promise(function(O,G){$=(X)=>X?G(X):O()});return this.native.end(function(){E._errorAllQueries(Error("Connection terminated")),process.nextTick(()=>{if(E.emit("end"),$)$()})}),_};A.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};A.prototype._pulseQueryQueue=function($){if(!this._connected)return;if(this._hasActiveQuery())return;let E=this._queryQueue.shift();if(!E){if(!$)this.emit("drain");return}this._activeQuery=E,E.submit(this);let _=this;E.once("_done",function(){_._pulseQueryQueue()})};A.prototype.cancel=function($){if(this._activeQuery===$)this.native.cancel(function(){});else if(this._queryQueue.indexOf($)!==-1)this._queryQueue.splice(this._queryQueue.indexOf($),1)};A.prototype.ref=function(){};A.prototype.unref=function(){};A.prototype.setTypeParser=function($,E,_){return this._types.setTypeParser($,E,_)};A.prototype.getTypeParser=function($,E){return this._types.getTypeParser($,E)}});var o$=R((b8,R$)=>{var SG=JO(),CG=s(),IG=f$(),qG=x$(),BG=b(),kG=KO(),wG=G$(),{DatabaseError:xG}=m$(),{escapeIdentifier:hG,escapeLiteral:bG}=b(),yG=($)=>{return class extends kG{constructor(_){super(_,$)}}},PO=function($){this.defaults=CG,this.Client=$,this.Query=this.Client.Query,this.Pool=yG(this.Client),this._pools=[],this.Connection=IG,this.types=i(),this.DatabaseError=xG,this.TypeOverrides=wG,this.escapeIdentifier=hG,this.escapeLiteral=bG,this.Result=qG,this.utils=BG},AO=SG,DO=!1;try{DO=!!process.env.NODE_PG_FORCE_NATIVE}catch{}if(DO)AO=i$();R$.exports=new PO(AO);Object.defineProperty(R$.exports,"native",{configurable:!0,enumerable:!1,get(){let $=null;try{$=new PO(i$())}catch(E){if(E.code!=="MODULE_NOT_FOUND")throw E}return Object.defineProperty(R$.exports,"native",{value:$}),$}})});var g=($)=>{return["checkpoints","checkpoint_blobs","checkpoint_migrations","checkpoint_writes"].reduce((E,_)=>{return E[_]=`"${$}".${_}`,E},{})},a$=($)=>{let E=g($);return{SELECT_SQL:`select
|
|
10
|
+
thread_id,
|
|
11
|
+
checkpoint,
|
|
12
|
+
checkpoint_ns,
|
|
13
|
+
checkpoint_id,
|
|
14
|
+
parent_checkpoint_id,
|
|
15
|
+
metadata,
|
|
16
|
+
(
|
|
17
|
+
select array_agg(array[bl.channel::bytea, bl.type::bytea, bl.blob])
|
|
18
|
+
from jsonb_each_text(checkpoint -> 'channel_versions')
|
|
19
|
+
inner join ${E.checkpoint_blobs} bl
|
|
20
|
+
on bl.thread_id = cp.thread_id
|
|
21
|
+
and bl.checkpoint_ns = cp.checkpoint_ns
|
|
22
|
+
and bl.channel = jsonb_each_text.key
|
|
23
|
+
and bl.version = jsonb_each_text.value
|
|
24
|
+
) as channel_values,
|
|
25
|
+
(
|
|
26
|
+
select
|
|
27
|
+
array_agg(array[cw.task_id::text::bytea, cw.channel::bytea, cw.type::bytea, cw.blob] order by cw.task_id, cw.idx)
|
|
28
|
+
from ${E.checkpoint_writes} cw
|
|
29
|
+
where cw.thread_id = cp.thread_id
|
|
30
|
+
and cw.checkpoint_ns = cp.checkpoint_ns
|
|
31
|
+
and cw.checkpoint_id = cp.checkpoint_id
|
|
32
|
+
) as pending_writes
|
|
33
|
+
from ${E.checkpoints} cp `,SELECT_PENDING_SENDS_SQL:`select
|
|
34
|
+
checkpoint_id,
|
|
35
|
+
array_agg(array[cw.type::bytea, cw.blob] order by cw.task_id, cw.idx) as pending_sends
|
|
36
|
+
from ${E.checkpoint_writes} cw
|
|
37
|
+
where cw.thread_id = $1
|
|
38
|
+
and cw.checkpoint_id = any($2)
|
|
39
|
+
and cw.channel = '${u}'
|
|
40
|
+
group by cw.checkpoint_id
|
|
41
|
+
`,UPSERT_CHECKPOINT_BLOBS_SQL:`INSERT INTO ${E.checkpoint_blobs} (thread_id, checkpoint_ns, channel, version, type, blob)
|
|
42
|
+
VALUES ($1, $2, $3, $4, $5, $6)
|
|
43
|
+
ON CONFLICT (thread_id, checkpoint_ns, channel, version) DO NOTHING
|
|
44
|
+
`,UPSERT_CHECKPOINTS_SQL:`INSERT INTO ${E.checkpoints} (thread_id, checkpoint_ns, checkpoint_id, parent_checkpoint_id, checkpoint, metadata)
|
|
45
|
+
VALUES ($1, $2, $3, $4, $5, $6)
|
|
46
|
+
ON CONFLICT (thread_id, checkpoint_ns, checkpoint_id)
|
|
47
|
+
DO UPDATE SET
|
|
48
|
+
checkpoint = EXCLUDED.checkpoint,
|
|
49
|
+
metadata = EXCLUDED.metadata;
|
|
50
|
+
`,UPSERT_CHECKPOINT_WRITES_SQL:`INSERT INTO ${E.checkpoint_writes} (thread_id, checkpoint_ns, checkpoint_id, task_id, idx, channel, type, blob)
|
|
51
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
|
52
|
+
ON CONFLICT (thread_id, checkpoint_ns, checkpoint_id, task_id, idx) DO UPDATE SET
|
|
53
|
+
channel = EXCLUDED.channel,
|
|
54
|
+
type = EXCLUDED.type,
|
|
55
|
+
blob = EXCLUDED.blob;
|
|
56
|
+
`,INSERT_CHECKPOINT_WRITES_SQL:`INSERT INTO ${E.checkpoint_writes} (thread_id, checkpoint_ns, checkpoint_id, task_id, idx, channel, type, blob)
|
|
57
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
|
58
|
+
ON CONFLICT (thread_id, checkpoint_ns, checkpoint_id, task_id, idx) DO NOTHING
|
|
59
|
+
`,DELETE_CHECKPOINTS_SQL:`DELETE FROM ${E.checkpoints} WHERE thread_id = $1`,DELETE_CHECKPOINT_BLOBS_SQL:`DELETE FROM ${E.checkpoint_blobs} WHERE thread_id = $1`,DELETE_CHECKPOINT_WRITES_SQL:`DELETE FROM ${E.checkpoint_writes} WHERE thread_id = $1`}};var r$=($)=>{let E=g($);return[`CREATE TABLE IF NOT EXISTS ${E.checkpoint_migrations} (
|
|
60
|
+
v INTEGER PRIMARY KEY
|
|
61
|
+
);`,`CREATE TABLE IF NOT EXISTS ${E.checkpoints} (
|
|
62
|
+
thread_id TEXT NOT NULL,
|
|
63
|
+
checkpoint_ns TEXT NOT NULL DEFAULT '',
|
|
64
|
+
checkpoint_id TEXT NOT NULL,
|
|
65
|
+
parent_checkpoint_id TEXT,
|
|
66
|
+
type TEXT,
|
|
67
|
+
checkpoint JSONB NOT NULL,
|
|
68
|
+
metadata JSONB NOT NULL DEFAULT '{}',
|
|
69
|
+
PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id)
|
|
70
|
+
);`,`CREATE TABLE IF NOT EXISTS ${E.checkpoint_blobs} (
|
|
71
|
+
thread_id TEXT NOT NULL,
|
|
72
|
+
checkpoint_ns TEXT NOT NULL DEFAULT '',
|
|
73
|
+
channel TEXT NOT NULL,
|
|
74
|
+
version TEXT NOT NULL,
|
|
75
|
+
type TEXT NOT NULL,
|
|
76
|
+
blob BYTEA,
|
|
77
|
+
PRIMARY KEY (thread_id, checkpoint_ns, channel, version)
|
|
78
|
+
);`,`CREATE TABLE IF NOT EXISTS ${E.checkpoint_writes} (
|
|
79
|
+
thread_id TEXT NOT NULL,
|
|
80
|
+
checkpoint_ns TEXT NOT NULL DEFAULT '',
|
|
81
|
+
checkpoint_id TEXT NOT NULL,
|
|
82
|
+
task_id TEXT NOT NULL,
|
|
83
|
+
idx INTEGER NOT NULL,
|
|
84
|
+
channel TEXT NOT NULL,
|
|
85
|
+
type TEXT,
|
|
86
|
+
blob BYTEA NOT NULL,
|
|
87
|
+
PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id, task_id, idx)
|
|
88
|
+
);`,`ALTER TABLE ${E.checkpoint_blobs} ALTER COLUMN blob DROP not null;`]};var M=vG(o$(),1),y8=M.default.Client,v8=M.default.Pool,p8=M.default.Connection,m8=M.default.types,f8=M.default.Query,d8=M.default.DatabaseError,u8=M.default.escapeIdentifier,g8=M.default.escapeLiteral,c8=M.default.Result,l8=M.default.TypeOverrides,o8=M.default.defaults,MO=M.default;var pG={schema:"public"},mG=($)=>{return{...$,schema:$?.schema??pG.schema}},{Pool:fG}=MO,CO=class $ extends VO{pool;options;SQL_STATEMENTS;isSetup;constructor(E,_,O){super(_);this.pool=E,this.isSetup=!1,this.options=mG(O),this.SQL_STATEMENTS=a$(this.options.schema)}static fromConnString(E,_){return new $(new fG({connectionString:E}),void 0,_)}async setup(){let E=await this.pool.connect(),_=g(this.options.schema);try{await E.query(`CREATE SCHEMA IF NOT EXISTS "${this.options.schema}"`);let O=-1,G=r$(this.options.schema);try{let X=await E.query(`SELECT v FROM ${_.checkpoint_migrations} ORDER BY v DESC LIMIT 1`);if(X.rows.length>0)O=X.rows[0].v}catch(X){if(typeof X==="object"&&X!==null&&"code"in X&&typeof X.code==="string"&&X.code==="42P01")O=-1;else throw X}for(let X=O+1;X<G.length;X+=1)await E.query(G[X]),await E.query(`INSERT INTO ${_.checkpoint_migrations} (v) VALUES ($1)`,[X])}finally{E.release()}}async _loadCheckpoint(E,_){return{...E,channel_values:await this._loadBlobs(_)}}async _loadBlobs(E){if(!E||E.length===0)return{};let _=new TextDecoder,O=await Promise.all(E.filter(([,G])=>_.decode(G)!=="empty").map(async([G,X,U])=>[_.decode(G),await this.serde.loadsTyped(_.decode(X),U)]));return Object.fromEntries(O)}async _loadMetadata(E){let[_,O]=await this.serde.dumpsTyped(E);return this.serde.loadsTyped(_,O)}async _loadWrites(E){let _=new TextDecoder;return E?await Promise.all(E.map(async([O,G,X,U])=>[_.decode(O),_.decode(G),await this.serde.loadsTyped(_.decode(X),U)])):[]}async _dumpBlobs(E,_,O,G){if(Object.keys(G).length===0)return[];return Promise.all(Object.entries(G).map(async([X,U])=>{let[J,Z]=X in O?await this.serde.dumpsTyped(O[X]):["empty",null];return[E,_,X,U.toString(),J,Z?new Uint8Array(Z):void 0]}))}_dumpCheckpoint(E){let _={...E};if("channel_values"in _)delete _.channel_values;return _}async _dumpMetadata(E){let[,_]=await this.serde.dumpsTyped(E);return JSON.parse(new TextDecoder().decode(_).replace(/\0/g,""))}async _dumpWrites(E,_,O,G,X){return Promise.all(X.map(async([U,J],Z)=>{let[H,Y]=await this.serde.dumpsTyped(J);return[E,_,O,G,s$[U]??Z,U,H,new Uint8Array(Y)]}))}_searchWhere(E,_,O){let G=[],X=[];if(E?.configurable?.thread_id)G.push(`thread_id = $${X.length+1}`),X.push(E.configurable.thread_id);if(E?.configurable?.checkpoint_ns!==void 0&&E?.configurable?.checkpoint_ns!==null)G.push(`checkpoint_ns = $${X.length+1}`),X.push(E.configurable.checkpoint_ns);if(E?.configurable?.checkpoint_id)G.push(`checkpoint_id = $${X.length+1}`),X.push(E.configurable.checkpoint_id);if(_&&Object.keys(_).length>0)G.push(`metadata @> $${X.length+1}`),X.push(JSON.stringify(_));if(O?.configurable?.checkpoint_id!==void 0)G.push(`checkpoint_id < $${X.length+1}`),X.push(O.configurable.checkpoint_id);return[G.length>0?`WHERE ${G.join(" AND ")}`:"",X]}async getTuple(E){let{thread_id:_,checkpoint_ns:O="",checkpoint_id:G}=E.configurable??{},X,U;if(G)U="WHERE thread_id = $1 AND checkpoint_ns = $2 AND checkpoint_id = $3",X=[_,O,G];else U="WHERE thread_id = $1 AND checkpoint_ns = $2 ORDER BY checkpoint_id DESC LIMIT 1",X=[_,O];let[J]=(await this.pool.query(this.SQL_STATEMENTS.SELECT_SQL+U,X)).rows;if(J===void 0)return;if(J.checkpoint.v<4&&J.parent_checkpoint_id!=null){let[H]=(await this.pool.query(this.SQL_STATEMENTS.SELECT_PENDING_SENDS_SQL,[_,[J.parent_checkpoint_id]])).rows;if(H!=null)await this._migratePendingSends(H.pending_sends,J)}let Z=await this._loadCheckpoint(J.checkpoint,J.channel_values);return{config:{configurable:{thread_id:_,checkpoint_ns:O,checkpoint_id:J.checkpoint_id}},checkpoint:Z,metadata:await this._loadMetadata(J.metadata),parentConfig:J.parent_checkpoint_id?{configurable:{thread_id:_,checkpoint_ns:O,checkpoint_id:J.parent_checkpoint_id}}:void 0,pendingWrites:await this._loadWrites(J.pending_writes)}}async*list(E,_){let{filter:O,before:G,limit:X}=_??{},[U,J]=this._searchWhere(E,O,G),Z=`${this.SQL_STATEMENTS.SELECT_SQL}${U} ORDER BY checkpoint_id DESC`;if(X!==void 0)Z+=` LIMIT ${Number.parseInt(X.toString(),10)}`;let H=await this.pool.query(Z,J),Y=H.rows.filter((T)=>T.checkpoint.v<4&&T.parent_checkpoint_id!=null);if(Y.length>0){let T=await this.pool.query(this.SQL_STATEMENTS.SELECT_PENDING_SENDS_SQL,[Y[0].thread_id,Y.map((Q)=>Q.parent_checkpoint_id)]),K=Y.reduce((Q,C)=>{if(!C.parent_checkpoint_id)return Q;return Q[C.parent_checkpoint_id]??=[],Q[C.parent_checkpoint_id].push(C),Q},{});for(let Q of T.rows)for(let C of K[Q.checkpoint_id])await this._migratePendingSends(Q.pending_sends,C)}for(let T of H.rows)yield{config:{configurable:{thread_id:T.thread_id,checkpoint_ns:T.checkpoint_ns,checkpoint_id:T.checkpoint_id}},checkpoint:await this._loadCheckpoint(T.checkpoint,T.channel_values),metadata:await this._loadMetadata(T.metadata),parentConfig:T.parent_checkpoint_id?{configurable:{thread_id:T.thread_id,checkpoint_ns:T.checkpoint_ns,checkpoint_id:T.parent_checkpoint_id}}:void 0,pendingWrites:await this._loadWrites(T.pending_writes)}}async _migratePendingSends(E,_){let O=new TextEncoder,G=new TextDecoder,X=_,[U,J]=await this.serde.dumpsTyped(await Promise.all(E.map(([Z,H])=>this.serde.loadsTyped(G.decode(Z),H))));X.channel_values??=[],X.channel_values.push([O.encode(u),O.encode(U),J]),X.checkpoint.channel_versions[u]=Object.keys(_.checkpoint.channel_versions).length>0?SO(...Object.values(_.checkpoint.channel_versions)):this.getNextVersion(void 0)}async put(E,_,O,G){if(E.configurable===void 0)throw Error('Missing "configurable" field in "config" param');let{thread_id:X,checkpoint_ns:U="",checkpoint_id:J}=E.configurable,Z={configurable:{thread_id:X,checkpoint_ns:U,checkpoint_id:_.id}},H=await this.pool.connect(),Y=this._dumpCheckpoint(_);try{await H.query("BEGIN");let T=await this._dumpBlobs(X,U,_.channel_values,G);for(let K of T)await H.query(this.SQL_STATEMENTS.UPSERT_CHECKPOINT_BLOBS_SQL,K);await H.query(this.SQL_STATEMENTS.UPSERT_CHECKPOINTS_SQL,[X,U,_.id,J,Y,await this._dumpMetadata(O)]),await H.query("COMMIT")}catch(T){throw await H.query("ROLLBACK"),T}finally{H.release()}return Z}async putWrites(E,_,O){let G=_.every((J)=>(J[0]in s$))?this.SQL_STATEMENTS.UPSERT_CHECKPOINT_WRITES_SQL:this.SQL_STATEMENTS.INSERT_CHECKPOINT_WRITES_SQL,X=await this._dumpWrites(E.configurable?.thread_id,E.configurable?.checkpoint_ns,E.configurable?.checkpoint_id,O,_),U=await this.pool.connect();try{await U.query("BEGIN");for await(let J of X)await U.query(G,J);await U.query("COMMIT")}catch(J){throw await U.query("ROLLBACK"),J}finally{U.release()}}async end(){return this.pool.end()}async deleteThread(E){let _=await this.pool.connect();try{await _.query("BEGIN"),await _.query(this.SQL_STATEMENTS.DELETE_CHECKPOINT_BLOBS_SQL,[E]),await _.query(this.SQL_STATEMENTS.DELETE_CHECKPOINTS_SQL,[E]),await _.query(this.SQL_STATEMENTS.DELETE_CHECKPOINT_WRITES_SQL,[E]),await _.query("COMMIT")}catch(O){throw await _.query("ROLLBACK"),O}finally{_.release()}}};var $3=async()=>{let $=CO.fromConnString(process.env.DATABASE_URL);if(process.env.DATABASE_INIT==="true")console.debug("LG | Initializing postgres checkpoint"),await $.setup();return $};export{$3 as createPGCheckpoint};
|