Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Huge stacktrace #14

Closed
retrohacker opened this issue Apr 6, 2023 · 3 comments
Closed

Huge stacktrace #14

retrohacker opened this issue Apr 6, 2023 · 3 comments

Comments

@retrohacker
Copy link

When an exception is thrown from down inside the library in a cloudflare worker, the resulting stacktrace in the logs is massive. Not sure if there is a way to clean this up, but it's a real bummer because it pushes your console.log statements way up in the terminal. Here is some example output:

[api] [0] ✘ [ERROR] Uncaught (in promise) error: relation "users" does not exist
[api] [0] 
[api] [0]   `});var As={};le(As,{Socket:()=>J,isIP:()=>pc});function pc(r){return 0}var bs,G,J,Mt=te(()=>{"use strict";d();bs=lt(be(),1);vs();Es();G=class extends bs.EventEmitter{constructor(){super(...arguments);g(this,"defaultsKey","other");g(this,"_webSocketConstructor");g(this,"_wsProxy");g(this,"_coalesceWrites");g(this,"_useSecureWebSocket");g(this,"_disableSNI");g(this,"_pipelineConnect");g(this,"_pipelineTLS");g(this,"_rootCerts");g(this,"connecting",!1);g(this,"pending",!0);g(this,"writable",!0);g(this,"encrypted",!1);g(this,"authorized",!1);g(this,"destroyed",!1);g(this,"ws",null);g(this,"writeBuffer");g(this,"tlsState",0);g(this,"tlsRead");g(this,"tlsWrite")}get webSocketConstructor(){return this._webSocketConstructor??G.webSocketConstructor??G.defaults[this.defaultsKey].webSocketConstructor}set webSocketConstructor(t){this._webSocketConstructor=t}get wsProxy(){return this._wsProxy??G.wsProxy??G.defaults[this.defaultsKey].wsProxy}set wsProxy(t){this._wsProxy=t}get coalesceWrites(){return this._coalesceWrites??G.coalesceWrites??G.defaults[this.defaultsKey].coalesceWrites}set coalesceWrites(t){this._coalesceWrites=t}get useSecureWebSocket(){return this._useSecureWebSocket??G.useSecureWebSocket??G.defaults[this.defaultsKey].useSecureWebSocket}set useSecureWebSocket(t){this._useSecureWebSocket=t}get disableSNI(){return this._disableSNI??G.disableSNI??G.defaults[this.defaultsKey].disableSNI}set disableSNI(t){this._disableSNI=t}get pipelineConnect(){return this._pipelineConnect??G.pipelineConnect??G.defaults[this.defaultsKey].pipelineConnect}set pipelineConnect(t){this._pipelineConnect=t}get pipelineTLS(){return this._pipelineTLS??G.pipelineTLS??G.defaults[this.defaultsKey].pipelineTLS}set pipelineTLS(t){this._pipelineTLS=t}get rootCerts(){return this._rootCerts??G.rootCerts??G.defaults[this.defaultsKey].rootCerts}set rootCerts(t){this._rootCerts=t}wsProxyAddrForHost(t,n){let i=this.wsProxy;if(i===void 0){let s=`No WebSocket proxy is configured on the Neon serverless driver for database host "${t}". `,o="That's the fallback host when none is specified, so perhaps an environment variable (such as DATABASE_URL) is missing? ",a=`If "${t}" is the host you expected, then you'll need to set the 'wsProxy' option on the driver (see: https://github.com/neondatabase/serverless#run-your-own-websocket-proxy).`,u=s+(t==="localhost"?o:"")+a;throw new Error(u)}return typeof i=="function"?i(t,n):`${i}?address=${t}:${n}`}setNoDelay(){return this}setKeepAlive(){return this}ref(){return this}unref(){return this}async connect(t,n,i){/[.]neon[.](tech|build)(:|$)/.test(n)&&(this.defaultsKey="neon"),this.connecting=!0,i&&this.once("connect",i);let s=this.wsProxyAddrForHost(n,typeof t=="string"?parseInt(t,10):t);return this.ws=await new Promise(async o=>{try{let u=(this.useSecureWebSocket?"wss:":"ws:")+"//"+s,c;if(this.webSocketConstructor!==void 0)c=new this.webSocketConstructor(u);else try{c=new WebSocket(u)}catch{try{c=new __unstable_WebSocket(u)}catch{let{default:w}=await import(String.fromCharCode(119)+String.fromCharCode(115));c=new w(u)}}c.addEventListener("open",()=>{o(c)})}catch(a){try{let c=(this.useSecureWebSocket?"https:":"http:")+"//"+s;await fetch(c,{headers:{Upgrade:"websocket"}}).then(h=>{let f=h.webSocket;if(f==null)throw a;f.accept(),o(f)})}catch{throw new Error("All attempts to open a WebSocket to connect to the database failed. If using Node, please install the `ws` package (or simply use the `pg` package instead).")}}}),this.ws.binaryType="arraybuffer",this.ws.addEventListener("error",o=>{this.emit("error",o)}),this.ws.addEventListener("close",()=>{this.emit("close")}),this.ws.addEventListener("message",o=>{if(this.tlsState===0){let a=p.from(o.data);this.emit("data",a)}}),this.connecting=!1,this.pending=!1,this.emit("connect"),this.emit("ready"),this}async startTls(t){this.tlsState=1;let n=qr.fromPEM(Rt),i=new xs(this.ws),s=i.read.bind(i),o=this.rawWrite.bind(this),[a,u]=await Ss(t,n,s,o,!this.disableSNI,void 0,this.pipelineTLS?new Uint8Array([83]):void 0);this.tlsRead=a,this.tlsWrite=u,this.tlsState=2,this.encrypted=!0,this.authorized=!0,this.emit("secureConnection",this),this.tlsReadLoop()}async tlsReadLoop(){for(;;){let t=await this.tlsRead();if(t===void 0)break;{let n=p.from(t);this.emit("data",n)}}}rawWrite(t){if(!this.coalesceWrites){this.ws.send(t);return}if(this.writeBuffer===void 0)this.writeBuffer=t,setTimeout(()=>{this.ws.send(this.writeBuffer),this.writeBuffer=void 0},0);else{let n=new Uint8Array(this.writeBuffer.length+t.length);n.set(this.writeBuffer),n.set(t,this.writeBuffer.length),this.writeBuffer=n}}write(t,n="utf8",i=s=>{}){return t.length===0?i():(typeof t=="string"&&(t=p.from(t,n)),this.tlsState===0?this.rawWrite(t):this.tlsState===1?this.once("secureConnection",()=>this.write(t,n,i)):this.tlsWrite(t),!0)}end(t=p.alloc(0),n="utf8",i){return this.write(t,n,()=>{this.ws.close(),i&&i()}),this}destroy(){return this.destroyed=!0,this.end()}},J=G;g(J,"addNeonProjectToPassword",!1),g(J,"defaults",{neon:{webSocketConstructor:void 0,wsProxy:t=>t+"/v2",useSecureWebSocket:!0,coalesceWrites:!0,disableSNI:!1,pipelineConnect:"password",pipelineTLS:!0,rootCerts:Rt},other:{webSocketConstructor:void 0,wsProxy:void 0,useSecureWebSocket:!0,coalesceWrites:!0,disableSNI:!1,pipelineConnect:!1,pipelineTLS:!1,rootCerts:Rt}}),g(J,"webSocketConstructor"),g(J,"wsProxy"),g(J,"coalesceWrites"),g(J,"useSecureWebSocket"),g(J,"disableSNI"),g(J,"pipelineConnect"),g(J,"pipelineTLS"),g(J,"rootCerts")});var tn=C(A=>{"use strict";d();Object.defineProperty(A,"__esModule",{value:!0});A.NoticeMessage=A.DataRowMessage=A.CommandCompleteMessage=A.ReadyForQueryMessage=A.NotificationResponseMessage=A.BackendKeyDataMessage=A.AuthenticationMD5Password=A.ParameterStatusMessage=A.ParameterDescriptionMessage=A.RowDescriptionMessage=A.Field=A.CopyResponse=A.CopyDataMessage=A.DatabaseError=A.copyDone=A.emptyQuery=A.replicationStart=A.portalSuspended=A.noData=A.closeComplete=A.bindComplete=A.parseComplete=void 0;A.parseComplete={name:"parseComplete",length:5};A.bindComplete={name:"bindComplete",length:5};A.closeComplete={name:"closeComplete",length:5};A.noData={name:"noData",length:5};A.portalSuspended={name:"portalSuspended",length:5};A.replicationStart={name:"replicationStart",length:4};A.emptyQuery={name:"emptyQuery",length:4};A.copyDone={name:"copyDone",length:4};var Qr=class extends Error{constructor(e,t,n){super(e),this.length=t,this.name=n}};A.DatabaseError=Qr;var Hr=class{constructor(e,t){this.length=e,this.chunk=t,this.name="copyData"}};A.CopyDataMessage=Hr;var jr=class{constructor(e,t,n,i){this.length=e,this.name=t,this.binary=n,this.columnTypes=new Array(i)}};A.CopyResponse=jr;var Kr=class{constructor(e,t,n,i,s,o,a){this.name=e,this.tableID=t,this.columnID=n,this.dataTypeID=i,this.dataTypeSize=s,this.dataTypeModifier=o,this.format=a}};A.Field=Kr;var $r=class{constructor(e,t){this.length=e,this.fieldCount=t,this.name="rowDescription",this.fields=new Array(this.fieldCount)}};A.RowDescriptionMessage=$r;var Wr=class{constructor(e,t){this.length=e,this.parameterCount=t,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}};A.ParameterDescriptionMessage=Wr;var Gr=class{constructor(e,t,n){this.length=e,this.parameterName=t,this.parameterValue=n,this.name="parameterStatus"}};A.ParameterStatusMessage=Gr;var Vr=class{constructor(e,t){this.length=e,this.salt=t,this.name="authenticationMD5Password"}};A.AuthenticationMD5Password=Vr;var zr=class{constructor(e,t,n){this.length=e,this.processID=t,this.secretKey=n,this.name="backendKeyData"}};A.BackendKeyDataMessage=zr;var Yr=class{constructor(e,t,n,i){this.length=e,this.processId=t,this.channel=n,this.payload=i,this.name="notification"}};A.NotificationResponseMessage=Yr;var Jr=class{constructor(e,t){this.length=e,this.status=t,this.name="readyForQuery"}};A.ReadyForQueryMessage=Jr;var Zr=class{constructor(e,t){this.length=e,this.text=t,this.name="commandComplete"}};A.CommandCompleteMessage=Zr;var Xr=class{constructor(e,t){this.length=e,this.fields=t,this.name="dataRow",this.fieldCount=t.length}};A.DataRowMessage=Xr;var en=class{constructor(e,t){this.length=e,this.message=t,this.name="notice"}};A.NoticeMessage=en});var _s=C(kt=>{"use strict";d();Object.defineProperty(kt,"__esModule",{value:!0});kt.Writer=void 0;var rn=class{constructor(e=256){this.size=e,this.offset=5,this.headerPosition=0,this.buffer=p.allocUnsafe(e)}ensure(e){var t=this.buffer.length-this.offset;if(t<e){var n=this.buffer,i=n.length+(n.length>>1)+e;this.buffer=p.allocUnsafe(i),n.copy(this.buffer)}}addInt32(e){return this.ensure(4),this.buffer[this.offset++]=e>>>24&255,this.buffer[this.offset++]=e>>>16&255,this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addInt16(e){return this.ensure(2),this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addCString(e){if(!e)this.ensure(1);else{var t=p.byteLength(e);this.ensure(t+1),this.buffer.write(e,this.offset,"utf-8"),this.offset+=t}return this.buffer[this.offset++]=0,this}addString(e=""){var t=p.byteLength(e);return this.ensure(t),this.buffer.write(e,this.offset),this.offset+=t,this}add(e){return this.ensure(e.length),e.copy(this.buffer,this.offset),this.offset+=e.length,this}join(e){if(e){this.buffer[this.headerPosition]=e;let t=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(t,this.headerPosition+1)}return this.buffer.slice(e?0:5,this.offset)}flush(e){var t=this.join(e);return this.offset=5,this.headerPosition=0,this.buffer=p.allocUnsafe(this.size),t}};kt.Writer=rn});var Us=C(Nt=>{"use strict";d();Object.defineProperty(Nt,"__esModule",{value:!0});Nt.serialize=void 0;var nn=_s(),O=new nn.Writer,yc=r=>{O.addInt16(3).addInt16(0);for(let n of Object.keys(r))O.addCString(n).addCString(r[n]);O.addCString("client_encoding").addCString("UTF8");var e=O.addCString("").flush(),t=e.length+4;return new nn.Writer().addInt32(t).add(e).flush()},wc=()=>{let r=p.allocUnsafe(8);return r.writeInt32BE(8,0),r.writeInt32BE(80877103,4),r},mc=r=>O.addCString(r).flush(112),gc=function(r,e){return O.addCString(r).addInt32(p.byteLength(e)).addString(e),O.flush(112)},Sc=function(r){return O.addString(r).flush(112)},xc=r=>O.addCString(r).flush(81),Cs=[],vc=r=>{let e=r.name||"";e.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",e,e.length),console.error("This can cause conflicts and silent errors executing queries"));let t=r.types||Cs;for(var n=t.length,i=O.addCString(e).addCString(r.text).addInt16(n),s=0;s<n;s++)i.addInt32(t[s]);return O.flush(80)},He=new nn.Writer,Ec=function(r,e){for(let t=0;t<r.length;t++){let n=e?e(r[t],t):r[t];n==null?(O.addInt16(0),He.addInt32(-1)):n instanceof p?(O.addInt16(1),He.addInt32(n.length),He.add(n)):(O.addInt16(0),He.addInt32(p.byteLength(n)),He.addString(n))}},bc=(r={})=>{let e=r.portal||"",t=r.statement||"",n=r.binary||!1,i=r.values||Cs,s=i.length;return O.addCString(e).addCString(t),O.addInt16(s),Ec(i,r.valueMapper),O.addInt16(s),O.add(He.flush()),O.addInt16(n?1:0),O.flush(66)},Ac=p.from([69,0,0,0,9,0,0,0,0,0]),_c=r=>{if(!r||!r.portal&&!r.rows)return Ac;let e=r.portal||"",t=r.rows||0,n=p.byteLength(e),i=4+n+1+4,s=p.allocUnsafe(1+i);return s[0]=69,s.writeInt32BE(i,1),s.write(e,5,"utf-8"),s[n+5]=0,s.writeUInt32BE(t,s.length-4),s},Cc=(r,e)=>{let t=p.allocUnsafe(16);return t.writeInt32BE(16,0),t.writeInt16BE(1234,4),t.writeInt16BE(5678,6),t.writeInt32BE(r,8),t.writeInt32BE(e,12),t},sn=(r,e)=>{let n=4+p.byteLength(e)+1,i=p.allocUnsafe(1+n);return i[0]=r,i.writeInt32BE(n,1),i.write(e,5,"utf-8"),i[n]=0,i},Uc=O.addCString("P").flush(68),Ic=O.addCString("S").flush(68),Lc=r=>r.name?sn(68,`${r.type}${r.name||""}`):r.type==="P"?Uc:Ic,Tc=r=>{let e=`${r.type}${r.name||""}`;return sn(67,e)},Bc=r=>O.add(r).flush(100),Pc=r=>sn(102,r),Ft=r=>p.from([r,0,0,0,4]),Rc=Ft(72),Mc=Ft(83),kc=Ft(88),Fc=Ft(99),Nc={startup:yc,password:mc,requestSsl:wc,sendSASLInitialResponseMessage:gc,sendSCRAMClientFinalMessage:Sc,query:xc,parse:vc,bind:bc,execute:_c,describe:Lc,close:Tc,flush:()=>Rc,sync:()=>Mc,end:()=>kc,copyData:Bc,copyDone:()=>Fc,copyFail:Pc,cancel:Cc};Nt.serialize=Nc});var Is=C(Dt=>{"use strict";d();Object.defineProperty(Dt,"__esModule",{value:!0});Dt.BufferReader=void 0;var Dc=p.allocUnsafe(0),on=class{constructor(e=0){this.offset=e,this.buffer=Dc,this.encoding="utf-8"}setBuffer(e,t){this.offset=e,this.buffer=t}int16(){let e=this.buffer.readInt16BE(this.offset);return this.offset+=2,e}byte(){let e=this.buffer[this.offset];return this.offset++,e}int32(){let e=this.buffer.readInt32BE(this.offset);return this.offset+=4,e}string(e){let t=this.buffer.toString(this.encoding,this.offset,this.offset+e);return this.offset+=e,t}cstring(){let e=this.offset,t=e;for(;this.buffer[t++]!==0;);return this.offset=t,this.buffer.toString(this.encoding,e,t-1)}bytes(e){let t=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t}};Dt.BufferReader=on});var Ls={};le(Ls,{default:()=>Oc});var Oc,Ts=te(()=>{d();Oc={}});var Rs=C(je=>{"use strict";d();var qc=je&&je.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(je,"__esModule",{value:!0});je.Parser=void 0;var H=tn(),Qc=Is(),Hc=qc((Ts(),j(Ls))),an=1,jc=4,Bs=an+jc,Ps=p.allocUnsafe(0),un=class{constructor(e){if(this.buffer=Ps,this.bufferLength=0,this.bufferOffset=0,this.reader=new Qc.BufferReader,e?.mode==="binary")throw new Error("Binary mode not supported yet");this.mode=e?.mode||"text"}parse(e,t){this.mergeBuffer(e);let n=this.bufferOffset+this.bufferLength,i=this.bufferOffset;for(;i+Bs<=n;){let s=this.buffer[i],o=this.buffer.readUInt32BE(i+an),a=an+o;if(a+i<=n){let u=this.handlePacket(i+Bs,s,o,this.buffer);t(u),i+=a}else break}i===n?(this.buffer=Ps,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=n-i,this.bufferOffset=i)}mergeBuffer(e){if(this.bufferLength>0){let t=this.bufferLength+e.byteLength;if(t+this.bufferOffset>this.buffer.byteLength){let i;if(t<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)i=this.buffer;else{let s=this.buffer.byteLength*2;for(;t>=s;)s*=2;i=p.allocUnsafe(s)}this.buffer.copy(i,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=i,this.bufferOffset=0}e.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=t}else this.buffer=e,this.bufferOffset=0,this.bufferLength=e.byteLength}handlePacket(e,t,n,i){switch(t){case 50:return H.bindComplete;case 49:return H.parseComplete;case 51:return H.closeComplete;case 110:return H.noData;case 115:return H.portalSuspended;case 99:return H.copyDone;case 87:return H.replicationStart;case 73:return H.emptyQuery;case 68:return this.parseDataRowMessage(e,n,i);case 67:return this.parseCommandCompleteMessage(e,n,i);case 90:return this.parseReadyForQueryMessage(e,n,i);case 65:return this.parseNotificationMessage(e,n,i);case 82:return this.parseAuthenticationResponse(e,n,i);case 83:return this.parseParameterStatusMessage(e,n,i);case 75:return this.parseBackendKeyData(e,n,i);case 69:return this.parseErrorMessage(e,n,i,"error");case 78:return this.parseErrorMessage(e,n,i,"notice");case 84:return this.parseRowDescriptionMessage(e,n,i);case 116:return this.parseParameterDescriptionMessage(e,n,i);case 71:return this.parseCopyInMessage(e,n,i);case 72:return this.parseCopyOutMessage(e,n,i);case 100:return this.parseCopyData(e,n,i);default:Hc.default.fail(`unknown message code: ${t.toString(16)}`)}}parseReadyForQueryMessage(e,t,n){this.reader.setBuffer(e,n);let i=this.reader.string(1);return new H.ReadyForQueryMessage(t,i)}parseCommandCompleteMessage(e,t,n){this.reader.setBuffer(e,n);let i=this.reader.cstring();return new H.CommandCompleteMessage(t,i)}parseCopyData(e,t,n){let i=n.slice(e,e+(t-4));return new H.CopyDataMessage(t,i)}parseCopyInMessage(e,t,n){return this.parseCopyMessage(e,t,n,"copyInResponse")}parseCopyOutMessage(e,t,n){return this.parseCopyMessage(e,t,n,"copyOutResponse")}parseCopyMessage(e,t,n,i){this.reader.setBuffer(e,n);let s=this.reader.byte()!==0,o=this.reader.int16(),a=new H.CopyResponse(t,i,s,o);for(let u=0;u<o;u++)a.columnTypes[u]=this.reader.int16();return a}parseNotificationMessage(e,t,n){this.reader.setBuffer(e,n);let i=this.reader.int32(),s=this.reader.cstring(),o=this.reader.cstring();return new H.NotificationResponseMessage(t,i,s,o)}parseRowDescriptionMessage(e,t,n){this.reader.setBuffer(e,n);let i=this.reader.int16(),s=new H.RowDescriptionMessage(t,i);for(let o=0;o<i;o++)s.fields[o]=this.parseField();return s}parseField(){let e=this.reader.cstring(),t=this.reader.int32(),n=this.reader.int16(),i=this.reader.int32(),s=this.reader.int16(),o=this.reader.int32(),a=this.reader.int16()===0?"text":"binary";return new H.Field(e,t,n,i,s,o,a)}parseParameterDescriptionMessage(e,t,n){this.reader.setBuffer(e,n);let i=this.reader.int16(),s=new H.ParameterDescriptionMessage(t,i);for(let o=0;o<i;o++)s.dataTypeIDs[o]=this.reader.int32();return s}parseDataRowMessage(e,t,n){this.reader.setBuffer(e,n);let i=this.reader.int16(),s=new Array(i);for(let o=0;o<i;o++){let a=this.reader.int32();s[o]=a===-1?null:this.reader.string(a)}return new H.DataRowMessage(t,s)}parseParameterStatusMessage(e,t,n){this.reader.setBuffer(e,n);let i=this.reader.cstring(),s=this.reader.cstring();return new H.ParameterStatusMessage(t,i,s)}parseBackendKeyData(e,t,n){this.reader.setBuffer(e,n);let i=this.reader.int32(),s=this.reader.int32();return new H.BackendKeyDataMessage(t,i,s)}parseAuthenticationResponse(e,t,n){this.reader.setBuffer(e,n);let i=this.reader.int32(),s={name:"authenticationOk",length:t};switch(i){case 0:break;case 3:s.length===8&&(s.name="authenticationCleartextPassword");break;case 5:if(s.length===12){s.name="authenticationMD5Password";let a=this.reader.bytes(4);return new H.AuthenticationMD5Password(t,a)}break;case 10:s.name="authenticationSASL",s.mechanisms=[];let o;do o=this.reader.cstring(),o&&s.mechanisms.push(o);while(o);break;case 11:s.name="authenticationSASLContinue",s.data=this.reader.string(t-8);break;case 12:s.name="authenticationSASLFinal",s.data=this.reader.string(t-8);break;default:throw new Error("Unknown authenticationOk message type "+i)}return s}parseErrorMessage(e,t,n,i){this.reader.setBuffer(e,n);let s={},o=this.reader.string(1);for(;o!=="\0";)s[o]=this.reader.cstring(),o=this.reader.string(1);let a=s.M,u=i==="notice"?new H.NoticeMessage(t,a):new H.DatabaseError(a,t,i);return u.severity=s.S,u.code=s.C,u.detail=s.D,u.hint=s.H,u.position=s.P,u.internalPosition=s.p,u.internalQuery=s.q,u.where=s.W,u.schema=s.s,u.table=s.t,u.column=s.c,u.dataType=s.d,u.constraint=s.n,u.file=s.F,u.line=s.L,u.routine=s.R,u}};je.Parser=un});var cn=C(Ce=>{"use strict";d();Object.defineProperty(Ce,"__esModule",{value:!0});Ce.DatabaseError=Ce.serialize=Ce.parse=void 0;var Kc=tn();Object.defineProperty(Ce,"DatabaseError",{enumerable:!0,get:function(){return Kc.DatabaseError}});var $c=Us();Object.defineProperty(Ce,"serialize",{enumerable:!0,get:function(){return $c.serialize}});var Wc=Rs();function Gc(r,e){let t=new Wc.Parser;return r.on("data",n=>t.parse(n,e)),new Promise(n=>r.on("end",()=>n()))}Ce.parse=Gc});var Ms={};le(Ms,{connect:()=>Vc});function Vc(r){let{socket:e,servername:t}=r;return e.startTls(t),e}var ks=te(()=>{d()});var ln=C((df,Ns)=>{"use strict";d();var Fs=(Mt(),j(As)),zc=be().EventEmitter,{parse:Yc,serialize:V}=cn(),Jc=V.flush(),Zc=V.sync(),Xc=V.end(),hn=class extends zc{constructor(e){super(),e=e||{},this.stream=e.stream||new Fs.Socket,typeof this.stream=="function"&&(this.stream=this.stream(e)),this._keepAlive=e.keepAlive,this._keepAliveInitialDelayMillis=e.keepAliveInitialDelayMillis,this.lastBuffer=!1,this.parsedStatements={},this.ssl=e.ssl||!1,this._ending=!1,this._emitMessage=!1;var t=this;this.on("newListener",function(n){n==="message"&&(t._emitMessage=!0)})}connect(e,t){var n=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(e,t),this.stream.once("connect",function(){n._keepAlive&&n.stream.setKeepAlive(!0,n._keepAliveInitialDelayMillis),n.emit("connect")});let i=function(s){n._ending&&(s.code==="ECONNRESET"||s.code==="EPIPE")||n.emit("error",s)};if(this.stream.on("error",i),this.stream.on("close",function(){n.emit("end")}),!this.ssl)return this.attachListeners(this.stream);this.stream.once("data",function(s){var o=s.toString("utf8");switch(o){case"S":break;case"N":return n.stream.end(),n.emit("error",new Error("The server does not support SSL connections"));default:return n.stream.end(),n.emit("error",new Error("There was an error establishing an SSL connection"))}var a=(ks(),j(Ms));let u={socket:n.stream};n.ssl!==!0&&(Object.assign(u,n.ssl),"key"in n.ssl&&(u.key=n.ssl.key)),Fs.isIP(t)===0&&(u.servername=t);try{n.stream=a.connect(u)}catch(c){return n.emit("error",c)}n.attachListeners(n.stream),n.stream.on("error",i),n.emit("sslconnect")})}attachListeners(e){e.on("end",()=>{this.emit("end")}),Yc(e,t=>{var n=t.name==="error"?"errorMessage":t.name;this._emitMessage&&this.emit("message",t),this.emit(n,t)})}requestSsl(){this.stream.write(V.requestSsl())}startup(e){this.stream.write(V.startup(e))}cancel(e,t){this._send(V.cancel(e,t))}password(e){this._send(V.password(e))}sendSASLInitialResponseMessage(e,t){this._send(V.sendSASLInitialResponseMessage(e,t))}sendSCRAMClientFinalMessage(e){this._send(V.sendSCRAMClientFinalMessage(e))}_send(e){return this.stream.writable?this.stream.write(e):!1}query(e){this._send(V.query(e))}parse(e){this._send(V.parse(e))}bind(e){this._send(V.bind(e))}execute(e){this._send(V.execute(e))}flush(){this.stream.writable&&this.stream.write(Jc)}sync(){this._ending=!0,this._send(Zc)}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(Xc,()=>{this.stream.end()})}close(e){this._send(V.close(e))}describe(e){this._send(V.describe(e))}sendCopyFromChunk(e){this._send(V.copyData(e))}endCopyFrom(){this._send(V.copyDone())}sendCopyFail(e){this._send(V.copyFail(e))}};Ns.exports=hn});var qs=C((yf,Os)=>{"use strict";d();var eh=be().EventEmitter,th=xt(),fn=Fi(),rh=Gi(),nh=_r(),ih=Tr(),Ds=cs(),sh=rt(),oh=ln(),Ot=class extends eh{constructor(e){super(),this.connectionParameters=new ih(e),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;var t=e||{};this._Promise=t.Promise||v.Promise,this._types=new nh(t.types),this._ending=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this.connection=t.connection||new oh({stream:t.stream,ssl:this.connectionParameters.ssl,keepAlive:t.keepAlive||!1,keepAliveInitialDelayMillis:t.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this.queryQueue=[],this.binary=t.binary||sh.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=t.connectionTimeoutMillis||0}_errorAllQueries(e){let t=n=>{y.nextTick(()=>{n.handleError(e,this.connection)})};this.activeQuery&&(t(this.activeQuery),this.activeQuery=null),this.queryQueue.forEach(t),this.queryQueue.length=0}_connect(e){var t=this,n=this.connection;if(this._connectionCallback=e,this._connecting||this._connected){let i=new Error("Client has already been connected. You cannot reuse a client.");y.nextTick(()=>{e(i)});return}this._connecting=!0,this.connectionTimeoutHandle,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{n._ending=!0,n.stream.destroy(new Error("timeout expired"))},this._connectionTimeoutMillis)),this.host&&this.host.indexOf("/")===0?n.connect(this.host+"/.s.PGSQL."+this.port):n.connect(this.port,this.host),n.on("connect",function(){t.ssl?n.requestSsl():n.startup(t.getStartupConf())}),n.on("sslconnect",function(){n.startup(t.getStartupConf())}),this._attachListeners(n),n.once("end",()=>{let i=this._ending?new Error("Connection terminated"):new Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(i),this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(i):this._handleErrorEvent(i):this._connectionError||this._handleErrorEvent(i)),y.nextTick(()=>{this.emit("end")})})}connect(e){if(e){this._connect(e);return}return new this._Promise((t,n)=>{this._connect(i=>{i?n(i):t()})})}_attachListeners(e){e.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),e.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),e.on("authenticationSASL",this._handleAuthSASL.bind(this)),e.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),e.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),e.on("backendKeyData",this._handleBackendKeyData.bind(this)),e.on("error",this._handleErrorEvent.bind(this)),e.on("errorMessage",this._handleErrorMessage.bind(this)),e.on("readyForQuery",this._handleReadyForQuery.bind(this)),e.on("notice",this._handleNotice.bind(this)),e.on("rowDescription",this._handleRowDescription.bind(this)),e.on("dataRow",this._handleDataRow.bind(this)),e.on("portalSuspended",this._handlePortalSuspended.bind(this)),e.on("emptyQuery",this._handleEmptyQuery.bind(this)),e.on("commandComplete",this._handleCommandComplete.bind(this)),e.on("parseComplete",this._handleParseComplete.bind(this)),e.on("copyInResponse",this._handleCopyInResponse.bind(this)),e.on("copyData",this._handleCopyData.bind(this)),e.on("notification",this._handleNotification.bind(this))}_checkPgPass(e){let t=this.connection;typeof this.password=="function"?this._Promise.resolve().then(()=>this.password()).then(n=>{if(n!==void 0){if(typeof n!="string"){t.emit("error",new TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=n}else this.connectionParameters.password=this.password=null;e()}).catch(n=>{t.emit("error",n)}):this.password!==null?e():rh(this.connectionParameters,n=>{n!==void 0&&(this.connectionParameters.password=this.password=n),e()})}_handleAuthCleartextPassword(e){this._checkPgPass(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){this._checkPgPass(()=>{let t=th.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(t)})}_handleAuthSASL(e){this._checkPgPass(()=>{try{this.saslSession=fn.startSession(e.mechanisms),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(t){this.connection.emit("error",t)}})}_handleAuthSASLContinue(e){try{fn.continueSession(this.saslSession,this.password,e.data),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(t){this.connection.emit("error",t)}}_handleAuthSASLFinal(e){try{fn.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(t){this.connection.emit("error",t)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let{activeQuery:t}=this;this.activeQuery=null,this.readyForQuery=!0,t&&t.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit("error",e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit("error",e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let t=this.activeQuery;if(!t){this._handleErrorEvent(e);return}this.activeQuery=null,t.handleError(e,this.connection)}_handleRowDescription(e){this.activeQuery.handleRowDescription(e)}_handleDataRow(e){this.activeQuery.handleDataRow(e)}_handlePortalSuspended(e){this.activeQuery.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){this.activeQuery.handleEmptyQuery(this.connection)}_handleCommandComplete(e){this.activeQuery.handleCommandComplete(e,this.connection)}_handleParseComplete(e){this.activeQuery.name&&(this.connection.parsedStatements[this.activeQuery.name]=this.activeQuery.text)}_handleCopyInResponse(e){this.activeQuery.handleCopyInResponse(this.connection)}_handleCopyData(e){this.activeQuery.handleCopyData(e,this.connection)}_handleNotification(e){this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){var e=this.connectionParameters,t={user:e.user,database:e.database},n=e.application_name||e.fallback_application_name;return n&&(t.application_name=n),e.replication&&(t.replication=""+e.replication),e.statement_timeout&&(t.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(t.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(t.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(t.options=e.options),t}cancel(e,t){if(e.activeQuery===t){var n=this.connection;this.host&&this.host.indexOf("/")===0?n.connect(this.host+"/.s.PGSQL."+this.port):n.connect(this.port,this.host),n.on("connect",function(){n.cancel(e.processID,e.secretKey)})}else e.queryQueue.indexOf(t)!==-1&&e.queryQueue.splice(e.queryQueue.indexOf(t),1)}setTypeParser(e,t,n){return this._types.setTypeParser(e,t,n)}getTypeParser(e,t){return this._types.getTypeParser(e,t)}escapeIdentifier(e){return'"'+e.replace(/"/g,'""')+'"'}escapeLiteral(e){for(var t=!1,n="'",i=0;i<e.length;i++){var s=e[i];s==="'"?n+=s+s:s==="\\"?(n+=s+s,t=!0):n+=s}return n+="'",t===!0&&(n=" E"+n),n}_pulseQueryQueue(){if(this.readyForQuery===!0)if(this.activeQuery=this.queryQueue.shift(),this.activeQuery){this.readyForQuery=!1,this.hasExecuted=!0;let e=this.activeQuery.submit(this.connection);e&&y.nextTick(()=>{this.activeQuery.handleError(e,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this.activeQuery=null,this.emit("drain"))}query(e,t,n){var i,s,o,a,u;if(e==null)throw new TypeError("Client was passed a null or undefined query");return typeof e.submit=="function"?(o=e.query_timeout||this.connectionParameters.query_timeout,s=i=e,typeof t=="function"&&(i.callback=i.callback||t)):(o=this.connectionParameters.query_timeout,i=new Ds(e,t,n),i.callback||(s=new this._Promise((c,h)=>{i.callback=(f,w)=>f?h(f):c(w)}))),o&&(u=i.callback,a=setTimeout(()=>{var c=new Error("Query read timeout");y.nextTick(()=>{i.handleError(c,this.connection)}),u(c),i.callback=()=>{};var h=this.queryQueue.indexOf(i);h>-1&&this.queryQueue.splice(h,1),this._pulseQueryQueue()},o),i.callback=(c,h)=>{clearTimeout(a),u(c,h)}),this.binary&&!i.binary&&(i.binary=!0),i._result&&!i._result._types&&(i._result._types=this._types),this._queryable?this._ending?(y.nextTick(()=>{i.handleError(new Error("Client was closed and is not queryable"),this.connection)}),s):(this.queryQueue.push(i),this._pulseQueryQueue(),s):(y.nextTick(()=>{i.handleError(new Error("Client has encountered a connection error and is not queryable"),this.connection)}),s)}ref(){this.connection.ref()}unref(){this.connection.unref()}end(e){if(this._ending=!0,!this.connection._connecting)if(e)e();else return this._Promise.resolve();if(this.activeQuery||!this._queryable?this.connection.stream.destroy():this.connection.end(),e)this.connection.once("end",e);else return new this._Promise(t=>{this.connection.once("end",t)})}};Ot.Query=Ds;Os.exports=Ot});var Ks=C((mf,js)=>{"use strict";d();var ah=be().EventEmitter,Qs=function(){},Hs=(r,e)=>{let t=r.findIndex(e);return t===-1?void 0:r.splice(t,1)[0]},dn=class{constructor(e,t,n){this.client=e,this.idleListener=t,this.timeoutId=n}},Ke=class{constructor(e){this.callback=e}};function uh(){throw new Error("Release called on client which has already been released to the pool.")}function qt(r,e){if(e)return{callback:e,result:void 0};let t,n,i=function(o,a){o?t(o):n(a)},s=new r(function(o,a){n=o,t=a});return{callback:i,result:s}}function ch(r,e){return function t(n){n.client=e,e.removeListener("error",t),e.on("error",()=>{r.log("additional client error after disconnection due to error",n)}),r._remove(e),r.emit("error",n,e)}}var pn=class extends ah{constructor(e,t){super(),this.options=Object.assign({},e),e!=null&&"password"in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,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||t||Qt().Client,this.Promise=this.options.Promise||v.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}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){this.log("pulse queue on ending"),this._idle.length&&this._idle.slice().map(t=>{this._remove(t.client)}),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 e=this._pendingQueue.shift();if(this._idle.length){let t=this._idle.pop();clearTimeout(t.timeoutId);let n=t.client;n.ref&&n.ref();let i=t.idleListener;return this._acquireClient(n,e,i,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpected condition")}_remove(e){let t=Hs(this._idle,n=>n.client===e);t!==void 0&&clearTimeout(t.timeoutId),this._clients=this._clients.filter(n=>n!==e),e.end(),this.emit("remove",e)}connect(e){if(this.ending){let i=new Error("Cannot use a pool after calling end on the pool");return e?e(i):this.Promise.reject(i)}let t=qt(this.Promise,e),n=t.result;if(this._isFull()||this._idle.length){if(this._idle.length&&y.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new Ke(t.callback)),n;let i=(a,u,c)=>{clearTimeout(o),t.callback(a,u,c)},s=new Ke(i),o=setTimeout(()=>{Hs(this._pendingQueue,a=>a.callback===i),s.timedOut=!0,t.callback(new Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return this._pendingQueue.push(s),n}return this.newClient(new Ke(t.callback)),n}newClient(e){let t=new this.Client(this.options);this._clients.push(t);let n=ch(this,t);this.log("checking client timeout");let i,s=!1;this.options.connectionTimeoutMillis&&(i=setTimeout(()=>{this.log("ending client due to timeout"),s=!0,t.connection?t.connection.stream.destroy():t.end()},this.options.connectionTimeoutMillis)),this.log("connecting new client"),t.connect(o=>{if(i&&clearTimeout(i),t.on("error",n),o)this.log("client failed to connect",o),this._clients=this._clients.filter(a=>a!==t),s&&(o.message="Connection terminated due to connection timeout"),this._pulseQueue(),e.timedOut||e.callback(o,void 0,Qs);else{if(this.log("new client connected"),this.options.maxLifetimeSeconds!==0){let a=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired.add(t),this._idle.findIndex(c=>c.client===t)!==-1&&this._acquireClient(t,new Ke((c,h,f)=>f()),n,!1)},this.options.maxLifetimeSeconds*1e3);a.unref(),t.once("end",()=>clearTimeout(a))}return this._acquireClient(t,e,n,!0)}})}_acquireClient(e,t,n,i){i&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,n),e.removeListener("error",n),t.timedOut?i&&this.options.verify?this.options.verify(e,e.release):e.release():i&&this.options.verify?this.options.verify(e,s=>{if(s)return e.release(s),t.callback(s,void 0,Qs);t.callback(void 0,e,e.release)}):t.callback(void 0,e,e.release)}_releaseOnce(e,t){let n=!1;return i=>{n&&uh(),n=!0,this._release(e,t,i)}}_release(e,t,n){if(e.on("error",t),e._poolUseCount=(e._poolUseCount||0)+1,n||this.ending||!e._queryable||e._ending||e._poolUseCount>=this.options.maxUses){e._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(e),this._pulseQueue();return}if(this._expired.has(e)){this.log("remove expired client"),this._expired.delete(e),this._remove(e),this._pulseQueue();return}let s;this.options.idleTimeoutMillis&&(s=setTimeout(()=>{this.log("remove idle client"),this._remove(e)},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&s.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new dn(e,t,s)),this._pulseQueue()}query(e,t,n){if(typeof e=="function"){let s=qt(this.Promise,e);return E(function(){return s.callback(new Error("Passing a function as the first parameter to pool.query is not supported"))}),s.result}typeof t=="function"&&(n=t,t=void 0);let i=qt(this.Promise,n);return n=i.callback,this.connect((s,o)=>{if(s)return n(s);let a=!1,u=c=>{a||(a=!0,o.release(c),n(c))};o.once("error",u),this.log("dispatching query");try{o.query(e,t,(c,h)=>{if(this.log("query dispatched"),o.removeListener("error",u),!a)return a=!0,o.release(c),c?n(c):n(void 0,h)})}catch(c){return o.release(c),n(c)}}),i.result}end(e){if(this.log("ending"),this.ending){let n=new Error("Called end on pool more than once");return e?e(n):this.Promise.reject(n)}this.ending=!0;let t=qt(this.Promise,e);return this._endCallback=t.callback,this._pulseQueue(),t.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,t)=>e+(this._expired.has(t)?1:0),0)}get totalCount(){return this._clients.length}};js.exports=pn});var $s={};le($s,{default:()=>hh});var hh,Ws=te(()=>{d();hh={}});var zs=C((xf,Vs)=>{"use strict";d();var Gs=be().EventEmitter,lh=(_t(),j(At)),yn=xt(),$e=Vs.exports=function(r,e,t){Gs.call(this),r=yn.normalizeQueryConfig(r,e,t),this.text=r.text,this.values=r.values,this.name=r.name,this.callback=r.callback,this.state="new",this._arrayMode=r.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(n){n==="row"&&(this._emitRowEvents=!0)}.bind(this))};lh.inherits($e,Gs);var fh={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};$e.prototype.handleError=function(r){var e=this.native.pq.resultErrorFields();if(e)for(var t in e){var n=fh[t]||t;r[n]=e[t]}this.callback?this.callback(r):this.emit("error",r),this.state="error"};$e.prototype.then=function(r,e){return this._getPromise().then(r,e)};$e.prototype.catch=function(r){return this._getPromise().catch(r)};$e.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(r,e){this._once("end",r),this._once("error",e)}.bind(this)),this._promise)};$e.prototype.submit=function(r){this.state="running";var e=this;this.native=r.native,r.native.arrayMode=this._arrayMode;var t=function(s,o,a){if(r.native.arrayMode=!1,E(function(){e.emit("_done")}),s)return e.handleError(s);e._emitRowEvents&&(a.length>1?o.forEach((u,c)=>{u.forEach(h=>{e.emit("row",h,a[c])})}):o.forEach(function(u){e.emit("row",u,a)})),e.state="end",e.emit("end",a),e.callback&&e.callback(null,a)};if(y.domain&&(t=y.domain.bind(t)),this.name){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"));var n=(this.values||[]).map(yn.prepareValue);if(r.namedQueries[this.name]){if(this.text&&r.namedQueries[this.name]!==this.text){let s=new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return t(s)}return r.native.execute(this.name,n,t)}return r.native.prepare(this.name,this.text,n.length,function(s){return s?t(s):(r.namedQueries[e.name]=e.text,e.native.execute(e.name,n,t))})}else if(this.values){if(!Array.isArray(this.values)){let s=new Error("Query values must be an array");return t(s)}var i=this.values.map(yn.prepareValue);r.native.query(this.text,i,t)}else r.native.query(this.text,t)}});var Xs=C((Ef,Zs)=>{"use strict";d();var dh=(Ws(),j($s)),ph=_r(),Ys=be().EventEmitter,yh=(_t(),j(At)),wh=Tr(),Js=zs(),ce=Zs.exports=function(r){Ys.call(this),r=r||{},this._Promise=r.Promise||v.Promise,this._types=new ph(r.types),this.native=new dh({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;var e=this.connectionParameters=new wh(r);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={}};ce.Query=Js;yh.inherits(ce,Ys);ce.prototype._errorAllQueries=function(r){let e=t=>{y.nextTick(()=>{t.native=this.native,t.handleError(r)})};this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(e),this._queryQueue.length=0};ce.prototype._connect=function(r){var e=this;if(this._connecting){y.nextTick(()=>r(new Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(t,n){if(t)return r(t);e.native.connect(n,function(i){if(i)return e.native.end(),r(i);e._connected=!0,e.native.on("error",function(s){e._queryable=!1,e._errorAllQueries(s),e.emit("error",s)}),e.native.on("notification",function(s){e.emit("notification",{channel:s.relname,payload:s.extra})}),e.emit("connect"),e._pulseQueryQueue(!0),r()})})};ce.prototype.connect=function(r){if(r){this._connect(r);return}return new this._Promise((e,t)=>{this._connect(n=>{n?t(n):e()})})};ce.prototype.query=function(r,e,t){var n,i,s,o,a;if(r==null)throw new TypeError("Client was passed a null or undefined query");if(typeof r.submit=="function")s=r.query_timeout||this.connectionParameters.query_timeout,i=n=r,typeof e=="function"&&(r.callback=e);else if(s=this.connectionParameters.query_timeout,n=new Js(r,e,t),!n.callback){let u,c;i=new this._Promise((h,f)=>{u=h,c=f}),n.callback=(h,f)=>h?c(h):u(f)}return s&&(a=n.callback,o=setTimeout(()=>{var u=new Error("Query read timeout");y.nextTick(()=>{n.handleError(u,this.connection)}),a(u),n.callback=()=>{};var c=this._queryQueue.indexOf(n);c>-1&&this._queryQueue.splice(c,1),this._pulseQueryQueue()},s),n.callback=(u,c)=>{clearTimeout(o),a(u,c)}),this._queryable?this._ending?(n.native=this.native,y.nextTick(()=>{n.handleError(new Error("Client was closed and is not queryable"))}),i):(this._queryQueue.push(n),this._pulseQueryQueue(),i):(n.native=this.native,y.nextTick(()=>{n.handleError(new Error("Client has encountered a connection error and is not queryable"))}),i)};ce.prototype.end=function(r){var e=this;this._ending=!0,this._connected||this.once("connect",this.end.bind(this,r));var t;return r||(t=new this._Promise(function(n,i){r=s=>s?i(s):n()})),this.native.end(function(){e._errorAllQueries(new Error("Connection terminated")),y.nextTick(()=>{e.emit("end"),r&&r()})}),t};ce.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};ce.prototype._pulseQueryQueue=function(r){if(!!this._connected&&!this._hasActiveQuery()){var e=this._queryQueue.shift();if(!e){r||this.emit("drain");return}this._activeQuery=e,e.submit(this);var t=this;e.once("_done",function(){t._pulseQueryQueue()})}};ce.prototype.cancel=function(r){this._activeQuery===r?this.native.cancel(function(){}):this._queryQueue.indexOf(r)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(r),1)};ce.prototype.ref=function(){};ce.prototype.unref=function(){};ce.prototype.setTypeParser=function(r,e,t){return this._types.setTypeParser(r,e,t)};ce.prototype.getTypeParser=function(r,e){return this._types.getTypeParser(r,e)}});var wn=C((Af,eo)=>{"use strict";d();eo.exports=Xs()});var Qt=C((Uf,at)=>{"use strict";d();var mh=qs(),gh=rt(),Sh=ln(),xh=Ks(),{DatabaseError:vh}=cn(),Eh=r=>class extends xh{constructor(t){super(t,r)}},mn=function(r){this.defaults=gh,this.Client=r,this.Query=this.Client.Query,this.Pool=Eh(this.Client),this._pools=[],this.Connection=Sh,this.types=tt(),this.DatabaseError=vh};typeof y.env.NODE_PG_FORCE_NATIVE<"u"?at.exports=new mn(wn()):(at.exports=new mn(mh),Object.defineProperty(at.exports,"native",{configurable:!0,enumerable:!1,get(){var r=null;try{r=new mn(wn())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(at.exports,"native",{value:r}),r}}))});var bh={};le(bh,{Client:()=>jt,ClientBase:()=>ye.ClientBase,Connection:()=>ye.Connection,DatabaseError:()=>ye.DatabaseError,Pool:()=>Sn,Query:()=>ye.Query,defaults:()=>ye.defaults,neonConfig:()=>J,types:()=>ye.types});module.exports=j(bh);d();var Kt=lt(Qt());Mt();d();Mt();var gn=lt(Ir());function Ht(r){let e=r??{};typeof e=="string"&&(e=(0,gn.parse)(e)),e.connectionString&&(e=Object.assign({},e,(0,gn.parse)(e.connectionString))),delete e.connectionString;let t=e.host??y.env.PGHOST??y.env.host;if(typeof t!="string"||!/[.]neon[.](tech|build)(:|$)/.test(t))return r;e.ssl=!1;let n=e.password??y.env.PGPASSWORD??y.env.password;if(typeof n!="string"||n==="")return console.warn(`No password was provided for Neon database host "${t}".`),e;if(!J.addNeonProjectToPassword)return e;let i=t.match(/^([^.]+)[.]/);if(i===null)return e;let s=i[1];return e.password=`project=${s};${n}`,e}var ye=lt(Qt());var jt=class extends Kt.Client{constructor(e){super(Ht(e))}get neonConfig(){return this.connection.stream}connect(e){let t=super.connect(e),n=this.neonConfig.pipelineTLS&&this.ssl,i=this.neonConfig.pipelineConnect==="password";if(!n&&!this.neonConfig.pipelineConnect)return t;let s=this.connection;if(n&&s.on("connect",()=>s.stream.emit("data","S")),i){s.removeAllListeners("authenticationCleartextPassword"),s.removeAllListeners("readyForQuery"),s.once("readyForQuery",()=>s.on("readyForQuery",this._handleReadyForQuery.bind(this)));let o=this.ssl?"sslconnect":"connect";s.on(o,()=>{this._handleAuthCleartextPassword(),this._handleReadyForQuery()})}return t}async _handleAuthSASLContinue(e){let t=this.saslSession,n=this.password,i=e.data;if(t.message!=="SASLInitialResponse"||typeof n!="string"||typeof i!="string")throw new Error("SASL: protocol error");let s=Object.fromEntries(i.split(",").map(B=>{if(!/^.=/.test(B))throw new Error("SASL: Invalid attribute pair entry");let N=B[0],we=B.substring(2);return[N,we]})),o=s.r,a=s.s,u=s.i;if(!o||!/^[!-+--~]+$/.test(o))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing/unprintable");if(!a||!/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(a))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing/not base64");if(!u||!/^[1-9][0-9]*$/.test(u))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: missing/invalid iteration count");if(!o.startsWith(t.clientNonce))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");if(o.length===t.clientNonce.length)throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short");let c=parseInt(u,10),h=p.from(a,"base64"),f=new TextEncoder,w=f.encode(n),S=await m.subtle.importKey("raw",w,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),b=new Uint8Array(await m.subtle.sign("HMAC",S,p.concat([h,p.from([0,0,0,1])]))),I=b;for(var T=0;T<c-1;T++)b=new Uint8Array(await m.subtle.sign("HMAC",S,b)),I=p.from(I.map((B,N)=>I[N]^b[N]));let k=I,_=await m.subtle.importKey("raw",k,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),x=new Uint8Array(await m.subtle.sign("HMAC",_,f.encode("Client Key"))),K=await m.subtle.digest("SHA-256",x),z="n=*,r="+t.clientNonce,P="r="+o+",s="+a+",i="+c,Z="c=biws,r="+o,$=z+","+P+","+Z,he=await m.subtle.importKey("raw",K,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);var U=new Uint8Array(await m.subtle.sign("HMAC",he,f.encode($))),R=p.from(x.map((B,N)=>x[N]^U[N])),F=R.toString("base64");let q=await m.subtle.importKey("raw",k,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),Q=await m.subtle.sign("HMAC",q,f.encode("Server Key")),X=await m.subtle.importKey("raw",Q,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);var ee=p.from(await m.subtle.sign("HMAC",X,f.encode($)));t.message="SASLResponse",t.serverSignature=ee.toString("base64"),t.response=Z+",p="+F,this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}},Sn=class extends Kt.Pool{constructor(t){super(Ht(t));g(this,"Client",jt)}};
@jawj
Copy link
Collaborator

jawj commented Apr 16, 2023

Thanks, this is an interesting point. I guess we'd ideally find a way to have esbuild emit shorter lines.

@jawj
Copy link
Collaborator

jawj commented Jun 16, 2023

evanw/esbuild#3170

@jawj jawj closed this as completed in 5dbfde8 Jun 25, 2023
@jawj
Copy link
Collaborator

jawj commented Jun 25, 2023

These changes are now released, in version 0.4.21.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants