@stackbone/cli 0.1.0-alpha.13 → 0.1.0-alpha.15
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/CHANGELOG.md +45 -0
- package/README.md +19 -16
- package/main.js +4390 -4407
- package/migrations/0021_trigger_subscriptions.sql +67 -0
- package/package.json +1 -1
- package/runtime-deps/@stackbone/workflow-world/index.js +8913 -0
- package/stackbone-cli-0.1.0-alpha.15.tgz +0 -0
- package/runtime-deps/@stackbone/agent-server/index.js +0 -52
- package/stackbone-cli-0.1.0-alpha.13.tgz +0 -0
|
Binary file
|
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import { createRequire as __sbCreateRequire } from 'module'; const require = __sbCreateRequire(import.meta.url);
|
|
2
|
-
var ts=Object.create;var Xt=Object.defineProperty;var rs=Object.getOwnPropertyDescriptor;var ns=Object.getOwnPropertyNames;var ss=Object.getPrototypeOf,is=Object.prototype.hasOwnProperty;var _=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var f=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var os=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ns(e))!is.call(t,s)&&s!==r&&Xt(t,s,{get:()=>e[s],enumerable:!(n=rs(e,s))||n.enumerable});return t};var as=(t,e,r)=>(r=t!=null?ts(ss(t)):{},os(e||!t||!t.__esModule?Xt(r,"default",{value:t,enumerable:!0}):r,t));var Ge=f(sr=>{"use strict";sr.parse=function(t,e){return new je(t,e).parse()};var je=class t{constructor(e,r){this.source=e,this.transform=r||Us,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var e=this.source[this.position++];return e==="\\"?{value:this.source[this.position++],escaped:!0}:{value:e,escaped:!1}}record(e){this.recorded.push(e)}newEntry(e){var r;(this.recorded.length>0||e)&&(r=this.recorded.join(""),r==="NULL"&&!e&&(r=null),r!==null&&(r=this.transform(r)),this.entries.push(r),this.recorded=[])}consumeDimensions(){if(this.source[0]==="[")for(;!this.isEof();){var e=this.nextCharacter();if(e.value==="=")break}}parse(e){var r,n,s;for(this.consumeDimensions();!this.isEof();)if(r=this.nextCharacter(),r.value==="{"&&!s)this.dimension++,this.dimension>1&&(n=new t(this.source.substr(this.position-1),this.transform),this.entries.push(n.parse(!0)),this.position+=n.position-2);else if(r.value==="}"&&!s){if(this.dimension--,!this.dimension&&(this.newEntry(),e))return this.entries}else r.value==='"'&&!r.escaped?(s&&this.newEntry(!0),s=!s):r.value===","&&!s?this.newEntry():this.record(r.value);if(this.dimension!==0)throw new Error("array dimension not balanced");return this.entries}};function Us(t){return t}});var $e=f((qu,ir)=>{var js=Ge();ir.exports={create:function(t,e){return{parse:function(){return js.parse(t,e)}}}}});var ur=f((Du,ar)=>{"use strict";var Gs=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,$s=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,Ws=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,Vs=/^-?infinity$/;ar.exports=function(e){if(Vs.test(e))return Number(e.replace("i","I"));var r=Gs.exec(e);if(!r)return Js(e)||null;var n=!!r[8],s=parseInt(r[1],10);n&&(s=or(s));var i=parseInt(r[2],10)-1,o=r[3],u=parseInt(r[4],10),a=parseInt(r[5],10),c=parseInt(r[6],10),l=r[7];l=l?1e3*parseFloat(l):0;var d,y=zs(e);return y!=null?(d=new Date(Date.UTC(s,i,o,u,a,c,l)),We(s)&&d.setUTCFullYear(s),y!==0&&d.setTime(d.getTime()-y)):(d=new Date(s,i,o,u,a,c,l),We(s)&&d.setFullYear(s)),d};function Js(t){var e=$s.exec(t);if(e){var r=parseInt(e[1],10),n=!!e[4];n&&(r=or(r));var s=parseInt(e[2],10)-1,i=e[3],o=new Date(r,s,i);return We(r)&&o.setFullYear(r),o}}function zs(t){if(t.endsWith("+00"))return 0;var e=Ws.exec(t.split(" ")[1]);if(e){var r=e[1];if(r==="Z")return 0;var n=r==="-"?-1:1,s=parseInt(e[2],10)*3600+parseInt(e[3]||0,10)*60+parseInt(e[4]||0,10);return s*n*1e3}}function or(t){return-(t-1)}function We(t){return t>=0&&t<100}});var lr=f((Lu,cr)=>{cr.exports=Ys;var Ks=Object.prototype.hasOwnProperty;function Ys(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Ks.call(r,n)&&(t[n]=r[n])}return t}});var fr=f((Ou,hr)=>{"use strict";var Xs=lr();hr.exports=z;function z(t){if(!(this instanceof z))return new z(t);Xs(this,li(t))}var Zs=["seconds","minutes","hours","days","months","years"];z.prototype.toPostgres=function(){var t=Zs.filter(this.hasOwnProperty,this);return this.milliseconds&&t.indexOf("seconds")<0&&t.push("seconds"),t.length===0?"0":t.map(function(e){var r=this[e]||0;return e==="seconds"&&this.milliseconds&&(r=(r+this.milliseconds/1e3).toFixed(6).replace(/\.?0+$/,"")),r+" "+e},this).join(" ")};var ei={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},ti=["years","months","days"],ri=["hours","minutes","seconds"];z.prototype.toISOString=z.prototype.toISO=function(){var t=ti.map(r,this).join(""),e=ri.map(r,this).join("");return"P"+t+"T"+e;function r(n){var s=this[n]||0;return n==="seconds"&&this.milliseconds&&(s=(s+this.milliseconds/1e3).toFixed(6).replace(/0+$/,"")),s+ei[n]}};var Ve="([+-]?\\d+)",ni=Ve+"\\s+years?",si=Ve+"\\s+mons?",ii=Ve+"\\s+days?",oi="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",ai=new RegExp([ni,si,ii,oi].map(function(t){return"("+t+")?"}).join("\\s*")),dr={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},ui=["hours","minutes","seconds","milliseconds"];function ci(t){var e=t+"000000".slice(t.length);return parseInt(e,10)/1e3}function li(t){if(!t)return{};var e=ai.exec(t),r=e[8]==="-";return Object.keys(dr).reduce(function(n,s){var i=dr[s],o=e[i];return!o||(o=s==="milliseconds"?ci(o):parseInt(o,10),!o)||(r&&~ui.indexOf(s)&&(o*=-1),n[s]=o),n},{})}});var yr=f((Bu,mr)=>{"use strict";var pr=Buffer.from||Buffer;mr.exports=function(e){if(/^\\x/.test(e))return pr(e.substr(2),"hex");for(var r="",n=0;n<e.length;)if(e[n]!=="\\")r+=e[n],++n;else if(/[0-7]{3}/.test(e.substr(n+1,3)))r+=String.fromCharCode(parseInt(e.substr(n+1,3),8)),n+=4;else{for(var s=1;n+s<e.length&&e[n+s]==="\\";)s++;for(var i=0;i<Math.floor(s/2);++i)r+="\\";n+=Math.floor(s/2)*2}return pr(r,"binary")}});var Er=f((Nu,vr)=>{var ue=Ge(),ce=$e(),Ce=ur(),_r=fr(),wr=yr();function ke(t){return function(r){return r===null?r:t(r)}}function br(t){return t===null?t:t==="TRUE"||t==="t"||t==="true"||t==="y"||t==="yes"||t==="on"||t==="1"}function di(t){return t?ue.parse(t,br):null}function hi(t){return parseInt(t,10)}function Je(t){return t?ue.parse(t,ke(hi)):null}function fi(t){return t?ue.parse(t,ke(function(e){return Sr(e).trim()})):null}var pi=function(t){if(!t)return null;var e=ce.create(t,function(r){return r!==null&&(r=Xe(r)),r});return e.parse()},ze=function(t){if(!t)return null;var e=ce.create(t,function(r){return r!==null&&(r=parseFloat(r)),r});return e.parse()},L=function(t){if(!t)return null;var e=ce.create(t);return e.parse()},Ke=function(t){if(!t)return null;var e=ce.create(t,function(r){return r!==null&&(r=Ce(r)),r});return e.parse()},mi=function(t){if(!t)return null;var e=ce.create(t,function(r){return r!==null&&(r=_r(r)),r});return e.parse()},yi=function(t){return t?ue.parse(t,ke(wr)):null},Ye=function(t){return parseInt(t,10)},Sr=function(t){var e=String(t);return/^\d+$/.test(e)?e:t},gr=function(t){return t?ue.parse(t,ke(JSON.parse)):null},Xe=function(t){return t[0]!=="("?null:(t=t.substring(1,t.length-1).split(","),{x:parseFloat(t[0]),y:parseFloat(t[1])})},gi=function(t){if(t[0]!=="<"&&t[1]!=="(")return null;for(var e="(",r="",n=!1,s=2;s<t.length-1;s++){if(n||(e+=t[s]),t[s]===")"){n=!0;continue}else if(!n)continue;t[s]!==","&&(r+=t[s])}var i=Xe(e);return i.radius=parseFloat(r),i},_i=function(t){t(20,Sr),t(21,Ye),t(23,Ye),t(26,Ye),t(700,parseFloat),t(701,parseFloat),t(16,br),t(1082,Ce),t(1114,Ce),t(1184,Ce),t(600,Xe),t(651,L),t(718,gi),t(1e3,di),t(1001,yi),t(1005,Je),t(1007,Je),t(1028,Je),t(1016,fi),t(1017,pi),t(1021,ze),t(1022,ze),t(1231,ze),t(1014,L),t(1015,L),t(1008,L),t(1009,L),t(1040,L),t(1041,L),t(1115,Ke),t(1182,Ke),t(1185,Ke),t(1186,_r),t(1187,mi),t(17,wr),t(114,JSON.parse.bind(JSON)),t(3802,JSON.parse.bind(JSON)),t(199,gr),t(3807,gr),t(3907,L),t(2951,L),t(791,L),t(1183,L),t(1270,L)};vr.exports={init:_i}});var Cr=f((Qu,Ar)=>{"use strict";var x=1e6;function wi(t){var e=t.readInt32BE(0),r=t.readUInt32BE(4),n="";e<0&&(e=~e+(r===0),r=~r+1>>>0,n="-");var s="",i,o,u,a,c,l;{if(i=e%x,e=e/x>>>0,o=4294967296*i+r,r=o/x>>>0,u=""+(o-x*r),r===0&&e===0)return n+u+s;for(a="",c=6-u.length,l=0;l<c;l++)a+="0";s=a+u+s}{if(i=e%x,e=e/x>>>0,o=4294967296*i+r,r=o/x>>>0,u=""+(o-x*r),r===0&&e===0)return n+u+s;for(a="",c=6-u.length,l=0;l<c;l++)a+="0";s=a+u+s}{if(i=e%x,e=e/x>>>0,o=4294967296*i+r,r=o/x>>>0,u=""+(o-x*r),r===0&&e===0)return n+u+s;for(a="",c=6-u.length,l=0;l<c;l++)a+="0";s=a+u+s}return i=e%x,o=4294967296*i+r,u=""+o%x,n+u+s}Ar.exports=wi});var Tr=f((Fu,Pr)=>{var bi=Cr(),S=function(t,e,r,n,s){r=r||0,n=n||!1,s=s||function(w,k,G){return w*Math.pow(2,G)+k};var i=r>>3,o=function(w){return n?~w&255:w},u=255,a=8-r%8;e<a&&(u=255<<8-e&255,a=e),r&&(u=u>>r%8);var c=0;r%8+e>=8&&(c=s(0,o(t[i])&u,a));for(var l=e+r>>3,d=i+1;d<l;d++)c=s(c,o(t[d]),8);var y=(e+r)%8;return y>0&&(c=s(c,o(t[l])>>8-y,y)),c},Ir=function(t,e,r){var n=Math.pow(2,r-1)-1,s=S(t,1),i=S(t,r,1);if(i===0)return 0;var o=1,u=function(c,l,d){c===0&&(c=1);for(var y=1;y<=d;y++)o/=2,(l&1<<d-y)>0&&(c+=o);return c},a=S(t,e,r+1,!1,u);return i==Math.pow(2,r+1)-1?a===0?s===0?1/0:-1/0:NaN:(s===0?1:-1)*Math.pow(2,i-n)*a},Si=function(t){return S(t,1)==1?-1*(S(t,15,1,!0)+1):S(t,15,1)},kr=function(t){return S(t,1)==1?-1*(S(t,31,1,!0)+1):S(t,31,1)},vi=function(t){return Ir(t,23,8)},Ei=function(t){return Ir(t,52,11)},Ai=function(t){var e=S(t,16,32);if(e==49152)return NaN;for(var r=Math.pow(1e4,S(t,16,16)),n=0,s=[],i=S(t,16),o=0;o<i;o++)n+=S(t,16,64+16*o)*r,r/=1e4;var u=Math.pow(10,S(t,16,48));return(e===0?1:-1)*Math.round(n*u)/u},Rr=function(t,e){var r=S(e,1),n=S(e,63,1),s=new Date((r===0?1:-1)*n/1e3+9466848e5);return t||s.setTime(s.getTime()+s.getTimezoneOffset()*6e4),s.usec=n%1e3,s.getMicroSeconds=function(){return this.usec},s.setMicroSeconds=function(i){this.usec=i},s.getUTCMicroSeconds=function(){return this.usec},s},le=function(t){for(var e=S(t,32),r=S(t,32,32),n=S(t,32,64),s=96,i=[],o=0;o<e;o++)i[o]=S(t,32,s),s+=32,s+=32;var u=function(c){var l=S(t,32,s);if(s+=32,l==4294967295)return null;var d;if(c==23||c==20)return d=S(t,l*8,s),s+=l*8,d;if(c==25)return d=t.toString(this.encoding,s>>3,(s+=l<<3)>>3),d;console.log("ERROR: ElementType not implemented: "+c)},a=function(c,l){var d=[],y;if(c.length>1){var w=c.shift();for(y=0;y<w;y++)d[y]=a(c,l);c.unshift(w)}else for(y=0;y<c[0];y++)d[y]=u(l);return d};return a(i,n)},Ci=function(t){return t.toString("utf8")},ki=function(t){return t===null?null:S(t,8)>0},Ri=function(t){t(20,bi),t(21,Si),t(23,kr),t(26,kr),t(1700,Ai),t(700,vi),t(701,Ei),t(16,ki),t(1114,Rr.bind(null,!1)),t(1184,Rr.bind(null,!0)),t(1e3,le),t(1007,le),t(1016,le),t(1008,le),t(1009,le),t(25,Ci)};Pr.exports={init:Ri}});var Mr=f((Hu,xr)=>{xr.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 fe=f(he=>{var Ii=Er(),Pi=Tr(),Ti=$e(),xi=Mr();he.getTypeParser=Mi;he.setTypeParser=qi;he.arrayParser=Ti;he.builtins=xi;var de={text:{},binary:{}};function qr(t){return String(t)}function Mi(t,e){return e=e||"text",de[e]&&de[e][t]||qr}function qi(t,e,r){typeof e=="function"&&(r=e,e="text"),de[e][t]=r}Ii.init(function(t,e){de.text[t]=e});Pi.init(function(t,e){de.binary[t]=e})});var pe=f((ju,Ze)=>{"use strict";var Dr;try{Dr=process.platform==="win32"?process.env.USERNAME:process.env.USER}catch{}Ze.exports={host:"localhost",user:Dr,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:3e4,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 K=fe(),Di=K.getTypeParser(20,"text"),Li=K.getTypeParser(1016,"text");Ze.exports.__defineSetter__("parseInt8",function(t){K.setTypeParser(20,"text",t?K.getTypeParser(23,"text"):Di),K.setTypeParser(1016,"text",t?K.getTypeParser(1007,"text"):Li)})});var Y=f((Gu,Br)=>{"use strict";var Oi=pe(),Lr=_("util"),{isDate:Bi}=Lr.types||Lr;function Ni(t){return'"'+t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}function Or(t){let e="{";for(let r=0;r<t.length;r++)if(r>0&&(e=e+","),t[r]===null||typeof t[r]>"u")e=e+"NULL";else if(Array.isArray(t[r]))e=e+Or(t[r]);else if(ArrayBuffer.isView(t[r])){let n=t[r];if(!(n instanceof Buffer)){let s=Buffer.from(n.buffer,n.byteOffset,n.byteLength);s.length===n.byteLength?n=s:n=s.slice(n.byteOffset,n.byteOffset+n.byteLength)}e+="\\\\x"+n.toString("hex")}else e+=Ni(Re(t[r]));return e=e+"}",e}var Re=function(t,e){if(t==null)return null;if(typeof t=="object"){if(t instanceof Buffer)return t;if(ArrayBuffer.isView(t)){let r=Buffer.from(t.buffer,t.byteOffset,t.byteLength);return r.length===t.byteLength?r:r.slice(t.byteOffset,t.byteOffset+t.byteLength)}return Bi(t)?Oi.parseInputDatesAsUTC?Hi(t):Fi(t):Array.isArray(t)?Or(t):Qi(t,e)}return t.toString()};function Qi(t,e){if(t&&typeof t.toPostgres=="function"){if(e=e||[],e.indexOf(t)!==-1)throw new Error('circular reference detected while preparing "'+t+'" for query');return e.push(t),Re(t.toPostgres(Re),e)}return JSON.stringify(t)}function Fi(t){let e=-t.getTimezoneOffset(),r=t.getFullYear(),n=r<1;n&&(r=Math.abs(r)+1);let s=String(r).padStart(4,"0")+"-"+String(t.getMonth()+1).padStart(2,"0")+"-"+String(t.getDate()).padStart(2,"0")+"T"+String(t.getHours()).padStart(2,"0")+":"+String(t.getMinutes()).padStart(2,"0")+":"+String(t.getSeconds()).padStart(2,"0")+"."+String(t.getMilliseconds()).padStart(3,"0");return e<0?(s+="-",e*=-1):s+="+",s+=String(Math.floor(e/60)).padStart(2,"0")+":"+String(e%60).padStart(2,"0"),n&&(s+=" BC"),s}function Hi(t){let e=t.getUTCFullYear(),r=e<1;r&&(e=Math.abs(e)+1);let n=String(e).padStart(4,"0")+"-"+String(t.getUTCMonth()+1).padStart(2,"0")+"-"+String(t.getUTCDate()).padStart(2,"0")+"T"+String(t.getUTCHours()).padStart(2,"0")+":"+String(t.getUTCMinutes()).padStart(2,"0")+":"+String(t.getUTCSeconds()).padStart(2,"0")+"."+String(t.getUTCMilliseconds()).padStart(3,"0");return n+="+00:00",r&&(n+=" BC"),n}function Ui(t,e,r){return t=typeof t=="string"?{text:t}:t,e&&(typeof e=="function"?t.callback=e:t.values=e),r&&(t.callback=r),t}var ji=function(t){return'"'+t.replace(/"/g,'""')+'"'},Gi=function(t){let e=!1,r="'";if(t==null||typeof t!="string")return"''";for(let n=0;n<t.length;n++){let s=t[n];s==="'"?r+=s+s:s==="\\"?(r+=s+s,e=!0):r+=s}return r+="'",e===!0&&(r=" E"+r),r};Br.exports={prepareValue:function(e){return Re(e)},normalizeQueryConfig:Ui,escapeIdentifier:ji,escapeLiteral:Gi}});var Qr=f(($u,Nr)=>{"use strict";var X=_("crypto");function et(t){return X.createHash("md5").update(t,"utf-8").digest("hex")}function $i(t,e,r){let n=et(e+t);return"md5"+et(Buffer.concat([Buffer.from(n),r]))}function Wi(t){return X.createHash("sha256").update(t).digest()}function Vi(t,e){return t=t.replace(/(\D)-/,"$1"),X.createHash(t).update(e).digest()}function Ji(t,e){return X.createHmac("sha256",t).update(e).digest()}async function zi(t,e,r){return X.pbkdf2Sync(t,e,r,32,"sha256")}Nr.exports={postgresMd5PasswordHash:$i,randomBytes:X.randomBytes,deriveKey:zi,sha256:Wi,hashByName:Vi,hmacSha256:Ji,md5:et}});var jr=f((Wu,Ur)=>{var Fr=_("crypto");Ur.exports={postgresMd5PasswordHash:Yi,randomBytes:Ki,deriveKey:to,sha256:Xi,hashByName:Zi,hmacSha256:eo,md5:tt};var Hr=Fr.webcrypto||globalThis.crypto,$=Hr.subtle,rt=new TextEncoder;function Ki(t){return Hr.getRandomValues(Buffer.alloc(t))}async function tt(t){try{return Fr.createHash("md5").update(t,"utf-8").digest("hex")}catch{let r=typeof t=="string"?rt.encode(t):t,n=await $.digest("MD5",r);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}}async function Yi(t,e,r){let n=await tt(e+t);return"md5"+await tt(Buffer.concat([Buffer.from(n),r]))}async function Xi(t){return await $.digest("SHA-256",t)}async function Zi(t,e){return await $.digest(t,e)}async function eo(t,e){let r=await $.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return await $.sign("HMAC",r,rt.encode(e))}async function to(t,e,r){let n=await $.importKey("raw",rt.encode(t),"PBKDF2",!1,["deriveBits"]),s={name:"PBKDF2",hash:"SHA-256",salt:e,iterations:r};return await $.deriveBits(s,n,256,["deriveBits"])}});var st=f((Vu,nt)=>{"use strict";var ro=parseInt(process.versions&&process.versions.node&&process.versions.node.split(".")[0])<15;ro?nt.exports=Qr():nt.exports=jr()});var Wr=f((Ju,$r)=>{function W(t,e){return new Error("SASL channel binding: "+t+" when parsing public certificate "+e.toString("base64"))}function it(t,e){let r=t[e++];if(r<128)return{length:r,index:e};let n=r&127;if(n>4)throw W("bad length",t);r=0;for(let s=0;s<n;s++)r=r<<8|t[e++];return{length:r,index:e}}function Gr(t,e){if(t[e++]!==6)throw W("non-OID data",t);let{length:r,index:n}=it(t,e);e=n;let s=e+r,i=t[e++],o=(i/40>>0)+"."+i%40;for(;e<s;){let u=0;for(;e<s;){let a=t[e++];if(u=u<<7|a&127,a<128)break}o+="."+u}return{oid:o,index:e}}function me(t,e){if(t[e++]!==48)throw W("non-sequence data",t);return it(t,e)}function no(t,e){e===void 0&&(e=0),e=me(t,e).index;let{length:r,index:n}=me(t,e);e=n+r,e=me(t,e).index;let{oid:s,index:i}=Gr(t,e);switch(s){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=i,e=me(t,e).index,t[e++]!==160)throw W("non-tag data",t);e=it(t,e).index,e=me(t,e).index;let{oid:o}=Gr(t,e);switch(o){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 "+o,t)}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 "+s,t)}$r.exports={signatureAlgorithmHashFromCertificate:no}});var Kr=f((zu,zr)=>{"use strict";var H=st(),{signatureAlgorithmHashFromCertificate:so}=Wr();function io(t,e){let r=["SCRAM-SHA-256"];e&&r.unshift("SCRAM-SHA-256-PLUS");let n=r.find(o=>t.includes(o));if(!n)throw new Error("SASL: Only mechanism(s) "+r.join(" and ")+" are supported");if(n==="SCRAM-SHA-256-PLUS"&&typeof e.getPeerCertificate!="function")throw new Error("SASL: Mechanism SCRAM-SHA-256-PLUS requires a certificate");let s=H.randomBytes(18).toString("base64");return{mechanism:n,clientNonce:s,response:(n==="SCRAM-SHA-256-PLUS"?"p=tls-server-end-point":e?"y":"n")+",,n=*,r="+s,message:"SASLInitialResponse"}}async function oo(t,e,r,n){if(t.message!=="SASLInitialResponse")throw new Error("SASL: Last message was not SASLInitialResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(e==="")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string");if(typeof r!="string")throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let s=co(r);if(s.nonce.startsWith(t.clientNonce)){if(s.nonce.length===t.clientNonce.length)throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");let i="n=*,r="+t.clientNonce,o="r="+s.nonce+",s="+s.salt+",i="+s.iteration,u=n?"eSws":"biws";if(t.mechanism==="SCRAM-SHA-256-PLUS"){let T=n.getPeerCertificate().raw,F=so(T);(F==="MD5"||F==="SHA-1")&&(F="SHA-256");let _e=await H.hashByName(F,T);u=Buffer.concat([Buffer.from("p=tls-server-end-point,,"),Buffer.from(_e)]).toString("base64")}let a="c="+u+",r="+s.nonce,c=i+","+o+","+a,l=Buffer.from(s.salt,"base64"),d=await H.deriveKey(e,l,s.iteration),y=await H.hmacSha256(d,"Client Key"),w=await H.sha256(y),k=await H.hmacSha256(w,c),G=ho(Buffer.from(y),Buffer.from(k)).toString("base64"),V=await H.hmacSha256(d,"Server Key"),N=await H.hmacSha256(V,c);t.message="SASLResponse",t.serverSignature=Buffer.from(N).toString("base64"),t.response=a+",p="+G}function ao(t,e){if(t.message!=="SASLResponse")throw new Error("SASL: Last message was not SASLResponse");if(typeof e!="string")throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature:r}=lo(e);if(r!==t.serverSignature)throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}function uo(t){if(typeof t!="string")throw new TypeError("SASL: text must be a string");return t.split("").map((e,r)=>t.charCodeAt(r)).every(e=>e>=33&&e<=43||e>=45&&e<=126)}function Vr(t){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(t)}function Jr(t){if(typeof t!="string")throw new TypeError("SASL: attribute pairs text must be a string");return new Map(t.split(",").map(e=>{if(!/^.=/.test(e))throw new Error("SASL: Invalid attribute pair entry");let r=e[0],n=e.substring(2);return[r,n]}))}function co(t){let e=Jr(t),r=e.get("r");if(r){if(!uo(r))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");let n=e.get("s");if(n){if(!Vr(n))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");let s=e.get("i");if(s){if(!/^[1-9][0-9]*$/.test(s))throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count")}else throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");let i=parseInt(s,10);return{nonce:r,salt:n,iteration:i}}function lo(t){let r=Jr(t).get("v");if(r){if(!Vr(r))throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64")}else throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");return{serverSignature:r}}function ho(t,e){if(!Buffer.isBuffer(t))throw new TypeError("first argument must be a Buffer");if(!Buffer.isBuffer(e))throw new TypeError("second argument must be a Buffer");if(t.length!==e.length)throw new Error("Buffer lengths must match");if(t.length===0)throw new Error("Buffers cannot be empty");return Buffer.from(t.map((r,n)=>t[n]^e[n]))}zr.exports={startSession:io,continueSession:oo,finalizeSession:ao}});var Pe=f((Ku,Yr)=>{"use strict";var fo=fe();function Ie(t){this._types=t||fo,this.text={},this.binary={}}Ie.prototype.getOverrides=function(t){switch(t){case"text":return this.text;case"binary":return this.binary;default:return{}}};Ie.prototype.setTypeParser=function(t,e,r){typeof e=="function"&&(r=e,e="text"),this.getOverrides(e)[t]=r};Ie.prototype.getTypeParser=function(t,e){return e=e||"text",this.getOverrides(e)[t]||this._types.getTypeParser(t,e)};Yr.exports=Ie});var en=f((Yu,Zr)=>{"use strict";function Z(t,e={}){if(t.charAt(0)==="/"){let a=t.split(" ");return{host:a[0],database:a[1]}}let r={},n,s=!1;/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(t)&&(t=encodeURI(t).replace(/%25(\d\d)/g,"%$1"));try{try{n=new URL(t,"postgres://base")}catch{n=new URL(t.replace("@/","@___DUMMY___/"),"postgres://base"),s=!0}}catch(a){throw a.input&&(a.input="*****REDACTED*****"),a}for(let a of n.searchParams.entries())r[a[0]]=a[1];if(r.user=r.user||decodeURIComponent(n.username),r.password=r.password||decodeURIComponent(n.password),n.protocol=="socket:")return r.host=decodeURI(n.pathname),r.database=n.searchParams.get("db"),r.client_encoding=n.searchParams.get("encoding"),r;let i=s?"":n.hostname;r.host?i&&/^%2f/i.test(i)&&(n.pathname=i+n.pathname):r.host=decodeURIComponent(i),r.port||(r.port=n.port);let o=n.pathname.slice(1)||null;r.database=o?decodeURI(o):null,(r.ssl==="true"||r.ssl==="1")&&(r.ssl=!0),r.ssl==="0"&&(r.ssl=!1),(r.sslcert||r.sslkey||r.sslrootcert||r.sslmode)&&(r.ssl={});let u=r.sslcert||r.sslkey||r.sslrootcert?_("fs"):null;if(r.sslcert&&(r.ssl.cert=u.readFileSync(r.sslcert).toString()),r.sslkey&&(r.ssl.key=u.readFileSync(r.sslkey).toString()),r.sslrootcert&&(r.ssl.ca=u.readFileSync(r.sslrootcert).toString()),e.useLibpqCompat&&r.uselibpqcompat)throw new Error("Both useLibpqCompat and uselibpqcompat are set. Please use only one of them.");if(r.uselibpqcompat==="true"||e.useLibpqCompat)switch(r.sslmode){case"disable":{r.ssl=!1;break}case"prefer":{r.ssl.rejectUnauthorized=!1;break}case"require":{r.sslrootcert?r.ssl.checkServerIdentity=function(){}:r.ssl.rejectUnauthorized=!1;break}case"verify-ca":{if(!r.ssl.ca)throw new 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.");r.ssl.checkServerIdentity=function(){};break}case"verify-full":break}else switch(r.sslmode){case"disable":{r.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":{r.sslmode!=="verify-full"&&ot(r.sslmode);break}case"no-verify":{r.ssl.rejectUnauthorized=!1;break}}return r}function po(t){return Object.entries(t).reduce((r,[n,s])=>(s!=null&&(r[n]=s),r),{})}function Xr(t){return Object.entries(t).reduce((r,[n,s])=>{if(n==="ssl"){let i=s;typeof i=="boolean"&&(r[n]=i),typeof i=="object"&&(r[n]=po(i))}else if(s!=null)if(n==="port"){if(s!==""){let i=parseInt(s,10);if(isNaN(i))throw new Error(`Invalid ${n}: ${s}`);r[n]=i}}else r[n]=s;return r},{})}function mo(t){return Xr(Z(t))}function ot(t){!ot.warned&&typeof process<"u"&&process.emitWarning&&(ot.warned=!0,process.emitWarning(`SECURITY WARNING: The SSL modes 'prefer', 'require', and 'verify-ca' are treated as aliases for 'verify-full'.
|
|
3
|
-
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.
|
|
4
|
-
|
|
5
|
-
To prepare for this change:
|
|
6
|
-
- If you want the current behavior, explicitly use 'sslmode=verify-full'
|
|
7
|
-
- If you want libpq compatibility now, use 'uselibpqcompat=true&sslmode=${t}'
|
|
8
|
-
|
|
9
|
-
See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode definitions.`))}Zr.exports=Z;Z.parse=Z;Z.toClientConfig=Xr;Z.parseIntoClientConfig=mo});var ut=f((Xu,nn)=>{"use strict";var yo=_("dns"),rn=pe(),tn=en().parse,I=function(t,e,r){return e[t]?e[t]:(r===void 0?r=process.env["PG"+t.toUpperCase()]:r===!1||(r=process.env[r]),r||rn[t])},go=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 rn.ssl},ee=function(t){return"'"+(""+t).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},O=function(t,e,r){let n=e[r];n!=null&&t.push(r+"="+ee(n))},at=class{constructor(e){e=typeof e=="string"?tn(e):e||{},e.connectionString&&(e=Object.assign({},e,tn(e.connectionString))),this.user=I("user",e),this.database=I("database",e),this.database===void 0&&(this.database=this.user),this.port=parseInt(I("port",e),10),this.host=I("host",e),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:I("password",e)}),this.binary=I("binary",e),this.options=I("options",e),this.ssl=typeof e.ssl>"u"?go():e.ssl,typeof this.ssl=="string"&&this.ssl==="true"&&(this.ssl=!0),this.ssl==="no-verify"&&(this.ssl={rejectUnauthorized:!1}),this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this.client_encoding=I("client_encoding",e),this.replication=I("replication",e),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=I("application_name",e,"PGAPPNAME"),this.fallback_application_name=I("fallback_application_name",e,!1),this.statement_timeout=I("statement_timeout",e,!1),this.lock_timeout=I("lock_timeout",e,!1),this.idle_in_transaction_session_timeout=I("idle_in_transaction_session_timeout",e,!1),this.query_timeout=I("query_timeout",e,!1),e.connectionTimeoutMillis===void 0?this.connect_timeout=process.env.PGCONNECT_TIMEOUT||0:this.connect_timeout=Math.floor(e.connectionTimeoutMillis/1e3),e.keepAlive===!1?this.keepalives=0:e.keepAlive===!0&&(this.keepalives=1),typeof e.keepAliveInitialDelayMillis=="number"&&(this.keepalives_idle=Math.floor(e.keepAliveInitialDelayMillis/1e3))}getLibpqConnectionString(e){let r=[];O(r,this,"user"),O(r,this,"password"),O(r,this,"port"),O(r,this,"application_name"),O(r,this,"fallback_application_name"),O(r,this,"connect_timeout"),O(r,this,"options");let n=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(O(r,n,"sslmode"),O(r,n,"sslca"),O(r,n,"sslkey"),O(r,n,"sslcert"),O(r,n,"sslrootcert"),this.database&&r.push("dbname="+ee(this.database)),this.replication&&r.push("replication="+ee(this.replication)),this.host&&r.push("host="+ee(this.host)),this.isDomainSocket)return e(null,r.join(" "));this.client_encoding&&r.push("client_encoding="+ee(this.client_encoding)),yo.lookup(this.host,function(s,i){return s?e(s,null):(r.push("hostaddr="+ee(i)),e(null,r.join(" ")))})}};nn.exports=at});var lt=f((Zu,on)=>{"use strict";var _o=fe(),sn=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,ct=class{constructor(e,r){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=r,this.RowCtor=null,this.rowAsArray=e==="array",this.rowAsArray&&(this.parseRow=this._parseRowAsArray),this._prebuiltEmptyResultObject=null}addCommandComplete(e){let r;e.text?r=sn.exec(e.text):r=sn.exec(e.command),r&&(this.command=r[1],r[3]?(this.oid=parseInt(r[2],10),this.rowCount=parseInt(r[3],10)):r[2]&&(this.rowCount=parseInt(r[2],10)))}_parseRowAsArray(e){let r=new Array(e.length);for(let n=0,s=e.length;n<s;n++){let i=e[n];i!==null?r[n]=this._parsers[n](i):r[n]=null}return r}parseRow(e){let r={...this._prebuiltEmptyResultObject};for(let n=0,s=e.length;n<s;n++){let i=e[n],o=this.fields[n].name;if(i!==null){let u=this.fields[n].format==="binary"?Buffer.from(i):i;r[o]=this._parsers[n](u)}else r[o]=null}return r}addRow(e){this.rows.push(e)}addFields(e){this.fields=e,this.fields.length&&(this._parsers=new Array(e.length));let r={};for(let n=0;n<e.length;n++){let s=e[n];r[s.name]=null,this._types?this._parsers[n]=this._types.getTypeParser(s.dataTypeID,s.format||"text"):this._parsers[n]=_o.getTypeParser(s.dataTypeID,s.format||"text")}this._prebuiltEmptyResultObject={...r}}};on.exports=ct});var ln=f((ec,cn)=>{"use strict";var{EventEmitter:wo}=_("events"),an=lt(),un=Y(),dt=class extends wo{constructor(e,r,n){super(),e=un.normalizeQueryConfig(e,r,n),this.text=e.text,this.values=e.values,this.rows=e.rows,this.types=e.types,this.name=e.name,this.queryMode=e.queryMode,this.binary=e.binary,this.portal=e.portal||"",this.callback=e.callback,this._rowMode=e.rowMode,process.domain&&e.callback&&(this.callback=process.domain.bind(e.callback)),this._result=new an(this._rowMode,this.types),this._results=this._result,this._canceledDueToError=!1}requiresPreparation(){return this.queryMode==="extended"||this.name||this.rows?!0:!this.text||!this.values?!1:this.values.length>0}_checkForMultirow(){this._result.command&&(Array.isArray(this._results)||(this._results=[this._result]),this._result=new an(this._rowMode,this._result._types),this._results.push(this._result))}handleRowDescription(e){this._checkForMultirow(),this._result.addFields(e.fields),this._accumulateRows=this.callback||!this.listeners("row").length}handleDataRow(e){let r;if(!this._canceledDueToError){try{r=this._result.parseRow(e.fields)}catch(n){this._canceledDueToError=n;return}this.emit("row",r,this._result),this._accumulateRows&&this._result.addRow(r)}}handleCommandComplete(e,r){this._checkForMultirow(),this._result.addCommandComplete(e),this.rows&&r.sync()}handleEmptyQuery(e){this.rows&&e.sync()}handleError(e,r){if(this._canceledDueToError&&(e=this._canceledDueToError,this._canceledDueToError=!1),this.callback)return this.callback(e);this.emit("error",e)}handleReadyForQuery(e){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,e);if(this.callback)try{this.callback(null,this._results)}catch(r){process.nextTick(()=>{throw r})}this.emit("end",this._results)}submit(e){if(typeof this.text!="string"&&typeof this.name!="string")return new Error("A query must have either text or a name. Supplying neither is unsupported.");let r=e.parsedStatements[this.name];if(this.text&&r&&this.text!==r)return new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);if(this.values&&!Array.isArray(this.values))return new Error("Query values must be an array");if(this.requiresPreparation()){e.stream.cork&&e.stream.cork();try{this.prepare(e)}finally{e.stream.uncork&&e.stream.uncork()}}else e.query(this.text);return null}hasBeenParsed(e){return this.name&&e.parsedStatements[this.name]}handlePortalSuspended(e){this._getRows(e,this.rows)}_getRows(e,r){e.execute({portal:this.portal,rows:r}),r?e.flush():e.sync()}prepare(e){this.hasBeenParsed(e)||e.parse({text:this.text,name:this.name,types:this.types});try{e.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:un.prepareValue})}catch(r){this.handleError(r,e);return}e.describe({type:"P",name:this.portal||""}),this._getRows(e,this.rows)}handleCopyInResponse(e){e.sendCopyFail("No source stream defined")}handleCopyData(e,r){}};cn.exports=dt});var kt=f(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.NoticeMessage=h.DataRowMessage=h.CommandCompleteMessage=h.ReadyForQueryMessage=h.NotificationResponseMessage=h.BackendKeyDataMessage=h.AuthenticationMD5Password=h.ParameterStatusMessage=h.ParameterDescriptionMessage=h.RowDescriptionMessage=h.Field=h.CopyResponse=h.CopyDataMessage=h.DatabaseError=h.copyDone=h.emptyQuery=h.replicationStart=h.portalSuspended=h.noData=h.closeComplete=h.bindComplete=h.parseComplete=void 0;h.parseComplete={name:"parseComplete",length:5};h.bindComplete={name:"bindComplete",length:5};h.closeComplete={name:"closeComplete",length:5};h.noData={name:"noData",length:5};h.portalSuspended={name:"portalSuspended",length:5};h.replicationStart={name:"replicationStart",length:4};h.emptyQuery={name:"emptyQuery",length:4};h.copyDone={name:"copyDone",length:4};var ht=class extends Error{constructor(e,r,n){super(e),this.length=r,this.name=n}};h.DatabaseError=ht;var ft=class{constructor(e,r){this.length=e,this.chunk=r,this.name="copyData"}};h.CopyDataMessage=ft;var pt=class{constructor(e,r,n,s){this.length=e,this.name=r,this.binary=n,this.columnTypes=new Array(s)}};h.CopyResponse=pt;var mt=class{constructor(e,r,n,s,i,o,u){this.name=e,this.tableID=r,this.columnID=n,this.dataTypeID=s,this.dataTypeSize=i,this.dataTypeModifier=o,this.format=u}};h.Field=mt;var yt=class{constructor(e,r){this.length=e,this.fieldCount=r,this.name="rowDescription",this.fields=new Array(this.fieldCount)}};h.RowDescriptionMessage=yt;var gt=class{constructor(e,r){this.length=e,this.parameterCount=r,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}};h.ParameterDescriptionMessage=gt;var _t=class{constructor(e,r,n){this.length=e,this.parameterName=r,this.parameterValue=n,this.name="parameterStatus"}};h.ParameterStatusMessage=_t;var wt=class{constructor(e,r){this.length=e,this.salt=r,this.name="authenticationMD5Password"}};h.AuthenticationMD5Password=wt;var bt=class{constructor(e,r,n){this.length=e,this.processID=r,this.secretKey=n,this.name="backendKeyData"}};h.BackendKeyDataMessage=bt;var St=class{constructor(e,r,n,s){this.length=e,this.processId=r,this.channel=n,this.payload=s,this.name="notification"}};h.NotificationResponseMessage=St;var vt=class{constructor(e,r){this.length=e,this.status=r,this.name="readyForQuery"}};h.ReadyForQueryMessage=vt;var Et=class{constructor(e,r){this.length=e,this.text=r,this.name="commandComplete"}};h.CommandCompleteMessage=Et;var At=class{constructor(e,r){this.length=e,this.fields=r,this.name="dataRow",this.fieldCount=r.length}};h.DataRowMessage=At;var Ct=class{constructor(e,r){this.length=e,this.message=r,this.name="notice"}};h.NoticeMessage=Ct});var dn=f(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.Writer=void 0;var Rt=class{constructor(e=256){this.size=e,this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(e)}ensure(e){if(this.buffer.length-this.offset<e){let n=this.buffer,s=n.length+(n.length>>1)+e;this.buffer=Buffer.allocUnsafe(s),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{let r=Buffer.byteLength(e);this.ensure(r+1),this.buffer.write(e,this.offset,"utf-8"),this.offset+=r}return this.buffer[this.offset++]=0,this}addString(e=""){let r=Buffer.byteLength(e);return this.ensure(r),this.buffer.write(e,this.offset),this.offset+=r,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 r=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(r,this.headerPosition+1)}return this.buffer.slice(e?0:5,this.offset)}flush(e){let r=this.join(e);return this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(this.size),r}};Te.Writer=Rt});var fn=f(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.serialize=void 0;var It=dn(),b=new It.Writer,bo=t=>{b.addInt16(3).addInt16(0);for(let n of Object.keys(t))b.addCString(n).addCString(t[n]);b.addCString("client_encoding").addCString("UTF8");let e=b.addCString("").flush(),r=e.length+4;return new It.Writer().addInt32(r).add(e).flush()},So=()=>{let t=Buffer.allocUnsafe(8);return t.writeInt32BE(8,0),t.writeInt32BE(80877103,4),t},vo=t=>b.addCString(t).flush(112),Eo=function(t,e){return b.addCString(t).addInt32(Buffer.byteLength(e)).addString(e),b.flush(112)},Ao=function(t){return b.addString(t).flush(112)},Co=t=>b.addCString(t).flush(81),hn=[],ko=t=>{let e=t.name||"";e.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",e,e.length),console.error("This can cause conflicts and silent errors executing queries"));let r=t.types||hn,n=r.length,s=b.addCString(e).addCString(t.text).addInt16(n);for(let i=0;i<n;i++)s.addInt32(r[i]);return b.flush(80)},te=new It.Writer,Ro=function(t,e){for(let r=0;r<t.length;r++){let n=e?e(t[r],r):t[r];n==null?(b.addInt16(0),te.addInt32(-1)):n instanceof Buffer?(b.addInt16(1),te.addInt32(n.length),te.add(n)):(b.addInt16(0),te.addInt32(Buffer.byteLength(n)),te.addString(n))}},Io=(t={})=>{let e=t.portal||"",r=t.statement||"",n=t.binary||!1,s=t.values||hn,i=s.length;return b.addCString(e).addCString(r),b.addInt16(i),Ro(s,t.valueMapper),b.addInt16(i),b.add(te.flush()),b.addInt16(1),b.addInt16(n?1:0),b.flush(66)},Po=Buffer.from([69,0,0,0,9,0,0,0,0,0]),To=t=>{if(!t||!t.portal&&!t.rows)return Po;let e=t.portal||"",r=t.rows||0,n=Buffer.byteLength(e),s=4+n+1+4,i=Buffer.allocUnsafe(1+s);return i[0]=69,i.writeInt32BE(s,1),i.write(e,5,"utf-8"),i[n+5]=0,i.writeUInt32BE(r,i.length-4),i},xo=(t,e)=>{let r=Buffer.allocUnsafe(16);return r.writeInt32BE(16,0),r.writeInt16BE(1234,4),r.writeInt16BE(5678,6),r.writeInt32BE(t,8),r.writeInt32BE(e,12),r},Pt=(t,e)=>{let n=4+Buffer.byteLength(e)+1,s=Buffer.allocUnsafe(1+n);return s[0]=t,s.writeInt32BE(n,1),s.write(e,5,"utf-8"),s[n]=0,s},Mo=b.addCString("P").flush(68),qo=b.addCString("S").flush(68),Do=t=>t.name?Pt(68,`${t.type}${t.name||""}`):t.type==="P"?Mo:qo,Lo=t=>{let e=`${t.type}${t.name||""}`;return Pt(67,e)},Oo=t=>b.add(t).flush(100),Bo=t=>Pt(102,t),xe=t=>Buffer.from([t,0,0,0,4]),No=xe(72),Qo=xe(83),Fo=xe(88),Ho=xe(99),Uo={startup:bo,password:vo,requestSsl:So,sendSASLInitialResponseMessage:Eo,sendSCRAMClientFinalMessage:Ao,query:Co,parse:ko,bind:Io,execute:To,describe:Do,close:Lo,flush:()=>No,sync:()=>Qo,end:()=>Fo,copyData:Oo,copyDone:()=>Ho,copyFail:Bo,cancel:xo};Me.serialize=Uo});var pn=f(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.BufferReader=void 0;var Tt=class{constructor(e=0){this.offset=e,this.buffer=Buffer.allocUnsafe(0),this.encoding="utf-8"}setBuffer(e,r){this.offset=e,this.buffer=r}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}uint32(){let e=this.buffer.readUInt32BE(this.offset);return this.offset+=4,e}string(e){let r=this.buffer.toString(this.encoding,this.offset,this.offset+e);return this.offset+=e,r}cstring(){let e=this.offset,r=e;for(;this.buffer[r++]!==0;);return this.offset=r,this.buffer.toString(this.encoding,e,r-1)}bytes(e){let r=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,r}};qe.BufferReader=Tt});var _n=f(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.Parser=void 0;var v=kt(),jo=pn(),Mt=1,Go=4,mn=Mt+Go,D=-1,xt=Buffer.allocUnsafe(0),qt=class{constructor(e){if(this.buffer=xt,this.bufferLength=0,this.bufferOffset=0,this.reader=new jo.BufferReader,e?.mode==="binary")throw new Error("Binary mode not supported yet");this.mode=e?.mode||"text"}parse(e,r){this.mergeBuffer(e);let n=this.bufferOffset+this.bufferLength,s=this.bufferOffset;for(;s+mn<=n;){let i=this.buffer[s],o=this.buffer.readUInt32BE(s+Mt),u=Mt+o;if(u+s<=n){let a=this.handlePacket(s+mn,i,o,this.buffer);r(a),s+=u}else break}s===n?(this.buffer=xt,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=n-s,this.bufferOffset=s)}mergeBuffer(e){if(this.bufferLength>0){let r=this.bufferLength+e.byteLength;if(r+this.bufferOffset>this.buffer.byteLength){let s;if(r<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)s=this.buffer;else{let i=this.buffer.byteLength*2;for(;r>=i;)i*=2;s=Buffer.allocUnsafe(i)}this.buffer.copy(s,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=s,this.bufferOffset=0}e.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=r}else this.buffer=e,this.bufferOffset=0,this.bufferLength=e.byteLength}handlePacket(e,r,n,s){let{reader:i}=this;i.setBuffer(e,s);let o;switch(r){case 50:o=v.bindComplete;break;case 49:o=v.parseComplete;break;case 51:o=v.closeComplete;break;case 110:o=v.noData;break;case 115:o=v.portalSuspended;break;case 99:o=v.copyDone;break;case 87:o=v.replicationStart;break;case 73:o=v.emptyQuery;break;case 68:o=ea(i);break;case 67:o=Wo(i);break;case 90:o=$o(i);break;case 65:o=Ko(i);break;case 82:o=na(i,n);break;case 83:o=ta(i);break;case 75:o=ra(i);break;case 69:o=yn(i,"error");break;case 78:o=yn(i,"notice");break;case 84:o=Yo(i);break;case 116:o=Zo(i);break;case 71:o=Jo(i);break;case 72:o=zo(i);break;case 100:o=Vo(i,n);break;default:return new v.DatabaseError("received invalid response: "+r.toString(16),n,"error")}return i.setBuffer(0,xt),o.length=n,o}};De.Parser=qt;var $o=t=>{let e=t.string(1);return new v.ReadyForQueryMessage(D,e)},Wo=t=>{let e=t.cstring();return new v.CommandCompleteMessage(D,e)},Vo=(t,e)=>{let r=t.bytes(e-4);return new v.CopyDataMessage(D,r)},Jo=t=>gn(t,"copyInResponse"),zo=t=>gn(t,"copyOutResponse"),gn=(t,e)=>{let r=t.byte()!==0,n=t.int16(),s=new v.CopyResponse(D,e,r,n);for(let i=0;i<n;i++)s.columnTypes[i]=t.int16();return s},Ko=t=>{let e=t.int32(),r=t.cstring(),n=t.cstring();return new v.NotificationResponseMessage(D,e,r,n)},Yo=t=>{let e=t.int16(),r=new v.RowDescriptionMessage(D,e);for(let n=0;n<e;n++)r.fields[n]=Xo(t);return r},Xo=t=>{let e=t.cstring(),r=t.uint32(),n=t.int16(),s=t.uint32(),i=t.int16(),o=t.int32(),u=t.int16()===0?"text":"binary";return new v.Field(e,r,n,s,i,o,u)},Zo=t=>{let e=t.int16(),r=new v.ParameterDescriptionMessage(D,e);for(let n=0;n<e;n++)r.dataTypeIDs[n]=t.int32();return r},ea=t=>{let e=t.int16(),r=new Array(e);for(let n=0;n<e;n++){let s=t.int32();r[n]=s===-1?null:t.string(s)}return new v.DataRowMessage(D,r)},ta=t=>{let e=t.cstring(),r=t.cstring();return new v.ParameterStatusMessage(D,e,r)},ra=t=>{let e=t.int32(),r=t.int32();return new v.BackendKeyDataMessage(D,e,r)},na=(t,e)=>{let r=t.int32(),n={name:"authenticationOk",length:e};switch(r){case 0:break;case 3:n.length===8&&(n.name="authenticationCleartextPassword");break;case 5:if(n.length===12){n.name="authenticationMD5Password";let s=t.bytes(4);return new v.AuthenticationMD5Password(D,s)}break;case 10:{n.name="authenticationSASL",n.mechanisms=[];let s;do s=t.cstring(),s&&n.mechanisms.push(s);while(s)}break;case 11:n.name="authenticationSASLContinue",n.data=t.string(e-8);break;case 12:n.name="authenticationSASLFinal",n.data=t.string(e-8);break;default:throw new Error("Unknown authenticationOk message type "+r)}return n},yn=(t,e)=>{let r={},n=t.string(1);for(;n!=="\0";)r[n]=t.cstring(),n=t.string(1);let s=r.M,i=e==="notice"?new v.NoticeMessage(D,s):new v.DatabaseError(s,D,e);return i.severity=r.S,i.code=r.C,i.detail=r.D,i.hint=r.H,i.position=r.P,i.internalPosition=r.p,i.internalQuery=r.q,i.where=r.W,i.schema=r.s,i.table=r.t,i.column=r.c,i.dataType=r.d,i.constraint=r.n,i.file=r.F,i.line=r.L,i.routine=r.R,i}});var Dt=f(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.DatabaseError=U.serialize=U.parse=void 0;var sa=kt();Object.defineProperty(U,"DatabaseError",{enumerable:!0,get:function(){return sa.DatabaseError}});var ia=fn();Object.defineProperty(U,"serialize",{enumerable:!0,get:function(){return ia.serialize}});var oa=_n();function aa(t,e){let r=new oa.Parser;return t.on("data",n=>r.parse(n,e)),new Promise(n=>t.on("end",()=>n()))}U.parse=aa});var wn=f(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.default={}});var Sn=f((uc,bn)=>{var{getStream:ua,getSecureStream:ca}=fa();bn.exports={getStream:ua,getSecureStream:ca};function la(){function t(r){let n=_("net");return new n.Socket}function e(r){return _("tls").connect(r)}return{getStream:t,getSecureStream:e}}function da(){function t(r){let{CloudflareSocket:n}=wn();return new n(r)}function e(r){return r.socket.startTls(r),r.socket}return{getStream:t,getSecureStream:e}}function ha(){if(typeof navigator=="object"&&navigator!==null&&typeof navigator.userAgent=="string")return navigator.userAgent==="Cloudflare-Workers";if(typeof Response=="function"){let t=new Response(null,{cf:{thing:!0}});if(typeof t.cf=="object"&&t.cf!==null&&t.cf.thing)return!0}return!1}function fa(){return ha()?da():la()}});var Bt=f((cc,vn)=>{"use strict";var pa=_("events").EventEmitter,{parse:ma,serialize:C}=Dt(),{getStream:ya,getSecureStream:ga}=Sn(),_a=C.flush(),wa=C.sync(),ba=C.end(),Ot=class extends pa{constructor(e){super(),e=e||{},this.stream=e.stream||ya(e.ssl),typeof this.stream=="function"&&(this.stream=this.stream(e)),this._keepAlive=e.keepAlive,this._keepAliveInitialDelayMillis=e.keepAliveInitialDelayMillis,this.parsedStatements={},this.ssl=e.ssl||!1,this._ending=!1,this._emitMessage=!1;let r=this;this.on("newListener",function(n){n==="message"&&(r._emitMessage=!0)})}connect(e,r){let n=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(e,r),this.stream.once("connect",function(){n._keepAlive&&n.stream.setKeepAlive(!0,n._keepAliveInitialDelayMillis),n.emit("connect")});let s=function(i){n._ending&&(i.code==="ECONNRESET"||i.code==="EPIPE")||n.emit("error",i)};if(this.stream.on("error",s),this.stream.on("close",function(){n.emit("end")}),!this.ssl)return this.attachListeners(this.stream);this.stream.once("data",function(i){switch(i.toString("utf8")){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"))}let u={socket:n.stream};n.ssl!==!0&&(Object.assign(u,n.ssl),"key"in n.ssl&&(u.key=n.ssl.key));let a=_("net");a.isIP&&a.isIP(r)===0&&(u.servername=r);try{n.stream=ga(u)}catch(c){return n.emit("error",c)}n.attachListeners(n.stream),n.stream.on("error",s),n.emit("sslconnect")})}attachListeners(e){ma(e,r=>{let n=r.name==="error"?"errorMessage":r.name;this._emitMessage&&this.emit("message",r),this.emit(n,r)})}requestSsl(){this.stream.write(C.requestSsl())}startup(e){this.stream.write(C.startup(e))}cancel(e,r){this._send(C.cancel(e,r))}password(e){this._send(C.password(e))}sendSASLInitialResponseMessage(e,r){this._send(C.sendSASLInitialResponseMessage(e,r))}sendSCRAMClientFinalMessage(e){this._send(C.sendSCRAMClientFinalMessage(e))}_send(e){return this.stream.writable?this.stream.write(e):!1}query(e){this._send(C.query(e))}parse(e){this._send(C.parse(e))}bind(e){this._send(C.bind(e))}execute(e){this._send(C.execute(e))}flush(){this.stream.writable&&this.stream.write(_a)}sync(){this._ending=!0,this._send(wa)}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(ba,()=>{this.stream.end()})}close(e){this._send(C.close(e))}describe(e){this._send(C.describe(e))}sendCopyFromChunk(e){this._send(C.copyData(e))}endCopyFrom(){this._send(C.copyDone())}sendCopyFail(e){this._send(C.copyFail(e))}};vn.exports=Ot});var kn=f((lc,Cn)=>{"use strict";var{Transform:Sa}=_("stream"),{StringDecoder:va}=_("string_decoder"),j=Symbol("last"),Le=Symbol("decoder");function Ea(t,e,r){let n;if(this.overflow){if(n=this[Le].write(t).split(this.matcher),n.length===1)return r();n.shift(),this.overflow=!1}else this[j]+=this[Le].write(t),n=this[j].split(this.matcher);this[j]=n.pop();for(let s=0;s<n.length;s++)try{An(this,this.mapper(n[s]))}catch(i){return r(i)}if(this.overflow=this[j].length>this.maxLength,this.overflow&&!this.skipOverflow){r(new Error("maximum buffer reached"));return}r()}function Aa(t){if(this[j]+=this[Le].end(),this[j])try{An(this,this.mapper(this[j]))}catch(e){return t(e)}t()}function An(t,e){e!==void 0&&t.push(e)}function En(t){return t}function Ca(t,e,r){switch(t=t||/\r?\n/,e=e||En,r=r||{},arguments.length){case 1:typeof t=="function"?(e=t,t=/\r?\n/):typeof t=="object"&&!(t instanceof RegExp)&&!t[Symbol.split]&&(r=t,t=/\r?\n/);break;case 2:typeof t=="function"?(r=e,e=t,t=/\r?\n/):typeof e=="object"&&(r=e,e=En)}r=Object.assign({},r),r.autoDestroy=!0,r.transform=Ea,r.flush=Aa,r.readableObjectMode=!0;let n=new Sa(r);return n[j]="",n[Le]=new va("utf8"),n.matcher=t,n.mapper=e,n.maxLength=r.maxLength,n.skipOverflow=r.skipOverflow||!1,n.overflow=!1,n._destroy=function(s,i){this._writableState.errorEmitted=!1,i(s)},n}Cn.exports=Ca});var Pn=f((dc,Q)=>{"use strict";var Rn=_("path"),ka=_("stream").Stream,Ra=kn(),In=_("util"),Ia=5432,Oe=process.platform==="win32",ye=process.stderr,Pa=56,Ta=7,xa=61440,Ma=32768;function qa(t){return(t&xa)==Ma}var re=["host","port","database","user","password"],Nt=re.length,Da=re[Nt-1];function Qt(){var t=ye instanceof ka&&ye.writable===!0;if(t){var e=Array.prototype.slice.call(arguments).concat(`
|
|
10
|
-
`);ye.write(In.format.apply(In,e))}}Object.defineProperty(Q.exports,"isWin",{get:function(){return Oe},set:function(t){Oe=t}});Q.exports.warnTo=function(t){var e=ye;return ye=t,e};Q.exports.getFileName=function(t){var e=t||process.env,r=e.PGPASSFILE||(Oe?Rn.join(e.APPDATA||"./","postgresql","pgpass.conf"):Rn.join(e.HOME||"./",".pgpass"));return r};Q.exports.usePgPass=function(t,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:Oe?!0:(e=e||"<unkn>",qa(t.mode)?t.mode&(Pa|Ta)?(Qt('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(Qt('WARNING: password file "%s" is not a plain file',e),!1))};var La=Q.exports.match=function(t,e){return re.slice(0,-1).reduce(function(r,n,s){return s==1&&Number(t[n]||Ia)===Number(e[n])?r&&!0:r&&(e[n]==="*"||e[n]===t[n])},!0)};Q.exports.getPassword=function(t,e,r){var n,s=e.pipe(Ra());function i(a){var c=Oa(a);c&&Ba(c)&&La(t,c)&&(n=c[Da],s.end())}var o=function(){e.destroy(),r(n)},u=function(a){e.destroy(),Qt("WARNING: error on reading file: %s",a),r(void 0)};e.on("error",u),s.on("data",i).on("end",o).on("error",u)};var Oa=Q.exports.parseLine=function(t){if(t.length<11||t.match(/^\s+#/))return null;for(var e="",r="",n=0,s=0,i=0,o={},u=!1,a=function(l,d,y){var w=t.substring(d,y);Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE")||(w=w.replace(/\\([:\\])/g,"$1")),o[re[l]]=w},c=0;c<t.length-1;c+=1){if(e=t.charAt(c+1),r=t.charAt(c),u=n==Nt-1,u){a(n,s);break}c>=0&&e==":"&&r!=="\\"&&(a(n,s,c+1),s=c+2,n+=1)}return o=Object.keys(o).length===Nt?o:null,o},Ba=Q.exports.isValidEntry=function(t){for(var e={0:function(o){return o.length>0},1:function(o){return o==="*"?!0:(o=Number(o),isFinite(o)&&o>0&&o<9007199254740992&&Math.floor(o)===o)},2:function(o){return o.length>0},3:function(o){return o.length>0},4:function(o){return o.length>0}},r=0;r<re.length;r+=1){var n=e[r],s=t[re[r]]||"",i=n(s);if(!i)return!1}return!0}});var xn=f((fc,Ft)=>{"use strict";var hc=_("path"),Tn=_("fs"),Be=Pn();Ft.exports=function(t,e){var r=Be.getFileName();Tn.stat(r,function(n,s){if(n||!Be.usePgPass(s,r))return e(void 0);var i=Tn.createReadStream(r);Be.getPassword(t,i,e)})};Ft.exports.warnTo=Be.warnTo});var On=f((pc,Ln)=>{var Na=_("events").EventEmitter,Mn=Y(),ge=_("util"),Ht=Kr(),Qa=Pe(),Fa=ut(),Dn=ln(),Ha=pe(),Ua=Bt(),ja=st(),qn=ge.deprecate(()=>{},"Client.activeQuery is deprecated and will be removed in pg@9.0"),Ga=ge.deprecate(()=>{},"Client.queryQueue is deprecated and will be removed in pg@9.0."),$a=ge.deprecate(()=>{},"pgpass support is deprecated and will be removed in pg@9.0. You can provide an async function as the password property to the Client/Pool constructor that returns a password instead. Within this function you can call the pgpass module in your own code."),Wa=ge.deprecate(()=>{},"Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0."),Va=ge.deprecate(()=>{},"Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead."),Ne=class extends Na{constructor(e){super(),this.connectionParameters=new Fa(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;let r=e||{};r.Promise&&Wa(),this._Promise=r.Promise||global.Promise,this._types=new Qa(r.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this._activeQuery=null,this.enableChannelBinding=!!r.enableChannelBinding,this.connection=r.connection||new Ua({stream:r.stream,ssl:this.connectionParameters.ssl,keepAlive:r.keepAlive||!1,keepAliveInitialDelayMillis:r.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this._queryQueue=[],this.binary=r.binary||Ha.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=r.connectionTimeoutMillis||0}get activeQuery(){return qn(),this._activeQuery}set activeQuery(e){qn(),this._activeQuery=e}_getActiveQuery(){return this._activeQuery}_errorAllQueries(e){let r=s=>{process.nextTick(()=>{s.handleError(e,this.connection)})},n=this._getActiveQuery();n&&(r(n),this._activeQuery=null),this._queryQueue.forEach(r),this._queryQueue.length=0}_connect(e){let r=this,n=this.connection;if(this._connectionCallback=e,this._connecting||this._connected){let s=new Error("Client has already been connected. You cannot reuse a client.");process.nextTick(()=>{e(s)});return}this._connecting=!0,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{n._ending=!0,n.stream.destroy(new Error("timeout expired"))},this._connectionTimeoutMillis),this.connectionTimeoutHandle.unref&&this.connectionTimeoutHandle.unref()),this.host&&this.host.indexOf("/")===0?n.connect(this.host+"/.s.PGSQL."+this.port):n.connect(this.port,this.host),n.on("connect",function(){r.ssl?n.requestSsl():n.startup(r.getStartupConf())}),n.on("sslconnect",function(){n.startup(r.getStartupConf())}),this._attachListeners(n),n.once("end",()=>{let s=this._ending?new Error("Connection terminated"):new Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(s),this._ended=!0,this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(s):this._handleErrorEvent(s):this._connectionError||this._handleErrorEvent(s)),process.nextTick(()=>{this.emit("end")})})}connect(e){if(e){this._connect(e);return}return new this._Promise((r,n)=>{this._connect(s=>{s?n(s):r(this)})})}_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))}_getPassword(e){let r=this.connection;if(typeof this.password=="function")this._Promise.resolve().then(()=>this.password(this.connectionParameters)).then(n=>{if(n!==void 0){if(typeof n!="string"){r.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=>{r.emit("error",n)});else if(this.password!==null)e();else try{xn()(this.connectionParameters,s=>{s!==void 0&&($a(),this.connectionParameters.password=this.password=s),e()})}catch(n){this.emit("error",n)}}_handleAuthCleartextPassword(e){this._getPassword(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){this._getPassword(async()=>{try{let r=await ja.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(r)}catch(r){this.emit("error",r)}})}_handleAuthSASL(e){this._getPassword(()=>{try{this.saslSession=Ht.startSession(e.mechanisms,this.enableChannelBinding&&this.connection.stream),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(r){this.connection.emit("error",r)}})}async _handleAuthSASLContinue(e){try{await Ht.continueSession(this.saslSession,this.password,e.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(r){this.connection.emit("error",r)}}_handleAuthSASLFinal(e){try{Ht.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(r){this.connection.emit("error",r)}}_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 r=this._getActiveQuery();this._activeQuery=null,this.readyForQuery=!0,r&&r.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 r=this._getActiveQuery();if(!r){this._handleErrorEvent(e);return}this._activeQuery=null,r.handleError(e,this.connection)}_handleRowDescription(e){let r=this._getActiveQuery();if(r==null){let n=new Error("Received unexpected rowDescription message from backend.");this._handleErrorEvent(n);return}r.handleRowDescription(e)}_handleDataRow(e){let r=this._getActiveQuery();if(r==null){let n=new Error("Received unexpected dataRow message from backend.");this._handleErrorEvent(n);return}r.handleDataRow(e)}_handlePortalSuspended(e){let r=this._getActiveQuery();if(r==null){let n=new Error("Received unexpected portalSuspended message from backend.");this._handleErrorEvent(n);return}r.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){let r=this._getActiveQuery();if(r==null){let n=new Error("Received unexpected emptyQuery message from backend.");this._handleErrorEvent(n);return}r.handleEmptyQuery(this.connection)}_handleCommandComplete(e){let r=this._getActiveQuery();if(r==null){let n=new Error("Received unexpected commandComplete message from backend.");this._handleErrorEvent(n);return}r.handleCommandComplete(e,this.connection)}_handleParseComplete(){let e=this._getActiveQuery();if(e==null){let r=new Error("Received unexpected parseComplete message from backend.");this._handleErrorEvent(r);return}e.name&&(this.connection.parsedStatements[e.name]=e.text)}_handleCopyInResponse(e){let r=this._getActiveQuery();if(r==null){let n=new Error("Received unexpected copyInResponse message from backend.");this._handleErrorEvent(n);return}r.handleCopyInResponse(this.connection)}_handleCopyData(e){let r=this._getActiveQuery();if(r==null){let n=new Error("Received unexpected copyData message from backend.");this._handleErrorEvent(n);return}r.handleCopyData(e,this.connection)}_handleNotification(e){this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){let e=this.connectionParameters,r={user:e.user,database:e.database},n=e.application_name||e.fallback_application_name;return n&&(r.application_name=n),e.replication&&(r.replication=""+e.replication),e.statement_timeout&&(r.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(r.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(r.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(r.options=e.options),r}cancel(e,r){if(e.activeQuery===r){let 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(r)!==-1&&e._queryQueue.splice(e._queryQueue.indexOf(r),1)}setTypeParser(e,r,n){return this._types.setTypeParser(e,r,n)}getTypeParser(e,r){return this._types.getTypeParser(e,r)}escapeIdentifier(e){return Mn.escapeIdentifier(e)}escapeLiteral(e){return Mn.escapeLiteral(e)}_pulseQueryQueue(){if(this.readyForQuery===!0){this._activeQuery=this._queryQueue.shift();let e=this._getActiveQuery();if(e){this.readyForQuery=!1,this.hasExecuted=!0;let r=e.submit(this.connection);r&&process.nextTick(()=>{e.handleError(r,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this._activeQuery=null,this.emit("drain"))}}query(e,r,n){let s,i,o,u,a;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,i=s=e,s.callback||(typeof r=="function"?s.callback=r:n&&(s.callback=n))):(o=e.query_timeout||this.connectionParameters.query_timeout,s=new Dn(e,r,n),s.callback||(i=new this._Promise((c,l)=>{s.callback=(d,y)=>d?l(d):c(y)}).catch(c=>{throw Error.captureStackTrace(c),c}))),o&&(a=s.callback||(()=>{}),u=setTimeout(()=>{let c=new Error("Query read timeout");process.nextTick(()=>{s.handleError(c,this.connection)}),a(c),s.callback=()=>{};let l=this._queryQueue.indexOf(s);l>-1&&this._queryQueue.splice(l,1),this._pulseQueryQueue()},o),s.callback=(c,l)=>{clearTimeout(u),a(c,l)}),this.binary&&!s.binary&&(s.binary=!0),s._result&&!s._result._types&&(s._result._types=this._types),this._queryable?this._ending?(process.nextTick(()=>{s.handleError(new Error("Client was closed and is not queryable"),this.connection)}),i):(this._queryQueue.length>0&&Va(),this._queryQueue.push(s),this._pulseQueryQueue(),i):(process.nextTick(()=>{s.handleError(new Error("Client has encountered a connection error and is not queryable"),this.connection)}),i)}ref(){this.connection.ref()}unref(){this.connection.unref()}end(e){if(this._ending=!0,!this.connection._connecting||this._ended)if(e)e();else return this._Promise.resolve();if(this._getActiveQuery()||!this._queryable?this.connection.stream.destroy():this.connection.end(),e)this.connection.once("end",e);else return new this._Promise(r=>{this.connection.once("end",r)})}get queryQueue(){return Ga(),this._queryQueue}};Ne.Query=Dn;Ln.exports=Ne});var Qn=f((mc,Nn)=>{"use strict";var Ja=_("events").EventEmitter,Ut=function(){},Bn=(t,e)=>{let r=t.findIndex(e);return r===-1?void 0:t.splice(r,1)[0]},jt=class{constructor(e,r,n){this.client=e,this.idleListener=r,this.timeoutId=n}},ne=class{constructor(e){this.callback=e}};function za(){throw new Error("Release called on client which has already been released to the pool.")}function Qe(t,e){if(e)return{callback:e,result:void 0};let r,n,s=function(o,u){o?r(o):n(u)},i=new t(function(o,u){n=o,r=u}).catch(o=>{throw Error.captureStackTrace(o),o});return{callback:s,result:i}}function Ka(t,e){return function r(n){n.client=e,e.removeListener("error",r),e.on("error",()=>{t.log("additional client error after disconnection due to error",n)}),t._remove(e),t.emit("error",n,e)}}var Gt=class extends Ja{constructor(e,r){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.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||r||$t().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}_promiseTry(e){let r=this.Promise;return typeof r.try=="function"?r.try(e):new r(n=>n(e()))}_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){this.log("pulse queue on ending"),this._idle.length&&this._idle.slice().map(r=>{this._remove(r.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 r=this._idle.pop();clearTimeout(r.timeoutId);let n=r.client;n.ref&&n.ref();let s=r.idleListener;return this._acquireClient(n,e,s,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpected condition")}_remove(e,r){let n=Bn(this._idle,i=>i.client===e);n!==void 0&&clearTimeout(n.timeoutId),this._clients=this._clients.filter(i=>i!==e);let s=this;e.end(()=>{s.emit("remove",e),typeof r=="function"&&r()})}connect(e){if(this.ending){let s=new Error("Cannot use a pool after calling end on the pool");return e?e(s):this.Promise.reject(s)}let r=Qe(this.Promise,e),n=r.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new ne(r.callback)),n;let s=(u,a,c)=>{clearTimeout(o),r.callback(u,a,c)},i=new ne(s),o=setTimeout(()=>{Bn(this._pendingQueue,u=>u.callback===s),i.timedOut=!0,r.callback(new Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return o.unref&&o.unref(),this._pendingQueue.push(i),n}return this.newClient(new ne(r.callback)),n}newClient(e){let r=new this.Client(this.options);this._clients.push(r);let n=Ka(this,r);this.log("checking client timeout");let s,i=!1;this.options.connectionTimeoutMillis&&(s=setTimeout(()=>{r.connection?(this.log("ending client due to timeout"),i=!0,r.connection.stream.destroy()):r.isConnected()||(this.log("ending client due to timeout"),i=!0,r.end())},this.options.connectionTimeoutMillis)),this.log("connecting new client"),r.connect(o=>{if(s&&clearTimeout(s),r.on("error",n),o)this.log("client failed to connect",o),this._clients=this._clients.filter(u=>u!==r),i&&(o=new Error("Connection terminated due to connection timeout",{cause:o})),this._pulseQueue(),e.timedOut||e.callback(o,void 0,Ut);else{if(this.log("new client connected"),this.options.onConnect){this._promiseTry(()=>this.options.onConnect(r)).then(()=>{this._afterConnect(r,e,n)},u=>{this._clients=this._clients.filter(a=>a!==r),r.end(()=>{this._pulseQueue(),e.timedOut||e.callback(u,void 0,Ut)})});return}return this._afterConnect(r,e,n)}})}_afterConnect(e,r,n){if(this.options.maxLifetimeSeconds!==0){let s=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired.add(e),this._idle.findIndex(o=>o.client===e)!==-1&&this._acquireClient(e,new ne((o,u,a)=>a()),n,!1)},this.options.maxLifetimeSeconds*1e3);s.unref(),e.once("end",()=>clearTimeout(s))}return this._acquireClient(e,r,n,!0)}_acquireClient(e,r,n,s){s&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,n),e.removeListener("error",n),r.timedOut?s&&this.options.verify?this.options.verify(e,e.release):e.release():s&&this.options.verify?this.options.verify(e,i=>{if(i)return e.release(i),r.callback(i,void 0,Ut);r.callback(void 0,e,e.release)}):r.callback(void 0,e,e.release)}_releaseOnce(e,r){let n=!1;return s=>{n&&za(),n=!0,this._release(e,r,s)}}_release(e,r,n){if(e.on("error",r),e._poolUseCount=(e._poolUseCount||0)+1,this.emit("release",n,e),n||this.ending||!e._queryable||e._ending||e._poolUseCount>=this.options.maxUses)return e._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(e,this._pulseQueue.bind(this));if(this._expired.has(e))return this.log("remove expired client"),this._expired.delete(e),this._remove(e,this._pulseQueue.bind(this));let i;this.options.idleTimeoutMillis&&this._isAboveMin()&&(i=setTimeout(()=>{this._isAboveMin()&&(this.log("remove idle client"),this._remove(e,this._pulseQueue.bind(this)))},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&i.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new jt(e,r,i)),this._pulseQueue()}query(e,r,n){if(typeof e=="function"){let i=Qe(this.Promise,e);return setImmediate(function(){return i.callback(new Error("Passing a function as the first parameter to pool.query is not supported"))}),i.result}typeof r=="function"&&(n=r,r=void 0);let s=Qe(this.Promise,n);return n=s.callback,this.connect((i,o)=>{if(i)return n(i);let u=!1,a=c=>{u||(u=!0,o.release(c),n(c))};o.once("error",a),this.log("dispatching query");try{o.query(e,r,(c,l)=>{if(this.log("query dispatched"),o.removeListener("error",a),!u)return u=!0,o.release(c),c?n(c):n(void 0,l)})}catch(c){return o.release(c),n(c)}}),s.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 r=Qe(this.Promise,e);return this._endCallback=r.callback,this._pulseQueue(),r.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,r)=>e+(this._expired.has(r)?1:0),0)}get totalCount(){return this._clients.length}};Nn.exports=Gt});var Un=f((yc,Hn)=>{"use strict";var Fn=_("events").EventEmitter,Ya=_("util"),Wt=Y(),se=Hn.exports=function(t,e,r){Fn.call(this),t=Wt.normalizeQueryConfig(t,e,r),this.text=t.text,this.values=t.values,this.name=t.name,this.queryMode=t.queryMode,this.callback=t.callback,this.state="new",this._arrayMode=t.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(n){n==="row"&&(this._emitRowEvents=!0)}.bind(this))};Ya.inherits(se,Fn);var Xa={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};se.prototype.handleError=function(t){let e=this.native.pq.resultErrorFields();if(e)for(let r in e){let n=Xa[r]||r;t[n]=e[r]}this.callback?this.callback(t):this.emit("error",t),this.state="error"};se.prototype.then=function(t,e){return this._getPromise().then(t,e)};se.prototype.catch=function(t){return this._getPromise().catch(t)};se.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(t,e){this._once("end",t),this._once("error",e)}.bind(this)),this._promise)};se.prototype.submit=function(t){this.state="running";let e=this;this.native=t.native,t.native.arrayMode=this._arrayMode;let r=function(n,s,i){if(t.native.arrayMode=!1,setImmediate(function(){e.emit("_done")}),n)return e.handleError(n);e._emitRowEvents&&(i.length>1?s.forEach((o,u)=>{o.forEach(a=>{e.emit("row",a,i[u])})}):s.forEach(function(o){e.emit("row",o,i)})),e.state="end",e.emit("end",i),e.callback&&e.callback(null,i)};if(process.domain&&(r=process.domain.bind(r)),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"));let n=(this.values||[]).map(Wt.prepareValue);if(t.namedQueries[this.name]){if(this.text&&t.namedQueries[this.name]!==this.text){let s=new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return r(s)}return t.native.execute(this.name,n,r)}return t.native.prepare(this.name,this.text,n.length,function(s){return s?r(s):(t.namedQueries[e.name]=e.text,e.native.execute(e.name,n,r))})}else if(this.values){if(!Array.isArray(this.values)){let s=new Error("Query values must be an array");return r(s)}let n=this.values.map(Wt.prepareValue);t.native.query(this.text,n,r)}else this.queryMode==="extended"?t.native.query(this.text,[],r):t.native.query(this.text,r)}});var Vn=f((gc,Wn)=>{var Za=_("util"),jn;try{jn=_("pg-native")}catch(t){throw t}var eu=Pe(),Gn=_("events").EventEmitter,tu=_("util"),ru=ut(),$n=Un(),nu=Za.deprecate(()=>{},"Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead."),P=Wn.exports=function(t){Gn.call(this),t=t||{},this._Promise=t.Promise||global.Promise,this._types=new eu(t.types),this.native=new jn({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;let e=this.connectionParameters=new ru(t);t.nativeConnectionString&&(e.nativeConnectionString=t.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={}};P.Query=$n;tu.inherits(P,Gn);P.prototype._errorAllQueries=function(t){let e=r=>{process.nextTick(()=>{r.native=this.native,r.handleError(t)})};this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(e),this._queryQueue.length=0};P.prototype._connect=function(t){let e=this;if(this._connecting){process.nextTick(()=>t(new Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(r,n){if(e.connectionParameters.nativeConnectionString&&(n=e.connectionParameters.nativeConnectionString),r)return t(r);e.native.connect(n,function(s){if(s)return e.native.end(),t(s);e._connected=!0,e.native.on("error",function(i){e._queryable=!1,e._errorAllQueries(i),e.emit("error",i)}),e.native.on("notification",function(i){e.emit("notification",{channel:i.relname,payload:i.extra})}),e.emit("connect"),e._pulseQueryQueue(!0),t(null,this)})})};P.prototype.connect=function(t){if(t){this._connect(t);return}return new this._Promise((e,r)=>{this._connect(n=>{n?r(n):e(this)})})};P.prototype.query=function(t,e,r){let n,s,i,o,u;if(t==null)throw new TypeError("Client was passed a null or undefined query");if(typeof t.submit=="function")i=t.query_timeout||this.connectionParameters.query_timeout,s=n=t,typeof e=="function"&&(t.callback=e);else if(i=t.query_timeout||this.connectionParameters.query_timeout,n=new $n(t,e,r),!n.callback){let a,c;s=new this._Promise((l,d)=>{a=l,c=d}).catch(l=>{throw Error.captureStackTrace(l),l}),n.callback=(l,d)=>l?c(l):a(d)}return i&&(u=n.callback||(()=>{}),o=setTimeout(()=>{let a=new Error("Query read timeout");process.nextTick(()=>{n.handleError(a,this.connection)}),u(a),n.callback=()=>{};let c=this._queryQueue.indexOf(n);c>-1&&this._queryQueue.splice(c,1),this._pulseQueryQueue()},i),n.callback=(a,c)=>{clearTimeout(o),u(a,c)}),this._queryable?this._ending?(n.native=this.native,process.nextTick(()=>{n.handleError(new Error("Client was closed and is not queryable"))}),s):(this._queryQueue.length>0&&nu(),this._queryQueue.push(n),this._pulseQueryQueue(),s):(n.native=this.native,process.nextTick(()=>{n.handleError(new Error("Client has encountered a connection error and is not queryable"))}),s)};P.prototype.end=function(t){let e=this;this._ending=!0,this._connected||this.once("connect",this.end.bind(this,t));let r;return t||(r=new this._Promise(function(n,s){t=i=>i?s(i):n()})),this.native.end(function(){e._connected=!1,e._errorAllQueries(new Error("Connection terminated")),process.nextTick(()=>{e.emit("end"),t&&t()})}),r};P.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};P.prototype._pulseQueryQueue=function(t){if(!this._connected||this._hasActiveQuery())return;let e=this._queryQueue.shift();if(!e){t||this.emit("drain");return}this._activeQuery=e,e.submit(this);let r=this;e.once("_done",function(){r._pulseQueryQueue()})};P.prototype.cancel=function(t){this._activeQuery===t?this.native.cancel(function(){}):this._queryQueue.indexOf(t)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(t),1)};P.prototype.ref=function(){};P.prototype.unref=function(){};P.prototype.setTypeParser=function(t,e,r){return this._types.setTypeParser(t,e,r)};P.prototype.getTypeParser=function(t,e){return this._types.getTypeParser(t,e)};P.prototype.isConnected=function(){return this._connected}});var Vt=f((_c,Jn)=>{"use strict";Jn.exports=Vn()});var $t=f((bc,Fe)=>{"use strict";var su=On(),iu=pe(),ou=Bt(),au=lt(),uu=Y(),cu=Qn(),lu=Pe(),{DatabaseError:du}=Dt(),{escapeIdentifier:hu,escapeLiteral:fu}=Y(),pu=t=>class extends cu{constructor(r){super(r,t)}},zn=function(t){this.defaults=iu,this.Client=t,this.Query=this.Client.Query,this.Pool=pu(this.Client),this._pools=[],this.Connection=ou,this.types=fe(),this.DatabaseError=du,this.TypeOverrides=lu,this.escapeIdentifier=hu,this.escapeLiteral=fu,this.Result=au,this.utils=uu},Kn=su,Yn=!1;try{Yn=!!process.env.NODE_PG_FORCE_NATIVE}catch{}Yn&&(Kn=Vt());Fe.exports=new zn(Kn);Object.defineProperty(Fe.exports,"native",{configurable:!0,enumerable:!1,get(){let t=null;try{t=new zn(Vt())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(Fe.exports,"native",{value:t}),t}})});import{createClient as fs,z as q,RESERVED_HANDLER_NAMES as ps,runWithInvocationContext as ms}from"@stackbone/sdk";import{createHmac as us,timingSafeEqual as cs}from"node:crypto";var ls=3e5,J={timestamp:"x-stackbone-timestamp",signature:"x-stackbone-signature"};function ve(t){let e=t.driftToleranceMs??ls,r=Number(t.timestamp);if(!Number.isFinite(r)||Math.abs(Date.now()-r)>e)return!1;let s=ds({method:t.method,path:t.path,body:t.body,secret:t.secret,timestamp:t.timestamp});return hs(s,t.signature)}function ds(t){let e=`${t.method}${t.path}${t.timestamp}${t.body}`;return us("sha256",t.secret).update(e).digest("hex")}function hs(t,e){if(t.length!==e.length)return!1;let r,n;try{r=Buffer.from(t,"hex"),n=Buffer.from(e,"hex")}catch{return!1}return r.length!==n.length?!1:cs(r,n)}var ys=3e4,gs=5e3,tr=15e3,rr=q.object({invocationId:q.string().min(1),runId:q.string().min(1),payload:q.unknown(),dispatch_id:q.string().min(1).optional(),name:q.string().optional(),attempts:q.number().int().nonnegative().optional(),handler:q.string().min(1).optional(),persist_run:q.boolean().optional(),is_playground:q.boolean().optional()}),_s={handler_error:"error",output_validation_error:"error",timeout_error:"error",unknown_job:"error",validation_error:"warn",unknown_handler:"warn"},ws={handler_error:"invoke failed: handler threw",output_validation_error:"invoke failed: output validation failed",timeout_error:"invoke failed: timed out",unknown_job:"invoke failed: unknown job handler",validation_error:"invoke failed: input validation failed",unknown_handler:"invoke failed: unknown handler"};function bs(t){let e=t.client??fs(),r=new Map;return async n=>n.method==="GET"&&n.path==="/live"?vs():n.method==="GET"&&n.path==="/health"?Es(t.probes??{},t.probeTimeoutMs??gs):n.method==="GET"&&n.path==="/schema"?Cs(t.spec):n.method==="GET"&&n.path==="/runs/active"?Ss(n,t,r):n.method==="POST"&&n.path==="/invoke"?ks(n,t,e,r):A(404,{error:"not_found"})}function Ss(t,e,r){let n=oe(t.headers,J.timestamp),s=oe(t.headers,J.signature);if(!n||!s)return A(401,{error:"missing_hmac_headers"});if(!ve({method:"GET",path:"/runs/active",body:"",secret:e.hmacSecret,timestamp:n,signature:s}))return A(401,{error:"invalid_hmac"});let o=[...r.entries()].map(([u,a])=>({dispatch_id:u,run_id:a.runId,name:a.name,started_at:a.startedAt.toISOString(),heartbeat_at:a.heartbeatAt.toISOString(),deadline_at:a.deadlineAt.toISOString()}));return A(200,{active:o})}function vs(){return{status:200,headers:{},body:""}}async function Es(t,e){let r=Object.entries(t),n=await Promise.all(r.map(async([u,a])=>{let c=Date.now();try{let l=await As(a(),e);return[u,{...l,latencyMs:Date.now()-c}]}catch(l){return[u,{ok:!1,error:l instanceof Error?l.message:String(l),latencyMs:Date.now()-c}]}})),s={},i=!0;for(let[u,a]of n)a.ok||(i=!1),s[u]={status:a.ok?"ok":"degraded",latencyMs:a.latencyMs,...a.error?{error:a.error}:{}};return A(i?200:503,{status:i?"ok":"degraded",checks:s})}async function As(t,e){let r,n=new Promise((s,i)=>{r=setTimeout(()=>i(new Error(`probe timed out after ${e}ms`)),e)});try{return await Promise.race([t,n])}finally{clearTimeout(r)}}function Cs(t){let e=q.toJSONSchema(t.invoke.input),r=t.invoke.output?q.toJSONSchema(t.invoke.output):{},n={};for(let s of Object.keys(t)){let i=t[s];i&&(n[s]={input:Zt(i.input),output:i.output?Zt(i.output):{}})}return A(200,{input:e,output:r,handlers:n})}function Zt(t){try{return q.toJSONSchema(t)}catch{return null}}async function ks(t,e,r,n){let s=oe(t.headers,J.timestamp),i=oe(t.headers,J.signature);if(!s||!i)return A(401,{error:"missing_hmac_headers"});if(!ve({method:"POST",path:"/invoke",body:t.body,secret:e.hmacSecret,timestamp:s,signature:i}))return A(401,{error:"invalid_hmac"});let u;try{u=await e.loadAgentConfig()}catch(p){let E=p instanceof Error?p.message:String(p);return A(500,{error:"agent_config_unavailable",message:`Failed to load stackbone_platform.agent_config: ${E}`})}let a;try{let p=JSON.parse(t.body);a=rr.parse(p)}catch(p){return A(400,{error:"invalid_envelope",message:p instanceof Error?p.message:String(p)})}let{journal:c,runWriter:l}=e,d=a.dispatch_id,y=async p=>{if(!(!c||d===void 0))try{await c.recordStarted({dispatchId:d,name:a.name??"",payload:a.payload,attempt:a.attempts??1,runId:a.runId,deadlineAt:p})}catch(E){e.logger?.warn("queue_journal.start_failed",{event:"queue_journal.start_failed",dispatch_id:d,error:E instanceof Error?E.message:String(E)})}},w=async(p,E)=>{if(!(!c||d===void 0))try{await c.recordFinished({dispatchId:d,status:p,error:E})}catch(m){let g=m instanceof Error?m.message:String(m);p==="done"?e.logger?.error("queue_journal.completed_write_lost",{event:"queue_journal.completed_write_lost",severity:"data_loss",dispatch_id:d,error:g}):e.logger?.warn("queue_journal.finish_failed",{event:"queue_journal.finish_failed",dispatch_id:d,status:p,error:g})}},k=l!==void 0&&(d!==void 0||a.persist_run===!0),G=d!==void 0?"job":"manual",V=d===void 0&&a.is_playground===!0,N=async()=>{if(!(!l||!k))try{await l.open({runId:a.runId,trigger:G,isPlayground:V,traceId:a.invocationId,input:a.payload})}catch(p){e.logger?.warn("run_row.start_failed",{event:"run_row.start_failed",run_id:a.runId,error:p instanceof Error?p.message:String(p)})}},T=async(p,E,m)=>{if(!(!l||!k))try{await l.close({runId:a.runId,status:p,error:E,output:m})}catch(g){e.logger?.warn("run_row.finish_failed",{event:"run_row.finish_failed",run_id:a.runId,status:p,error:g instanceof Error?g.message:String(g)})}},F={trace_id:a.invocationId,run_id:a.runId,installation_id:e.installationId,organization_id:e.organizationId,agent_id:e.agentId};e.logger?.info("invoke.received",{event:"invoke.received",...F});let _e=Date.now(),we={},R=(p,E,m)=>{let g=we.name?{handler:we.name}:{};if(e.logger?.info("invoke.completed",{event:"invoke.completed",...F,...g,status:p,latency_ms:Date.now()-_e,...E?{last_error_reason:E}:{}}),p==="failed"&&E){let es=m?.message??ws[E];e.logger?.[_s[E]](es,{event:"invoke.failed",...F,...g,status:p,reason:E,latency_ms:Date.now()-_e,...m?.stack?{stack:m.stack}:{},...m?.issues!==void 0?{issues:m.issues}:{}})}},zt=Ps(e.spec,a);if(!zt)return a.dispatch_id!==void 0?(R("failed","unknown_job"),A(422,{error:"unknown_job",name:a.name??null,message:`No job handler named \`${a.name??""}\`. Declare it as a top-level handler in defineAgent({...}).`})):(R("failed","unknown_handler"),A(422,{error:"unknown_handler",handler:a.handler??null,message:`No handler named \`${a.handler??""}\`. Declare it as a top-level handler in defineAgent({...}).`}));let{capability:be,name:Se}=zt;we.name=Se;let ie=be.input.safeParse(a.payload);if(!ie.success)return R("failed","validation_error",{issues:ie.error.issues}),A(400,{error:"validation_error",issues:ie.error.issues});let Ue=be.timeoutMs??ys,Kt=new Date(Date.now()+Ue);await y(Kt),await N();let Yt=()=>er({capability:be,handlerName:Se,input:ie.data,agentConfig:u,client:r,logger:e.logger,invocationId:a.invocationId,runId:a.runId,timeoutMs:Ue});if(d!==void 0){let p=new Date;n.set(d,{runId:a.runId,name:Se,startedAt:p,deadlineAt:Kt,heartbeatAt:p});let E=setInterval(()=>{let m=n.get(d);m&&(m.heartbeatAt=new Date),Promise.resolve().then(()=>c?.recordHeartbeat({dispatchId:d})).catch(g=>{e.logger?.warn("queue_journal.heartbeat_failed",{event:"queue_journal.heartbeat_failed",dispatch_id:d,error:g instanceof Error?g.message:String(g)})})},tr);return E.unref?.(),(async()=>{let m;try{let g=await Yt();g.kind==="success"?(R("succeeded"),await w("done",null),await T("done",null,g.outputData),m="done"):g.kind==="output_validation_error"?(R("failed","output_validation_error",{issues:g.issues}),await w("failed","output validation failed"),await T("failed","output validation failed",null),m="failed"):g.kind==="timeout"?(R("failed","timeout_error",{message:g.message}),await w("failed",g.message),await T("failed",g.message,null),m="failed"):(R("failed","handler_error",{message:g.message,...g.stack?{stack:g.stack}:{}}),await w("failed",g.message),await T("failed",g.message,null),m="failed")}finally{clearInterval(E),n.delete(d)}m!==void 0&&await Rs(e,{dispatchId:d,runId:a.runId,status:m})})(),A(202,{dispatch_id:d,runId:a.runId})}if((oe(t.headers,"accept")??"").includes("text/event-stream")){let p=Is(),E;return(async()=>{try{let m=await er({capability:be,handlerName:Se,input:ie.data,agentConfig:u,client:r,logger:e.logger,invocationId:a.invocationId,runId:a.runId,timeoutMs:Ue,stream:p.sink,onController:g=>{E=g}});m.kind==="success"?(R("succeeded"),p.result(m.outputData),await T("done",null,m.outputData)):m.kind==="output_validation_error"?(R("failed","output_validation_error",{issues:m.issues}),p.error("output_validation_error","output validation failed"),await T("failed","output validation failed",null)):m.kind==="timeout"?(R("failed","timeout_error",{message:m.message}),p.error("timeout_error",m.message),await T("failed",m.message,null)):(R("failed","handler_error",{message:m.message,...m.stack?{stack:m.stack}:{}}),p.error("handler_error",m.message),await T("failed",m.message,null))}finally{p.close()}})(),{status:200,headers:{"content-type":"text/event-stream","cache-control":"no-cache, no-transform",connection:"keep-alive"},stream:p.iterable(()=>E?.abort())}}let M=await Yt();return M.kind==="success"?(R("succeeded"),await w("done",null),A(200,{invocationId:a.invocationId,runId:a.runId,result:M.outputData})):M.kind==="output_validation_error"?(R("failed","output_validation_error",{issues:M.issues}),await w("failed","output validation failed"),A(500,{error:"output_validation_error",issues:M.issues})):M.kind==="timeout"?(R("failed","timeout_error",{message:M.message}),await w("failed",M.message),A(504,{error:"timeout_error"})):(R("failed","handler_error",{message:M.message,...M.stack?{stack:M.stack}:{}}),await w("failed",M.message),A(500,{error:"handler_error",message:M.message}))}async function Rs(t,e){let{completionCallback:r}=t;if(r)try{await r(e)}catch(n){t.logger?.warn("completion_callback.failed",{event:"completion_callback.failed",dispatch_id:e.dispatchId,run_id:e.runId,status:e.status,error:n instanceof Error?n.message:String(n)})}}async function er(t){let{capability:e,handlerName:r,input:n,agentConfig:s,client:i,logger:o,invocationId:u,runId:a,timeoutMs:c,stream:l}=t,d=new AbortController;t.onController?.(d);let y=!1,w;try{let k=o?.child({trace_id:u,run_id:a,handler:r}),G={input:n,signal:d.signal,invocationId:u,runId:a,client:i,logger:k,config:s,...l?{stream:l}:{}},V=await new Promise((N,T)=>{w=setTimeout(()=>{y=!0,d.abort(),T(new Error(`invoke exceeded its ${c}ms timeout`))},c),Promise.resolve(ms({invocationId:u,runId:a,handler:r},()=>e.run(G))).then(N,T)});if(e.output){let N=e.output.safeParse(V);return N.success?{kind:"success",outputData:N.data}:{kind:"output_validation_error",issues:N.error.issues}}return{kind:"success",outputData:V}}catch(k){return y?{kind:"timeout",message:`invoke exceeded its ${c}ms timeout`}:{kind:"handler_error",message:k instanceof Error?k.message:String(k),...k instanceof Error&&k.stack?{stack:k.stack}:{}}}finally{clearTimeout(w)}}function Is(){let t=[],e=!1,r,n=0,s=()=>n+=1,i=u=>{e||(t.push(u),r?.(),r=void 0)};return{sink:{delta(u){i(Ee(s(),"delta",{text:u}))},event(u,a){i(Ee(s(),"event",{name:u,data:a}))}},result(u){i(Ee(s(),"result",u))},error(u,a){i(Ee(s(),"error",{code:u,message:a}))},close(){e=!0,r?.(),r=void 0},iterable(u){let a=setInterval(()=>i(`: ping
|
|
11
|
-
|
|
12
|
-
`),tr);a.unref?.();let c=()=>clearInterval(a);return{[Symbol.asyncIterator](){return{async next(){for(;;){let l=t.shift();if(l!==void 0)return{value:l,done:!1};if(e)return c(),{value:void 0,done:!0};await new Promise(d=>{r=d})}},async return(){return c(),e=!0,u(),r?.(),r=void 0,{value:void 0,done:!0}}}}}}}}function Ee(t,e,r){return`id: ${t}
|
|
13
|
-
event: ${e}
|
|
14
|
-
data: ${JSON.stringify(r??null)}
|
|
15
|
-
|
|
16
|
-
`}function oe(t,e){let r=e.toLowerCase();for(let[n,s]of Object.entries(t))if(n.toLowerCase()===r&&s!==void 0)return s}function A(t,e){return{status:t,headers:{"content-type":"application/json"},body:JSON.stringify(e)}}function Ps(t,e){if(e.dispatch_id!==void 0){let n=e.name??"";if(!n||ps.includes(n))return null;let s=t[n];return s?{capability:s,name:n}:null}let r=e.handler;if(r!==void 0&&r!=="invoke"){let n=t[r];return n?{capability:n,name:r}:null}return{capability:t.invoke,name:"invoke"}}import{pathToFileURL as Ts}from"node:url";var ae=class extends Error{constructor(e,r){super(r),this.name="LoadSpecError",this.code=e}};async function xs(t){let e;try{e=await import(Ts(t).href)}catch(n){throw new ae("BUNDLE_IMPORT_FAILED",`Failed to import agent bundle at ${t}: ${n instanceof Error?n.message:String(n)}`)}let r=e.default;if(!Ms(r))throw new ae("BUNDLE_MISSING_AGENT_EXPORT","Bundle default export is not a valid agent: expected `{ invoke: { run: (ctx) => ... } }`. Did you forget `export default defineAgent({ invoke: { input, output, run } })`?");return{spec:r,sourcePath:t}}function Ms(t){if(typeof t!="object"||t===null||!("invoke"in t))return!1;let e=t.invoke;return typeof e!="object"||e===null||!("run"in e)?!1:typeof e.run=="function"}import{createServer as qs}from"node:http";var Ds=5*1024*1024,Ae=class extends Error{constructor(){super("request body exceeds the configured limit"),this.name="PayloadTooLargeError"}};function Ls(t){let e=t.maxBodyBytes??Ds,r=qs((n,s)=>{Os(t.handler,n,s,e)});return new Promise((n,s)=>{r.once("error",s),r.listen(t.port,t.host??"0.0.0.0",()=>{r.removeListener("error",s);let i=r.address();if(i===null||typeof i=="string"){s(new Error("createNodeHttpServer: server did not bind to a TCP port"));return}n({port:i.port,close:()=>new Promise((o,u)=>{r.close(a=>a?u(a):o())})})})})}async function Os(t,e,r,n){try{let s=Number(e.headers["content-length"]);if(Number.isFinite(s)&&s>n){nr(r);return}let i={method:e.method??"GET",path:e.url??"/",headers:Fs(e.headers),body:await Hs(e,n)},o=await t(i);if(Bs(o)){await Ns(e,r,o);return}r.statusCode=o.status;for(let[u,a]of Object.entries(o.headers))r.setHeader(u,a);r.end(o.body)}catch(s){if(s instanceof Ae){nr(r);return}console.error("[agent-server] request handler threw:",s),r.headersSent||(r.statusCode=500,r.setHeader("content-type","application/json"),r.end(JSON.stringify({error:"internal"})))}}function nr(t){t.headersSent||(t.statusCode=413,t.setHeader("content-type","application/json"),t.setHeader("connection","close"),t.end(JSON.stringify({error:"payload_too_large"})))}function Bs(t){return"stream"in t}async function Ns(t,e,r){e.statusCode=r.status;for(let[o,u]of Object.entries(r.headers))e.setHeader(o,u);e.flushHeaders();let n=r.stream[Symbol.asyncIterator](),s=!1,i=()=>{e.writableEnded||(s=!0,n.return?.().catch(()=>{}))};e.on("close",i),t.on("aborted",i);try{for(;!s;){let{value:o,done:u}=await n.next();if(u||s)break;e.write(o)||await Qs(e)}}finally{e.off("close",i),t.off("aborted",i),e.writableEnded||e.end()}}function Qs(t){return t.writableEnded?Promise.resolve():new Promise(e=>{let r=()=>{t.off("close",n),e()},n=()=>{t.off("drain",r),e()};t.once("drain",r),t.once("close",n)})}function Fs(t){let e={};for(let[r,n]of Object.entries(t))e[r]=Array.isArray(n)?n.join(", "):n;return e}async function Hs(t,e){let r=[],n=0;for await(let s of t){let i=typeof s=="string"?Buffer.from(s):s;if(n+=i.length,n>e)throw new Ae;r.push(i)}return Buffer.concat(r).toString("utf8")}var B=as($t(),1),He=B.default.Client,Sc=B.default.Pool,vc=B.default.Connection,Ec=B.default.types,Ac=B.default.Query,Cc=B.default.DatabaseError,kc=B.default.escapeIdentifier,Rc=B.default.escapeLiteral,Ic=B.default.Result,Pc=B.default.TypeOverrides,Tc=B.default.defaults;var Jt=async(t,e)=>{let r=new He({connectionString:t});await r.connect();try{return await e(r)}finally{await r.end().catch(()=>{})}};function mu(t){return{recordStarted:async e=>{await Jt(t,r=>r.query(`INSERT INTO stackbone_platform._queue_jobs
|
|
17
|
-
(dispatch_id, name, payload, attempts, started_at,
|
|
18
|
-
run_id, deadline_at, heartbeat_at)
|
|
19
|
-
VALUES ($1, $2, $3::jsonb, $4, now(), $5, $6, now())
|
|
20
|
-
ON CONFLICT (dispatch_id) DO UPDATE SET
|
|
21
|
-
name = EXCLUDED.name,
|
|
22
|
-
payload = EXCLUDED.payload,
|
|
23
|
-
attempts = EXCLUDED.attempts,
|
|
24
|
-
started_at = now(),
|
|
25
|
-
run_id = EXCLUDED.run_id,
|
|
26
|
-
deadline_at = EXCLUDED.deadline_at,
|
|
27
|
-
heartbeat_at = now(),
|
|
28
|
-
status = NULL,
|
|
29
|
-
finished_at = NULL,
|
|
30
|
-
error = NULL`,[e.dispatchId,e.name,JSON.stringify(e.payload??{}),e.attempt,e.runId,e.deadlineAt]))},recordHeartbeat:async e=>{await Jt(t,r=>r.query(`UPDATE stackbone_platform._queue_jobs
|
|
31
|
-
SET heartbeat_at = now()
|
|
32
|
-
WHERE dispatch_id = $1`,[e.dispatchId]))},recordFinished:async e=>{await Jt(t,r=>r.query(`UPDATE stackbone_platform._queue_jobs
|
|
33
|
-
SET status = $2, finished_at = now(), error = $3
|
|
34
|
-
WHERE dispatch_id = $1 AND status IS NULL`,[e.dispatchId,e.status,e.error]))}}}var Xn=async(t,e)=>{let r=new He({connectionString:t});await r.connect();try{return await e(r)}finally{await r.end().catch(()=>{})}},Zn=t=>t==null?null:JSON.stringify(t);function yu(t){return{open:async e=>{await Xn(t,r=>r.query(`INSERT INTO stackbone_platform.runs
|
|
35
|
-
(id, trigger, status, trace_id, input, started_at, is_playground)
|
|
36
|
-
VALUES ($1::uuid, $2, 'running', $3, $4::jsonb, now(), $5)
|
|
37
|
-
ON CONFLICT (id) DO UPDATE
|
|
38
|
-
SET status = 'running',
|
|
39
|
-
error = NULL,
|
|
40
|
-
output = NULL,
|
|
41
|
-
finished_at = NULL,
|
|
42
|
-
started_at = now(),
|
|
43
|
-
trigger = EXCLUDED.trigger,
|
|
44
|
-
trace_id = EXCLUDED.trace_id,
|
|
45
|
-
input = EXCLUDED.input,
|
|
46
|
-
is_playground = EXCLUDED.is_playground`,[e.runId,e.trigger,e.traceId,Zn(e.input),e.isPlayground]))},close:async e=>{await Xn(t,r=>r.query(`UPDATE stackbone_platform.runs
|
|
47
|
-
SET status = $2,
|
|
48
|
-
error = $3::jsonb,
|
|
49
|
-
output = COALESCE($4::jsonb, output),
|
|
50
|
-
finished_at = now(),
|
|
51
|
-
duration_ms = GREATEST(0, (EXTRACT(EPOCH FROM (now() - started_at)) * 1000)::int)
|
|
52
|
-
WHERE id = $1::uuid AND finished_at IS NULL`,[e.runId,e.status,e.error===null?null:JSON.stringify({message:e.error}),Zn(e.output)]))}}}import{loadSystemSecretsIntoEnv as jc}from"@stackbone/sdk";export{ae as LoadSpecError,bs as createAgentRequestHandler,Ls as createNodeHttpServer,mu as createPostgresQueueJournalAccess,yu as createPostgresRunWriter,rr as invokeEnvelopeSchema,xs as loadSpec,jc as loadSystemSecretsIntoEnv};
|
|
Binary file
|