@toolpack-sdk/knowledge 2.1.1 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +36 -1
- package/dist/index.d.ts +36 -1
- package/dist/index.js +2 -2
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -6,7 +6,7 @@ To prepare for this change:
|
|
|
6
6
|
- If you want libpq compatibility now, use 'uselibpqcompat=true&sslmode=${r}'
|
|
7
7
|
|
|
8
8
|
See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode definitions.`))}gn.exports=ee;ee.parse=ee;ee.toClientConfig=yn;ee.parseIntoClientConfig=eo});var Et=g((Ku,vn)=>{"use strict";l();var to=require("dns"),Sn=pe(),wn=bn().parse,x=function(r,e,t){return e[r]?e[r]:(t===void 0?t=process.env["PG"+r.toUpperCase()]:t===!1||(t=process.env[t]),t||Sn[r])},ro=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 Sn.ssl},te=function(r){return"'"+(""+r).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},q=function(r,e,t){let n=e[t];n!=null&&r.push(t+"="+te(n))},vt=class{constructor(e){e=typeof e=="string"?wn(e):e||{},e.connectionString&&(e=Object.assign({},e,wn(e.connectionString))),this.user=x("user",e),this.database=x("database",e),this.database===void 0&&(this.database=this.user),this.port=parseInt(x("port",e),10),this.host=x("host",e),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:x("password",e)}),this.binary=x("binary",e),this.options=x("options",e),this.ssl=typeof e.ssl>"u"?ro():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=x("client_encoding",e),this.replication=x("replication",e),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=x("application_name",e,"PGAPPNAME"),this.fallback_application_name=x("fallback_application_name",e,!1),this.statement_timeout=x("statement_timeout",e,!1),this.lock_timeout=x("lock_timeout",e,!1),this.idle_in_transaction_session_timeout=x("idle_in_transaction_session_timeout",e,!1),this.query_timeout=x("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 t=[];q(t,this,"user"),q(t,this,"password"),q(t,this,"port"),q(t,this,"application_name"),q(t,this,"fallback_application_name"),q(t,this,"connect_timeout"),q(t,this,"options");let n=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(q(t,n,"sslmode"),q(t,n,"sslca"),q(t,n,"sslkey"),q(t,n,"sslcert"),q(t,n,"sslrootcert"),this.database&&t.push("dbname="+te(this.database)),this.replication&&t.push("replication="+te(this.replication)),this.host&&t.push("host="+te(this.host)),this.isDomainSocket)return e(null,t.join(" "));this.client_encoding&&t.push("client_encoding="+te(this.client_encoding)),to.lookup(this.host,function(s,i){return s?e(s,null):(t.push("hostaddr="+te(i)),e(null,t.join(" ")))})}};vn.exports=vt});var kt=g((Wu,_n)=>{"use strict";l();var no=fe(),En=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,_t=class{constructor(e,t){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=t,this.RowCtor=null,this.rowAsArray=e==="array",this.rowAsArray&&(this.parseRow=this._parseRowAsArray),this._prebuiltEmptyResultObject=null}addCommandComplete(e){let t;e.text?t=En.exec(e.text):t=En.exec(e.command),t&&(this.command=t[1],t[3]?(this.oid=parseInt(t[2],10),this.rowCount=parseInt(t[3],10)):t[2]&&(this.rowCount=parseInt(t[2],10)))}_parseRowAsArray(e){let t=new Array(e.length);for(let n=0,s=e.length;n<s;n++){let i=e[n];i!==null?t[n]=this._parsers[n](i):t[n]=null}return t}parseRow(e){let t={...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 a=this.fields[n].format==="binary"?Buffer.from(i):i;t[o]=this._parsers[n](a)}else t[o]=null}return t}addRow(e){this.rows.push(e)}addFields(e){this.fields=e,this.fields.length&&(this._parsers=new Array(e.length));let t={};for(let n=0;n<e.length;n++){let s=e[n];t[s.name]=null,this._types?this._parsers[n]=this._types.getTypeParser(s.dataTypeID,s.format||"text"):this._parsers[n]=no.getTypeParser(s.dataTypeID,s.format||"text")}this._prebuiltEmptyResultObject={...t}}};_n.exports=_t});var Pn=g((Yu,xn)=>{"use strict";l();var{EventEmitter:so}=require("events"),kn=kt(),Cn=X(),Ct=class extends so{constructor(e,t,n){super(),e=Cn.normalizeQueryConfig(e,t,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 kn(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 kn(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 t;if(!this._canceledDueToError){try{t=this._result.parseRow(e.fields)}catch(n){this._canceledDueToError=n;return}this.emit("row",t,this._result),this._accumulateRows&&this._result.addRow(t)}}handleCommandComplete(e,t){this._checkForMultirow(),this._result.addCommandComplete(e),this.rows&&t.sync()}handleEmptyQuery(e){this.rows&&e.sync()}handleError(e,t){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(t){process.nextTick(()=>{throw t})}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 t=e.parsedStatements[this.name];if(this.text&&t&&this.text!==t)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,t){e.execute({portal:this.portal,rows:t}),t?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:Cn.prepareValue})}catch(t){this.handleError(t,e);return}e.describe({type:"P",name:this.portal||""}),this._getRows(e,this.rows)}handleCopyInResponse(e){e.sendCopyFail("No source stream defined")}handleCopyData(e,t){}};xn.exports=Ct});var Ft=g(y=>{"use strict";l();Object.defineProperty(y,"__esModule",{value:!0});y.NoticeMessage=y.DataRowMessage=y.CommandCompleteMessage=y.ReadyForQueryMessage=y.NotificationResponseMessage=y.BackendKeyDataMessage=y.AuthenticationMD5Password=y.ParameterStatusMessage=y.ParameterDescriptionMessage=y.RowDescriptionMessage=y.Field=y.CopyResponse=y.CopyDataMessage=y.DatabaseError=y.copyDone=y.emptyQuery=y.replicationStart=y.portalSuspended=y.noData=y.closeComplete=y.bindComplete=y.parseComplete=void 0;y.parseComplete={name:"parseComplete",length:5};y.bindComplete={name:"bindComplete",length:5};y.closeComplete={name:"closeComplete",length:5};y.noData={name:"noData",length:5};y.portalSuspended={name:"portalSuspended",length:5};y.replicationStart={name:"replicationStart",length:4};y.emptyQuery={name:"emptyQuery",length:4};y.copyDone={name:"copyDone",length:4};var xt=class extends Error{constructor(e,t,n){super(e),this.length=t,this.name=n}};y.DatabaseError=xt;var Pt=class{constructor(e,t){this.length=e,this.chunk=t,this.name="copyData"}};y.CopyDataMessage=Pt;var At=class{constructor(e,t,n,s){this.length=e,this.name=t,this.binary=n,this.columnTypes=new Array(s)}};y.CopyResponse=At;var Rt=class{constructor(e,t,n,s,i,o,a){this.name=e,this.tableID=t,this.columnID=n,this.dataTypeID=s,this.dataTypeSize=i,this.dataTypeModifier=o,this.format=a}};y.Field=Rt;var Tt=class{constructor(e,t){this.length=e,this.fieldCount=t,this.name="rowDescription",this.fields=new Array(this.fieldCount)}};y.RowDescriptionMessage=Tt;var It=class{constructor(e,t){this.length=e,this.parameterCount=t,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}};y.ParameterDescriptionMessage=It;var Ot=class{constructor(e,t,n){this.length=e,this.parameterName=t,this.parameterValue=n,this.name="parameterStatus"}};y.ParameterStatusMessage=Ot;var Mt=class{constructor(e,t){this.length=e,this.salt=t,this.name="authenticationMD5Password"}};y.AuthenticationMD5Password=Mt;var qt=class{constructor(e,t,n){this.length=e,this.processID=t,this.secretKey=n,this.name="backendKeyData"}};y.BackendKeyDataMessage=qt;var Dt=class{constructor(e,t,n,s){this.length=e,this.processId=t,this.channel=n,this.payload=s,this.name="notification"}};y.NotificationResponseMessage=Dt;var Lt=class{constructor(e,t){this.length=e,this.status=t,this.name="readyForQuery"}};y.ReadyForQueryMessage=Lt;var Qt=class{constructor(e,t){this.length=e,this.text=t,this.name="commandComplete"}};y.CommandCompleteMessage=Qt;var Nt=class{constructor(e,t){this.length=e,this.fields=t,this.name="dataRow",this.fieldCount=t.length}};y.DataRowMessage=Nt;var Bt=class{constructor(e,t){this.length=e,this.message=t,this.name="notice"}};y.NoticeMessage=Bt});var An=g(qe=>{"use strict";l();Object.defineProperty(qe,"__esModule",{value:!0});qe.Writer=void 0;var Ut=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 t=Buffer.byteLength(e);this.ensure(t+1),this.buffer.write(e,this.offset,"utf-8"),this.offset+=t}return this.buffer[this.offset++]=0,this}addString(e=""){let t=Buffer.byteLength(e);return this.ensure(t),this.buffer.write(e,this.offset),this.offset+=t,this}add(e){return this.ensure(e.length),e.copy(this.buffer,this.offset),this.offset+=e.length,this}join(e){if(e){this.buffer[this.headerPosition]=e;let t=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(t,this.headerPosition+1)}return this.buffer.slice(e?0:5,this.offset)}flush(e){let t=this.join(e);return this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(this.size),t}};qe.Writer=Ut});var Tn=g(Le=>{"use strict";l();Object.defineProperty(Le,"__esModule",{value:!0});Le.serialize=void 0;var jt=An(),w=new jt.Writer,io=r=>{w.addInt16(3).addInt16(0);for(let n of Object.keys(r))w.addCString(n).addCString(r[n]);w.addCString("client_encoding").addCString("UTF8");let e=w.addCString("").flush(),t=e.length+4;return new jt.Writer().addInt32(t).add(e).flush()},oo=()=>{let r=Buffer.allocUnsafe(8);return r.writeInt32BE(8,0),r.writeInt32BE(80877103,4),r},ao=r=>w.addCString(r).flush(112),co=function(r,e){return w.addCString(r).addInt32(Buffer.byteLength(e)).addString(e),w.flush(112)},uo=function(r){return w.addString(r).flush(112)},lo=r=>w.addCString(r).flush(81),Rn=[],ho=r=>{let e=r.name||"";e.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",e,e.length),console.error("This can cause conflicts and silent errors executing queries"));let t=r.types||Rn,n=t.length,s=w.addCString(e).addCString(r.text).addInt16(n);for(let i=0;i<n;i++)s.addInt32(t[i]);return w.flush(80)},re=new jt.Writer,fo=function(r,e){for(let t=0;t<r.length;t++){let n=e?e(r[t],t):r[t];n==null?(w.addInt16(0),re.addInt32(-1)):n instanceof Buffer?(w.addInt16(1),re.addInt32(n.length),re.add(n)):(w.addInt16(0),re.addInt32(Buffer.byteLength(n)),re.addString(n))}},po=(r={})=>{let e=r.portal||"",t=r.statement||"",n=r.binary||!1,s=r.values||Rn,i=s.length;return w.addCString(e).addCString(t),w.addInt16(i),fo(s,r.valueMapper),w.addInt16(i),w.add(re.flush()),w.addInt16(1),w.addInt16(n?1:0),w.flush(66)},mo=Buffer.from([69,0,0,0,9,0,0,0,0,0]),yo=r=>{if(!r||!r.portal&&!r.rows)return mo;let e=r.portal||"",t=r.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(t,i.length-4),i},go=(r,e)=>{let t=Buffer.allocUnsafe(16);return t.writeInt32BE(16,0),t.writeInt16BE(1234,4),t.writeInt16BE(5678,6),t.writeInt32BE(r,8),t.writeInt32BE(e,12),t},$t=(r,e)=>{let n=4+Buffer.byteLength(e)+1,s=Buffer.allocUnsafe(1+n);return s[0]=r,s.writeInt32BE(n,1),s.write(e,5,"utf-8"),s[n]=0,s},bo=w.addCString("P").flush(68),wo=w.addCString("S").flush(68),So=r=>r.name?$t(68,`${r.type}${r.name||""}`):r.type==="P"?bo:wo,vo=r=>{let e=`${r.type}${r.name||""}`;return $t(67,e)},Eo=r=>w.add(r).flush(100),_o=r=>$t(102,r),De=r=>Buffer.from([r,0,0,0,4]),ko=De(72),Co=De(83),xo=De(88),Po=De(99),Ao={startup:io,password:ao,requestSsl:oo,sendSASLInitialResponseMessage:co,sendSCRAMClientFinalMessage:uo,query:lo,parse:ho,bind:po,execute:yo,describe:So,close:vo,flush:()=>ko,sync:()=>Co,end:()=>xo,copyData:Eo,copyDone:()=>Po,copyFail:_o,cancel:go};Le.serialize=Ao});var In=g(Qe=>{"use strict";l();Object.defineProperty(Qe,"__esModule",{value:!0});Qe.BufferReader=void 0;var Ht=class{constructor(e=0){this.offset=e,this.buffer=Buffer.allocUnsafe(0),this.encoding="utf-8"}setBuffer(e,t){this.offset=e,this.buffer=t}int16(){let e=this.buffer.readInt16BE(this.offset);return this.offset+=2,e}byte(){let e=this.buffer[this.offset];return this.offset++,e}int32(){let e=this.buffer.readInt32BE(this.offset);return this.offset+=4,e}uint32(){let e=this.buffer.readUInt32BE(this.offset);return this.offset+=4,e}string(e){let t=this.buffer.toString(this.encoding,this.offset,this.offset+e);return this.offset+=e,t}cstring(){let e=this.offset,t=e;for(;this.buffer[t++]!==0;);return this.offset=t,this.buffer.toString(this.encoding,e,t-1)}bytes(e){let t=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t}};Qe.BufferReader=Ht});var Dn=g(Ne=>{"use strict";l();Object.defineProperty(Ne,"__esModule",{value:!0});Ne.Parser=void 0;var v=Ft(),Ro=In(),Gt=1,To=4,On=Gt+To,T=-1,zt=Buffer.allocUnsafe(0),Kt=class{constructor(e){if(this.buffer=zt,this.bufferLength=0,this.bufferOffset=0,this.reader=new Ro.BufferReader,e?.mode==="binary")throw new Error("Binary mode not supported yet");this.mode=e?.mode||"text"}parse(e,t){this.mergeBuffer(e);let n=this.bufferOffset+this.bufferLength,s=this.bufferOffset;for(;s+On<=n;){let i=this.buffer[s],o=this.buffer.readUInt32BE(s+Gt),a=Gt+o;if(a+s<=n){let u=this.handlePacket(s+On,i,o,this.buffer);t(u),s+=a}else break}s===n?(this.buffer=zt,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=n-s,this.bufferOffset=s)}mergeBuffer(e){if(this.bufferLength>0){let t=this.bufferLength+e.byteLength;if(t+this.bufferOffset>this.buffer.byteLength){let s;if(t<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)s=this.buffer;else{let i=this.buffer.byteLength*2;for(;t>=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=t}else this.buffer=e,this.bufferOffset=0,this.bufferLength=e.byteLength}handlePacket(e,t,n,s){let{reader:i}=this;i.setBuffer(e,s);let o;switch(t){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=Fo(i);break;case 67:o=Oo(i);break;case 90:o=Io(i);break;case 65:o=Lo(i);break;case 82:o=$o(i,n);break;case 83:o=Uo(i);break;case 75:o=jo(i);break;case 69:o=Mn(i,"error");break;case 78:o=Mn(i,"notice");break;case 84:o=Qo(i);break;case 116:o=Bo(i);break;case 71:o=qo(i);break;case 72:o=Do(i);break;case 100:o=Mo(i,n);break;default:return new v.DatabaseError("received invalid response: "+t.toString(16),n,"error")}return i.setBuffer(0,zt),o.length=n,o}};Ne.Parser=Kt;var Io=r=>{let e=r.string(1);return new v.ReadyForQueryMessage(T,e)},Oo=r=>{let e=r.cstring();return new v.CommandCompleteMessage(T,e)},Mo=(r,e)=>{let t=r.bytes(e-4);return new v.CopyDataMessage(T,t)},qo=r=>qn(r,"copyInResponse"),Do=r=>qn(r,"copyOutResponse"),qn=(r,e)=>{let t=r.byte()!==0,n=r.int16(),s=new v.CopyResponse(T,e,t,n);for(let i=0;i<n;i++)s.columnTypes[i]=r.int16();return s},Lo=r=>{let e=r.int32(),t=r.cstring(),n=r.cstring();return new v.NotificationResponseMessage(T,e,t,n)},Qo=r=>{let e=r.int16(),t=new v.RowDescriptionMessage(T,e);for(let n=0;n<e;n++)t.fields[n]=No(r);return t},No=r=>{let e=r.cstring(),t=r.uint32(),n=r.int16(),s=r.uint32(),i=r.int16(),o=r.int32(),a=r.int16()===0?"text":"binary";return new v.Field(e,t,n,s,i,o,a)},Bo=r=>{let e=r.int16(),t=new v.ParameterDescriptionMessage(T,e);for(let n=0;n<e;n++)t.dataTypeIDs[n]=r.int32();return t},Fo=r=>{let e=r.int16(),t=new Array(e);for(let n=0;n<e;n++){let s=r.int32();t[n]=s===-1?null:r.string(s)}return new v.DataRowMessage(T,t)},Uo=r=>{let e=r.cstring(),t=r.cstring();return new v.ParameterStatusMessage(T,e,t)},jo=r=>{let e=r.int32(),t=r.int32();return new v.BackendKeyDataMessage(T,e,t)},$o=(r,e)=>{let t=r.int32(),n={name:"authenticationOk",length:e};switch(t){case 0:break;case 3:n.length===8&&(n.name="authenticationCleartextPassword");break;case 5:if(n.length===12){n.name="authenticationMD5Password";let s=r.bytes(4);return new v.AuthenticationMD5Password(T,s)}break;case 10:{n.name="authenticationSASL",n.mechanisms=[];let s;do s=r.cstring(),s&&n.mechanisms.push(s);while(s)}break;case 11:n.name="authenticationSASLContinue",n.data=r.string(e-8);break;case 12:n.name="authenticationSASLFinal",n.data=r.string(e-8);break;default:throw new Error("Unknown authenticationOk message type "+t)}return n},Mn=(r,e)=>{let t={},n=r.string(1);for(;n!=="\0";)t[n]=r.cstring(),n=r.string(1);let s=t.M,i=e==="notice"?new v.NoticeMessage(T,s):new v.DatabaseError(s,T,e);return i.severity=t.S,i.code=t.C,i.detail=t.D,i.hint=t.H,i.position=t.P,i.internalPosition=t.p,i.internalQuery=t.q,i.where=t.W,i.schema=t.s,i.table=t.t,i.column=t.c,i.dataType=t.d,i.constraint=t.n,i.file=t.F,i.line=t.L,i.routine=t.R,i}});var Vt=g(j=>{"use strict";l();Object.defineProperty(j,"__esModule",{value:!0});j.DatabaseError=j.serialize=j.parse=void 0;var Ho=Ft();Object.defineProperty(j,"DatabaseError",{enumerable:!0,get:function(){return Ho.DatabaseError}});var zo=Tn();Object.defineProperty(j,"serialize",{enumerable:!0,get:function(){return zo.serialize}});var Go=Dn();function Ko(r,e){let t=new Go.Parser;return r.on("data",n=>t.parse(n,e)),new Promise(n=>r.on("end",()=>n()))}j.parse=Ko});var Ln=g(Wt=>{"use strict";l();Object.defineProperty(Wt,"__esModule",{value:!0});Wt.default={}});var Nn=g((fl,Qn)=>{"use strict";l();var{getStream:Vo,getSecureStream:Wo}=Zo();Qn.exports={getStream:Vo,getSecureStream:Wo};function Jo(){function r(t){let n=require("net");return new n.Socket}function e(t){return require("tls").connect(t)}return{getStream:r,getSecureStream:e}}function Yo(){function r(t){let{CloudflareSocket:n}=Ln();return new n(t)}function e(t){return t.socket.startTls(t),t.socket}return{getStream:r,getSecureStream:e}}function Xo(){if(typeof navigator=="object"&&navigator!==null&&typeof navigator.userAgent=="string")return navigator.userAgent==="Cloudflare-Workers";if(typeof Response=="function"){let r=new Response(null,{cf:{thing:!0}});if(typeof r.cf=="object"&&r.cf!==null&&r.cf.thing)return!0}return!1}function Zo(){return Xo()?Yo():Jo()}});var Yt=g((ml,Bn)=>{"use strict";l();var ea=require("events").EventEmitter,{parse:ta,serialize:C}=Vt(),{getStream:ra,getSecureStream:na}=Nn(),sa=C.flush(),ia=C.sync(),oa=C.end(),Jt=class extends ea{constructor(e){super(),e=e||{},this.stream=e.stream||ra(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 t=this;this.on("newListener",function(n){n==="message"&&(t._emitMessage=!0)})}connect(e,t){let n=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(e,t),this.stream.once("connect",function(){n._keepAlive&&n.stream.setKeepAlive(!0,n._keepAliveInitialDelayMillis),n.emit("connect")});let 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 a={socket:n.stream};n.ssl!==!0&&(Object.assign(a,n.ssl),"key"in n.ssl&&(a.key=n.ssl.key));let u=require("net");u.isIP&&u.isIP(t)===0&&(a.servername=t);try{n.stream=na(a)}catch(c){return n.emit("error",c)}n.attachListeners(n.stream),n.stream.on("error",s),n.emit("sslconnect")})}attachListeners(e){ta(e,t=>{let n=t.name==="error"?"errorMessage":t.name;this._emitMessage&&this.emit("message",t),this.emit(n,t)})}requestSsl(){this.stream.write(C.requestSsl())}startup(e){this.stream.write(C.startup(e))}cancel(e,t){this._send(C.cancel(e,t))}password(e){this._send(C.password(e))}sendSASLInitialResponseMessage(e,t){this._send(C.sendSASLInitialResponseMessage(e,t))}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(sa)}sync(){this._ending=!0,this._send(ia)}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(oa,()=>{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))}};Bn.exports=Jt});var $n=g((gl,jn)=>{"use strict";l();var{Transform:aa}=require("stream"),{StringDecoder:ca}=require("string_decoder"),$=Symbol("last"),Be=Symbol("decoder");function ua(r,e,t){let n;if(this.overflow){if(n=this[Be].write(r).split(this.matcher),n.length===1)return t();n.shift(),this.overflow=!1}else this[$]+=this[Be].write(r),n=this[$].split(this.matcher);this[$]=n.pop();for(let s=0;s<n.length;s++)try{Un(this,this.mapper(n[s]))}catch(i){return t(i)}if(this.overflow=this[$].length>this.maxLength,this.overflow&&!this.skipOverflow){t(new Error("maximum buffer reached"));return}t()}function la(r){if(this[$]+=this[Be].end(),this[$])try{Un(this,this.mapper(this[$]))}catch(e){return r(e)}r()}function Un(r,e){e!==void 0&&r.push(e)}function Fn(r){return r}function ha(r,e,t){switch(r=r||/\r?\n/,e=e||Fn,t=t||{},arguments.length){case 1:typeof r=="function"?(e=r,r=/\r?\n/):typeof r=="object"&&!(r instanceof RegExp)&&!r[Symbol.split]&&(t=r,r=/\r?\n/);break;case 2:typeof r=="function"?(t=e,e=r,r=/\r?\n/):typeof e=="object"&&(t=e,e=Fn)}t=Object.assign({},t),t.autoDestroy=!0,t.transform=ua,t.flush=la,t.readableObjectMode=!0;let n=new aa(t);return n[$]="",n[Be]=new ca("utf8"),n.matcher=r,n.mapper=e,n.maxLength=t.maxLength,n.skipOverflow=t.skipOverflow||!1,n.overflow=!1,n._destroy=function(s,i){this._writableState.errorEmitted=!1,i(s)},n}jn.exports=ha});var Gn=g((wl,D)=>{"use strict";l();var Hn=require("path"),da=require("stream").Stream,fa=$n(),zn=require("util"),pa=5432,Fe=process.platform==="win32",ye=process.stderr,ma=56,ya=7,ga=61440,ba=32768;function wa(r){return(r&ga)==ba}var ne=["host","port","database","user","password"],Xt=ne.length,Sa=ne[Xt-1];function Zt(){var r=ye instanceof da&&ye.writable===!0;if(r){var e=Array.prototype.slice.call(arguments).concat(`
|
|
9
|
-
`);ye.write(zn.format.apply(zn,e))}}Object.defineProperty(D.exports,"isWin",{get:function(){return Fe},set:function(r){Fe=r}});D.exports.warnTo=function(r){var e=ye;return ye=r,e};D.exports.getFileName=function(r){var e=r||process.env,t=e.PGPASSFILE||(Fe?Hn.join(e.APPDATA||"./","postgresql","pgpass.conf"):Hn.join(e.HOME||"./",".pgpass"));return t};D.exports.usePgPass=function(r,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:Fe?!0:(e=e||"<unkn>",wa(r.mode)?r.mode&(ma|ya)?(Zt('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(Zt('WARNING: password file "%s" is not a plain file',e),!1))};var va=D.exports.match=function(r,e){return ne.slice(0,-1).reduce(function(t,n,s){return s==1&&Number(r[n]||pa)===Number(e[n])?t&&!0:t&&(e[n]==="*"||e[n]===r[n])},!0)};D.exports.getPassword=function(r,e,t){var n,s=e.pipe(fa());function i(u){var c=Ea(u);c&&_a(c)&&va(r,c)&&(n=c[Sa],s.end())}var o=function(){e.destroy(),t(n)},a=function(u){e.destroy(),Zt("WARNING: error on reading file: %s",u),t(void 0)};e.on("error",a),s.on("data",i).on("end",o).on("error",a)};var Ea=D.exports.parseLine=function(r){if(r.length<11||r.match(/^\s+#/))return null;for(var e="",t="",n=0,s=0,i=0,o={},a=!1,u=function(h,d,p){var m=r.substring(d,p);Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE")||(m=m.replace(/\\([:\\])/g,"$1")),o[ne[h]]=m},c=0;c<r.length-1;c+=1){if(e=r.charAt(c+1),t=r.charAt(c),a=n==Xt-1,a){u(n,s);break}c>=0&&e==":"&&t!=="\\"&&(u(n,s,c+1),s=c+2,n+=1)}return o=Object.keys(o).length===Xt?o:null,o},_a=D.exports.isValidEntry=function(r){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}},t=0;t<ne.length;t+=1){var n=e[t],s=r[ne[t]]||"",i=n(s);if(!i)return!1}return!0}});var Vn=g((El,er)=>{"use strict";l();var vl=require("path"),Kn=require("fs"),Ue=Gn();er.exports=function(r,e){var t=Ue.getFileName();Kn.stat(t,function(n,s){if(n||!Ue.usePgPass(s,t))return e(void 0);var i=Kn.createReadStream(t);Ue.getPassword(r,i,e)})};er.exports.warnTo=Ue.warnTo});var Zn=g((kl,Xn)=>{"use strict";l();var ka=require("events").EventEmitter,Wn=X(),ge=require("util"),tr=pn(),Ca=Me(),xa=Et(),Yn=Pn(),Pa=pe(),Aa=Yt(),Ra=bt(),Jn=ge.deprecate(()=>{},"Client.activeQuery is deprecated and will be removed in pg@9.0"),Ta=ge.deprecate(()=>{},"Client.queryQueue is deprecated and will be removed in pg@9.0."),Ia=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."),Oa=ge.deprecate(()=>{},"Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0."),Ma=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."),je=class extends ka{constructor(e){super(),this.connectionParameters=new xa(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 t=e||{};t.Promise&&Oa(),this._Promise=t.Promise||global.Promise,this._types=new Ca(t.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this._activeQuery=null,this.enableChannelBinding=!!t.enableChannelBinding,this.connection=t.connection||new Aa({stream:t.stream,ssl:this.connectionParameters.ssl,keepAlive:t.keepAlive||!1,keepAliveInitialDelayMillis:t.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this._queryQueue=[],this.binary=t.binary||Pa.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=t.connectionTimeoutMillis||0}get activeQuery(){return Jn(),this._activeQuery}set activeQuery(e){Jn(),this._activeQuery=e}_getActiveQuery(){return this._activeQuery}_errorAllQueries(e){let t=s=>{process.nextTick(()=>{s.handleError(e,this.connection)})},n=this._getActiveQuery();n&&(t(n),this._activeQuery=null),this._queryQueue.forEach(t),this._queryQueue.length=0}_connect(e){let t=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(){t.ssl?n.requestSsl():n.startup(t.getStartupConf())}),n.on("sslconnect",function(){n.startup(t.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((t,n)=>{this._connect(s=>{s?n(s):t(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 t=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"){t.emit("error",new TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=n}else this.connectionParameters.password=this.password=null;e()}).catch(n=>{t.emit("error",n)});else if(this.password!==null)e();else try{Vn()(this.connectionParameters,s=>{s!==void 0&&(Ia(),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 t=await Ra.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(t)}catch(t){this.emit("error",t)}})}_handleAuthSASL(e){this._getPassword(()=>{try{this.saslSession=tr.startSession(e.mechanisms,this.enableChannelBinding&&this.connection.stream),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(t){this.connection.emit("error",t)}})}async _handleAuthSASLContinue(e){try{await tr.continueSession(this.saslSession,this.password,e.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(t){this.connection.emit("error",t)}}_handleAuthSASLFinal(e){try{tr.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(t){this.connection.emit("error",t)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let t=this._getActiveQuery();this._activeQuery=null,this.readyForQuery=!0,t&&t.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit("error",e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit("error",e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let t=this._getActiveQuery();if(!t){this._handleErrorEvent(e);return}this._activeQuery=null,t.handleError(e,this.connection)}_handleRowDescription(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected rowDescription message from backend.");this._handleErrorEvent(n);return}t.handleRowDescription(e)}_handleDataRow(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected dataRow message from backend.");this._handleErrorEvent(n);return}t.handleDataRow(e)}_handlePortalSuspended(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected portalSuspended message from backend.");this._handleErrorEvent(n);return}t.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected emptyQuery message from backend.");this._handleErrorEvent(n);return}t.handleEmptyQuery(this.connection)}_handleCommandComplete(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected commandComplete message from backend.");this._handleErrorEvent(n);return}t.handleCommandComplete(e,this.connection)}_handleParseComplete(){let e=this._getActiveQuery();if(e==null){let t=new Error("Received unexpected parseComplete message from backend.");this._handleErrorEvent(t);return}e.name&&(this.connection.parsedStatements[e.name]=e.text)}_handleCopyInResponse(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected copyInResponse message from backend.");this._handleErrorEvent(n);return}t.handleCopyInResponse(this.connection)}_handleCopyData(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected copyData message from backend.");this._handleErrorEvent(n);return}t.handleCopyData(e,this.connection)}_handleNotification(e){this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){let e=this.connectionParameters,t={user:e.user,database:e.database},n=e.application_name||e.fallback_application_name;return n&&(t.application_name=n),e.replication&&(t.replication=""+e.replication),e.statement_timeout&&(t.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(t.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(t.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(t.options=e.options),t}cancel(e,t){if(e.activeQuery===t){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(t)!==-1&&e._queryQueue.splice(e._queryQueue.indexOf(t),1)}setTypeParser(e,t,n){return this._types.setTypeParser(e,t,n)}getTypeParser(e,t){return this._types.getTypeParser(e,t)}escapeIdentifier(e){return Wn.escapeIdentifier(e)}escapeLiteral(e){return Wn.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 t=e.submit(this.connection);t&&process.nextTick(()=>{e.handleError(t,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this._activeQuery=null,this.emit("drain"))}}query(e,t,n){let s,i,o,a,u;if(e==null)throw new TypeError("Client was passed a null or undefined query");return typeof e.submit=="function"?(o=e.query_timeout||this.connectionParameters.query_timeout,i=s=e,s.callback||(typeof t=="function"?s.callback=t:n&&(s.callback=n))):(o=e.query_timeout||this.connectionParameters.query_timeout,s=new Yn(e,t,n),s.callback||(i=new this._Promise((c,h)=>{s.callback=(d,p)=>d?h(d):c(p)}).catch(c=>{throw Error.captureStackTrace(c),c}))),o&&(u=s.callback||(()=>{}),a=setTimeout(()=>{let c=new Error("Query read timeout");process.nextTick(()=>{s.handleError(c,this.connection)}),u(c),s.callback=()=>{};let h=this._queryQueue.indexOf(s);h>-1&&this._queryQueue.splice(h,1),this._pulseQueryQueue()},o),s.callback=(c,h)=>{clearTimeout(a),u(c,h)}),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&&Ma(),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(t=>{this.connection.once("end",t)})}get queryQueue(){return Ta(),this._queryQueue}};je.Query=Yn;Xn.exports=je});var rs=g((xl,ts)=>{"use strict";l();var qa=require("events").EventEmitter,rr=function(){},es=(r,e)=>{let t=r.findIndex(e);return t===-1?void 0:r.splice(t,1)[0]},nr=class{constructor(e,t,n){this.client=e,this.idleListener=t,this.timeoutId=n}},se=class{constructor(e){this.callback=e}};function Da(){throw new Error("Release called on client which has already been released to the pool.")}function $e(r,e){if(e)return{callback:e,result:void 0};let t,n,s=function(o,a){o?t(o):n(a)},i=new r(function(o,a){n=o,t=a}).catch(o=>{throw Error.captureStackTrace(o),o});return{callback:s,result:i}}function La(r,e){return function t(n){n.client=e,e.removeListener("error",t),e.on("error",()=>{r.log("additional client error after disconnection due to error",n)}),r._remove(e),r.emit("error",n,e)}}var sr=class extends qa{constructor(e,t){super(),this.options=Object.assign({},e),e!=null&&"password"in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.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||t||ir().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 t=this.Promise;return typeof t.try=="function"?t.try(e):new t(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(t=>{this._remove(t.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let t=this._idle.pop();clearTimeout(t.timeoutId);let n=t.client;n.ref&&n.ref();let s=t.idleListener;return this._acquireClient(n,e,s,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpected condition")}_remove(e,t){let n=es(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 t=="function"&&t()})}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 t=$e(this.Promise,e),n=t.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new se(t.callback)),n;let s=(a,u,c)=>{clearTimeout(o),t.callback(a,u,c)},i=new se(s),o=setTimeout(()=>{es(this._pendingQueue,a=>a.callback===s),i.timedOut=!0,t.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 se(t.callback)),n}newClient(e){let t=new this.Client(this.options);this._clients.push(t);let n=La(this,t);this.log("checking client timeout");let s,i=!1;this.options.connectionTimeoutMillis&&(s=setTimeout(()=>{t.connection?(this.log("ending client due to timeout"),i=!0,t.connection.stream.destroy()):t.isConnected()||(this.log("ending client due to timeout"),i=!0,t.end())},this.options.connectionTimeoutMillis)),this.log("connecting new client"),t.connect(o=>{if(s&&clearTimeout(s),t.on("error",n),o)this.log("client failed to connect",o),this._clients=this._clients.filter(a=>a!==t),i&&(o=new Error("Connection terminated due to connection timeout",{cause:o})),this._pulseQueue(),e.timedOut||e.callback(o,void 0,rr);else{if(this.log("new client connected"),this.options.onConnect){this._promiseTry(()=>this.options.onConnect(t)).then(()=>{this._afterConnect(t,e,n)},a=>{this._clients=this._clients.filter(u=>u!==t),t.end(()=>{this._pulseQueue(),e.timedOut||e.callback(a,void 0,rr)})});return}return this._afterConnect(t,e,n)}})}_afterConnect(e,t,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 se((o,a,u)=>u()),n,!1)},this.options.maxLifetimeSeconds*1e3);s.unref(),e.once("end",()=>clearTimeout(s))}return this._acquireClient(e,t,n,!0)}_acquireClient(e,t,n,s){s&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,n),e.removeListener("error",n),t.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),t.callback(i,void 0,rr);t.callback(void 0,e,e.release)}):t.callback(void 0,e,e.release)}_releaseOnce(e,t){let n=!1;return s=>{n&&Da(),n=!0,this._release(e,t,s)}}_release(e,t,n){if(e.on("error",t),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 nr(e,t,i)),this._pulseQueue()}query(e,t,n){if(typeof e=="function"){let i=$e(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 t=="function"&&(n=t,t=void 0);let s=$e(this.Promise,n);return n=s.callback,this.connect((i,o)=>{if(i)return n(i);let a=!1,u=c=>{a||(a=!0,o.release(c),n(c))};o.once("error",u),this.log("dispatching query");try{o.query(e,t,(c,h)=>{if(this.log("query dispatched"),o.removeListener("error",u),!a)return a=!0,o.release(c),c?n(c):n(void 0,h)})}catch(c){return o.release(c),n(c)}}),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 t=$e(this.Promise,e);return this._endCallback=t.callback,this._pulseQueue(),t.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,t)=>e+(this._expired.has(t)?1:0),0)}get totalCount(){return this._clients.length}};ts.exports=sr});var is=g((Al,ss)=>{"use strict";l();var ns=require("events").EventEmitter,Qa=require("util"),or=X(),ie=ss.exports=function(r,e,t){ns.call(this),r=or.normalizeQueryConfig(r,e,t),this.text=r.text,this.values=r.values,this.name=r.name,this.queryMode=r.queryMode,this.callback=r.callback,this.state="new",this._arrayMode=r.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(n){n==="row"&&(this._emitRowEvents=!0)}.bind(this))};Qa.inherits(ie,ns);var Na={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};ie.prototype.handleError=function(r){let e=this.native.pq.resultErrorFields();if(e)for(let t in e){let n=Na[t]||t;r[n]=e[t]}this.callback?this.callback(r):this.emit("error",r),this.state="error"};ie.prototype.then=function(r,e){return this._getPromise().then(r,e)};ie.prototype.catch=function(r){return this._getPromise().catch(r)};ie.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(r,e){this._once("end",r),this._once("error",e)}.bind(this)),this._promise)};ie.prototype.submit=function(r){this.state="running";let e=this;this.native=r.native,r.native.arrayMode=this._arrayMode;let t=function(n,s,i){if(r.native.arrayMode=!1,setImmediate(function(){e.emit("_done")}),n)return e.handleError(n);e._emitRowEvents&&(i.length>1?s.forEach((o,a)=>{o.forEach(u=>{e.emit("row",u,i[a])})}):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&&(t=process.domain.bind(t)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));let n=(this.values||[]).map(or.prepareValue);if(r.namedQueries[this.name]){if(this.text&&r.namedQueries[this.name]!==this.text){let s=new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return t(s)}return r.native.execute(this.name,n,t)}return r.native.prepare(this.name,this.text,n.length,function(s){return s?t(s):(r.namedQueries[e.name]=e.text,e.native.execute(e.name,n,t))})}else if(this.values){if(!Array.isArray(this.values)){let s=new Error("Query values must be an array");return t(s)}let n=this.values.map(or.prepareValue);r.native.query(this.text,n,t)}else this.queryMode==="extended"?r.native.query(this.text,[],t):r.native.query(this.text,t)}});var ls=g((Tl,us)=>{"use strict";l();var Ba=require("util"),os;try{os=require("pg-native")}catch(r){throw r}var Fa=Me(),as=require("events").EventEmitter,Ua=require("util"),ja=Et(),cs=is(),$a=Ba.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=us.exports=function(r){as.call(this),r=r||{},this._Promise=r.Promise||global.Promise,this._types=new Fa(r.types),this.native=new os({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;let e=this.connectionParameters=new ja(r);r.nativeConnectionString&&(e.nativeConnectionString=r.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=cs;Ua.inherits(P,as);P.prototype._errorAllQueries=function(r){let e=t=>{process.nextTick(()=>{t.native=this.native,t.handleError(r)})};this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(e),this._queryQueue.length=0};P.prototype._connect=function(r){let e=this;if(this._connecting){process.nextTick(()=>r(new Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(t,n){if(e.connectionParameters.nativeConnectionString&&(n=e.connectionParameters.nativeConnectionString),t)return r(t);e.native.connect(n,function(s){if(s)return e.native.end(),r(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),r(null,this)})})};P.prototype.connect=function(r){if(r){this._connect(r);return}return new this._Promise((e,t)=>{this._connect(n=>{n?t(n):e(this)})})};P.prototype.query=function(r,e,t){let n,s,i,o,a;if(r==null)throw new TypeError("Client was passed a null or undefined query");if(typeof r.submit=="function")i=r.query_timeout||this.connectionParameters.query_timeout,s=n=r,typeof e=="function"&&(r.callback=e);else if(i=r.query_timeout||this.connectionParameters.query_timeout,n=new cs(r,e,t),!n.callback){let u,c;s=new this._Promise((h,d)=>{u=h,c=d}).catch(h=>{throw Error.captureStackTrace(h),h}),n.callback=(h,d)=>h?c(h):u(d)}return i&&(a=n.callback||(()=>{}),o=setTimeout(()=>{let u=new Error("Query read timeout");process.nextTick(()=>{n.handleError(u,this.connection)}),a(u),n.callback=()=>{};let c=this._queryQueue.indexOf(n);c>-1&&this._queryQueue.splice(c,1),this._pulseQueryQueue()},i),n.callback=(u,c)=>{clearTimeout(o),a(u,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&&$a(),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(r){let e=this;this._ending=!0,this._connected||this.once("connect",this.end.bind(this,r));let t;return r||(t=new this._Promise(function(n,s){r=i=>i?s(i):n()})),this.native.end(function(){e._connected=!1,e._errorAllQueries(new Error("Connection terminated")),process.nextTick(()=>{e.emit("end"),r&&r()})}),t};P.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};P.prototype._pulseQueryQueue=function(r){if(!this._connected||this._hasActiveQuery())return;let e=this._queryQueue.shift();if(!e){r||this.emit("drain");return}this._activeQuery=e,e.submit(this);let t=this;e.once("_done",function(){t._pulseQueryQueue()})};P.prototype.cancel=function(r){this._activeQuery===r?this.native.cancel(function(){}):this._queryQueue.indexOf(r)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(r),1)};P.prototype.ref=function(){};P.prototype.unref=function(){};P.prototype.setTypeParser=function(r,e,t){return this._types.setTypeParser(r,e,t)};P.prototype.getTypeParser=function(r,e){return this._types.getTypeParser(r,e)};P.prototype.isConnected=function(){return this._connected}});var ar=g((Ol,hs)=>{"use strict";l();hs.exports=ls()});var ir=g((Dl,He)=>{"use strict";l();var Ha=Zn(),za=pe(),Ga=Yt(),Ka=kt(),Va=X(),Wa=rs(),Ja=Me(),{DatabaseError:Ya}=Vt(),{escapeIdentifier:Xa,escapeLiteral:Za}=X(),ec=r=>class extends Wa{constructor(t){super(t,r)}},ds=function(r){this.defaults=za,this.Client=r,this.Query=this.Client.Query,this.Pool=ec(this.Client),this._pools=[],this.Connection=Ga,this.types=fe(),this.DatabaseError=Ya,this.TypeOverrides=Ja,this.escapeIdentifier=Xa,this.escapeLiteral=Za,this.Result=Ka,this.utils=Va},fs=Ha,ps=!1;try{ps=!!process.env.NODE_PG_FORCE_NATIVE}catch{}ps&&(fs=ar());He.exports=new ds(fs);Object.defineProperty(He.exports,"native",{configurable:!0,enumerable:!1,get(){let r=null;try{r=new ds(ar())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(He.exports,"native",{value:r}),r}})});var ms={};ur(ms,{Client:()=>tc,Connection:()=>nc,DatabaseError:()=>oc,Pool:()=>rc,Query:()=>ic,Result:()=>uc,TypeOverrides:()=>lc,default:()=>dc,defaults:()=>hc,escapeIdentifier:()=>ac,escapeLiteral:()=>cc,types:()=>sc});var I,tc,rc,nc,sc,ic,oc,ac,cc,uc,lc,hc,dc,ys=cr(()=>{"use strict";l();I=_(ir(),1),tc=I.default.Client,rc=I.default.Pool,nc=I.default.Connection,sc=I.default.types,ic=I.default.Query,oc=I.default.DatabaseError,ac=I.default.escapeIdentifier,cc=I.default.escapeLiteral,uc=I.default.Result,lc=I.default.TypeOverrides,hc=I.default.defaults,dc=I.default});var mc={};ur(mc,{ApiDataSource:()=>xe,ChunkTooLargeError:()=>Xe,DimensionMismatchError:()=>H,EmbeddingError:()=>k,IngestionError:()=>E,JSONSource:()=>Pe,Knowledge:()=>Ze,KnowledgeError:()=>L,KnowledgeProviderError:()=>Q,MarkdownSource:()=>ke,MemoryProvider:()=>Ee,OllamaEmbedder:()=>Ge,OpenAIEmbedder:()=>Ke,OpenRouterEmbedder:()=>Ve,PersistentKnowledgeProvider:()=>_e,PostgresSource:()=>ze,SQLiteSource:()=>Ae,VertexAIEmbedder:()=>We,WebUrlSource:()=>Ce,combineScores:()=>Se,keywordSearch:()=>N});module.exports=Cs(mc);l();l();l();var L=class extends Error{constructor(t,n){super(t);this.code=n;this.name="KnowledgeError"}code},k=class extends L{constructor(t,n){super(t,"EMBEDDING_ERROR");this.statusCode=n;this.name="EmbeddingError"}statusCode},E=class extends L{constructor(t,n){super(t,"INGESTION_ERROR");this.file=n;this.name="IngestionError"}file},Xe=class extends L{constructor(t,n){super(t,"CHUNK_TOO_LARGE");this.chunkSize=n;this.name="ChunkTooLargeError"}chunkSize},H=class extends L{expected;actual;constructor(e,t){super(`Dimension mismatch: expected ${e}, got ${t}`,"DIMENSION_MISMATCH"),this.name="DimensionMismatchError",this.expected=e,this.actual=t}},Q=class extends L{constructor(e){super(e,"PROVIDER_ERROR"),this.name="KnowledgeProviderError"}};l();var hr=require("crypto");l();function N(r,e){let t=r.toLowerCase(),n=e.toLowerCase();if(t.includes(n))return 1;let s=n.split(/\s+/).filter(o=>o.length>2);if(s.length===0)return 0;let i=0;for(let o of s)t.includes(o)&&i++;return i/s.length}function Se(r,e,t=.7){let n=1-t;return r*t+e*n}l();function ve(r,e){if(r.length!==e.length)throw new Error("Vectors must have same dimensions");let t=0,n=0,s=0;for(let o=0;o<r.length;o++)t+=r[o]*e[o],n+=r[o]*r[o],s+=e[o]*e[o];let i=Math.sqrt(n)*Math.sqrt(s);return i===0?0:t/i}function B(r,e){if(!e)return!0;for(let[t,n]of Object.entries(e)){let s=r[t];if(typeof n=="object"&&n!==null&&!Array.isArray(n)){if("$in"in n){if(!n.$in.includes(s))return!1}else if("$gt"in n){let i=n.$gt;if(typeof s!="number"||s<=i)return!1}else if("$lt"in n){let i=n.$lt;if(typeof s!="number"||s>=i)return!1}}else if(s!==n)return!1}return!0}var Ze=class r{constructor(e,t,n,s,i){this.provider=e;this.embedder=t;this.description=n;this.sources=s;this.options=i}provider;embedder;description;sources;options;static async create(e){await e.provider.validateDimensions(e.embedder.dimensions);let t=new r(e.provider,e.embedder,e.description,e.sources,e),n=e.reSync!==!1;return!n&&"shouldReSync"in e.provider?(e.provider.shouldReSync()&&await t.sync(),t):(n&&await t.sync(),t)}async query(e,t){let n=t?.searchType??"semantic",s=t?.semanticWeight??.7;if(n==="keyword")return this.keywordQuery(e,t);if(n==="hybrid"){let[i,o]=await Promise.all([this.semanticQuery(e,t),this.keywordQuery(e,t)]);return this.combineHybridResults(i,o,s,t)}else return this.semanticQuery(e,t)}async semanticQuery(e,t){let n=await this.embedder.embed(e);return this.provider.query(n,t)}async keywordQuery(e,t){let{limit:n=10,threshold:s=.1,filter:i,includeMetadata:o=!0,includeVectors:a=!1}=t||{};if(typeof this.provider.keywordQuery=="function")return this.provider.keywordQuery(e,t);let u=await this.getAllChunks(),c=[];for(let h of u){if(i&&!B(h.metadata,i))continue;let d=N(h.content,e);d>=s&&c.push({chunk:{id:h.id,content:h.content,metadata:o?h.metadata:{},vector:a?h.vector:void 0},score:d,distance:1-d})}return c.sort((h,d)=>d.score-h.score),c.slice(0,n)}combineHybridResults(e,t,n,s){let{limit:i=10,threshold:o=.5,includeMetadata:a=!0,includeVectors:u=!1}=s||{},c=new Map(e.map(m=>[m.chunk.id,m])),h=new Map(t.map(m=>[m.chunk.id,m])),d=[],p=new Set([...c.keys(),...h.keys()]);for(let m of p){let b=c.get(m),R=h.get(m);if(!b&&!R)continue;let Je=b?.score??0,Ye=R?.score??0,K=Se(Je,Ye,n);K>=o&&d.push({chunk:{id:m,content:b?.chunk.content??R.chunk.content,metadata:a?b?.chunk.metadata??R.chunk.metadata:{},vector:u?b?.chunk.vector??R.chunk.vector:void 0},score:K,distance:1-K})}return d.sort((m,b)=>b.score-m.score),d.slice(0,i)}async getAllChunks(){if(typeof this.provider.getAllChunks=="function")return this.provider.getAllChunks();let e=new Array(this.embedder.dimensions).fill(0);return(await this.provider.query(e,{limit:1e4,threshold:0})).map(t=>t.chunk)}async sync(){this.options.onSync?.({type:"start"});try{let e=this.embedder.dimensions;await this.provider.clear(),await this.provider.validateDimensions(e);let t=this.options.streamingBatchSize??100,n=0,s=[];for(let i of this.sources)for await(let o of i.load())if(s.push(o),s.length>=t){let a=await this.embedChunks(s);a.length>0&&(await this.provider.add(a),n+=a.length),s.length=0}if(s.length>0){let i=await this.embedChunks(s);i.length>0&&(await this.provider.add(i),n+=i.length)}this.options.onSync?.({type:"complete",chunksAffected:n})}catch(e){throw this.options.onSync?.({type:"error",error:e}),e}}async embedChunks(e){if(e.length===0)return[];let t=[];try{let n=e.map(i=>i.content),s=await this.embedder.embedBatch(n);for(let i=0;i<e.length;i++)t.push({...e[i],vector:s[i]}),this.options.onEmbeddingProgress?.({source:"sync",current:i+1,total:e.length,percent:Math.round((i+1)/e.length*100)})}catch(n){if(this.options.onError?.(n,{})==="abort")throw n;for(let i=0;i<e.length;i++)try{let o=await this.embedder.embed(e[i].content);t.push({...e[i],vector:o}),this.options.onEmbeddingProgress?.({source:"sync",current:i+1,total:e.length,percent:Math.round((i+1)/e.length*100)})}catch(o){if(this.options.onError?.(o,{chunk:e[i]})==="abort")throw o}}return t}async add(e,t){try{let n=(0,hr.randomUUID)(),s=await this.embedder.embed(e),i={id:n,content:e,metadata:t||{},vector:s};return await this.provider.add([i]),n}catch(n){throw new E(`Failed to add content to knowledge base: ${n.message}`,"add")}}async stop(){this.provider.close&&this.provider.close()}toTool(){return{name:"knowledge_search",displayName:"Knowledge Search",description:this.description||"Search the knowledge base for relevant information",category:"search",cacheable:!1,parameters:{type:"object",properties:{query:{type:"string",description:"Search query to find relevant information"},limit:{type:"number",description:"Maximum number of results to return (default: 10)"},threshold:{type:"number",description:"Minimum similarity threshold 0-1 (default: 0.3)"},filter:{type:"object",description:"Optional metadata filters"}},required:["query"]},execute:async e=>(await this.query(e.query,{limit:e.limit,threshold:e.threshold??.3,filter:e.filter,searchType:"hybrid"})).map(n=>({content:n.chunk.content,score:n.score,metadata:n.chunk.metadata}))}}};l();var Ee=class{constructor(e={}){this.options=e}options;chunks=new Map;dimensions;async validateDimensions(e){if(this.dimensions&&this.dimensions!==e)throw new H(this.dimensions,e);this.dimensions=e}async add(e){for(let t of e){if(!t.vector)throw new Q("Chunk missing vector");if(this.options.maxChunks&&this.chunks.size>=this.options.maxChunks)throw new Q(`Max chunks limit reached: ${this.options.maxChunks}`);this.chunks.set(t.id,{chunk:{id:t.id,content:t.content,metadata:t.metadata},vector:t.vector})}}async query(e,t={}){let{limit:n=10,threshold:s=.7,filter:i,includeMetadata:o=!0,includeVectors:a=!1}=t,u=[];for(let{chunk:c,vector:h}of this.chunks.values()){if(i&&!B(c.metadata,i))continue;let d=ve(e,h);d>=s&&u.push({chunk:{id:c.id,content:c.content,metadata:o?c.metadata:{},vector:a?h:void 0},score:d,distance:1-d})}return u.sort((c,h)=>h.score-c.score),u.slice(0,n)}async keywordQuery(e,t={}){let{limit:n=10,threshold:s=.1,filter:i,includeMetadata:o=!0,includeVectors:a=!1}=t,u=[];for(let{chunk:c,vector:h}of this.chunks.values()){if(i&&!B(c.metadata,i))continue;let d=N(c.content,e);d>=s&&u.push({chunk:{id:c.id,content:c.content,metadata:o?c.metadata:{},vector:a?h:void 0},score:d,distance:1-d})}return u.sort((c,h)=>h.score-c.score),u.slice(0,n)}async delete(e){for(let t of e)this.chunks.delete(t)}async clear(){this.chunks.clear(),this.dimensions=void 0}async getAllChunks(){return Array.from(this.chunks.values()).map(({chunk:e,vector:t})=>({...e,vector:t}))}};l();var dr=_(require("better-sqlite3"),1),oe=_(require("fs"),1),F=_(require("path"),1),fr=_(require("os"),1);var _e=class{constructor(e){this.options=e;let t=fr.homedir(),n=`${e.namespace}.db`,s;if(e.storagePath)s=e.storagePath;else{let i=F.join(t,".toolpack","db","knowledge"),o=F.join(t,".toolpack","knowledge"),a=F.join(i,n),u=F.join(o,n);oe.existsSync(u)&&!oe.existsSync(a)?s=o:s=i}this.dbPath=F.join(s,n),oe.mkdirSync(F.dirname(this.dbPath),{recursive:!0}),this.db=new dr.default(this.dbPath),this.db.pragma("journal_mode = WAL"),this.initSchema(),this.loadDimensions()}options;db;dimensions;dbPath;initSchema(){this.db.exec(`
|
|
9
|
+
`);ye.write(zn.format.apply(zn,e))}}Object.defineProperty(D.exports,"isWin",{get:function(){return Fe},set:function(r){Fe=r}});D.exports.warnTo=function(r){var e=ye;return ye=r,e};D.exports.getFileName=function(r){var e=r||process.env,t=e.PGPASSFILE||(Fe?Hn.join(e.APPDATA||"./","postgresql","pgpass.conf"):Hn.join(e.HOME||"./",".pgpass"));return t};D.exports.usePgPass=function(r,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:Fe?!0:(e=e||"<unkn>",wa(r.mode)?r.mode&(ma|ya)?(Zt('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(Zt('WARNING: password file "%s" is not a plain file',e),!1))};var va=D.exports.match=function(r,e){return ne.slice(0,-1).reduce(function(t,n,s){return s==1&&Number(r[n]||pa)===Number(e[n])?t&&!0:t&&(e[n]==="*"||e[n]===r[n])},!0)};D.exports.getPassword=function(r,e,t){var n,s=e.pipe(fa());function i(u){var c=Ea(u);c&&_a(c)&&va(r,c)&&(n=c[Sa],s.end())}var o=function(){e.destroy(),t(n)},a=function(u){e.destroy(),Zt("WARNING: error on reading file: %s",u),t(void 0)};e.on("error",a),s.on("data",i).on("end",o).on("error",a)};var Ea=D.exports.parseLine=function(r){if(r.length<11||r.match(/^\s+#/))return null;for(var e="",t="",n=0,s=0,i=0,o={},a=!1,u=function(h,d,p){var m=r.substring(d,p);Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE")||(m=m.replace(/\\([:\\])/g,"$1")),o[ne[h]]=m},c=0;c<r.length-1;c+=1){if(e=r.charAt(c+1),t=r.charAt(c),a=n==Xt-1,a){u(n,s);break}c>=0&&e==":"&&t!=="\\"&&(u(n,s,c+1),s=c+2,n+=1)}return o=Object.keys(o).length===Xt?o:null,o},_a=D.exports.isValidEntry=function(r){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}},t=0;t<ne.length;t+=1){var n=e[t],s=r[ne[t]]||"",i=n(s);if(!i)return!1}return!0}});var Vn=g((El,er)=>{"use strict";l();var vl=require("path"),Kn=require("fs"),Ue=Gn();er.exports=function(r,e){var t=Ue.getFileName();Kn.stat(t,function(n,s){if(n||!Ue.usePgPass(s,t))return e(void 0);var i=Kn.createReadStream(t);Ue.getPassword(r,i,e)})};er.exports.warnTo=Ue.warnTo});var Zn=g((kl,Xn)=>{"use strict";l();var ka=require("events").EventEmitter,Wn=X(),ge=require("util"),tr=pn(),Ca=Me(),xa=Et(),Yn=Pn(),Pa=pe(),Aa=Yt(),Ra=bt(),Jn=ge.deprecate(()=>{},"Client.activeQuery is deprecated and will be removed in pg@9.0"),Ta=ge.deprecate(()=>{},"Client.queryQueue is deprecated and will be removed in pg@9.0."),Ia=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."),Oa=ge.deprecate(()=>{},"Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0."),Ma=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."),je=class extends ka{constructor(e){super(),this.connectionParameters=new xa(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 t=e||{};t.Promise&&Oa(),this._Promise=t.Promise||global.Promise,this._types=new Ca(t.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this._activeQuery=null,this.enableChannelBinding=!!t.enableChannelBinding,this.connection=t.connection||new Aa({stream:t.stream,ssl:this.connectionParameters.ssl,keepAlive:t.keepAlive||!1,keepAliveInitialDelayMillis:t.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this._queryQueue=[],this.binary=t.binary||Pa.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=t.connectionTimeoutMillis||0}get activeQuery(){return Jn(),this._activeQuery}set activeQuery(e){Jn(),this._activeQuery=e}_getActiveQuery(){return this._activeQuery}_errorAllQueries(e){let t=s=>{process.nextTick(()=>{s.handleError(e,this.connection)})},n=this._getActiveQuery();n&&(t(n),this._activeQuery=null),this._queryQueue.forEach(t),this._queryQueue.length=0}_connect(e){let t=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(){t.ssl?n.requestSsl():n.startup(t.getStartupConf())}),n.on("sslconnect",function(){n.startup(t.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((t,n)=>{this._connect(s=>{s?n(s):t(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 t=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"){t.emit("error",new TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=n}else this.connectionParameters.password=this.password=null;e()}).catch(n=>{t.emit("error",n)});else if(this.password!==null)e();else try{Vn()(this.connectionParameters,s=>{s!==void 0&&(Ia(),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 t=await Ra.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(t)}catch(t){this.emit("error",t)}})}_handleAuthSASL(e){this._getPassword(()=>{try{this.saslSession=tr.startSession(e.mechanisms,this.enableChannelBinding&&this.connection.stream),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(t){this.connection.emit("error",t)}})}async _handleAuthSASLContinue(e){try{await tr.continueSession(this.saslSession,this.password,e.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(t){this.connection.emit("error",t)}}_handleAuthSASLFinal(e){try{tr.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(t){this.connection.emit("error",t)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let t=this._getActiveQuery();this._activeQuery=null,this.readyForQuery=!0,t&&t.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit("error",e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit("error",e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let t=this._getActiveQuery();if(!t){this._handleErrorEvent(e);return}this._activeQuery=null,t.handleError(e,this.connection)}_handleRowDescription(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected rowDescription message from backend.");this._handleErrorEvent(n);return}t.handleRowDescription(e)}_handleDataRow(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected dataRow message from backend.");this._handleErrorEvent(n);return}t.handleDataRow(e)}_handlePortalSuspended(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected portalSuspended message from backend.");this._handleErrorEvent(n);return}t.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected emptyQuery message from backend.");this._handleErrorEvent(n);return}t.handleEmptyQuery(this.connection)}_handleCommandComplete(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected commandComplete message from backend.");this._handleErrorEvent(n);return}t.handleCommandComplete(e,this.connection)}_handleParseComplete(){let e=this._getActiveQuery();if(e==null){let t=new Error("Received unexpected parseComplete message from backend.");this._handleErrorEvent(t);return}e.name&&(this.connection.parsedStatements[e.name]=e.text)}_handleCopyInResponse(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected copyInResponse message from backend.");this._handleErrorEvent(n);return}t.handleCopyInResponse(this.connection)}_handleCopyData(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected copyData message from backend.");this._handleErrorEvent(n);return}t.handleCopyData(e,this.connection)}_handleNotification(e){this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){let e=this.connectionParameters,t={user:e.user,database:e.database},n=e.application_name||e.fallback_application_name;return n&&(t.application_name=n),e.replication&&(t.replication=""+e.replication),e.statement_timeout&&(t.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(t.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(t.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(t.options=e.options),t}cancel(e,t){if(e.activeQuery===t){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(t)!==-1&&e._queryQueue.splice(e._queryQueue.indexOf(t),1)}setTypeParser(e,t,n){return this._types.setTypeParser(e,t,n)}getTypeParser(e,t){return this._types.getTypeParser(e,t)}escapeIdentifier(e){return Wn.escapeIdentifier(e)}escapeLiteral(e){return Wn.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 t=e.submit(this.connection);t&&process.nextTick(()=>{e.handleError(t,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this._activeQuery=null,this.emit("drain"))}}query(e,t,n){let s,i,o,a,u;if(e==null)throw new TypeError("Client was passed a null or undefined query");return typeof e.submit=="function"?(o=e.query_timeout||this.connectionParameters.query_timeout,i=s=e,s.callback||(typeof t=="function"?s.callback=t:n&&(s.callback=n))):(o=e.query_timeout||this.connectionParameters.query_timeout,s=new Yn(e,t,n),s.callback||(i=new this._Promise((c,h)=>{s.callback=(d,p)=>d?h(d):c(p)}).catch(c=>{throw Error.captureStackTrace(c),c}))),o&&(u=s.callback||(()=>{}),a=setTimeout(()=>{let c=new Error("Query read timeout");process.nextTick(()=>{s.handleError(c,this.connection)}),u(c),s.callback=()=>{};let h=this._queryQueue.indexOf(s);h>-1&&this._queryQueue.splice(h,1),this._pulseQueryQueue()},o),s.callback=(c,h)=>{clearTimeout(a),u(c,h)}),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&&Ma(),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(t=>{this.connection.once("end",t)})}get queryQueue(){return Ta(),this._queryQueue}};je.Query=Yn;Xn.exports=je});var rs=g((xl,ts)=>{"use strict";l();var qa=require("events").EventEmitter,rr=function(){},es=(r,e)=>{let t=r.findIndex(e);return t===-1?void 0:r.splice(t,1)[0]},nr=class{constructor(e,t,n){this.client=e,this.idleListener=t,this.timeoutId=n}},se=class{constructor(e){this.callback=e}};function Da(){throw new Error("Release called on client which has already been released to the pool.")}function $e(r,e){if(e)return{callback:e,result:void 0};let t,n,s=function(o,a){o?t(o):n(a)},i=new r(function(o,a){n=o,t=a}).catch(o=>{throw Error.captureStackTrace(o),o});return{callback:s,result:i}}function La(r,e){return function t(n){n.client=e,e.removeListener("error",t),e.on("error",()=>{r.log("additional client error after disconnection due to error",n)}),r._remove(e),r.emit("error",n,e)}}var sr=class extends qa{constructor(e,t){super(),this.options=Object.assign({},e),e!=null&&"password"in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.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||t||ir().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 t=this.Promise;return typeof t.try=="function"?t.try(e):new t(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(t=>{this._remove(t.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let t=this._idle.pop();clearTimeout(t.timeoutId);let n=t.client;n.ref&&n.ref();let s=t.idleListener;return this._acquireClient(n,e,s,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpected condition")}_remove(e,t){let n=es(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 t=="function"&&t()})}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 t=$e(this.Promise,e),n=t.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new se(t.callback)),n;let s=(a,u,c)=>{clearTimeout(o),t.callback(a,u,c)},i=new se(s),o=setTimeout(()=>{es(this._pendingQueue,a=>a.callback===s),i.timedOut=!0,t.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 se(t.callback)),n}newClient(e){let t=new this.Client(this.options);this._clients.push(t);let n=La(this,t);this.log("checking client timeout");let s,i=!1;this.options.connectionTimeoutMillis&&(s=setTimeout(()=>{t.connection?(this.log("ending client due to timeout"),i=!0,t.connection.stream.destroy()):t.isConnected()||(this.log("ending client due to timeout"),i=!0,t.end())},this.options.connectionTimeoutMillis)),this.log("connecting new client"),t.connect(o=>{if(s&&clearTimeout(s),t.on("error",n),o)this.log("client failed to connect",o),this._clients=this._clients.filter(a=>a!==t),i&&(o=new Error("Connection terminated due to connection timeout",{cause:o})),this._pulseQueue(),e.timedOut||e.callback(o,void 0,rr);else{if(this.log("new client connected"),this.options.onConnect){this._promiseTry(()=>this.options.onConnect(t)).then(()=>{this._afterConnect(t,e,n)},a=>{this._clients=this._clients.filter(u=>u!==t),t.end(()=>{this._pulseQueue(),e.timedOut||e.callback(a,void 0,rr)})});return}return this._afterConnect(t,e,n)}})}_afterConnect(e,t,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 se((o,a,u)=>u()),n,!1)},this.options.maxLifetimeSeconds*1e3);s.unref(),e.once("end",()=>clearTimeout(s))}return this._acquireClient(e,t,n,!0)}_acquireClient(e,t,n,s){s&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,n),e.removeListener("error",n),t.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),t.callback(i,void 0,rr);t.callback(void 0,e,e.release)}):t.callback(void 0,e,e.release)}_releaseOnce(e,t){let n=!1;return s=>{n&&Da(),n=!0,this._release(e,t,s)}}_release(e,t,n){if(e.on("error",t),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 nr(e,t,i)),this._pulseQueue()}query(e,t,n){if(typeof e=="function"){let i=$e(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 t=="function"&&(n=t,t=void 0);let s=$e(this.Promise,n);return n=s.callback,this.connect((i,o)=>{if(i)return n(i);let a=!1,u=c=>{a||(a=!0,o.release(c),n(c))};o.once("error",u),this.log("dispatching query");try{o.query(e,t,(c,h)=>{if(this.log("query dispatched"),o.removeListener("error",u),!a)return a=!0,o.release(c),c?n(c):n(void 0,h)})}catch(c){return o.release(c),n(c)}}),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 t=$e(this.Promise,e);return this._endCallback=t.callback,this._pulseQueue(),t.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,t)=>e+(this._expired.has(t)?1:0),0)}get totalCount(){return this._clients.length}};ts.exports=sr});var is=g((Al,ss)=>{"use strict";l();var ns=require("events").EventEmitter,Qa=require("util"),or=X(),ie=ss.exports=function(r,e,t){ns.call(this),r=or.normalizeQueryConfig(r,e,t),this.text=r.text,this.values=r.values,this.name=r.name,this.queryMode=r.queryMode,this.callback=r.callback,this.state="new",this._arrayMode=r.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(n){n==="row"&&(this._emitRowEvents=!0)}.bind(this))};Qa.inherits(ie,ns);var Na={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};ie.prototype.handleError=function(r){let e=this.native.pq.resultErrorFields();if(e)for(let t in e){let n=Na[t]||t;r[n]=e[t]}this.callback?this.callback(r):this.emit("error",r),this.state="error"};ie.prototype.then=function(r,e){return this._getPromise().then(r,e)};ie.prototype.catch=function(r){return this._getPromise().catch(r)};ie.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(r,e){this._once("end",r),this._once("error",e)}.bind(this)),this._promise)};ie.prototype.submit=function(r){this.state="running";let e=this;this.native=r.native,r.native.arrayMode=this._arrayMode;let t=function(n,s,i){if(r.native.arrayMode=!1,setImmediate(function(){e.emit("_done")}),n)return e.handleError(n);e._emitRowEvents&&(i.length>1?s.forEach((o,a)=>{o.forEach(u=>{e.emit("row",u,i[a])})}):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&&(t=process.domain.bind(t)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));let n=(this.values||[]).map(or.prepareValue);if(r.namedQueries[this.name]){if(this.text&&r.namedQueries[this.name]!==this.text){let s=new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return t(s)}return r.native.execute(this.name,n,t)}return r.native.prepare(this.name,this.text,n.length,function(s){return s?t(s):(r.namedQueries[e.name]=e.text,e.native.execute(e.name,n,t))})}else if(this.values){if(!Array.isArray(this.values)){let s=new Error("Query values must be an array");return t(s)}let n=this.values.map(or.prepareValue);r.native.query(this.text,n,t)}else this.queryMode==="extended"?r.native.query(this.text,[],t):r.native.query(this.text,t)}});var ls=g((Tl,us)=>{"use strict";l();var Ba=require("util"),os;try{os=require("pg-native")}catch(r){throw r}var Fa=Me(),as=require("events").EventEmitter,Ua=require("util"),ja=Et(),cs=is(),$a=Ba.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=us.exports=function(r){as.call(this),r=r||{},this._Promise=r.Promise||global.Promise,this._types=new Fa(r.types),this.native=new os({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;let e=this.connectionParameters=new ja(r);r.nativeConnectionString&&(e.nativeConnectionString=r.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=cs;Ua.inherits(P,as);P.prototype._errorAllQueries=function(r){let e=t=>{process.nextTick(()=>{t.native=this.native,t.handleError(r)})};this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(e),this._queryQueue.length=0};P.prototype._connect=function(r){let e=this;if(this._connecting){process.nextTick(()=>r(new Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(t,n){if(e.connectionParameters.nativeConnectionString&&(n=e.connectionParameters.nativeConnectionString),t)return r(t);e.native.connect(n,function(s){if(s)return e.native.end(),r(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),r(null,this)})})};P.prototype.connect=function(r){if(r){this._connect(r);return}return new this._Promise((e,t)=>{this._connect(n=>{n?t(n):e(this)})})};P.prototype.query=function(r,e,t){let n,s,i,o,a;if(r==null)throw new TypeError("Client was passed a null or undefined query");if(typeof r.submit=="function")i=r.query_timeout||this.connectionParameters.query_timeout,s=n=r,typeof e=="function"&&(r.callback=e);else if(i=r.query_timeout||this.connectionParameters.query_timeout,n=new cs(r,e,t),!n.callback){let u,c;s=new this._Promise((h,d)=>{u=h,c=d}).catch(h=>{throw Error.captureStackTrace(h),h}),n.callback=(h,d)=>h?c(h):u(d)}return i&&(a=n.callback||(()=>{}),o=setTimeout(()=>{let u=new Error("Query read timeout");process.nextTick(()=>{n.handleError(u,this.connection)}),a(u),n.callback=()=>{};let c=this._queryQueue.indexOf(n);c>-1&&this._queryQueue.splice(c,1),this._pulseQueryQueue()},i),n.callback=(u,c)=>{clearTimeout(o),a(u,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&&$a(),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(r){let e=this;this._ending=!0,this._connected||this.once("connect",this.end.bind(this,r));let t;return r||(t=new this._Promise(function(n,s){r=i=>i?s(i):n()})),this.native.end(function(){e._connected=!1,e._errorAllQueries(new Error("Connection terminated")),process.nextTick(()=>{e.emit("end"),r&&r()})}),t};P.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};P.prototype._pulseQueryQueue=function(r){if(!this._connected||this._hasActiveQuery())return;let e=this._queryQueue.shift();if(!e){r||this.emit("drain");return}this._activeQuery=e,e.submit(this);let t=this;e.once("_done",function(){t._pulseQueryQueue()})};P.prototype.cancel=function(r){this._activeQuery===r?this.native.cancel(function(){}):this._queryQueue.indexOf(r)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(r),1)};P.prototype.ref=function(){};P.prototype.unref=function(){};P.prototype.setTypeParser=function(r,e,t){return this._types.setTypeParser(r,e,t)};P.prototype.getTypeParser=function(r,e){return this._types.getTypeParser(r,e)};P.prototype.isConnected=function(){return this._connected}});var ar=g((Ol,hs)=>{"use strict";l();hs.exports=ls()});var ir=g((Dl,He)=>{"use strict";l();var Ha=Zn(),za=pe(),Ga=Yt(),Ka=kt(),Va=X(),Wa=rs(),Ja=Me(),{DatabaseError:Ya}=Vt(),{escapeIdentifier:Xa,escapeLiteral:Za}=X(),ec=r=>class extends Wa{constructor(t){super(t,r)}},ds=function(r){this.defaults=za,this.Client=r,this.Query=this.Client.Query,this.Pool=ec(this.Client),this._pools=[],this.Connection=Ga,this.types=fe(),this.DatabaseError=Ya,this.TypeOverrides=Ja,this.escapeIdentifier=Xa,this.escapeLiteral=Za,this.Result=Ka,this.utils=Va},fs=Ha,ps=!1;try{ps=!!process.env.NODE_PG_FORCE_NATIVE}catch{}ps&&(fs=ar());He.exports=new ds(fs);Object.defineProperty(He.exports,"native",{configurable:!0,enumerable:!1,get(){let r=null;try{r=new ds(ar())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(He.exports,"native",{value:r}),r}})});var ms={};ur(ms,{Client:()=>tc,Connection:()=>nc,DatabaseError:()=>oc,Pool:()=>rc,Query:()=>ic,Result:()=>uc,TypeOverrides:()=>lc,default:()=>dc,defaults:()=>hc,escapeIdentifier:()=>ac,escapeLiteral:()=>cc,types:()=>sc});var I,tc,rc,nc,sc,ic,oc,ac,cc,uc,lc,hc,dc,ys=cr(()=>{"use strict";l();I=_(ir(),1),tc=I.default.Client,rc=I.default.Pool,nc=I.default.Connection,sc=I.default.types,ic=I.default.Query,oc=I.default.DatabaseError,ac=I.default.escapeIdentifier,cc=I.default.escapeLiteral,uc=I.default.Result,lc=I.default.TypeOverrides,hc=I.default.defaults,dc=I.default});var mc={};ur(mc,{ApiDataSource:()=>xe,ChunkTooLargeError:()=>Xe,DimensionMismatchError:()=>H,EmbeddingError:()=>k,IngestionError:()=>E,JSONSource:()=>Pe,Knowledge:()=>Ze,KnowledgeError:()=>L,KnowledgeProviderError:()=>Q,MarkdownSource:()=>ke,MemoryProvider:()=>Ee,OllamaEmbedder:()=>Ge,OpenAIEmbedder:()=>Ke,OpenRouterEmbedder:()=>Ve,PersistentKnowledgeProvider:()=>_e,PostgresSource:()=>ze,SQLiteSource:()=>Ae,VertexAIEmbedder:()=>We,WebUrlSource:()=>Ce,combineScores:()=>Se,keywordSearch:()=>N});module.exports=Cs(mc);l();l();l();var L=class extends Error{constructor(t,n){super(t);this.code=n;this.name="KnowledgeError"}code},k=class extends L{constructor(t,n){super(t,"EMBEDDING_ERROR");this.statusCode=n;this.name="EmbeddingError"}statusCode},E=class extends L{constructor(t,n){super(t,"INGESTION_ERROR");this.file=n;this.name="IngestionError"}file},Xe=class extends L{constructor(t,n){super(t,"CHUNK_TOO_LARGE");this.chunkSize=n;this.name="ChunkTooLargeError"}chunkSize},H=class extends L{expected;actual;constructor(e,t){super(`Dimension mismatch: expected ${e}, got ${t}`,"DIMENSION_MISMATCH"),this.name="DimensionMismatchError",this.expected=e,this.actual=t}},Q=class extends L{constructor(e){super(e,"PROVIDER_ERROR"),this.name="KnowledgeProviderError"}};l();var hr=require("crypto");l();function N(r,e){let t=r.toLowerCase(),n=e.toLowerCase();if(t.includes(n))return 1;let s=n.split(/\s+/).filter(o=>o.length>2);if(s.length===0)return 0;let i=0;for(let o of s)t.includes(o)&&i++;return i/s.length}function Se(r,e,t=.7){let n=1-t;return r*t+e*n}l();function ve(r,e){if(r.length!==e.length)throw new Error("Vectors must have same dimensions");let t=0,n=0,s=0;for(let o=0;o<r.length;o++)t+=r[o]*e[o],n+=r[o]*r[o],s+=e[o]*e[o];let i=Math.sqrt(n)*Math.sqrt(s);return i===0?0:t/i}function B(r,e){if(!e)return!0;for(let[t,n]of Object.entries(e)){let s=r[t];if(typeof n=="object"&&n!==null&&!Array.isArray(n)){if("$in"in n){if(!n.$in.includes(s))return!1}else if("$gt"in n){let i=n.$gt;if(typeof s!="number"||s<=i)return!1}else if("$lt"in n){let i=n.$lt;if(typeof s!="number"||s>=i)return!1}}else if(s!==n)return!1}return!0}var Ze=class r{constructor(e,t,n,s,i){this.provider=e;this.embedder=t;this.description=n;this.sources=s;this.options=i}provider;embedder;description;sources;options;static async create(e){await e.provider.validateDimensions(e.embedder.dimensions);let t=new r(e.provider,e.embedder,e.description,e.sources,e);return e.reSync!==!0&&"shouldReSync"in e.provider?(e.provider.shouldReSync(e.reSync)&&await t.sync(),t):(e.reSync!==!1&&await t.sync(),t)}async query(e,t){let n=t?.searchType??"semantic",s=t?.semanticWeight??.7;if(n==="keyword")return this.keywordQuery(e,t);if(n==="hybrid"){let[i,o]=await Promise.all([this.semanticQuery(e,t),this.keywordQuery(e,t)]);return this.combineHybridResults(i,o,s,t)}else return this.semanticQuery(e,t)}async semanticQuery(e,t){let n=await this.embedder.embed(e);return this.provider.query(n,t)}async keywordQuery(e,t){let{limit:n=10,threshold:s=.1,filter:i,includeMetadata:o=!0,includeVectors:a=!1}=t||{};if(typeof this.provider.keywordQuery=="function")return this.provider.keywordQuery(e,t);let u=await this.getAllChunks(),c=[];for(let h of u){if(i&&!B(h.metadata,i))continue;let d=N(h.content,e);d>=s&&c.push({chunk:{id:h.id,content:h.content,metadata:o?h.metadata:{},vector:a?h.vector:void 0},score:d,distance:1-d})}return c.sort((h,d)=>d.score-h.score),c.slice(0,n)}combineHybridResults(e,t,n,s){let{limit:i=10,threshold:o=.5,includeMetadata:a=!0,includeVectors:u=!1}=s||{},c=new Map(e.map(m=>[m.chunk.id,m])),h=new Map(t.map(m=>[m.chunk.id,m])),d=[],p=new Set([...c.keys(),...h.keys()]);for(let m of p){let b=c.get(m),R=h.get(m);if(!b&&!R)continue;let Je=b?.score??0,Ye=R?.score??0,K=Se(Je,Ye,n);K>=o&&d.push({chunk:{id:m,content:b?.chunk.content??R.chunk.content,metadata:a?b?.chunk.metadata??R.chunk.metadata:{},vector:u?b?.chunk.vector??R.chunk.vector:void 0},score:K,distance:1-K})}return d.sort((m,b)=>b.score-m.score),d.slice(0,i)}async getAllChunks(){if(typeof this.provider.getAllChunks=="function")return this.provider.getAllChunks();let e=new Array(this.embedder.dimensions).fill(0);return(await this.provider.query(e,{limit:1e4,threshold:0})).map(t=>t.chunk)}async sync(){this.options.onSync?.({type:"start"});try{let e=this.embedder.dimensions;await this.provider.clear(),await this.provider.validateDimensions(e);let t=this.options.streamingBatchSize??100,n=0,s=[];for(let i of this.sources)for await(let o of i.load())if(s.push(o),s.length>=t){let a=await this.embedChunks(s);a.length>0&&(await this.provider.add(a),n+=a.length),s.length=0}if(s.length>0){let i=await this.embedChunks(s);i.length>0&&(await this.provider.add(i),n+=i.length)}this.options.onSync?.({type:"complete",chunksAffected:n})}catch(e){throw this.options.onSync?.({type:"error",error:e}),e}}async embedChunks(e){if(e.length===0)return[];let t=[];try{let n=e.map(i=>i.content),s=await this.embedder.embedBatch(n);for(let i=0;i<e.length;i++)t.push({...e[i],vector:s[i]}),this.options.onEmbeddingProgress?.({source:"sync",current:i+1,total:e.length,percent:Math.round((i+1)/e.length*100)})}catch(n){if(this.options.onError?.(n,{})==="abort")throw n;for(let i=0;i<e.length;i++)try{let o=await this.embedder.embed(e[i].content);t.push({...e[i],vector:o}),this.options.onEmbeddingProgress?.({source:"sync",current:i+1,total:e.length,percent:Math.round((i+1)/e.length*100)})}catch(o){if(this.options.onError?.(o,{chunk:e[i]})==="abort")throw o}}return t}async add(e,t){try{let n=(0,hr.randomUUID)(),s=await this.embedder.embed(e),i={id:n,content:e,metadata:t||{},vector:s};return await this.provider.add([i]),n}catch(n){throw new E(`Failed to add content to knowledge base: ${n.message}`,"add")}}async stop(){this.provider.close&&this.provider.close()}toTool(){return{name:"knowledge_search",displayName:"Knowledge Search",description:this.description||"Search the knowledge base for relevant information",category:"search",cacheable:!1,parameters:{type:"object",properties:{query:{type:"string",description:"Search query to find relevant information"},limit:{type:"number",description:"Maximum number of results to return (default: 10)"},threshold:{type:"number",description:"Minimum similarity threshold 0-1 (default: 0.3)"},filter:{type:"object",description:"Optional metadata filters"}},required:["query"]},execute:async e=>(await this.query(e.query,{limit:e.limit,threshold:e.threshold??.3,filter:e.filter,searchType:"hybrid"})).map(n=>({content:n.chunk.content,score:n.score,metadata:n.chunk.metadata}))}}};l();var Ee=class{constructor(e={}){this.options=e}options;chunks=new Map;dimensions;async validateDimensions(e){if(this.dimensions&&this.dimensions!==e)throw new H(this.dimensions,e);this.dimensions=e}async add(e){for(let t of e){if(!t.vector)throw new Q("Chunk missing vector");if(this.options.maxChunks&&this.chunks.size>=this.options.maxChunks)throw new Q(`Max chunks limit reached: ${this.options.maxChunks}`);this.chunks.set(t.id,{chunk:{id:t.id,content:t.content,metadata:t.metadata},vector:t.vector})}}async query(e,t={}){let{limit:n=10,threshold:s=.7,filter:i,includeMetadata:o=!0,includeVectors:a=!1}=t,u=[];for(let{chunk:c,vector:h}of this.chunks.values()){if(i&&!B(c.metadata,i))continue;let d=ve(e,h);d>=s&&u.push({chunk:{id:c.id,content:c.content,metadata:o?c.metadata:{},vector:a?h:void 0},score:d,distance:1-d})}return u.sort((c,h)=>h.score-c.score),u.slice(0,n)}async keywordQuery(e,t={}){let{limit:n=10,threshold:s=.1,filter:i,includeMetadata:o=!0,includeVectors:a=!1}=t,u=[];for(let{chunk:c,vector:h}of this.chunks.values()){if(i&&!B(c.metadata,i))continue;let d=N(c.content,e);d>=s&&u.push({chunk:{id:c.id,content:c.content,metadata:o?c.metadata:{},vector:a?h:void 0},score:d,distance:1-d})}return u.sort((c,h)=>h.score-c.score),u.slice(0,n)}async delete(e){for(let t of e)this.chunks.delete(t)}async clear(){this.chunks.clear(),this.dimensions=void 0}async getAllChunks(){return Array.from(this.chunks.values()).map(({chunk:e,vector:t})=>({...e,vector:t}))}};l();var dr=_(require("better-sqlite3"),1),oe=_(require("fs"),1),F=_(require("path"),1),fr=_(require("os"),1);var _e=class{constructor(e){this.options=e;let t=fr.homedir(),n=`${e.namespace}.db`,s;if(e.storagePath)s=e.storagePath;else{let i=F.join(t,".toolpack","db","knowledge"),o=F.join(t,".toolpack","knowledge"),a=F.join(i,n),u=F.join(o,n);oe.existsSync(u)&&!oe.existsSync(a)?s=o:s=i}this.dbPath=F.join(s,n),oe.mkdirSync(F.dirname(this.dbPath),{recursive:!0}),this.db=new dr.default(this.dbPath),this.db.pragma("journal_mode = WAL"),this.initSchema(),this.loadDimensions()}options;db;dimensions;dbPath;initSchema(){this.db.exec(`
|
|
10
10
|
CREATE TABLE IF NOT EXISTS chunks (
|
|
11
11
|
id TEXT PRIMARY KEY,
|
|
12
12
|
content TEXT NOT NULL,
|
|
@@ -48,7 +48,7 @@ See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode de
|
|
|
48
48
|
WHERE chunks_fts MATCH ?
|
|
49
49
|
ORDER BY bm25(chunks_fts) DESC
|
|
50
50
|
LIMIT ?
|
|
51
|
-
`).all(u,n*2),h=[];for(let d of c){let p=JSON.parse(d.metadata);if(i&&!B(p,i))continue;let m=N(d.content,e);if(m>=s){let b=new Float32Array(d.vector.buffer,d.vector.byteOffset,d.vector.byteLength/4);h.push({chunk:{id:d.id,content:d.content,metadata:o?p:{},vector:a?Array.from(b):void 0},score:m,distance:1-m})}}return h.sort((d,p)=>p.score-d.score),h.slice(0,n)}async delete(e){let t=this.db.prepare("DELETE FROM chunks WHERE id = ?");this.db.transaction(s=>{for(let i of s)t.run(i)})(e)}async clear(){this.db.prepare("DELETE FROM chunks").run(),this.db.prepare("DELETE FROM provider_meta WHERE key = ?").run("dimensions"),this.dimensions=void 0}async getAllChunks(){return this.db.prepare("SELECT id, content, metadata, vector FROM chunks").all().map(t=>{let n=JSON.parse(t.metadata),s=new Float32Array(t.vector.buffer,t.vector.byteOffset,t.vector.byteLength/4);return{id:t.id,content:t.content,metadata:n,vector:Array.from(s)}})}shouldReSync(){return
|
|
51
|
+
`).all(u,n*2),h=[];for(let d of c){let p=JSON.parse(d.metadata);if(i&&!B(p,i))continue;let m=N(d.content,e);if(m>=s){let b=new Float32Array(d.vector.buffer,d.vector.byteOffset,d.vector.byteLength/4);h.push({chunk:{id:d.id,content:d.content,metadata:o?p:{},vector:a?Array.from(b):void 0},score:m,distance:1-m})}}return h.sort((d,p)=>p.score-d.score),h.slice(0,n)}async delete(e){let t=this.db.prepare("DELETE FROM chunks WHERE id = ?");this.db.transaction(s=>{for(let i of s)t.run(i)})(e)}async clear(){this.db.prepare("DELETE FROM chunks").run(),this.db.prepare("DELETE FROM provider_meta WHERE key = ?").run("dimensions"),this.dimensions=void 0}async getAllChunks(){return this.db.prepare("SELECT id, content, metadata, vector FROM chunks").all().map(t=>{let n=JSON.parse(t.metadata),s=new Float32Array(t.vector.buffer,t.vector.byteOffset,t.vector.byteLength/4);return{id:t.id,content:t.content,metadata:n,vector:Array.from(s)}})}shouldReSync(e){return(this.options.reSync??e)===!1?this.db.prepare("SELECT COUNT(*) as count FROM chunks").get().count===0:!0}close(){this.db.close()}};l();var pr=_(require("fs/promises"),1),ae=_(require("path"),1),mr=_(require("crypto"),1),yr=_(require("fast-glob"),1);l();function O(r){return Math.ceil(r.length/4)}function xs(r,e){let t=r.split(/\n\n+/),n=[],s="";for(let i of t){let o=O(i);O(s)+o>e&&s?(n.push(s.trim()),s=i):s+=(s?`
|
|
52
52
|
|
|
53
53
|
`:"")+i}return s&&n.push(s.trim()),n}function Ps(r,e){let t=r.match(/[^.!?]+[.!?]+/g)||[r],n=[],s="";for(let i of t){let o=O(i);O(s)+o>e&&s?(n.push(s.trim()),s=i):s+=(s?" ":"")+i}return s&&n.push(s.trim()),n}function V(r,e){if(r.length<=1||e===0)return r;let t=[];for(let n=0;n<r.length;n++){let s=r[n];if(n>0){let o=r[n-1].split(/\s+/),a=Math.ceil(e/4);s=o.slice(-a).join(" ")+" "+s}t.push(s)}return t}function W(r,e){if(O(r)<=e)return[r];let n=xs(r,e),s=[];for(let i of n)O(i)>e?s.push(...Ps(i,e)):s.push(i);return s}var ke=class{constructor(e,t={}){this.pattern=e;this.options={maxChunkSize:t.maxChunkSize??2e3,chunkOverlap:t.chunkOverlap??200,minChunkSize:t.minChunkSize??100,namespace:t.namespace??"markdown",metadata:t.metadata??{}}}pattern;options;async*load(){let e=this.pattern.replace(/\\/g,"/"),t=await(0,yr.default)(e,{absolute:!0});for(let n of t)try{let s=await pr.readFile(n,"utf-8"),i=this.chunkMarkdown(s,n);for(let o of i)yield o}catch(s){throw new E(`Failed to process file: ${s.message}`,n)}}chunkMarkdown(e,t){let n=this.extractFrontmatter(e),s=this.removeFrontmatter(e),i=this.parseHeadings(s),o=[],a=0;for(let u of i){let c=/```[\s\S]*?```/.test(u.content),h=O(u.content);if(h<this.options.minChunkSize&&o.length>0){let p=o[o.length-1];p.content+=`
|
|
54
54
|
|
package/dist/index.d.cts
CHANGED
|
@@ -81,6 +81,22 @@ interface KnowledgeOptions {
|
|
|
81
81
|
sources: KnowledgeSource[];
|
|
82
82
|
embedder: Embedder;
|
|
83
83
|
description: string;
|
|
84
|
+
/**
|
|
85
|
+
* Controls the full sync `create()` runs at startup. A full sync CLEARS the
|
|
86
|
+
* provider store and re-embeds it from `sources` — anything added at
|
|
87
|
+
* runtime via `knowledge.add()` is lost.
|
|
88
|
+
*
|
|
89
|
+
* `false`: skip the full sync when the store already has data (it still
|
|
90
|
+
* runs once on an empty store, so first-run indexing works). Use this with
|
|
91
|
+
* persistent providers so runtime-added chunks survive restarts. Setting
|
|
92
|
+
* the flag here OR on the provider (for providers with their own `reSync`
|
|
93
|
+
* option) is sufficient — when both are set, the provider's wins.
|
|
94
|
+
*
|
|
95
|
+
* `true`: always run the full sync.
|
|
96
|
+
*
|
|
97
|
+
* Omitted (default): full sync, unless the provider's own `reSync` option
|
|
98
|
+
* is explicitly `false`.
|
|
99
|
+
*/
|
|
84
100
|
reSync?: boolean;
|
|
85
101
|
onError?: ErrorHandler;
|
|
86
102
|
onSync?: SyncEventHandler;
|
|
@@ -182,6 +198,15 @@ declare class MemoryProvider implements KnowledgeProvider {
|
|
|
182
198
|
interface PersistentKnowledgeProviderOptions {
|
|
183
199
|
namespace: string;
|
|
184
200
|
storagePath?: string;
|
|
201
|
+
/**
|
|
202
|
+
* When false, `Knowledge.create()` skips the full re-sync (which CLEARS the
|
|
203
|
+
* store before re-embedding sources) as long as the store already has data.
|
|
204
|
+
* Runtime-added chunks (`knowledge.add()`) therefore survive restarts.
|
|
205
|
+
*
|
|
206
|
+
* Optional here: when omitted, the `reSync` flag passed to `Knowledge.create()`
|
|
207
|
+
* options applies. Set it explicitly on the provider only to override the
|
|
208
|
+
* Knowledge-level flag.
|
|
209
|
+
*/
|
|
185
210
|
reSync?: boolean;
|
|
186
211
|
}
|
|
187
212
|
declare class PersistentKnowledgeProvider implements KnowledgeProvider {
|
|
@@ -199,7 +224,17 @@ declare class PersistentKnowledgeProvider implements KnowledgeProvider {
|
|
|
199
224
|
delete(ids: string[]): Promise<void>;
|
|
200
225
|
clear(): Promise<void>;
|
|
201
226
|
getAllChunks(): Promise<Chunk[]>;
|
|
202
|
-
|
|
227
|
+
/**
|
|
228
|
+
* Whether `Knowledge.create()` should run a full sync (clear + re-embed
|
|
229
|
+
* sources) on startup.
|
|
230
|
+
*
|
|
231
|
+
* The effective reSync intent is the provider's own option when explicitly
|
|
232
|
+
* set, otherwise the Knowledge-level `reSync` flag passed by the caller.
|
|
233
|
+
* When the effective intent is `false`, sync only happens on an empty store
|
|
234
|
+
* (first run) — so runtime-added chunks survive restarts with a single
|
|
235
|
+
* `reSync: false` in either place.
|
|
236
|
+
*/
|
|
237
|
+
shouldReSync(callerReSync?: boolean): boolean;
|
|
203
238
|
close(): void;
|
|
204
239
|
}
|
|
205
240
|
|
package/dist/index.d.ts
CHANGED
|
@@ -81,6 +81,22 @@ interface KnowledgeOptions {
|
|
|
81
81
|
sources: KnowledgeSource[];
|
|
82
82
|
embedder: Embedder;
|
|
83
83
|
description: string;
|
|
84
|
+
/**
|
|
85
|
+
* Controls the full sync `create()` runs at startup. A full sync CLEARS the
|
|
86
|
+
* provider store and re-embeds it from `sources` — anything added at
|
|
87
|
+
* runtime via `knowledge.add()` is lost.
|
|
88
|
+
*
|
|
89
|
+
* `false`: skip the full sync when the store already has data (it still
|
|
90
|
+
* runs once on an empty store, so first-run indexing works). Use this with
|
|
91
|
+
* persistent providers so runtime-added chunks survive restarts. Setting
|
|
92
|
+
* the flag here OR on the provider (for providers with their own `reSync`
|
|
93
|
+
* option) is sufficient — when both are set, the provider's wins.
|
|
94
|
+
*
|
|
95
|
+
* `true`: always run the full sync.
|
|
96
|
+
*
|
|
97
|
+
* Omitted (default): full sync, unless the provider's own `reSync` option
|
|
98
|
+
* is explicitly `false`.
|
|
99
|
+
*/
|
|
84
100
|
reSync?: boolean;
|
|
85
101
|
onError?: ErrorHandler;
|
|
86
102
|
onSync?: SyncEventHandler;
|
|
@@ -182,6 +198,15 @@ declare class MemoryProvider implements KnowledgeProvider {
|
|
|
182
198
|
interface PersistentKnowledgeProviderOptions {
|
|
183
199
|
namespace: string;
|
|
184
200
|
storagePath?: string;
|
|
201
|
+
/**
|
|
202
|
+
* When false, `Knowledge.create()` skips the full re-sync (which CLEARS the
|
|
203
|
+
* store before re-embedding sources) as long as the store already has data.
|
|
204
|
+
* Runtime-added chunks (`knowledge.add()`) therefore survive restarts.
|
|
205
|
+
*
|
|
206
|
+
* Optional here: when omitted, the `reSync` flag passed to `Knowledge.create()`
|
|
207
|
+
* options applies. Set it explicitly on the provider only to override the
|
|
208
|
+
* Knowledge-level flag.
|
|
209
|
+
*/
|
|
185
210
|
reSync?: boolean;
|
|
186
211
|
}
|
|
187
212
|
declare class PersistentKnowledgeProvider implements KnowledgeProvider {
|
|
@@ -199,7 +224,17 @@ declare class PersistentKnowledgeProvider implements KnowledgeProvider {
|
|
|
199
224
|
delete(ids: string[]): Promise<void>;
|
|
200
225
|
clear(): Promise<void>;
|
|
201
226
|
getAllChunks(): Promise<Chunk[]>;
|
|
202
|
-
|
|
227
|
+
/**
|
|
228
|
+
* Whether `Knowledge.create()` should run a full sync (clear + re-embed
|
|
229
|
+
* sources) on startup.
|
|
230
|
+
*
|
|
231
|
+
* The effective reSync intent is the provider's own option when explicitly
|
|
232
|
+
* set, otherwise the Knowledge-level `reSync` flag passed by the caller.
|
|
233
|
+
* When the effective intent is `false`, sync only happens on an empty store
|
|
234
|
+
* (first run) — so runtime-added chunks survive restarts with a single
|
|
235
|
+
* `reSync: false` in either place.
|
|
236
|
+
*/
|
|
237
|
+
shouldReSync(callerReSync?: boolean): boolean;
|
|
203
238
|
close(): void;
|
|
204
239
|
}
|
|
205
240
|
|
package/dist/index.js
CHANGED
|
@@ -6,7 +6,7 @@ To prepare for this change:
|
|
|
6
6
|
- If you want libpq compatibility now, use 'uselibpqcompat=true&sslmode=${r}'
|
|
7
7
|
|
|
8
8
|
See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode definitions.`))}fn.exports=te;te.parse=te;te.toClientConfig=dn;te.parseIntoClientConfig=Zi});var yt=b((el,gn)=>{"use strict";l();var eo=S("dns"),yn=me(),mn=pn().parse,P=function(r,e,t){return e[r]?e[r]:(t===void 0?t=process.env["PG"+r.toUpperCase()]:t===!1||(t=process.env[t]),t||yn[r])},to=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 yn.ssl},re=function(r){return"'"+(""+r).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},D=function(r,e,t){let n=e[t];n!=null&&r.push(t+"="+re(n))},mt=class{constructor(e){e=typeof e=="string"?mn(e):e||{},e.connectionString&&(e=Object.assign({},e,mn(e.connectionString))),this.user=P("user",e),this.database=P("database",e),this.database===void 0&&(this.database=this.user),this.port=parseInt(P("port",e),10),this.host=P("host",e),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:P("password",e)}),this.binary=P("binary",e),this.options=P("options",e),this.ssl=typeof e.ssl>"u"?to():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=P("client_encoding",e),this.replication=P("replication",e),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=P("application_name",e,"PGAPPNAME"),this.fallback_application_name=P("fallback_application_name",e,!1),this.statement_timeout=P("statement_timeout",e,!1),this.lock_timeout=P("lock_timeout",e,!1),this.idle_in_transaction_session_timeout=P("idle_in_transaction_session_timeout",e,!1),this.query_timeout=P("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 t=[];D(t,this,"user"),D(t,this,"password"),D(t,this,"port"),D(t,this,"application_name"),D(t,this,"fallback_application_name"),D(t,this,"connect_timeout"),D(t,this,"options");let n=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(D(t,n,"sslmode"),D(t,n,"sslca"),D(t,n,"sslkey"),D(t,n,"sslcert"),D(t,n,"sslrootcert"),this.database&&t.push("dbname="+re(this.database)),this.replication&&t.push("replication="+re(this.replication)),this.host&&t.push("host="+re(this.host)),this.isDomainSocket)return e(null,t.join(" "));this.client_encoding&&t.push("client_encoding="+re(this.client_encoding)),eo.lookup(this.host,function(s,i){return s?e(s,null):(t.push("hostaddr="+re(i)),e(null,t.join(" ")))})}};gn.exports=mt});var bt=b((rl,wn)=>{"use strict";l();var ro=pe(),bn=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,gt=class{constructor(e,t){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=t,this.RowCtor=null,this.rowAsArray=e==="array",this.rowAsArray&&(this.parseRow=this._parseRowAsArray),this._prebuiltEmptyResultObject=null}addCommandComplete(e){let t;e.text?t=bn.exec(e.text):t=bn.exec(e.command),t&&(this.command=t[1],t[3]?(this.oid=parseInt(t[2],10),this.rowCount=parseInt(t[3],10)):t[2]&&(this.rowCount=parseInt(t[2],10)))}_parseRowAsArray(e){let t=new Array(e.length);for(let n=0,s=e.length;n<s;n++){let i=e[n];i!==null?t[n]=this._parsers[n](i):t[n]=null}return t}parseRow(e){let t={...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 a=this.fields[n].format==="binary"?Buffer.from(i):i;t[o]=this._parsers[n](a)}else t[o]=null}return t}addRow(e){this.rows.push(e)}addFields(e){this.fields=e,this.fields.length&&(this._parsers=new Array(e.length));let t={};for(let n=0;n<e.length;n++){let s=e[n];t[s.name]=null,this._types?this._parsers[n]=this._types.getTypeParser(s.dataTypeID,s.format||"text"):this._parsers[n]=ro.getTypeParser(s.dataTypeID,s.format||"text")}this._prebuiltEmptyResultObject={...t}}};wn.exports=gt});var _n=b((sl,En)=>{"use strict";l();var{EventEmitter:no}=S("events"),Sn=bt(),vn=Z(),wt=class extends no{constructor(e,t,n){super(),e=vn.normalizeQueryConfig(e,t,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 Sn(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 Sn(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 t;if(!this._canceledDueToError){try{t=this._result.parseRow(e.fields)}catch(n){this._canceledDueToError=n;return}this.emit("row",t,this._result),this._accumulateRows&&this._result.addRow(t)}}handleCommandComplete(e,t){this._checkForMultirow(),this._result.addCommandComplete(e),this.rows&&t.sync()}handleEmptyQuery(e){this.rows&&e.sync()}handleError(e,t){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(t){process.nextTick(()=>{throw t})}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 t=e.parsedStatements[this.name];if(this.text&&t&&this.text!==t)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,t){e.execute({portal:this.portal,rows:t}),t?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:vn.prepareValue})}catch(t){this.handleError(t,e);return}e.describe({type:"P",name:this.portal||""}),this._getRows(e,this.rows)}handleCopyInResponse(e){e.sendCopyFail("No source stream defined")}handleCopyData(e,t){}};En.exports=wt});var qt=b(g=>{"use strict";l();Object.defineProperty(g,"__esModule",{value:!0});g.NoticeMessage=g.DataRowMessage=g.CommandCompleteMessage=g.ReadyForQueryMessage=g.NotificationResponseMessage=g.BackendKeyDataMessage=g.AuthenticationMD5Password=g.ParameterStatusMessage=g.ParameterDescriptionMessage=g.RowDescriptionMessage=g.Field=g.CopyResponse=g.CopyDataMessage=g.DatabaseError=g.copyDone=g.emptyQuery=g.replicationStart=g.portalSuspended=g.noData=g.closeComplete=g.bindComplete=g.parseComplete=void 0;g.parseComplete={name:"parseComplete",length:5};g.bindComplete={name:"bindComplete",length:5};g.closeComplete={name:"closeComplete",length:5};g.noData={name:"noData",length:5};g.portalSuspended={name:"portalSuspended",length:5};g.replicationStart={name:"replicationStart",length:4};g.emptyQuery={name:"emptyQuery",length:4};g.copyDone={name:"copyDone",length:4};var St=class extends Error{constructor(e,t,n){super(e),this.length=t,this.name=n}};g.DatabaseError=St;var vt=class{constructor(e,t){this.length=e,this.chunk=t,this.name="copyData"}};g.CopyDataMessage=vt;var Et=class{constructor(e,t,n,s){this.length=e,this.name=t,this.binary=n,this.columnTypes=new Array(s)}};g.CopyResponse=Et;var _t=class{constructor(e,t,n,s,i,o,a){this.name=e,this.tableID=t,this.columnID=n,this.dataTypeID=s,this.dataTypeSize=i,this.dataTypeModifier=o,this.format=a}};g.Field=_t;var kt=class{constructor(e,t){this.length=e,this.fieldCount=t,this.name="rowDescription",this.fields=new Array(this.fieldCount)}};g.RowDescriptionMessage=kt;var Ct=class{constructor(e,t){this.length=e,this.parameterCount=t,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}};g.ParameterDescriptionMessage=Ct;var xt=class{constructor(e,t,n){this.length=e,this.parameterName=t,this.parameterValue=n,this.name="parameterStatus"}};g.ParameterStatusMessage=xt;var Pt=class{constructor(e,t){this.length=e,this.salt=t,this.name="authenticationMD5Password"}};g.AuthenticationMD5Password=Pt;var At=class{constructor(e,t,n){this.length=e,this.processID=t,this.secretKey=n,this.name="backendKeyData"}};g.BackendKeyDataMessage=At;var Rt=class{constructor(e,t,n,s){this.length=e,this.processId=t,this.channel=n,this.payload=s,this.name="notification"}};g.NotificationResponseMessage=Rt;var Tt=class{constructor(e,t){this.length=e,this.status=t,this.name="readyForQuery"}};g.ReadyForQueryMessage=Tt;var Ot=class{constructor(e,t){this.length=e,this.text=t,this.name="commandComplete"}};g.CommandCompleteMessage=Ot;var It=class{constructor(e,t){this.length=e,this.fields=t,this.name="dataRow",this.fieldCount=t.length}};g.DataRowMessage=It;var Mt=class{constructor(e,t){this.length=e,this.message=t,this.name="notice"}};g.NoticeMessage=Mt});var kn=b(xe=>{"use strict";l();Object.defineProperty(xe,"__esModule",{value:!0});xe.Writer=void 0;var Dt=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 t=Buffer.byteLength(e);this.ensure(t+1),this.buffer.write(e,this.offset,"utf-8"),this.offset+=t}return this.buffer[this.offset++]=0,this}addString(e=""){let t=Buffer.byteLength(e);return this.ensure(t),this.buffer.write(e,this.offset),this.offset+=t,this}add(e){return this.ensure(e.length),e.copy(this.buffer,this.offset),this.offset+=e.length,this}join(e){if(e){this.buffer[this.headerPosition]=e;let t=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(t,this.headerPosition+1)}return this.buffer.slice(e?0:5,this.offset)}flush(e){let t=this.join(e);return this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(this.size),t}};xe.Writer=Dt});var xn=b(Ae=>{"use strict";l();Object.defineProperty(Ae,"__esModule",{value:!0});Ae.serialize=void 0;var Lt=kn(),v=new Lt.Writer,so=r=>{v.addInt16(3).addInt16(0);for(let n of Object.keys(r))v.addCString(n).addCString(r[n]);v.addCString("client_encoding").addCString("UTF8");let e=v.addCString("").flush(),t=e.length+4;return new Lt.Writer().addInt32(t).add(e).flush()},io=()=>{let r=Buffer.allocUnsafe(8);return r.writeInt32BE(8,0),r.writeInt32BE(80877103,4),r},oo=r=>v.addCString(r).flush(112),ao=function(r,e){return v.addCString(r).addInt32(Buffer.byteLength(e)).addString(e),v.flush(112)},co=function(r){return v.addString(r).flush(112)},uo=r=>v.addCString(r).flush(81),Cn=[],lo=r=>{let e=r.name||"";e.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",e,e.length),console.error("This can cause conflicts and silent errors executing queries"));let t=r.types||Cn,n=t.length,s=v.addCString(e).addCString(r.text).addInt16(n);for(let i=0;i<n;i++)s.addInt32(t[i]);return v.flush(80)},ne=new Lt.Writer,ho=function(r,e){for(let t=0;t<r.length;t++){let n=e?e(r[t],t):r[t];n==null?(v.addInt16(0),ne.addInt32(-1)):n instanceof Buffer?(v.addInt16(1),ne.addInt32(n.length),ne.add(n)):(v.addInt16(0),ne.addInt32(Buffer.byteLength(n)),ne.addString(n))}},fo=(r={})=>{let e=r.portal||"",t=r.statement||"",n=r.binary||!1,s=r.values||Cn,i=s.length;return v.addCString(e).addCString(t),v.addInt16(i),ho(s,r.valueMapper),v.addInt16(i),v.add(ne.flush()),v.addInt16(1),v.addInt16(n?1:0),v.flush(66)},po=Buffer.from([69,0,0,0,9,0,0,0,0,0]),mo=r=>{if(!r||!r.portal&&!r.rows)return po;let e=r.portal||"",t=r.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(t,i.length-4),i},yo=(r,e)=>{let t=Buffer.allocUnsafe(16);return t.writeInt32BE(16,0),t.writeInt16BE(1234,4),t.writeInt16BE(5678,6),t.writeInt32BE(r,8),t.writeInt32BE(e,12),t},Qt=(r,e)=>{let n=4+Buffer.byteLength(e)+1,s=Buffer.allocUnsafe(1+n);return s[0]=r,s.writeInt32BE(n,1),s.write(e,5,"utf-8"),s[n]=0,s},go=v.addCString("P").flush(68),bo=v.addCString("S").flush(68),wo=r=>r.name?Qt(68,`${r.type}${r.name||""}`):r.type==="P"?go:bo,So=r=>{let e=`${r.type}${r.name||""}`;return Qt(67,e)},vo=r=>v.add(r).flush(100),Eo=r=>Qt(102,r),Pe=r=>Buffer.from([r,0,0,0,4]),_o=Pe(72),ko=Pe(83),Co=Pe(88),xo=Pe(99),Po={startup:so,password:oo,requestSsl:io,sendSASLInitialResponseMessage:ao,sendSCRAMClientFinalMessage:co,query:uo,parse:lo,bind:fo,execute:mo,describe:wo,close:So,flush:()=>_o,sync:()=>ko,end:()=>Co,copyData:vo,copyDone:()=>xo,copyFail:Eo,cancel:yo};Ae.serialize=Po});var Pn=b(Re=>{"use strict";l();Object.defineProperty(Re,"__esModule",{value:!0});Re.BufferReader=void 0;var Nt=class{constructor(e=0){this.offset=e,this.buffer=Buffer.allocUnsafe(0),this.encoding="utf-8"}setBuffer(e,t){this.offset=e,this.buffer=t}int16(){let e=this.buffer.readInt16BE(this.offset);return this.offset+=2,e}byte(){let e=this.buffer[this.offset];return this.offset++,e}int32(){let e=this.buffer.readInt32BE(this.offset);return this.offset+=4,e}uint32(){let e=this.buffer.readUInt32BE(this.offset);return this.offset+=4,e}string(e){let t=this.buffer.toString(this.encoding,this.offset,this.offset+e);return this.offset+=e,t}cstring(){let e=this.offset,t=e;for(;this.buffer[t++]!==0;);return this.offset=t,this.buffer.toString(this.encoding,e,t-1)}bytes(e){let t=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t}};Re.BufferReader=Nt});var On=b(Te=>{"use strict";l();Object.defineProperty(Te,"__esModule",{value:!0});Te.Parser=void 0;var _=qt(),Ao=Pn(),Ft=1,Ro=4,An=Ft+Ro,O=-1,Bt=Buffer.allocUnsafe(0),Ut=class{constructor(e){if(this.buffer=Bt,this.bufferLength=0,this.bufferOffset=0,this.reader=new Ao.BufferReader,e?.mode==="binary")throw new Error("Binary mode not supported yet");this.mode=e?.mode||"text"}parse(e,t){this.mergeBuffer(e);let n=this.bufferOffset+this.bufferLength,s=this.bufferOffset;for(;s+An<=n;){let i=this.buffer[s],o=this.buffer.readUInt32BE(s+Ft),a=Ft+o;if(a+s<=n){let u=this.handlePacket(s+An,i,o,this.buffer);t(u),s+=a}else break}s===n?(this.buffer=Bt,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=n-s,this.bufferOffset=s)}mergeBuffer(e){if(this.bufferLength>0){let t=this.bufferLength+e.byteLength;if(t+this.bufferOffset>this.buffer.byteLength){let s;if(t<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)s=this.buffer;else{let i=this.buffer.byteLength*2;for(;t>=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=t}else this.buffer=e,this.bufferOffset=0,this.bufferLength=e.byteLength}handlePacket(e,t,n,s){let{reader:i}=this;i.setBuffer(e,s);let o;switch(t){case 50:o=_.bindComplete;break;case 49:o=_.parseComplete;break;case 51:o=_.closeComplete;break;case 110:o=_.noData;break;case 115:o=_.portalSuspended;break;case 99:o=_.copyDone;break;case 87:o=_.replicationStart;break;case 73:o=_.emptyQuery;break;case 68:o=Bo(i);break;case 67:o=Oo(i);break;case 90:o=To(i);break;case 65:o=Do(i);break;case 82:o=jo(i,n);break;case 83:o=Fo(i);break;case 75:o=Uo(i);break;case 69:o=Rn(i,"error");break;case 78:o=Rn(i,"notice");break;case 84:o=Lo(i);break;case 116:o=No(i);break;case 71:o=Mo(i);break;case 72:o=qo(i);break;case 100:o=Io(i,n);break;default:return new _.DatabaseError("received invalid response: "+t.toString(16),n,"error")}return i.setBuffer(0,Bt),o.length=n,o}};Te.Parser=Ut;var To=r=>{let e=r.string(1);return new _.ReadyForQueryMessage(O,e)},Oo=r=>{let e=r.cstring();return new _.CommandCompleteMessage(O,e)},Io=(r,e)=>{let t=r.bytes(e-4);return new _.CopyDataMessage(O,t)},Mo=r=>Tn(r,"copyInResponse"),qo=r=>Tn(r,"copyOutResponse"),Tn=(r,e)=>{let t=r.byte()!==0,n=r.int16(),s=new _.CopyResponse(O,e,t,n);for(let i=0;i<n;i++)s.columnTypes[i]=r.int16();return s},Do=r=>{let e=r.int32(),t=r.cstring(),n=r.cstring();return new _.NotificationResponseMessage(O,e,t,n)},Lo=r=>{let e=r.int16(),t=new _.RowDescriptionMessage(O,e);for(let n=0;n<e;n++)t.fields[n]=Qo(r);return t},Qo=r=>{let e=r.cstring(),t=r.uint32(),n=r.int16(),s=r.uint32(),i=r.int16(),o=r.int32(),a=r.int16()===0?"text":"binary";return new _.Field(e,t,n,s,i,o,a)},No=r=>{let e=r.int16(),t=new _.ParameterDescriptionMessage(O,e);for(let n=0;n<e;n++)t.dataTypeIDs[n]=r.int32();return t},Bo=r=>{let e=r.int16(),t=new Array(e);for(let n=0;n<e;n++){let s=r.int32();t[n]=s===-1?null:r.string(s)}return new _.DataRowMessage(O,t)},Fo=r=>{let e=r.cstring(),t=r.cstring();return new _.ParameterStatusMessage(O,e,t)},Uo=r=>{let e=r.int32(),t=r.int32();return new _.BackendKeyDataMessage(O,e,t)},jo=(r,e)=>{let t=r.int32(),n={name:"authenticationOk",length:e};switch(t){case 0:break;case 3:n.length===8&&(n.name="authenticationCleartextPassword");break;case 5:if(n.length===12){n.name="authenticationMD5Password";let s=r.bytes(4);return new _.AuthenticationMD5Password(O,s)}break;case 10:{n.name="authenticationSASL",n.mechanisms=[];let s;do s=r.cstring(),s&&n.mechanisms.push(s);while(s)}break;case 11:n.name="authenticationSASLContinue",n.data=r.string(e-8);break;case 12:n.name="authenticationSASLFinal",n.data=r.string(e-8);break;default:throw new Error("Unknown authenticationOk message type "+t)}return n},Rn=(r,e)=>{let t={},n=r.string(1);for(;n!=="\0";)t[n]=r.cstring(),n=r.string(1);let s=t.M,i=e==="notice"?new _.NoticeMessage(O,s):new _.DatabaseError(s,O,e);return i.severity=t.S,i.code=t.C,i.detail=t.D,i.hint=t.H,i.position=t.P,i.internalPosition=t.p,i.internalQuery=t.q,i.where=t.W,i.schema=t.s,i.table=t.t,i.column=t.c,i.dataType=t.d,i.constraint=t.n,i.file=t.F,i.line=t.L,i.routine=t.R,i}});var jt=b(F=>{"use strict";l();Object.defineProperty(F,"__esModule",{value:!0});F.DatabaseError=F.serialize=F.parse=void 0;var $o=qt();Object.defineProperty(F,"DatabaseError",{enumerable:!0,get:function(){return $o.DatabaseError}});var Ho=xn();Object.defineProperty(F,"serialize",{enumerable:!0,get:function(){return Ho.serialize}});var zo=On();function Go(r,e){let t=new zo.Parser;return r.on("data",n=>t.parse(n,e)),new Promise(n=>r.on("end",()=>n()))}F.parse=Go});var In=b($t=>{"use strict";l();Object.defineProperty($t,"__esModule",{value:!0});$t.default={}});var qn=b((Sl,Mn)=>{"use strict";l();var{getStream:Ko,getSecureStream:Vo}=Xo();Mn.exports={getStream:Ko,getSecureStream:Vo};function Wo(){function r(t){let n=S("net");return new n.Socket}function e(t){return S("tls").connect(t)}return{getStream:r,getSecureStream:e}}function Jo(){function r(t){let{CloudflareSocket:n}=In();return new n(t)}function e(t){return t.socket.startTls(t),t.socket}return{getStream:r,getSecureStream:e}}function Yo(){if(typeof navigator=="object"&&navigator!==null&&typeof navigator.userAgent=="string")return navigator.userAgent==="Cloudflare-Workers";if(typeof Response=="function"){let r=new Response(null,{cf:{thing:!0}});if(typeof r.cf=="object"&&r.cf!==null&&r.cf.thing)return!0}return!1}function Xo(){return Yo()?Jo():Wo()}});var zt=b((El,Dn)=>{"use strict";l();var Zo=S("events").EventEmitter,{parse:ea,serialize:x}=jt(),{getStream:ta,getSecureStream:ra}=qn(),na=x.flush(),sa=x.sync(),ia=x.end(),Ht=class extends Zo{constructor(e){super(),e=e||{},this.stream=e.stream||ta(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 t=this;this.on("newListener",function(n){n==="message"&&(t._emitMessage=!0)})}connect(e,t){let n=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(e,t),this.stream.once("connect",function(){n._keepAlive&&n.stream.setKeepAlive(!0,n._keepAliveInitialDelayMillis),n.emit("connect")});let 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 a={socket:n.stream};n.ssl!==!0&&(Object.assign(a,n.ssl),"key"in n.ssl&&(a.key=n.ssl.key));let u=S("net");u.isIP&&u.isIP(t)===0&&(a.servername=t);try{n.stream=ra(a)}catch(c){return n.emit("error",c)}n.attachListeners(n.stream),n.stream.on("error",s),n.emit("sslconnect")})}attachListeners(e){ea(e,t=>{let n=t.name==="error"?"errorMessage":t.name;this._emitMessage&&this.emit("message",t),this.emit(n,t)})}requestSsl(){this.stream.write(x.requestSsl())}startup(e){this.stream.write(x.startup(e))}cancel(e,t){this._send(x.cancel(e,t))}password(e){this._send(x.password(e))}sendSASLInitialResponseMessage(e,t){this._send(x.sendSASLInitialResponseMessage(e,t))}sendSCRAMClientFinalMessage(e){this._send(x.sendSCRAMClientFinalMessage(e))}_send(e){return this.stream.writable?this.stream.write(e):!1}query(e){this._send(x.query(e))}parse(e){this._send(x.parse(e))}bind(e){this._send(x.bind(e))}execute(e){this._send(x.execute(e))}flush(){this.stream.writable&&this.stream.write(na)}sync(){this._ending=!0,this._send(sa)}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(ia,()=>{this.stream.end()})}close(e){this._send(x.close(e))}describe(e){this._send(x.describe(e))}sendCopyFromChunk(e){this._send(x.copyData(e))}endCopyFrom(){this._send(x.copyDone())}sendCopyFail(e){this._send(x.copyFail(e))}};Dn.exports=Ht});var Bn=b((kl,Nn)=>{"use strict";l();var{Transform:oa}=S("stream"),{StringDecoder:aa}=S("string_decoder"),U=Symbol("last"),Oe=Symbol("decoder");function ca(r,e,t){let n;if(this.overflow){if(n=this[Oe].write(r).split(this.matcher),n.length===1)return t();n.shift(),this.overflow=!1}else this[U]+=this[Oe].write(r),n=this[U].split(this.matcher);this[U]=n.pop();for(let s=0;s<n.length;s++)try{Qn(this,this.mapper(n[s]))}catch(i){return t(i)}if(this.overflow=this[U].length>this.maxLength,this.overflow&&!this.skipOverflow){t(new Error("maximum buffer reached"));return}t()}function ua(r){if(this[U]+=this[Oe].end(),this[U])try{Qn(this,this.mapper(this[U]))}catch(e){return r(e)}r()}function Qn(r,e){e!==void 0&&r.push(e)}function Ln(r){return r}function la(r,e,t){switch(r=r||/\r?\n/,e=e||Ln,t=t||{},arguments.length){case 1:typeof r=="function"?(e=r,r=/\r?\n/):typeof r=="object"&&!(r instanceof RegExp)&&!r[Symbol.split]&&(t=r,r=/\r?\n/);break;case 2:typeof r=="function"?(t=e,e=r,r=/\r?\n/):typeof e=="object"&&(t=e,e=Ln)}t=Object.assign({},t),t.autoDestroy=!0,t.transform=ca,t.flush=ua,t.readableObjectMode=!0;let n=new oa(t);return n[U]="",n[Oe]=new aa("utf8"),n.matcher=r,n.mapper=e,n.maxLength=t.maxLength,n.skipOverflow=t.skipOverflow||!1,n.overflow=!1,n._destroy=function(s,i){this._writableState.errorEmitted=!1,i(s)},n}Nn.exports=la});var jn=b((xl,L)=>{"use strict";l();var Fn=S("path"),ha=S("stream").Stream,da=Bn(),Un=S("util"),fa=5432,Ie=process.platform==="win32",ge=process.stderr,pa=56,ma=7,ya=61440,ga=32768;function ba(r){return(r&ya)==ga}var se=["host","port","database","user","password"],Gt=se.length,wa=se[Gt-1];function Kt(){var r=ge instanceof ha&&ge.writable===!0;if(r){var e=Array.prototype.slice.call(arguments).concat(`
|
|
9
|
-
`);ge.write(Un.format.apply(Un,e))}}Object.defineProperty(L.exports,"isWin",{get:function(){return Ie},set:function(r){Ie=r}});L.exports.warnTo=function(r){var e=ge;return ge=r,e};L.exports.getFileName=function(r){var e=r||process.env,t=e.PGPASSFILE||(Ie?Fn.join(e.APPDATA||"./","postgresql","pgpass.conf"):Fn.join(e.HOME||"./",".pgpass"));return t};L.exports.usePgPass=function(r,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:Ie?!0:(e=e||"<unkn>",ba(r.mode)?r.mode&(pa|ma)?(Kt('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(Kt('WARNING: password file "%s" is not a plain file',e),!1))};var Sa=L.exports.match=function(r,e){return se.slice(0,-1).reduce(function(t,n,s){return s==1&&Number(r[n]||fa)===Number(e[n])?t&&!0:t&&(e[n]==="*"||e[n]===r[n])},!0)};L.exports.getPassword=function(r,e,t){var n,s=e.pipe(da());function i(u){var c=va(u);c&&Ea(c)&&Sa(r,c)&&(n=c[wa],s.end())}var o=function(){e.destroy(),t(n)},a=function(u){e.destroy(),Kt("WARNING: error on reading file: %s",u),t(void 0)};e.on("error",a),s.on("data",i).on("end",o).on("error",a)};var va=L.exports.parseLine=function(r){if(r.length<11||r.match(/^\s+#/))return null;for(var e="",t="",n=0,s=0,i=0,o={},a=!1,u=function(h,d,m){var y=r.substring(d,m);Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE")||(y=y.replace(/\\([:\\])/g,"$1")),o[se[h]]=y},c=0;c<r.length-1;c+=1){if(e=r.charAt(c+1),t=r.charAt(c),a=n==Gt-1,a){u(n,s);break}c>=0&&e==":"&&t!=="\\"&&(u(n,s,c+1),s=c+2,n+=1)}return o=Object.keys(o).length===Gt?o:null,o},Ea=L.exports.isValidEntry=function(r){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}},t=0;t<se.length;t+=1){var n=e[t],s=r[se[t]]||"",i=n(s);if(!i)return!1}return!0}});var Hn=b((Rl,Vt)=>{"use strict";l();var Al=S("path"),$n=S("fs"),Me=jn();Vt.exports=function(r,e){var t=Me.getFileName();$n.stat(t,function(n,s){if(n||!Me.usePgPass(s,t))return e(void 0);var i=$n.createReadStream(t);Me.getPassword(r,i,e)})};Vt.exports.warnTo=Me.warnTo});var Wn=b((Ol,Vn)=>{"use strict";l();var _a=S("events").EventEmitter,zn=Z(),be=S("util"),Wt=ln(),ka=Ce(),Ca=yt(),Kn=_n(),xa=me(),Pa=zt(),Aa=dt(),Gn=be.deprecate(()=>{},"Client.activeQuery is deprecated and will be removed in pg@9.0"),Ra=be.deprecate(()=>{},"Client.queryQueue is deprecated and will be removed in pg@9.0."),Ta=be.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."),Oa=be.deprecate(()=>{},"Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0."),Ia=be.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."),qe=class extends _a{constructor(e){super(),this.connectionParameters=new Ca(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 t=e||{};t.Promise&&Oa(),this._Promise=t.Promise||global.Promise,this._types=new ka(t.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this._activeQuery=null,this.enableChannelBinding=!!t.enableChannelBinding,this.connection=t.connection||new Pa({stream:t.stream,ssl:this.connectionParameters.ssl,keepAlive:t.keepAlive||!1,keepAliveInitialDelayMillis:t.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this._queryQueue=[],this.binary=t.binary||xa.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=t.connectionTimeoutMillis||0}get activeQuery(){return Gn(),this._activeQuery}set activeQuery(e){Gn(),this._activeQuery=e}_getActiveQuery(){return this._activeQuery}_errorAllQueries(e){let t=s=>{process.nextTick(()=>{s.handleError(e,this.connection)})},n=this._getActiveQuery();n&&(t(n),this._activeQuery=null),this._queryQueue.forEach(t),this._queryQueue.length=0}_connect(e){let t=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(){t.ssl?n.requestSsl():n.startup(t.getStartupConf())}),n.on("sslconnect",function(){n.startup(t.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((t,n)=>{this._connect(s=>{s?n(s):t(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 t=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"){t.emit("error",new TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=n}else this.connectionParameters.password=this.password=null;e()}).catch(n=>{t.emit("error",n)});else if(this.password!==null)e();else try{Hn()(this.connectionParameters,s=>{s!==void 0&&(Ta(),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 t=await Aa.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(t)}catch(t){this.emit("error",t)}})}_handleAuthSASL(e){this._getPassword(()=>{try{this.saslSession=Wt.startSession(e.mechanisms,this.enableChannelBinding&&this.connection.stream),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(t){this.connection.emit("error",t)}})}async _handleAuthSASLContinue(e){try{await Wt.continueSession(this.saslSession,this.password,e.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(t){this.connection.emit("error",t)}}_handleAuthSASLFinal(e){try{Wt.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(t){this.connection.emit("error",t)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let t=this._getActiveQuery();this._activeQuery=null,this.readyForQuery=!0,t&&t.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit("error",e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit("error",e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let t=this._getActiveQuery();if(!t){this._handleErrorEvent(e);return}this._activeQuery=null,t.handleError(e,this.connection)}_handleRowDescription(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected rowDescription message from backend.");this._handleErrorEvent(n);return}t.handleRowDescription(e)}_handleDataRow(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected dataRow message from backend.");this._handleErrorEvent(n);return}t.handleDataRow(e)}_handlePortalSuspended(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected portalSuspended message from backend.");this._handleErrorEvent(n);return}t.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected emptyQuery message from backend.");this._handleErrorEvent(n);return}t.handleEmptyQuery(this.connection)}_handleCommandComplete(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected commandComplete message from backend.");this._handleErrorEvent(n);return}t.handleCommandComplete(e,this.connection)}_handleParseComplete(){let e=this._getActiveQuery();if(e==null){let t=new Error("Received unexpected parseComplete message from backend.");this._handleErrorEvent(t);return}e.name&&(this.connection.parsedStatements[e.name]=e.text)}_handleCopyInResponse(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected copyInResponse message from backend.");this._handleErrorEvent(n);return}t.handleCopyInResponse(this.connection)}_handleCopyData(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected copyData message from backend.");this._handleErrorEvent(n);return}t.handleCopyData(e,this.connection)}_handleNotification(e){this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){let e=this.connectionParameters,t={user:e.user,database:e.database},n=e.application_name||e.fallback_application_name;return n&&(t.application_name=n),e.replication&&(t.replication=""+e.replication),e.statement_timeout&&(t.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(t.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(t.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(t.options=e.options),t}cancel(e,t){if(e.activeQuery===t){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(t)!==-1&&e._queryQueue.splice(e._queryQueue.indexOf(t),1)}setTypeParser(e,t,n){return this._types.setTypeParser(e,t,n)}getTypeParser(e,t){return this._types.getTypeParser(e,t)}escapeIdentifier(e){return zn.escapeIdentifier(e)}escapeLiteral(e){return zn.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 t=e.submit(this.connection);t&&process.nextTick(()=>{e.handleError(t,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this._activeQuery=null,this.emit("drain"))}}query(e,t,n){let s,i,o,a,u;if(e==null)throw new TypeError("Client was passed a null or undefined query");return typeof e.submit=="function"?(o=e.query_timeout||this.connectionParameters.query_timeout,i=s=e,s.callback||(typeof t=="function"?s.callback=t:n&&(s.callback=n))):(o=e.query_timeout||this.connectionParameters.query_timeout,s=new Kn(e,t,n),s.callback||(i=new this._Promise((c,h)=>{s.callback=(d,m)=>d?h(d):c(m)}).catch(c=>{throw Error.captureStackTrace(c),c}))),o&&(u=s.callback||(()=>{}),a=setTimeout(()=>{let c=new Error("Query read timeout");process.nextTick(()=>{s.handleError(c,this.connection)}),u(c),s.callback=()=>{};let h=this._queryQueue.indexOf(s);h>-1&&this._queryQueue.splice(h,1),this._pulseQueryQueue()},o),s.callback=(c,h)=>{clearTimeout(a),u(c,h)}),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&&Ia(),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(t=>{this.connection.once("end",t)})}get queryQueue(){return Ra(),this._queryQueue}};qe.Query=Kn;Vn.exports=qe});var Xn=b((Ml,Yn)=>{"use strict";l();var Ma=S("events").EventEmitter,Jt=function(){},Jn=(r,e)=>{let t=r.findIndex(e);return t===-1?void 0:r.splice(t,1)[0]},Yt=class{constructor(e,t,n){this.client=e,this.idleListener=t,this.timeoutId=n}},ie=class{constructor(e){this.callback=e}};function qa(){throw new Error("Release called on client which has already been released to the pool.")}function De(r,e){if(e)return{callback:e,result:void 0};let t,n,s=function(o,a){o?t(o):n(a)},i=new r(function(o,a){n=o,t=a}).catch(o=>{throw Error.captureStackTrace(o),o});return{callback:s,result:i}}function Da(r,e){return function t(n){n.client=e,e.removeListener("error",t),e.on("error",()=>{r.log("additional client error after disconnection due to error",n)}),r._remove(e),r.emit("error",n,e)}}var Xt=class extends Ma{constructor(e,t){super(),this.options=Object.assign({},e),e!=null&&"password"in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.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||t||Zt().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 t=this.Promise;return typeof t.try=="function"?t.try(e):new t(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(t=>{this._remove(t.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let t=this._idle.pop();clearTimeout(t.timeoutId);let n=t.client;n.ref&&n.ref();let s=t.idleListener;return this._acquireClient(n,e,s,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpected condition")}_remove(e,t){let n=Jn(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 t=="function"&&t()})}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 t=De(this.Promise,e),n=t.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new ie(t.callback)),n;let s=(a,u,c)=>{clearTimeout(o),t.callback(a,u,c)},i=new ie(s),o=setTimeout(()=>{Jn(this._pendingQueue,a=>a.callback===s),i.timedOut=!0,t.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 ie(t.callback)),n}newClient(e){let t=new this.Client(this.options);this._clients.push(t);let n=Da(this,t);this.log("checking client timeout");let s,i=!1;this.options.connectionTimeoutMillis&&(s=setTimeout(()=>{t.connection?(this.log("ending client due to timeout"),i=!0,t.connection.stream.destroy()):t.isConnected()||(this.log("ending client due to timeout"),i=!0,t.end())},this.options.connectionTimeoutMillis)),this.log("connecting new client"),t.connect(o=>{if(s&&clearTimeout(s),t.on("error",n),o)this.log("client failed to connect",o),this._clients=this._clients.filter(a=>a!==t),i&&(o=new Error("Connection terminated due to connection timeout",{cause:o})),this._pulseQueue(),e.timedOut||e.callback(o,void 0,Jt);else{if(this.log("new client connected"),this.options.onConnect){this._promiseTry(()=>this.options.onConnect(t)).then(()=>{this._afterConnect(t,e,n)},a=>{this._clients=this._clients.filter(u=>u!==t),t.end(()=>{this._pulseQueue(),e.timedOut||e.callback(a,void 0,Jt)})});return}return this._afterConnect(t,e,n)}})}_afterConnect(e,t,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 ie((o,a,u)=>u()),n,!1)},this.options.maxLifetimeSeconds*1e3);s.unref(),e.once("end",()=>clearTimeout(s))}return this._acquireClient(e,t,n,!0)}_acquireClient(e,t,n,s){s&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,n),e.removeListener("error",n),t.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),t.callback(i,void 0,Jt);t.callback(void 0,e,e.release)}):t.callback(void 0,e,e.release)}_releaseOnce(e,t){let n=!1;return s=>{n&&qa(),n=!0,this._release(e,t,s)}}_release(e,t,n){if(e.on("error",t),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 Yt(e,t,i)),this._pulseQueue()}query(e,t,n){if(typeof e=="function"){let i=De(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 t=="function"&&(n=t,t=void 0);let s=De(this.Promise,n);return n=s.callback,this.connect((i,o)=>{if(i)return n(i);let a=!1,u=c=>{a||(a=!0,o.release(c),n(c))};o.once("error",u),this.log("dispatching query");try{o.query(e,t,(c,h)=>{if(this.log("query dispatched"),o.removeListener("error",u),!a)return a=!0,o.release(c),c?n(c):n(void 0,h)})}catch(c){return o.release(c),n(c)}}),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 t=De(this.Promise,e);return this._endCallback=t.callback,this._pulseQueue(),t.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,t)=>e+(this._expired.has(t)?1:0),0)}get totalCount(){return this._clients.length}};Yn.exports=Xt});var ts=b((Dl,es)=>{"use strict";l();var Zn=S("events").EventEmitter,La=S("util"),er=Z(),oe=es.exports=function(r,e,t){Zn.call(this),r=er.normalizeQueryConfig(r,e,t),this.text=r.text,this.values=r.values,this.name=r.name,this.queryMode=r.queryMode,this.callback=r.callback,this.state="new",this._arrayMode=r.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(n){n==="row"&&(this._emitRowEvents=!0)}.bind(this))};La.inherits(oe,Zn);var Qa={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};oe.prototype.handleError=function(r){let e=this.native.pq.resultErrorFields();if(e)for(let t in e){let n=Qa[t]||t;r[n]=e[t]}this.callback?this.callback(r):this.emit("error",r),this.state="error"};oe.prototype.then=function(r,e){return this._getPromise().then(r,e)};oe.prototype.catch=function(r){return this._getPromise().catch(r)};oe.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(r,e){this._once("end",r),this._once("error",e)}.bind(this)),this._promise)};oe.prototype.submit=function(r){this.state="running";let e=this;this.native=r.native,r.native.arrayMode=this._arrayMode;let t=function(n,s,i){if(r.native.arrayMode=!1,setImmediate(function(){e.emit("_done")}),n)return e.handleError(n);e._emitRowEvents&&(i.length>1?s.forEach((o,a)=>{o.forEach(u=>{e.emit("row",u,i[a])})}):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&&(t=process.domain.bind(t)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));let n=(this.values||[]).map(er.prepareValue);if(r.namedQueries[this.name]){if(this.text&&r.namedQueries[this.name]!==this.text){let s=new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return t(s)}return r.native.execute(this.name,n,t)}return r.native.prepare(this.name,this.text,n.length,function(s){return s?t(s):(r.namedQueries[e.name]=e.text,e.native.execute(e.name,n,t))})}else if(this.values){if(!Array.isArray(this.values)){let s=new Error("Query values must be an array");return t(s)}let n=this.values.map(er.prepareValue);r.native.query(this.text,n,t)}else this.queryMode==="extended"?r.native.query(this.text,[],t):r.native.query(this.text,t)}});var os=b((Ql,is)=>{"use strict";l();var Na=S("util"),rs;try{rs=S("pg-native")}catch(r){throw r}var Ba=Ce(),ns=S("events").EventEmitter,Fa=S("util"),Ua=yt(),ss=ts(),ja=Na.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."),A=is.exports=function(r){ns.call(this),r=r||{},this._Promise=r.Promise||global.Promise,this._types=new Ba(r.types),this.native=new rs({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;let e=this.connectionParameters=new Ua(r);r.nativeConnectionString&&(e.nativeConnectionString=r.nativeConnectionString),this.user=e.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),this.database=e.database,this.host=e.host,this.port=e.port,this.namedQueries={}};A.Query=ss;Fa.inherits(A,ns);A.prototype._errorAllQueries=function(r){let e=t=>{process.nextTick(()=>{t.native=this.native,t.handleError(r)})};this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(e),this._queryQueue.length=0};A.prototype._connect=function(r){let e=this;if(this._connecting){process.nextTick(()=>r(new Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(t,n){if(e.connectionParameters.nativeConnectionString&&(n=e.connectionParameters.nativeConnectionString),t)return r(t);e.native.connect(n,function(s){if(s)return e.native.end(),r(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),r(null,this)})})};A.prototype.connect=function(r){if(r){this._connect(r);return}return new this._Promise((e,t)=>{this._connect(n=>{n?t(n):e(this)})})};A.prototype.query=function(r,e,t){let n,s,i,o,a;if(r==null)throw new TypeError("Client was passed a null or undefined query");if(typeof r.submit=="function")i=r.query_timeout||this.connectionParameters.query_timeout,s=n=r,typeof e=="function"&&(r.callback=e);else if(i=r.query_timeout||this.connectionParameters.query_timeout,n=new ss(r,e,t),!n.callback){let u,c;s=new this._Promise((h,d)=>{u=h,c=d}).catch(h=>{throw Error.captureStackTrace(h),h}),n.callback=(h,d)=>h?c(h):u(d)}return i&&(a=n.callback||(()=>{}),o=setTimeout(()=>{let u=new Error("Query read timeout");process.nextTick(()=>{n.handleError(u,this.connection)}),a(u),n.callback=()=>{};let c=this._queryQueue.indexOf(n);c>-1&&this._queryQueue.splice(c,1),this._pulseQueryQueue()},i),n.callback=(u,c)=>{clearTimeout(o),a(u,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&&ja(),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)};A.prototype.end=function(r){let e=this;this._ending=!0,this._connected||this.once("connect",this.end.bind(this,r));let t;return r||(t=new this._Promise(function(n,s){r=i=>i?s(i):n()})),this.native.end(function(){e._connected=!1,e._errorAllQueries(new Error("Connection terminated")),process.nextTick(()=>{e.emit("end"),r&&r()})}),t};A.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};A.prototype._pulseQueryQueue=function(r){if(!this._connected||this._hasActiveQuery())return;let e=this._queryQueue.shift();if(!e){r||this.emit("drain");return}this._activeQuery=e,e.submit(this);let t=this;e.once("_done",function(){t._pulseQueryQueue()})};A.prototype.cancel=function(r){this._activeQuery===r?this.native.cancel(function(){}):this._queryQueue.indexOf(r)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(r),1)};A.prototype.ref=function(){};A.prototype.unref=function(){};A.prototype.setTypeParser=function(r,e,t){return this._types.setTypeParser(r,e,t)};A.prototype.getTypeParser=function(r,e){return this._types.getTypeParser(r,e)};A.prototype.isConnected=function(){return this._connected}});var tr=b((Bl,as)=>{"use strict";l();as.exports=os()});var Zt=b((jl,Le)=>{"use strict";l();var $a=Wn(),Ha=me(),za=zt(),Ga=bt(),Ka=Z(),Va=Xn(),Wa=Ce(),{DatabaseError:Ja}=jt(),{escapeIdentifier:Ya,escapeLiteral:Xa}=Z(),Za=r=>class extends Va{constructor(t){super(t,r)}},cs=function(r){this.defaults=Ha,this.Client=r,this.Query=this.Client.Query,this.Pool=Za(this.Client),this._pools=[],this.Connection=za,this.types=pe(),this.DatabaseError=Ja,this.TypeOverrides=Wa,this.escapeIdentifier=Ya,this.escapeLiteral=Xa,this.Result=Ga,this.utils=Ka},us=$a,ls=!1;try{ls=!!process.env.NODE_PG_FORCE_NATIVE}catch{}ls&&(us=tr());Le.exports=new cs(us);Object.defineProperty(Le.exports,"native",{configurable:!0,enumerable:!1,get(){let r=null;try{r=new cs(tr())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(Le.exports,"native",{value:r}),r}})});var hs={};ws(hs,{Client:()=>ec,Connection:()=>rc,DatabaseError:()=>ic,Pool:()=>tc,Query:()=>sc,Result:()=>cc,TypeOverrides:()=>uc,default:()=>hc,defaults:()=>lc,escapeIdentifier:()=>oc,escapeLiteral:()=>ac,types:()=>nc});var I,ec,tc,rc,nc,sc,ic,oc,ac,cc,uc,lc,hc,ds=ar(()=>{"use strict";l();I=vs(Zt(),1),ec=I.default.Client,tc=I.default.Pool,rc=I.default.Connection,nc=I.default.types,sc=I.default.Query,ic=I.default.DatabaseError,oc=I.default.escapeIdentifier,ac=I.default.escapeLiteral,cc=I.default.Result,uc=I.default.TypeOverrides,lc=I.default.defaults,hc=I.default});l();l();l();var j=class extends Error{constructor(t,n){super(t);this.code=n;this.name="KnowledgeError"}code},C=class extends j{constructor(t,n){super(t,"EMBEDDING_ERROR");this.statusCode=n;this.name="EmbeddingError"}statusCode},k=class extends j{constructor(t,n){super(t,"INGESTION_ERROR");this.file=n;this.name="IngestionError"}file},cr=class extends j{constructor(t,n){super(t,"CHUNK_TOO_LARGE");this.chunkSize=n;this.name="ChunkTooLargeError"}chunkSize},V=class extends j{expected;actual;constructor(e,t){super(`Dimension mismatch: expected ${e}, got ${t}`,"DIMENSION_MISMATCH"),this.name="DimensionMismatchError",this.expected=e,this.actual=t}},$=class extends j{constructor(e){super(e,"PROVIDER_ERROR"),this.name="KnowledgeProviderError"}};l();import{randomUUID as Es}from"crypto";l();function H(r,e){let t=r.toLowerCase(),n=e.toLowerCase();if(t.includes(n))return 1;let s=n.split(/\s+/).filter(o=>o.length>2);if(s.length===0)return 0;let i=0;for(let o of s)t.includes(o)&&i++;return i/s.length}function Fe(r,e,t=.7){let n=1-t;return r*t+e*n}l();function Se(r,e){if(r.length!==e.length)throw new Error("Vectors must have same dimensions");let t=0,n=0,s=0;for(let o=0;o<r.length;o++)t+=r[o]*e[o],n+=r[o]*r[o],s+=e[o]*e[o];let i=Math.sqrt(n)*Math.sqrt(s);return i===0?0:t/i}function Q(r,e){if(!e)return!0;for(let[t,n]of Object.entries(e)){let s=r[t];if(typeof n=="object"&&n!==null&&!Array.isArray(n)){if("$in"in n){if(!n.$in.includes(s))return!1}else if("$gt"in n){let i=n.$gt;if(typeof s!="number"||s<=i)return!1}else if("$lt"in n){let i=n.$lt;if(typeof s!="number"||s>=i)return!1}}else if(s!==n)return!1}return!0}var ur=class r{constructor(e,t,n,s,i){this.provider=e;this.embedder=t;this.description=n;this.sources=s;this.options=i}provider;embedder;description;sources;options;static async create(e){await e.provider.validateDimensions(e.embedder.dimensions);let t=new r(e.provider,e.embedder,e.description,e.sources,e),n=e.reSync!==!1;return!n&&"shouldReSync"in e.provider?(e.provider.shouldReSync()&&await t.sync(),t):(n&&await t.sync(),t)}async query(e,t){let n=t?.searchType??"semantic",s=t?.semanticWeight??.7;if(n==="keyword")return this.keywordQuery(e,t);if(n==="hybrid"){let[i,o]=await Promise.all([this.semanticQuery(e,t),this.keywordQuery(e,t)]);return this.combineHybridResults(i,o,s,t)}else return this.semanticQuery(e,t)}async semanticQuery(e,t){let n=await this.embedder.embed(e);return this.provider.query(n,t)}async keywordQuery(e,t){let{limit:n=10,threshold:s=.1,filter:i,includeMetadata:o=!0,includeVectors:a=!1}=t||{};if(typeof this.provider.keywordQuery=="function")return this.provider.keywordQuery(e,t);let u=await this.getAllChunks(),c=[];for(let h of u){if(i&&!Q(h.metadata,i))continue;let d=H(h.content,e);d>=s&&c.push({chunk:{id:h.id,content:h.content,metadata:o?h.metadata:{},vector:a?h.vector:void 0},score:d,distance:1-d})}return c.sort((h,d)=>d.score-h.score),c.slice(0,n)}combineHybridResults(e,t,n,s){let{limit:i=10,threshold:o=.5,includeMetadata:a=!0,includeVectors:u=!1}=s||{},c=new Map(e.map(y=>[y.chunk.id,y])),h=new Map(t.map(y=>[y.chunk.id,y])),d=[],m=new Set([...c.keys(),...h.keys()]);for(let y of m){let w=c.get(y),T=h.get(y);if(!w&&!T)continue;let Qe=w?.score??0,Ne=T?.score??0,K=Fe(Qe,Ne,n);K>=o&&d.push({chunk:{id:y,content:w?.chunk.content??T.chunk.content,metadata:a?w?.chunk.metadata??T.chunk.metadata:{},vector:u?w?.chunk.vector??T.chunk.vector:void 0},score:K,distance:1-K})}return d.sort((y,w)=>w.score-y.score),d.slice(0,i)}async getAllChunks(){if(typeof this.provider.getAllChunks=="function")return this.provider.getAllChunks();let e=new Array(this.embedder.dimensions).fill(0);return(await this.provider.query(e,{limit:1e4,threshold:0})).map(t=>t.chunk)}async sync(){this.options.onSync?.({type:"start"});try{let e=this.embedder.dimensions;await this.provider.clear(),await this.provider.validateDimensions(e);let t=this.options.streamingBatchSize??100,n=0,s=[];for(let i of this.sources)for await(let o of i.load())if(s.push(o),s.length>=t){let a=await this.embedChunks(s);a.length>0&&(await this.provider.add(a),n+=a.length),s.length=0}if(s.length>0){let i=await this.embedChunks(s);i.length>0&&(await this.provider.add(i),n+=i.length)}this.options.onSync?.({type:"complete",chunksAffected:n})}catch(e){throw this.options.onSync?.({type:"error",error:e}),e}}async embedChunks(e){if(e.length===0)return[];let t=[];try{let n=e.map(i=>i.content),s=await this.embedder.embedBatch(n);for(let i=0;i<e.length;i++)t.push({...e[i],vector:s[i]}),this.options.onEmbeddingProgress?.({source:"sync",current:i+1,total:e.length,percent:Math.round((i+1)/e.length*100)})}catch(n){if(this.options.onError?.(n,{})==="abort")throw n;for(let i=0;i<e.length;i++)try{let o=await this.embedder.embed(e[i].content);t.push({...e[i],vector:o}),this.options.onEmbeddingProgress?.({source:"sync",current:i+1,total:e.length,percent:Math.round((i+1)/e.length*100)})}catch(o){if(this.options.onError?.(o,{chunk:e[i]})==="abort")throw o}}return t}async add(e,t){try{let n=Es(),s=await this.embedder.embed(e),i={id:n,content:e,metadata:t||{},vector:s};return await this.provider.add([i]),n}catch(n){throw new k(`Failed to add content to knowledge base: ${n.message}`,"add")}}async stop(){this.provider.close&&this.provider.close()}toTool(){return{name:"knowledge_search",displayName:"Knowledge Search",description:this.description||"Search the knowledge base for relevant information",category:"search",cacheable:!1,parameters:{type:"object",properties:{query:{type:"string",description:"Search query to find relevant information"},limit:{type:"number",description:"Maximum number of results to return (default: 10)"},threshold:{type:"number",description:"Minimum similarity threshold 0-1 (default: 0.3)"},filter:{type:"object",description:"Optional metadata filters"}},required:["query"]},execute:async e=>(await this.query(e.query,{limit:e.limit,threshold:e.threshold??.3,filter:e.filter,searchType:"hybrid"})).map(n=>({content:n.chunk.content,score:n.score,metadata:n.chunk.metadata}))}}};l();var Ue=class{constructor(e={}){this.options=e}options;chunks=new Map;dimensions;async validateDimensions(e){if(this.dimensions&&this.dimensions!==e)throw new V(this.dimensions,e);this.dimensions=e}async add(e){for(let t of e){if(!t.vector)throw new $("Chunk missing vector");if(this.options.maxChunks&&this.chunks.size>=this.options.maxChunks)throw new $(`Max chunks limit reached: ${this.options.maxChunks}`);this.chunks.set(t.id,{chunk:{id:t.id,content:t.content,metadata:t.metadata},vector:t.vector})}}async query(e,t={}){let{limit:n=10,threshold:s=.7,filter:i,includeMetadata:o=!0,includeVectors:a=!1}=t,u=[];for(let{chunk:c,vector:h}of this.chunks.values()){if(i&&!Q(c.metadata,i))continue;let d=Se(e,h);d>=s&&u.push({chunk:{id:c.id,content:c.content,metadata:o?c.metadata:{},vector:a?h:void 0},score:d,distance:1-d})}return u.sort((c,h)=>h.score-c.score),u.slice(0,n)}async keywordQuery(e,t={}){let{limit:n=10,threshold:s=.1,filter:i,includeMetadata:o=!0,includeVectors:a=!1}=t,u=[];for(let{chunk:c,vector:h}of this.chunks.values()){if(i&&!Q(c.metadata,i))continue;let d=H(c.content,e);d>=s&&u.push({chunk:{id:c.id,content:c.content,metadata:o?c.metadata:{},vector:a?h:void 0},score:d,distance:1-d})}return u.sort((c,h)=>h.score-c.score),u.slice(0,n)}async delete(e){for(let t of e)this.chunks.delete(t)}async clear(){this.chunks.clear(),this.dimensions=void 0}async getAllChunks(){return Array.from(this.chunks.values()).map(({chunk:e,vector:t})=>({...e,vector:t}))}};l();import _s from"better-sqlite3";import*as ae from"fs";import*as N from"path";import*as lr from"os";var je=class{constructor(e){this.options=e;let t=lr.homedir(),n=`${e.namespace}.db`,s;if(e.storagePath)s=e.storagePath;else{let i=N.join(t,".toolpack","db","knowledge"),o=N.join(t,".toolpack","knowledge"),a=N.join(i,n),u=N.join(o,n);ae.existsSync(u)&&!ae.existsSync(a)?s=o:s=i}this.dbPath=N.join(s,n),ae.mkdirSync(N.dirname(this.dbPath),{recursive:!0}),this.db=new _s(this.dbPath),this.db.pragma("journal_mode = WAL"),this.initSchema(),this.loadDimensions()}options;db;dimensions;dbPath;initSchema(){this.db.exec(`
|
|
9
|
+
`);ge.write(Un.format.apply(Un,e))}}Object.defineProperty(L.exports,"isWin",{get:function(){return Ie},set:function(r){Ie=r}});L.exports.warnTo=function(r){var e=ge;return ge=r,e};L.exports.getFileName=function(r){var e=r||process.env,t=e.PGPASSFILE||(Ie?Fn.join(e.APPDATA||"./","postgresql","pgpass.conf"):Fn.join(e.HOME||"./",".pgpass"));return t};L.exports.usePgPass=function(r,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:Ie?!0:(e=e||"<unkn>",ba(r.mode)?r.mode&(pa|ma)?(Kt('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(Kt('WARNING: password file "%s" is not a plain file',e),!1))};var Sa=L.exports.match=function(r,e){return se.slice(0,-1).reduce(function(t,n,s){return s==1&&Number(r[n]||fa)===Number(e[n])?t&&!0:t&&(e[n]==="*"||e[n]===r[n])},!0)};L.exports.getPassword=function(r,e,t){var n,s=e.pipe(da());function i(u){var c=va(u);c&&Ea(c)&&Sa(r,c)&&(n=c[wa],s.end())}var o=function(){e.destroy(),t(n)},a=function(u){e.destroy(),Kt("WARNING: error on reading file: %s",u),t(void 0)};e.on("error",a),s.on("data",i).on("end",o).on("error",a)};var va=L.exports.parseLine=function(r){if(r.length<11||r.match(/^\s+#/))return null;for(var e="",t="",n=0,s=0,i=0,o={},a=!1,u=function(h,d,m){var y=r.substring(d,m);Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE")||(y=y.replace(/\\([:\\])/g,"$1")),o[se[h]]=y},c=0;c<r.length-1;c+=1){if(e=r.charAt(c+1),t=r.charAt(c),a=n==Gt-1,a){u(n,s);break}c>=0&&e==":"&&t!=="\\"&&(u(n,s,c+1),s=c+2,n+=1)}return o=Object.keys(o).length===Gt?o:null,o},Ea=L.exports.isValidEntry=function(r){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}},t=0;t<se.length;t+=1){var n=e[t],s=r[se[t]]||"",i=n(s);if(!i)return!1}return!0}});var Hn=b((Rl,Vt)=>{"use strict";l();var Al=S("path"),$n=S("fs"),Me=jn();Vt.exports=function(r,e){var t=Me.getFileName();$n.stat(t,function(n,s){if(n||!Me.usePgPass(s,t))return e(void 0);var i=$n.createReadStream(t);Me.getPassword(r,i,e)})};Vt.exports.warnTo=Me.warnTo});var Wn=b((Ol,Vn)=>{"use strict";l();var _a=S("events").EventEmitter,zn=Z(),be=S("util"),Wt=ln(),ka=Ce(),Ca=yt(),Kn=_n(),xa=me(),Pa=zt(),Aa=dt(),Gn=be.deprecate(()=>{},"Client.activeQuery is deprecated and will be removed in pg@9.0"),Ra=be.deprecate(()=>{},"Client.queryQueue is deprecated and will be removed in pg@9.0."),Ta=be.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."),Oa=be.deprecate(()=>{},"Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0."),Ia=be.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."),qe=class extends _a{constructor(e){super(),this.connectionParameters=new Ca(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 t=e||{};t.Promise&&Oa(),this._Promise=t.Promise||global.Promise,this._types=new ka(t.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this._activeQuery=null,this.enableChannelBinding=!!t.enableChannelBinding,this.connection=t.connection||new Pa({stream:t.stream,ssl:this.connectionParameters.ssl,keepAlive:t.keepAlive||!1,keepAliveInitialDelayMillis:t.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this._queryQueue=[],this.binary=t.binary||xa.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=t.connectionTimeoutMillis||0}get activeQuery(){return Gn(),this._activeQuery}set activeQuery(e){Gn(),this._activeQuery=e}_getActiveQuery(){return this._activeQuery}_errorAllQueries(e){let t=s=>{process.nextTick(()=>{s.handleError(e,this.connection)})},n=this._getActiveQuery();n&&(t(n),this._activeQuery=null),this._queryQueue.forEach(t),this._queryQueue.length=0}_connect(e){let t=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(){t.ssl?n.requestSsl():n.startup(t.getStartupConf())}),n.on("sslconnect",function(){n.startup(t.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((t,n)=>{this._connect(s=>{s?n(s):t(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 t=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"){t.emit("error",new TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=n}else this.connectionParameters.password=this.password=null;e()}).catch(n=>{t.emit("error",n)});else if(this.password!==null)e();else try{Hn()(this.connectionParameters,s=>{s!==void 0&&(Ta(),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 t=await Aa.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(t)}catch(t){this.emit("error",t)}})}_handleAuthSASL(e){this._getPassword(()=>{try{this.saslSession=Wt.startSession(e.mechanisms,this.enableChannelBinding&&this.connection.stream),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(t){this.connection.emit("error",t)}})}async _handleAuthSASLContinue(e){try{await Wt.continueSession(this.saslSession,this.password,e.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(t){this.connection.emit("error",t)}}_handleAuthSASLFinal(e){try{Wt.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(t){this.connection.emit("error",t)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let t=this._getActiveQuery();this._activeQuery=null,this.readyForQuery=!0,t&&t.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit("error",e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit("error",e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let t=this._getActiveQuery();if(!t){this._handleErrorEvent(e);return}this._activeQuery=null,t.handleError(e,this.connection)}_handleRowDescription(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected rowDescription message from backend.");this._handleErrorEvent(n);return}t.handleRowDescription(e)}_handleDataRow(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected dataRow message from backend.");this._handleErrorEvent(n);return}t.handleDataRow(e)}_handlePortalSuspended(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected portalSuspended message from backend.");this._handleErrorEvent(n);return}t.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected emptyQuery message from backend.");this._handleErrorEvent(n);return}t.handleEmptyQuery(this.connection)}_handleCommandComplete(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected commandComplete message from backend.");this._handleErrorEvent(n);return}t.handleCommandComplete(e,this.connection)}_handleParseComplete(){let e=this._getActiveQuery();if(e==null){let t=new Error("Received unexpected parseComplete message from backend.");this._handleErrorEvent(t);return}e.name&&(this.connection.parsedStatements[e.name]=e.text)}_handleCopyInResponse(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected copyInResponse message from backend.");this._handleErrorEvent(n);return}t.handleCopyInResponse(this.connection)}_handleCopyData(e){let t=this._getActiveQuery();if(t==null){let n=new Error("Received unexpected copyData message from backend.");this._handleErrorEvent(n);return}t.handleCopyData(e,this.connection)}_handleNotification(e){this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){let e=this.connectionParameters,t={user:e.user,database:e.database},n=e.application_name||e.fallback_application_name;return n&&(t.application_name=n),e.replication&&(t.replication=""+e.replication),e.statement_timeout&&(t.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(t.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(t.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(t.options=e.options),t}cancel(e,t){if(e.activeQuery===t){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(t)!==-1&&e._queryQueue.splice(e._queryQueue.indexOf(t),1)}setTypeParser(e,t,n){return this._types.setTypeParser(e,t,n)}getTypeParser(e,t){return this._types.getTypeParser(e,t)}escapeIdentifier(e){return zn.escapeIdentifier(e)}escapeLiteral(e){return zn.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 t=e.submit(this.connection);t&&process.nextTick(()=>{e.handleError(t,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this._activeQuery=null,this.emit("drain"))}}query(e,t,n){let s,i,o,a,u;if(e==null)throw new TypeError("Client was passed a null or undefined query");return typeof e.submit=="function"?(o=e.query_timeout||this.connectionParameters.query_timeout,i=s=e,s.callback||(typeof t=="function"?s.callback=t:n&&(s.callback=n))):(o=e.query_timeout||this.connectionParameters.query_timeout,s=new Kn(e,t,n),s.callback||(i=new this._Promise((c,h)=>{s.callback=(d,m)=>d?h(d):c(m)}).catch(c=>{throw Error.captureStackTrace(c),c}))),o&&(u=s.callback||(()=>{}),a=setTimeout(()=>{let c=new Error("Query read timeout");process.nextTick(()=>{s.handleError(c,this.connection)}),u(c),s.callback=()=>{};let h=this._queryQueue.indexOf(s);h>-1&&this._queryQueue.splice(h,1),this._pulseQueryQueue()},o),s.callback=(c,h)=>{clearTimeout(a),u(c,h)}),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&&Ia(),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(t=>{this.connection.once("end",t)})}get queryQueue(){return Ra(),this._queryQueue}};qe.Query=Kn;Vn.exports=qe});var Xn=b((Ml,Yn)=>{"use strict";l();var Ma=S("events").EventEmitter,Jt=function(){},Jn=(r,e)=>{let t=r.findIndex(e);return t===-1?void 0:r.splice(t,1)[0]},Yt=class{constructor(e,t,n){this.client=e,this.idleListener=t,this.timeoutId=n}},ie=class{constructor(e){this.callback=e}};function qa(){throw new Error("Release called on client which has already been released to the pool.")}function De(r,e){if(e)return{callback:e,result:void 0};let t,n,s=function(o,a){o?t(o):n(a)},i=new r(function(o,a){n=o,t=a}).catch(o=>{throw Error.captureStackTrace(o),o});return{callback:s,result:i}}function Da(r,e){return function t(n){n.client=e,e.removeListener("error",t),e.on("error",()=>{r.log("additional client error after disconnection due to error",n)}),r._remove(e),r.emit("error",n,e)}}var Xt=class extends Ma{constructor(e,t){super(),this.options=Object.assign({},e),e!=null&&"password"in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.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||t||Zt().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 t=this.Promise;return typeof t.try=="function"?t.try(e):new t(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(t=>{this._remove(t.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let t=this._idle.pop();clearTimeout(t.timeoutId);let n=t.client;n.ref&&n.ref();let s=t.idleListener;return this._acquireClient(n,e,s,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpected condition")}_remove(e,t){let n=Jn(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 t=="function"&&t()})}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 t=De(this.Promise,e),n=t.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new ie(t.callback)),n;let s=(a,u,c)=>{clearTimeout(o),t.callback(a,u,c)},i=new ie(s),o=setTimeout(()=>{Jn(this._pendingQueue,a=>a.callback===s),i.timedOut=!0,t.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 ie(t.callback)),n}newClient(e){let t=new this.Client(this.options);this._clients.push(t);let n=Da(this,t);this.log("checking client timeout");let s,i=!1;this.options.connectionTimeoutMillis&&(s=setTimeout(()=>{t.connection?(this.log("ending client due to timeout"),i=!0,t.connection.stream.destroy()):t.isConnected()||(this.log("ending client due to timeout"),i=!0,t.end())},this.options.connectionTimeoutMillis)),this.log("connecting new client"),t.connect(o=>{if(s&&clearTimeout(s),t.on("error",n),o)this.log("client failed to connect",o),this._clients=this._clients.filter(a=>a!==t),i&&(o=new Error("Connection terminated due to connection timeout",{cause:o})),this._pulseQueue(),e.timedOut||e.callback(o,void 0,Jt);else{if(this.log("new client connected"),this.options.onConnect){this._promiseTry(()=>this.options.onConnect(t)).then(()=>{this._afterConnect(t,e,n)},a=>{this._clients=this._clients.filter(u=>u!==t),t.end(()=>{this._pulseQueue(),e.timedOut||e.callback(a,void 0,Jt)})});return}return this._afterConnect(t,e,n)}})}_afterConnect(e,t,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 ie((o,a,u)=>u()),n,!1)},this.options.maxLifetimeSeconds*1e3);s.unref(),e.once("end",()=>clearTimeout(s))}return this._acquireClient(e,t,n,!0)}_acquireClient(e,t,n,s){s&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,n),e.removeListener("error",n),t.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),t.callback(i,void 0,Jt);t.callback(void 0,e,e.release)}):t.callback(void 0,e,e.release)}_releaseOnce(e,t){let n=!1;return s=>{n&&qa(),n=!0,this._release(e,t,s)}}_release(e,t,n){if(e.on("error",t),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 Yt(e,t,i)),this._pulseQueue()}query(e,t,n){if(typeof e=="function"){let i=De(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 t=="function"&&(n=t,t=void 0);let s=De(this.Promise,n);return n=s.callback,this.connect((i,o)=>{if(i)return n(i);let a=!1,u=c=>{a||(a=!0,o.release(c),n(c))};o.once("error",u),this.log("dispatching query");try{o.query(e,t,(c,h)=>{if(this.log("query dispatched"),o.removeListener("error",u),!a)return a=!0,o.release(c),c?n(c):n(void 0,h)})}catch(c){return o.release(c),n(c)}}),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 t=De(this.Promise,e);return this._endCallback=t.callback,this._pulseQueue(),t.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,t)=>e+(this._expired.has(t)?1:0),0)}get totalCount(){return this._clients.length}};Yn.exports=Xt});var ts=b((Dl,es)=>{"use strict";l();var Zn=S("events").EventEmitter,La=S("util"),er=Z(),oe=es.exports=function(r,e,t){Zn.call(this),r=er.normalizeQueryConfig(r,e,t),this.text=r.text,this.values=r.values,this.name=r.name,this.queryMode=r.queryMode,this.callback=r.callback,this.state="new",this._arrayMode=r.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(n){n==="row"&&(this._emitRowEvents=!0)}.bind(this))};La.inherits(oe,Zn);var Qa={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};oe.prototype.handleError=function(r){let e=this.native.pq.resultErrorFields();if(e)for(let t in e){let n=Qa[t]||t;r[n]=e[t]}this.callback?this.callback(r):this.emit("error",r),this.state="error"};oe.prototype.then=function(r,e){return this._getPromise().then(r,e)};oe.prototype.catch=function(r){return this._getPromise().catch(r)};oe.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(r,e){this._once("end",r),this._once("error",e)}.bind(this)),this._promise)};oe.prototype.submit=function(r){this.state="running";let e=this;this.native=r.native,r.native.arrayMode=this._arrayMode;let t=function(n,s,i){if(r.native.arrayMode=!1,setImmediate(function(){e.emit("_done")}),n)return e.handleError(n);e._emitRowEvents&&(i.length>1?s.forEach((o,a)=>{o.forEach(u=>{e.emit("row",u,i[a])})}):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&&(t=process.domain.bind(t)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));let n=(this.values||[]).map(er.prepareValue);if(r.namedQueries[this.name]){if(this.text&&r.namedQueries[this.name]!==this.text){let s=new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return t(s)}return r.native.execute(this.name,n,t)}return r.native.prepare(this.name,this.text,n.length,function(s){return s?t(s):(r.namedQueries[e.name]=e.text,e.native.execute(e.name,n,t))})}else if(this.values){if(!Array.isArray(this.values)){let s=new Error("Query values must be an array");return t(s)}let n=this.values.map(er.prepareValue);r.native.query(this.text,n,t)}else this.queryMode==="extended"?r.native.query(this.text,[],t):r.native.query(this.text,t)}});var os=b((Ql,is)=>{"use strict";l();var Na=S("util"),rs;try{rs=S("pg-native")}catch(r){throw r}var Ba=Ce(),ns=S("events").EventEmitter,Fa=S("util"),Ua=yt(),ss=ts(),ja=Na.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."),A=is.exports=function(r){ns.call(this),r=r||{},this._Promise=r.Promise||global.Promise,this._types=new Ba(r.types),this.native=new rs({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;let e=this.connectionParameters=new Ua(r);r.nativeConnectionString&&(e.nativeConnectionString=r.nativeConnectionString),this.user=e.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),this.database=e.database,this.host=e.host,this.port=e.port,this.namedQueries={}};A.Query=ss;Fa.inherits(A,ns);A.prototype._errorAllQueries=function(r){let e=t=>{process.nextTick(()=>{t.native=this.native,t.handleError(r)})};this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(e),this._queryQueue.length=0};A.prototype._connect=function(r){let e=this;if(this._connecting){process.nextTick(()=>r(new Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(t,n){if(e.connectionParameters.nativeConnectionString&&(n=e.connectionParameters.nativeConnectionString),t)return r(t);e.native.connect(n,function(s){if(s)return e.native.end(),r(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),r(null,this)})})};A.prototype.connect=function(r){if(r){this._connect(r);return}return new this._Promise((e,t)=>{this._connect(n=>{n?t(n):e(this)})})};A.prototype.query=function(r,e,t){let n,s,i,o,a;if(r==null)throw new TypeError("Client was passed a null or undefined query");if(typeof r.submit=="function")i=r.query_timeout||this.connectionParameters.query_timeout,s=n=r,typeof e=="function"&&(r.callback=e);else if(i=r.query_timeout||this.connectionParameters.query_timeout,n=new ss(r,e,t),!n.callback){let u,c;s=new this._Promise((h,d)=>{u=h,c=d}).catch(h=>{throw Error.captureStackTrace(h),h}),n.callback=(h,d)=>h?c(h):u(d)}return i&&(a=n.callback||(()=>{}),o=setTimeout(()=>{let u=new Error("Query read timeout");process.nextTick(()=>{n.handleError(u,this.connection)}),a(u),n.callback=()=>{};let c=this._queryQueue.indexOf(n);c>-1&&this._queryQueue.splice(c,1),this._pulseQueryQueue()},i),n.callback=(u,c)=>{clearTimeout(o),a(u,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&&ja(),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)};A.prototype.end=function(r){let e=this;this._ending=!0,this._connected||this.once("connect",this.end.bind(this,r));let t;return r||(t=new this._Promise(function(n,s){r=i=>i?s(i):n()})),this.native.end(function(){e._connected=!1,e._errorAllQueries(new Error("Connection terminated")),process.nextTick(()=>{e.emit("end"),r&&r()})}),t};A.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};A.prototype._pulseQueryQueue=function(r){if(!this._connected||this._hasActiveQuery())return;let e=this._queryQueue.shift();if(!e){r||this.emit("drain");return}this._activeQuery=e,e.submit(this);let t=this;e.once("_done",function(){t._pulseQueryQueue()})};A.prototype.cancel=function(r){this._activeQuery===r?this.native.cancel(function(){}):this._queryQueue.indexOf(r)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(r),1)};A.prototype.ref=function(){};A.prototype.unref=function(){};A.prototype.setTypeParser=function(r,e,t){return this._types.setTypeParser(r,e,t)};A.prototype.getTypeParser=function(r,e){return this._types.getTypeParser(r,e)};A.prototype.isConnected=function(){return this._connected}});var tr=b((Bl,as)=>{"use strict";l();as.exports=os()});var Zt=b((jl,Le)=>{"use strict";l();var $a=Wn(),Ha=me(),za=zt(),Ga=bt(),Ka=Z(),Va=Xn(),Wa=Ce(),{DatabaseError:Ja}=jt(),{escapeIdentifier:Ya,escapeLiteral:Xa}=Z(),Za=r=>class extends Va{constructor(t){super(t,r)}},cs=function(r){this.defaults=Ha,this.Client=r,this.Query=this.Client.Query,this.Pool=Za(this.Client),this._pools=[],this.Connection=za,this.types=pe(),this.DatabaseError=Ja,this.TypeOverrides=Wa,this.escapeIdentifier=Ya,this.escapeLiteral=Xa,this.Result=Ga,this.utils=Ka},us=$a,ls=!1;try{ls=!!process.env.NODE_PG_FORCE_NATIVE}catch{}ls&&(us=tr());Le.exports=new cs(us);Object.defineProperty(Le.exports,"native",{configurable:!0,enumerable:!1,get(){let r=null;try{r=new cs(tr())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(Le.exports,"native",{value:r}),r}})});var hs={};ws(hs,{Client:()=>ec,Connection:()=>rc,DatabaseError:()=>ic,Pool:()=>tc,Query:()=>sc,Result:()=>cc,TypeOverrides:()=>uc,default:()=>hc,defaults:()=>lc,escapeIdentifier:()=>oc,escapeLiteral:()=>ac,types:()=>nc});var I,ec,tc,rc,nc,sc,ic,oc,ac,cc,uc,lc,hc,ds=ar(()=>{"use strict";l();I=vs(Zt(),1),ec=I.default.Client,tc=I.default.Pool,rc=I.default.Connection,nc=I.default.types,sc=I.default.Query,ic=I.default.DatabaseError,oc=I.default.escapeIdentifier,ac=I.default.escapeLiteral,cc=I.default.Result,uc=I.default.TypeOverrides,lc=I.default.defaults,hc=I.default});l();l();l();var j=class extends Error{constructor(t,n){super(t);this.code=n;this.name="KnowledgeError"}code},C=class extends j{constructor(t,n){super(t,"EMBEDDING_ERROR");this.statusCode=n;this.name="EmbeddingError"}statusCode},k=class extends j{constructor(t,n){super(t,"INGESTION_ERROR");this.file=n;this.name="IngestionError"}file},cr=class extends j{constructor(t,n){super(t,"CHUNK_TOO_LARGE");this.chunkSize=n;this.name="ChunkTooLargeError"}chunkSize},V=class extends j{expected;actual;constructor(e,t){super(`Dimension mismatch: expected ${e}, got ${t}`,"DIMENSION_MISMATCH"),this.name="DimensionMismatchError",this.expected=e,this.actual=t}},$=class extends j{constructor(e){super(e,"PROVIDER_ERROR"),this.name="KnowledgeProviderError"}};l();import{randomUUID as Es}from"crypto";l();function H(r,e){let t=r.toLowerCase(),n=e.toLowerCase();if(t.includes(n))return 1;let s=n.split(/\s+/).filter(o=>o.length>2);if(s.length===0)return 0;let i=0;for(let o of s)t.includes(o)&&i++;return i/s.length}function Fe(r,e,t=.7){let n=1-t;return r*t+e*n}l();function Se(r,e){if(r.length!==e.length)throw new Error("Vectors must have same dimensions");let t=0,n=0,s=0;for(let o=0;o<r.length;o++)t+=r[o]*e[o],n+=r[o]*r[o],s+=e[o]*e[o];let i=Math.sqrt(n)*Math.sqrt(s);return i===0?0:t/i}function Q(r,e){if(!e)return!0;for(let[t,n]of Object.entries(e)){let s=r[t];if(typeof n=="object"&&n!==null&&!Array.isArray(n)){if("$in"in n){if(!n.$in.includes(s))return!1}else if("$gt"in n){let i=n.$gt;if(typeof s!="number"||s<=i)return!1}else if("$lt"in n){let i=n.$lt;if(typeof s!="number"||s>=i)return!1}}else if(s!==n)return!1}return!0}var ur=class r{constructor(e,t,n,s,i){this.provider=e;this.embedder=t;this.description=n;this.sources=s;this.options=i}provider;embedder;description;sources;options;static async create(e){await e.provider.validateDimensions(e.embedder.dimensions);let t=new r(e.provider,e.embedder,e.description,e.sources,e);return e.reSync!==!0&&"shouldReSync"in e.provider?(e.provider.shouldReSync(e.reSync)&&await t.sync(),t):(e.reSync!==!1&&await t.sync(),t)}async query(e,t){let n=t?.searchType??"semantic",s=t?.semanticWeight??.7;if(n==="keyword")return this.keywordQuery(e,t);if(n==="hybrid"){let[i,o]=await Promise.all([this.semanticQuery(e,t),this.keywordQuery(e,t)]);return this.combineHybridResults(i,o,s,t)}else return this.semanticQuery(e,t)}async semanticQuery(e,t){let n=await this.embedder.embed(e);return this.provider.query(n,t)}async keywordQuery(e,t){let{limit:n=10,threshold:s=.1,filter:i,includeMetadata:o=!0,includeVectors:a=!1}=t||{};if(typeof this.provider.keywordQuery=="function")return this.provider.keywordQuery(e,t);let u=await this.getAllChunks(),c=[];for(let h of u){if(i&&!Q(h.metadata,i))continue;let d=H(h.content,e);d>=s&&c.push({chunk:{id:h.id,content:h.content,metadata:o?h.metadata:{},vector:a?h.vector:void 0},score:d,distance:1-d})}return c.sort((h,d)=>d.score-h.score),c.slice(0,n)}combineHybridResults(e,t,n,s){let{limit:i=10,threshold:o=.5,includeMetadata:a=!0,includeVectors:u=!1}=s||{},c=new Map(e.map(y=>[y.chunk.id,y])),h=new Map(t.map(y=>[y.chunk.id,y])),d=[],m=new Set([...c.keys(),...h.keys()]);for(let y of m){let w=c.get(y),T=h.get(y);if(!w&&!T)continue;let Qe=w?.score??0,Ne=T?.score??0,K=Fe(Qe,Ne,n);K>=o&&d.push({chunk:{id:y,content:w?.chunk.content??T.chunk.content,metadata:a?w?.chunk.metadata??T.chunk.metadata:{},vector:u?w?.chunk.vector??T.chunk.vector:void 0},score:K,distance:1-K})}return d.sort((y,w)=>w.score-y.score),d.slice(0,i)}async getAllChunks(){if(typeof this.provider.getAllChunks=="function")return this.provider.getAllChunks();let e=new Array(this.embedder.dimensions).fill(0);return(await this.provider.query(e,{limit:1e4,threshold:0})).map(t=>t.chunk)}async sync(){this.options.onSync?.({type:"start"});try{let e=this.embedder.dimensions;await this.provider.clear(),await this.provider.validateDimensions(e);let t=this.options.streamingBatchSize??100,n=0,s=[];for(let i of this.sources)for await(let o of i.load())if(s.push(o),s.length>=t){let a=await this.embedChunks(s);a.length>0&&(await this.provider.add(a),n+=a.length),s.length=0}if(s.length>0){let i=await this.embedChunks(s);i.length>0&&(await this.provider.add(i),n+=i.length)}this.options.onSync?.({type:"complete",chunksAffected:n})}catch(e){throw this.options.onSync?.({type:"error",error:e}),e}}async embedChunks(e){if(e.length===0)return[];let t=[];try{let n=e.map(i=>i.content),s=await this.embedder.embedBatch(n);for(let i=0;i<e.length;i++)t.push({...e[i],vector:s[i]}),this.options.onEmbeddingProgress?.({source:"sync",current:i+1,total:e.length,percent:Math.round((i+1)/e.length*100)})}catch(n){if(this.options.onError?.(n,{})==="abort")throw n;for(let i=0;i<e.length;i++)try{let o=await this.embedder.embed(e[i].content);t.push({...e[i],vector:o}),this.options.onEmbeddingProgress?.({source:"sync",current:i+1,total:e.length,percent:Math.round((i+1)/e.length*100)})}catch(o){if(this.options.onError?.(o,{chunk:e[i]})==="abort")throw o}}return t}async add(e,t){try{let n=Es(),s=await this.embedder.embed(e),i={id:n,content:e,metadata:t||{},vector:s};return await this.provider.add([i]),n}catch(n){throw new k(`Failed to add content to knowledge base: ${n.message}`,"add")}}async stop(){this.provider.close&&this.provider.close()}toTool(){return{name:"knowledge_search",displayName:"Knowledge Search",description:this.description||"Search the knowledge base for relevant information",category:"search",cacheable:!1,parameters:{type:"object",properties:{query:{type:"string",description:"Search query to find relevant information"},limit:{type:"number",description:"Maximum number of results to return (default: 10)"},threshold:{type:"number",description:"Minimum similarity threshold 0-1 (default: 0.3)"},filter:{type:"object",description:"Optional metadata filters"}},required:["query"]},execute:async e=>(await this.query(e.query,{limit:e.limit,threshold:e.threshold??.3,filter:e.filter,searchType:"hybrid"})).map(n=>({content:n.chunk.content,score:n.score,metadata:n.chunk.metadata}))}}};l();var Ue=class{constructor(e={}){this.options=e}options;chunks=new Map;dimensions;async validateDimensions(e){if(this.dimensions&&this.dimensions!==e)throw new V(this.dimensions,e);this.dimensions=e}async add(e){for(let t of e){if(!t.vector)throw new $("Chunk missing vector");if(this.options.maxChunks&&this.chunks.size>=this.options.maxChunks)throw new $(`Max chunks limit reached: ${this.options.maxChunks}`);this.chunks.set(t.id,{chunk:{id:t.id,content:t.content,metadata:t.metadata},vector:t.vector})}}async query(e,t={}){let{limit:n=10,threshold:s=.7,filter:i,includeMetadata:o=!0,includeVectors:a=!1}=t,u=[];for(let{chunk:c,vector:h}of this.chunks.values()){if(i&&!Q(c.metadata,i))continue;let d=Se(e,h);d>=s&&u.push({chunk:{id:c.id,content:c.content,metadata:o?c.metadata:{},vector:a?h:void 0},score:d,distance:1-d})}return u.sort((c,h)=>h.score-c.score),u.slice(0,n)}async keywordQuery(e,t={}){let{limit:n=10,threshold:s=.1,filter:i,includeMetadata:o=!0,includeVectors:a=!1}=t,u=[];for(let{chunk:c,vector:h}of this.chunks.values()){if(i&&!Q(c.metadata,i))continue;let d=H(c.content,e);d>=s&&u.push({chunk:{id:c.id,content:c.content,metadata:o?c.metadata:{},vector:a?h:void 0},score:d,distance:1-d})}return u.sort((c,h)=>h.score-c.score),u.slice(0,n)}async delete(e){for(let t of e)this.chunks.delete(t)}async clear(){this.chunks.clear(),this.dimensions=void 0}async getAllChunks(){return Array.from(this.chunks.values()).map(({chunk:e,vector:t})=>({...e,vector:t}))}};l();import _s from"better-sqlite3";import*as ae from"fs";import*as N from"path";import*as lr from"os";var je=class{constructor(e){this.options=e;let t=lr.homedir(),n=`${e.namespace}.db`,s;if(e.storagePath)s=e.storagePath;else{let i=N.join(t,".toolpack","db","knowledge"),o=N.join(t,".toolpack","knowledge"),a=N.join(i,n),u=N.join(o,n);ae.existsSync(u)&&!ae.existsSync(a)?s=o:s=i}this.dbPath=N.join(s,n),ae.mkdirSync(N.dirname(this.dbPath),{recursive:!0}),this.db=new _s(this.dbPath),this.db.pragma("journal_mode = WAL"),this.initSchema(),this.loadDimensions()}options;db;dimensions;dbPath;initSchema(){this.db.exec(`
|
|
10
10
|
CREATE TABLE IF NOT EXISTS chunks (
|
|
11
11
|
id TEXT PRIMARY KEY,
|
|
12
12
|
content TEXT NOT NULL,
|
|
@@ -48,7 +48,7 @@ See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode de
|
|
|
48
48
|
WHERE chunks_fts MATCH ?
|
|
49
49
|
ORDER BY bm25(chunks_fts) DESC
|
|
50
50
|
LIMIT ?
|
|
51
|
-
`).all(u,n*2),h=[];for(let d of c){let m=JSON.parse(d.metadata);if(i&&!Q(m,i))continue;let y=H(d.content,e);if(y>=s){let w=new Float32Array(d.vector.buffer,d.vector.byteOffset,d.vector.byteLength/4);h.push({chunk:{id:d.id,content:d.content,metadata:o?m:{},vector:a?Array.from(w):void 0},score:y,distance:1-y})}}return h.sort((d,m)=>m.score-d.score),h.slice(0,n)}async delete(e){let t=this.db.prepare("DELETE FROM chunks WHERE id = ?");this.db.transaction(s=>{for(let i of s)t.run(i)})(e)}async clear(){this.db.prepare("DELETE FROM chunks").run(),this.db.prepare("DELETE FROM provider_meta WHERE key = ?").run("dimensions"),this.dimensions=void 0}async getAllChunks(){return this.db.prepare("SELECT id, content, metadata, vector FROM chunks").all().map(t=>{let n=JSON.parse(t.metadata),s=new Float32Array(t.vector.buffer,t.vector.byteOffset,t.vector.byteLength/4);return{id:t.id,content:t.content,metadata:n,vector:Array.from(s)}})}shouldReSync(){return
|
|
51
|
+
`).all(u,n*2),h=[];for(let d of c){let m=JSON.parse(d.metadata);if(i&&!Q(m,i))continue;let y=H(d.content,e);if(y>=s){let w=new Float32Array(d.vector.buffer,d.vector.byteOffset,d.vector.byteLength/4);h.push({chunk:{id:d.id,content:d.content,metadata:o?m:{},vector:a?Array.from(w):void 0},score:y,distance:1-y})}}return h.sort((d,m)=>m.score-d.score),h.slice(0,n)}async delete(e){let t=this.db.prepare("DELETE FROM chunks WHERE id = ?");this.db.transaction(s=>{for(let i of s)t.run(i)})(e)}async clear(){this.db.prepare("DELETE FROM chunks").run(),this.db.prepare("DELETE FROM provider_meta WHERE key = ?").run("dimensions"),this.dimensions=void 0}async getAllChunks(){return this.db.prepare("SELECT id, content, metadata, vector FROM chunks").all().map(t=>{let n=JSON.parse(t.metadata),s=new Float32Array(t.vector.buffer,t.vector.byteOffset,t.vector.byteLength/4);return{id:t.id,content:t.content,metadata:n,vector:Array.from(s)}})}shouldReSync(e){return(this.options.reSync??e)===!1?this.db.prepare("SELECT COUNT(*) as count FROM chunks").get().count===0:!0}close(){this.db.close()}};l();import*as hr from"fs/promises";import*as ce from"path";import*as dr from"crypto";import xs from"fast-glob";l();function M(r){return Math.ceil(r.length/4)}function ks(r,e){let t=r.split(/\n\n+/),n=[],s="";for(let i of t){let o=M(i);M(s)+o>e&&s?(n.push(s.trim()),s=i):s+=(s?`
|
|
52
52
|
|
|
53
53
|
`:"")+i}return s&&n.push(s.trim()),n}function Cs(r,e){let t=r.match(/[^.!?]+[.!?]+/g)||[r],n=[],s="";for(let i of t){let o=M(i);M(s)+o>e&&s?(n.push(s.trim()),s=i):s+=(s?" ":"")+i}return s&&n.push(s.trim()),n}function W(r,e){if(r.length<=1||e===0)return r;let t=[];for(let n=0;n<r.length;n++){let s=r[n];if(n>0){let o=r[n-1].split(/\s+/),a=Math.ceil(e/4);s=o.slice(-a).join(" ")+" "+s}t.push(s)}return t}function J(r,e){if(M(r)<=e)return[r];let n=ks(r,e),s=[];for(let i of n)M(i)>e?s.push(...Cs(i,e)):s.push(i);return s}var $e=class{constructor(e,t={}){this.pattern=e;this.options={maxChunkSize:t.maxChunkSize??2e3,chunkOverlap:t.chunkOverlap??200,minChunkSize:t.minChunkSize??100,namespace:t.namespace??"markdown",metadata:t.metadata??{}}}pattern;options;async*load(){let e=this.pattern.replace(/\\/g,"/"),t=await xs(e,{absolute:!0});for(let n of t)try{let s=await hr.readFile(n,"utf-8"),i=this.chunkMarkdown(s,n);for(let o of i)yield o}catch(s){throw new k(`Failed to process file: ${s.message}`,n)}}chunkMarkdown(e,t){let n=this.extractFrontmatter(e),s=this.removeFrontmatter(e),i=this.parseHeadings(s),o=[],a=0;for(let u of i){let c=/```[\s\S]*?```/.test(u.content),h=M(u.content);if(h<this.options.minChunkSize&&o.length>0){let m=o[o.length-1];m.content+=`
|
|
54
54
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@toolpack-sdk/knowledge",
|
|
3
|
-
"version": "2.
|
|
4
|
-
"description": "RAG
|
|
3
|
+
"version": "2.3.0",
|
|
4
|
+
"description": "Knowledge/RAG package for Toolpack SDK — web crawling, REST API ingestion, hybrid semantic + keyword search, and streaming indexing across 6 source types (Markdown, Web, API, JSON, SQLite, PostgreSQL)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.cjs",
|
|
7
7
|
"module": "dist/index.js",
|