@vibecontrols/vibe-plugin-storage-postgres 2026.509.1 → 2026.509.2
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.d.ts +10 -17
- package/dist/index.js +3 -2
- package/package.json +4 -3
package/dist/index.d.ts
CHANGED
|
@@ -21,22 +21,15 @@
|
|
|
21
21
|
* The schema is created on first connection (`CREATE TABLE IF NOT EXISTS
|
|
22
22
|
* documents`). No manual migrations needed.
|
|
23
23
|
*/
|
|
24
|
+
import { type VibePlugin, type VibePluginFactory } from "@vibecontrols/plugin-sdk/contract";
|
|
24
25
|
import "./postgres.adapter.js";
|
|
25
26
|
export { createPostgresAgentDatabase } from "./postgres.adapter.js";
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
interface MinimalVibePlugin {
|
|
36
|
-
capabilities?: PluginCapabilities;
|
|
37
|
-
name: string;
|
|
38
|
-
version: string;
|
|
39
|
-
description?: string;
|
|
40
|
-
tags?: ("backend" | "frontend" | "cli" | "provider" | "adapter" | "integration")[];
|
|
41
|
-
}
|
|
42
|
-
export declare const vibePlugin: MinimalVibePlugin;
|
|
27
|
+
export declare const createPlugin: VibePluginFactory;
|
|
28
|
+
/**
|
|
29
|
+
* Static manifest export — kept for the agent's defensive plugin loader
|
|
30
|
+
* that reads `vibePlugin` directly without invoking the factory.
|
|
31
|
+
* Lifecycle hooks here are no-ops; real registration happens via the
|
|
32
|
+
* factory above.
|
|
33
|
+
*/
|
|
34
|
+
export declare const vibePlugin: VibePlugin;
|
|
35
|
+
export default createPlugin;
|
package/dist/index.js
CHANGED
|
@@ -7,7 +7,8 @@ To prepare for this change:
|
|
|
7
7
|
- If you want libpq compatibility now, use 'uselibpqcompat=true&sslmode=${sslmode}'
|
|
8
8
|
|
|
9
9
|
See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode definitions.`)}module.exports=parse;parse.parse=parse;parse.toClientConfig=toClientConfig;parse.parseIntoClientConfig=parseIntoClientConfig});var require_connection_parameters=__commonJS((exports,module)=>{var dns=__require("dns"),defaults=require_defaults(),parse=require_pg_connection_string().parse,val=function(key,config,envVar){if(config[key])return config[key];if(envVar===void 0)envVar=process.env["PG"+key.toUpperCase()];else if(envVar===!1);else envVar=process.env[envVar];return envVar||defaults[key]},readSSLConfigFromEnvironment=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 defaults.ssl},quoteParamValue=function(value){return"'"+(""+value).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},add=function(params,config,paramName){let value=config[paramName];if(value!==void 0&&value!==null)params.push(paramName+"="+quoteParamValue(value))};class ConnectionParameters{constructor(config){if(config=typeof config==="string"?parse(config):config||{},config.connectionString)config=Object.assign({},config,parse(config.connectionString));if(this.user=val("user",config),this.database=val("database",config),this.database===void 0)this.database=this.user;if(this.port=parseInt(val("port",config),10),this.host=val("host",config),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:val("password",config)}),this.binary=val("binary",config),this.options=val("options",config),this.ssl=typeof config.ssl>"u"?readSSLConfigFromEnvironment():config.ssl,typeof this.ssl==="string"){if(this.ssl==="true")this.ssl=!0}if(this.ssl==="no-verify")this.ssl={rejectUnauthorized:!1};if(this.ssl&&this.ssl.key)Object.defineProperty(this.ssl,"key",{enumerable:!1});if(this.client_encoding=val("client_encoding",config),this.replication=val("replication",config),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=val("application_name",config,"PGAPPNAME"),this.fallback_application_name=val("fallback_application_name",config,!1),this.statement_timeout=val("statement_timeout",config,!1),this.lock_timeout=val("lock_timeout",config,!1),this.idle_in_transaction_session_timeout=val("idle_in_transaction_session_timeout",config,!1),this.query_timeout=val("query_timeout",config,!1),config.connectionTimeoutMillis===void 0)this.connect_timeout=process.env.PGCONNECT_TIMEOUT||0;else this.connect_timeout=Math.floor(config.connectionTimeoutMillis/1000);if(config.keepAlive===!1)this.keepalives=0;else if(config.keepAlive===!0)this.keepalives=1;if(typeof config.keepAliveInitialDelayMillis==="number")this.keepalives_idle=Math.floor(config.keepAliveInitialDelayMillis/1000)}getLibpqConnectionString(cb){let params=[];add(params,this,"user"),add(params,this,"password"),add(params,this,"port"),add(params,this,"application_name"),add(params,this,"fallback_application_name"),add(params,this,"connect_timeout"),add(params,this,"options");let ssl=typeof this.ssl==="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(add(params,ssl,"sslmode"),add(params,ssl,"sslca"),add(params,ssl,"sslkey"),add(params,ssl,"sslcert"),add(params,ssl,"sslrootcert"),this.database)params.push("dbname="+quoteParamValue(this.database));if(this.replication)params.push("replication="+quoteParamValue(this.replication));if(this.host)params.push("host="+quoteParamValue(this.host));if(this.isDomainSocket)return cb(null,params.join(" "));if(this.client_encoding)params.push("client_encoding="+quoteParamValue(this.client_encoding));dns.lookup(this.host,function(err,address){if(err)return cb(err,null);return params.push("hostaddr="+quoteParamValue(address)),cb(null,params.join(" "))})}}module.exports=ConnectionParameters});var require_result=__commonJS((exports,module)=>{var types=require_pg_types(),matchRegexp=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/;class Result{constructor(rowMode,types2){if(this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=types2,this.RowCtor=null,this.rowAsArray=rowMode==="array",this.rowAsArray)this.parseRow=this._parseRowAsArray;this._prebuiltEmptyResultObject=null}addCommandComplete(msg){let match;if(msg.text)match=matchRegexp.exec(msg.text);else match=matchRegexp.exec(msg.command);if(match){if(this.command=match[1],match[3])this.oid=parseInt(match[2],10),this.rowCount=parseInt(match[3],10);else if(match[2])this.rowCount=parseInt(match[2],10)}}_parseRowAsArray(rowData){let row=Array(rowData.length);for(let i=0,len=rowData.length;i<len;i++){let rawValue=rowData[i];if(rawValue!==null)row[i]=this._parsers[i](rawValue);else row[i]=null}return row}parseRow(rowData){let row={...this._prebuiltEmptyResultObject};for(let i=0,len=rowData.length;i<len;i++){let rawValue=rowData[i],field=this.fields[i].name;if(rawValue!==null){let v=this.fields[i].format==="binary"?Buffer.from(rawValue):rawValue;row[field]=this._parsers[i](v)}else row[field]=null}return row}addRow(row){this.rows.push(row)}addFields(fieldDescriptions){if(this.fields=fieldDescriptions,this.fields.length)this._parsers=Array(fieldDescriptions.length);let row={};for(let i=0;i<fieldDescriptions.length;i++){let desc=fieldDescriptions[i];if(row[desc.name]=null,this._types)this._parsers[i]=this._types.getTypeParser(desc.dataTypeID,desc.format||"text");else this._parsers[i]=types.getTypeParser(desc.dataTypeID,desc.format||"text")}this._prebuiltEmptyResultObject={...row}}}module.exports=Result});var require_query=__commonJS((exports,module)=>{var{EventEmitter}=__require("events"),Result=require_result(),utils=require_utils();class Query extends EventEmitter{constructor(config,values,callback){super();if(config=utils.normalizeQueryConfig(config,values,callback),this.text=config.text,this.values=config.values,this.rows=config.rows,this.types=config.types,this.name=config.name,this.queryMode=config.queryMode,this.binary=config.binary,this.portal=config.portal||"",this.callback=config.callback,this._rowMode=config.rowMode,process.domain&&config.callback)this.callback=process.domain.bind(config.callback);this._result=new Result(this._rowMode,this.types),this._results=this._result,this._canceledDueToError=!1}requiresPreparation(){if(this.queryMode==="extended")return!0;if(this.name)return!0;if(this.rows)return!0;if(!this.text)return!1;if(!this.values)return!1;return this.values.length>0}_checkForMultirow(){if(this._result.command){if(!Array.isArray(this._results))this._results=[this._result];this._result=new Result(this._rowMode,this._result._types),this._results.push(this._result)}}handleRowDescription(msg){this._checkForMultirow(),this._result.addFields(msg.fields),this._accumulateRows=this.callback||!this.listeners("row").length}handleDataRow(msg){let row;if(this._canceledDueToError)return;try{row=this._result.parseRow(msg.fields)}catch(err){this._canceledDueToError=err;return}if(this.emit("row",row,this._result),this._accumulateRows)this._result.addRow(row)}handleCommandComplete(msg,connection){if(this._checkForMultirow(),this._result.addCommandComplete(msg),this.rows)connection.sync()}handleEmptyQuery(connection){if(this.rows)connection.sync()}handleError(err,connection){if(this._canceledDueToError)err=this._canceledDueToError,this._canceledDueToError=!1;if(this.callback)return this.callback(err);this.emit("error",err)}handleReadyForQuery(con){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,con);if(this.callback)try{this.callback(null,this._results)}catch(err){process.nextTick(()=>{throw err})}this.emit("end",this._results)}submit(connection){if(typeof this.text!=="string"&&typeof this.name!=="string")return Error("A query must have either text or a name. Supplying neither is unsupported.");let previous=connection.parsedStatements[this.name];if(this.text&&previous&&this.text!==previous)return Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);if(this.values&&!Array.isArray(this.values))return Error("Query values must be an array");if(this.requiresPreparation()){connection.stream.cork&&connection.stream.cork();try{this.prepare(connection)}finally{connection.stream.uncork&&connection.stream.uncork()}}else connection.query(this.text);return null}hasBeenParsed(connection){return this.name&&connection.parsedStatements[this.name]}handlePortalSuspended(connection){this._getRows(connection,this.rows)}_getRows(connection,rows){if(connection.execute({portal:this.portal,rows}),!rows)connection.sync();else connection.flush()}prepare(connection){if(!this.hasBeenParsed(connection))connection.parse({text:this.text,name:this.name,types:this.types});try{connection.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:utils.prepareValue})}catch(err){this.handleError(err,connection);return}connection.describe({type:"P",name:this.portal||""}),this._getRows(connection,this.rows)}handleCopyInResponse(connection){connection.sendCopyFail("No source stream defined")}handleCopyData(msg,connection){}}module.exports=Query});var require_messages=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.NoticeMessage=exports.DataRowMessage=exports.CommandCompleteMessage=exports.ReadyForQueryMessage=exports.NotificationResponseMessage=exports.BackendKeyDataMessage=exports.AuthenticationMD5Password=exports.ParameterStatusMessage=exports.ParameterDescriptionMessage=exports.RowDescriptionMessage=exports.Field=exports.CopyResponse=exports.CopyDataMessage=exports.DatabaseError=exports.copyDone=exports.emptyQuery=exports.replicationStart=exports.portalSuspended=exports.noData=exports.closeComplete=exports.bindComplete=exports.parseComplete=void 0;exports.parseComplete={name:"parseComplete",length:5};exports.bindComplete={name:"bindComplete",length:5};exports.closeComplete={name:"closeComplete",length:5};exports.noData={name:"noData",length:5};exports.portalSuspended={name:"portalSuspended",length:5};exports.replicationStart={name:"replicationStart",length:4};exports.emptyQuery={name:"emptyQuery",length:4};exports.copyDone={name:"copyDone",length:4};class DatabaseError extends Error{constructor(message,length,name){super(message);this.length=length,this.name=name}}exports.DatabaseError=DatabaseError;class CopyDataMessage{constructor(length,chunk){this.length=length,this.chunk=chunk,this.name="copyData"}}exports.CopyDataMessage=CopyDataMessage;class CopyResponse{constructor(length,name,binary,columnCount){this.length=length,this.name=name,this.binary=binary,this.columnTypes=Array(columnCount)}}exports.CopyResponse=CopyResponse;class Field{constructor(name,tableID,columnID,dataTypeID,dataTypeSize,dataTypeModifier,format){this.name=name,this.tableID=tableID,this.columnID=columnID,this.dataTypeID=dataTypeID,this.dataTypeSize=dataTypeSize,this.dataTypeModifier=dataTypeModifier,this.format=format}}exports.Field=Field;class RowDescriptionMessage{constructor(length,fieldCount){this.length=length,this.fieldCount=fieldCount,this.name="rowDescription",this.fields=Array(this.fieldCount)}}exports.RowDescriptionMessage=RowDescriptionMessage;class ParameterDescriptionMessage{constructor(length,parameterCount){this.length=length,this.parameterCount=parameterCount,this.name="parameterDescription",this.dataTypeIDs=Array(this.parameterCount)}}exports.ParameterDescriptionMessage=ParameterDescriptionMessage;class ParameterStatusMessage{constructor(length,parameterName,parameterValue){this.length=length,this.parameterName=parameterName,this.parameterValue=parameterValue,this.name="parameterStatus"}}exports.ParameterStatusMessage=ParameterStatusMessage;class AuthenticationMD5Password{constructor(length,salt){this.length=length,this.salt=salt,this.name="authenticationMD5Password"}}exports.AuthenticationMD5Password=AuthenticationMD5Password;class BackendKeyDataMessage{constructor(length,processID,secretKey){this.length=length,this.processID=processID,this.secretKey=secretKey,this.name="backendKeyData"}}exports.BackendKeyDataMessage=BackendKeyDataMessage;class NotificationResponseMessage{constructor(length,processId,channel,payload){this.length=length,this.processId=processId,this.channel=channel,this.payload=payload,this.name="notification"}}exports.NotificationResponseMessage=NotificationResponseMessage;class ReadyForQueryMessage{constructor(length,status){this.length=length,this.status=status,this.name="readyForQuery"}}exports.ReadyForQueryMessage=ReadyForQueryMessage;class CommandCompleteMessage{constructor(length,text){this.length=length,this.text=text,this.name="commandComplete"}}exports.CommandCompleteMessage=CommandCompleteMessage;class DataRowMessage{constructor(length,fields){this.length=length,this.fields=fields,this.name="dataRow",this.fieldCount=fields.length}}exports.DataRowMessage=DataRowMessage;class NoticeMessage{constructor(length,message){this.length=length,this.message=message,this.name="notice"}}exports.NoticeMessage=NoticeMessage});var require_buffer_writer=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.Writer=void 0;class Writer{constructor(size=256){this.size=size,this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(size)}ensure(size){if(this.buffer.length-this.offset<size){let oldBuffer=this.buffer,newSize=oldBuffer.length+(oldBuffer.length>>1)+size;this.buffer=Buffer.allocUnsafe(newSize),oldBuffer.copy(this.buffer)}}addInt32(num){return this.ensure(4),this.buffer[this.offset++]=num>>>24&255,this.buffer[this.offset++]=num>>>16&255,this.buffer[this.offset++]=num>>>8&255,this.buffer[this.offset++]=num>>>0&255,this}addInt16(num){return this.ensure(2),this.buffer[this.offset++]=num>>>8&255,this.buffer[this.offset++]=num>>>0&255,this}addCString(string){if(!string)this.ensure(1);else{let len=Buffer.byteLength(string);this.ensure(len+1),this.buffer.write(string,this.offset,"utf-8"),this.offset+=len}return this.buffer[this.offset++]=0,this}addString(string=""){let len=Buffer.byteLength(string);return this.ensure(len),this.buffer.write(string,this.offset),this.offset+=len,this}add(otherBuffer){return this.ensure(otherBuffer.length),otherBuffer.copy(this.buffer,this.offset),this.offset+=otherBuffer.length,this}join(code){if(code){this.buffer[this.headerPosition]=code;let length=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(length,this.headerPosition+1)}return this.buffer.slice(code?0:5,this.offset)}flush(code){let result=this.join(code);return this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(this.size),result}}exports.Writer=Writer});var require_serializer=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.serialize=void 0;var buffer_writer_1=require_buffer_writer(),writer=new buffer_writer_1.Writer,startup=(opts)=>{writer.addInt16(3).addInt16(0);for(let key of Object.keys(opts))writer.addCString(key).addCString(opts[key]);writer.addCString("client_encoding").addCString("UTF8");let bodyBuffer=writer.addCString("").flush(),length=bodyBuffer.length+4;return new buffer_writer_1.Writer().addInt32(length).add(bodyBuffer).flush()},requestSsl=()=>{let response=Buffer.allocUnsafe(8);return response.writeInt32BE(8,0),response.writeInt32BE(80877103,4),response},password=(password2)=>{return writer.addCString(password2).flush(112)},sendSASLInitialResponseMessage=function(mechanism,initialResponse){return writer.addCString(mechanism).addInt32(Buffer.byteLength(initialResponse)).addString(initialResponse),writer.flush(112)},sendSCRAMClientFinalMessage=function(additionalData){return writer.addString(additionalData).flush(112)},query=(text)=>{return writer.addCString(text).flush(81)},emptyArray=[],parse=(query2)=>{let name=query2.name||"";if(name.length>63)console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",name,name.length),console.error("This can cause conflicts and silent errors executing queries");let types=query2.types||emptyArray,len=types.length,buffer=writer.addCString(name).addCString(query2.text).addInt16(len);for(let i=0;i<len;i++)buffer.addInt32(types[i]);return writer.flush(80)},paramWriter=new buffer_writer_1.Writer,writeValues=function(values,valueMapper){for(let i=0;i<values.length;i++){let mappedVal=valueMapper?valueMapper(values[i],i):values[i];if(mappedVal==null)writer.addInt16(0),paramWriter.addInt32(-1);else if(mappedVal instanceof Buffer)writer.addInt16(1),paramWriter.addInt32(mappedVal.length),paramWriter.add(mappedVal);else writer.addInt16(0),paramWriter.addInt32(Buffer.byteLength(mappedVal)),paramWriter.addString(mappedVal)}},bind=(config={})=>{let portal=config.portal||"",statement=config.statement||"",binary=config.binary||!1,values=config.values||emptyArray,len=values.length;return writer.addCString(portal).addCString(statement),writer.addInt16(len),writeValues(values,config.valueMapper),writer.addInt16(len),writer.add(paramWriter.flush()),writer.addInt16(1),writer.addInt16(binary?1:0),writer.flush(66)},emptyExecute=Buffer.from([69,0,0,0,9,0,0,0,0,0]),execute=(config)=>{if(!config||!config.portal&&!config.rows)return emptyExecute;let portal=config.portal||"",rows=config.rows||0,portalLength=Buffer.byteLength(portal),len=4+portalLength+1+4,buff=Buffer.allocUnsafe(1+len);return buff[0]=69,buff.writeInt32BE(len,1),buff.write(portal,5,"utf-8"),buff[portalLength+5]=0,buff.writeUInt32BE(rows,buff.length-4),buff},cancel=(processID,secretKey)=>{let buffer=Buffer.allocUnsafe(16);return buffer.writeInt32BE(16,0),buffer.writeInt16BE(1234,4),buffer.writeInt16BE(5678,6),buffer.writeInt32BE(processID,8),buffer.writeInt32BE(secretKey,12),buffer},cstringMessage=(code,string)=>{let len=4+Buffer.byteLength(string)+1,buffer=Buffer.allocUnsafe(1+len);return buffer[0]=code,buffer.writeInt32BE(len,1),buffer.write(string,5,"utf-8"),buffer[len]=0,buffer},emptyDescribePortal=writer.addCString("P").flush(68),emptyDescribeStatement=writer.addCString("S").flush(68),describe=(msg)=>{return msg.name?cstringMessage(68,`${msg.type}${msg.name||""}`):msg.type==="P"?emptyDescribePortal:emptyDescribeStatement},close=(msg)=>{let text=`${msg.type}${msg.name||""}`;return cstringMessage(67,text)},copyData=(chunk)=>{return writer.add(chunk).flush(100)},copyFail=(message)=>{return cstringMessage(102,message)},codeOnlyBuffer=(code)=>Buffer.from([code,0,0,0,4]),flushBuffer=codeOnlyBuffer(72),syncBuffer=codeOnlyBuffer(83),endBuffer=codeOnlyBuffer(88),copyDoneBuffer=codeOnlyBuffer(99),serialize={startup,password,requestSsl,sendSASLInitialResponseMessage,sendSCRAMClientFinalMessage,query,parse,bind,execute,describe,close,flush:()=>flushBuffer,sync:()=>syncBuffer,end:()=>endBuffer,copyData,copyDone:()=>copyDoneBuffer,copyFail,cancel};exports.serialize=serialize});var require_buffer_reader=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.BufferReader=void 0;class BufferReader{constructor(offset=0){this.offset=offset,this.buffer=Buffer.allocUnsafe(0),this.encoding="utf-8"}setBuffer(offset,buffer){this.offset=offset,this.buffer=buffer}int16(){let result=this.buffer.readInt16BE(this.offset);return this.offset+=2,result}byte(){let result=this.buffer[this.offset];return this.offset++,result}int32(){let result=this.buffer.readInt32BE(this.offset);return this.offset+=4,result}uint32(){let result=this.buffer.readUInt32BE(this.offset);return this.offset+=4,result}string(length){let result=this.buffer.toString(this.encoding,this.offset,this.offset+length);return this.offset+=length,result}cstring(){let start=this.offset,end=start;while(this.buffer[end++]!==0);return this.offset=end,this.buffer.toString(this.encoding,start,end-1)}bytes(length){let result=this.buffer.slice(this.offset,this.offset+length);return this.offset+=length,result}}exports.BufferReader=BufferReader});var require_parser=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.Parser=void 0;var messages_1=require_messages(),buffer_reader_1=require_buffer_reader(),CODE_LENGTH=1,LEN_LENGTH=4,HEADER_LENGTH=CODE_LENGTH+LEN_LENGTH,LATEINIT_LENGTH=-1,emptyBuffer=Buffer.allocUnsafe(0);class Parser{constructor(opts){if(this.buffer=emptyBuffer,this.bufferLength=0,this.bufferOffset=0,this.reader=new buffer_reader_1.BufferReader,(opts===null||opts===void 0?void 0:opts.mode)==="binary")throw Error("Binary mode not supported yet");this.mode=(opts===null||opts===void 0?void 0:opts.mode)||"text"}parse(buffer,callback){this.mergeBuffer(buffer);let bufferFullLength=this.bufferOffset+this.bufferLength,offset=this.bufferOffset;while(offset+HEADER_LENGTH<=bufferFullLength){let code=this.buffer[offset],length=this.buffer.readUInt32BE(offset+CODE_LENGTH),fullMessageLength=CODE_LENGTH+length;if(fullMessageLength+offset<=bufferFullLength){let message=this.handlePacket(offset+HEADER_LENGTH,code,length,this.buffer);callback(message),offset+=fullMessageLength}else break}if(offset===bufferFullLength)this.buffer=emptyBuffer,this.bufferLength=0,this.bufferOffset=0;else this.bufferLength=bufferFullLength-offset,this.bufferOffset=offset}mergeBuffer(buffer){if(this.bufferLength>0){let newLength=this.bufferLength+buffer.byteLength;if(newLength+this.bufferOffset>this.buffer.byteLength){let newBuffer;if(newLength<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)newBuffer=this.buffer;else{let newBufferLength=this.buffer.byteLength*2;while(newLength>=newBufferLength)newBufferLength*=2;newBuffer=Buffer.allocUnsafe(newBufferLength)}this.buffer.copy(newBuffer,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=newBuffer,this.bufferOffset=0}buffer.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=newLength}else this.buffer=buffer,this.bufferOffset=0,this.bufferLength=buffer.byteLength}handlePacket(offset,code,length,bytes){let{reader}=this;reader.setBuffer(offset,bytes);let message;switch(code){case 50:message=messages_1.bindComplete;break;case 49:message=messages_1.parseComplete;break;case 51:message=messages_1.closeComplete;break;case 110:message=messages_1.noData;break;case 115:message=messages_1.portalSuspended;break;case 99:message=messages_1.copyDone;break;case 87:message=messages_1.replicationStart;break;case 73:message=messages_1.emptyQuery;break;case 68:message=parseDataRowMessage(reader);break;case 67:message=parseCommandCompleteMessage(reader);break;case 90:message=parseReadyForQueryMessage(reader);break;case 65:message=parseNotificationMessage(reader);break;case 82:message=parseAuthenticationResponse(reader,length);break;case 83:message=parseParameterStatusMessage(reader);break;case 75:message=parseBackendKeyData(reader);break;case 69:message=parseErrorMessage(reader,"error");break;case 78:message=parseErrorMessage(reader,"notice");break;case 84:message=parseRowDescriptionMessage(reader);break;case 116:message=parseParameterDescriptionMessage(reader);break;case 71:message=parseCopyInMessage(reader);break;case 72:message=parseCopyOutMessage(reader);break;case 100:message=parseCopyData(reader,length);break;default:return new messages_1.DatabaseError("received invalid response: "+code.toString(16),length,"error")}return reader.setBuffer(0,emptyBuffer),message.length=length,message}}exports.Parser=Parser;var parseReadyForQueryMessage=(reader)=>{let status=reader.string(1);return new messages_1.ReadyForQueryMessage(LATEINIT_LENGTH,status)},parseCommandCompleteMessage=(reader)=>{let text=reader.cstring();return new messages_1.CommandCompleteMessage(LATEINIT_LENGTH,text)},parseCopyData=(reader,length)=>{let chunk=reader.bytes(length-4);return new messages_1.CopyDataMessage(LATEINIT_LENGTH,chunk)},parseCopyInMessage=(reader)=>parseCopyMessage(reader,"copyInResponse"),parseCopyOutMessage=(reader)=>parseCopyMessage(reader,"copyOutResponse"),parseCopyMessage=(reader,messageName)=>{let isBinary=reader.byte()!==0,columnCount=reader.int16(),message=new messages_1.CopyResponse(LATEINIT_LENGTH,messageName,isBinary,columnCount);for(let i=0;i<columnCount;i++)message.columnTypes[i]=reader.int16();return message},parseNotificationMessage=(reader)=>{let processId=reader.int32(),channel=reader.cstring(),payload=reader.cstring();return new messages_1.NotificationResponseMessage(LATEINIT_LENGTH,processId,channel,payload)},parseRowDescriptionMessage=(reader)=>{let fieldCount=reader.int16(),message=new messages_1.RowDescriptionMessage(LATEINIT_LENGTH,fieldCount);for(let i=0;i<fieldCount;i++)message.fields[i]=parseField(reader);return message},parseField=(reader)=>{let name=reader.cstring(),tableID=reader.uint32(),columnID=reader.int16(),dataTypeID=reader.uint32(),dataTypeSize=reader.int16(),dataTypeModifier=reader.int32(),mode=reader.int16()===0?"text":"binary";return new messages_1.Field(name,tableID,columnID,dataTypeID,dataTypeSize,dataTypeModifier,mode)},parseParameterDescriptionMessage=(reader)=>{let parameterCount=reader.int16(),message=new messages_1.ParameterDescriptionMessage(LATEINIT_LENGTH,parameterCount);for(let i=0;i<parameterCount;i++)message.dataTypeIDs[i]=reader.int32();return message},parseDataRowMessage=(reader)=>{let fieldCount=reader.int16(),fields=Array(fieldCount);for(let i=0;i<fieldCount;i++){let len=reader.int32();fields[i]=len===-1?null:reader.string(len)}return new messages_1.DataRowMessage(LATEINIT_LENGTH,fields)},parseParameterStatusMessage=(reader)=>{let name=reader.cstring(),value=reader.cstring();return new messages_1.ParameterStatusMessage(LATEINIT_LENGTH,name,value)},parseBackendKeyData=(reader)=>{let processID=reader.int32(),secretKey=reader.int32();return new messages_1.BackendKeyDataMessage(LATEINIT_LENGTH,processID,secretKey)},parseAuthenticationResponse=(reader,length)=>{let code=reader.int32(),message={name:"authenticationOk",length};switch(code){case 0:break;case 3:if(message.length===8)message.name="authenticationCleartextPassword";break;case 5:if(message.length===12){message.name="authenticationMD5Password";let salt=reader.bytes(4);return new messages_1.AuthenticationMD5Password(LATEINIT_LENGTH,salt)}break;case 10:{message.name="authenticationSASL",message.mechanisms=[];let mechanism;do if(mechanism=reader.cstring(),mechanism)message.mechanisms.push(mechanism);while(mechanism)}break;case 11:message.name="authenticationSASLContinue",message.data=reader.string(length-8);break;case 12:message.name="authenticationSASLFinal",message.data=reader.string(length-8);break;default:throw Error("Unknown authenticationOk message type "+code)}return message},parseErrorMessage=(reader,name)=>{let fields={},fieldType=reader.string(1);while(fieldType!=="\x00")fields[fieldType]=reader.cstring(),fieldType=reader.string(1);let messageValue=fields.M,message=name==="notice"?new messages_1.NoticeMessage(LATEINIT_LENGTH,messageValue):new messages_1.DatabaseError(messageValue,LATEINIT_LENGTH,name);return message.severity=fields.S,message.code=fields.C,message.detail=fields.D,message.hint=fields.H,message.position=fields.P,message.internalPosition=fields.p,message.internalQuery=fields.q,message.where=fields.W,message.schema=fields.s,message.table=fields.t,message.column=fields.c,message.dataType=fields.d,message.constraint=fields.n,message.file=fields.F,message.line=fields.L,message.routine=fields.R,message}});var require_dist=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.DatabaseError=exports.serialize=exports.parse=void 0;var messages_1=require_messages();Object.defineProperty(exports,"DatabaseError",{enumerable:!0,get:function(){return messages_1.DatabaseError}});var serializer_1=require_serializer();Object.defineProperty(exports,"serialize",{enumerable:!0,get:function(){return serializer_1.serialize}});var parser_1=require_parser();function parse(stream,callback){let parser=new parser_1.Parser;return stream.on("data",(buffer)=>parser.parse(buffer,callback)),new Promise((resolve)=>stream.on("end",()=>resolve()))}exports.parse=parse});var require_empty=__commonJS((exports)=>{Object.defineProperty(exports,"__esModule",{value:!0});exports.default={}});var require_stream=__commonJS((exports,module)=>{var{getStream,getSecureStream}=getStreamFuncs();module.exports={getStream,getSecureStream};function getNodejsStreamFuncs(){function getStream2(ssl){return new(__require("net")).Socket}function getSecureStream2(options){return __require("tls").connect(options)}return{getStream:getStream2,getSecureStream:getSecureStream2}}function getCloudflareStreamFuncs(){function getStream2(ssl){let{CloudflareSocket}=require_empty();return new CloudflareSocket(ssl)}function getSecureStream2(options){return options.socket.startTls(options),options.socket}return{getStream:getStream2,getSecureStream:getSecureStream2}}function isCloudflareRuntime(){if(typeof navigator==="object"&&navigator!==null&&typeof navigator.userAgent==="string")return navigator.userAgent==="Cloudflare-Workers";if(typeof Response==="function"){let resp=new Response(null,{cf:{thing:!0}});if(typeof resp.cf==="object"&&resp.cf!==null&&resp.cf.thing)return!0}return!1}function getStreamFuncs(){if(isCloudflareRuntime())return getCloudflareStreamFuncs();return getNodejsStreamFuncs()}});var require_connection=__commonJS((exports,module)=>{var EventEmitter=__require("events").EventEmitter,{parse,serialize}=require_dist(),{getStream,getSecureStream}=require_stream(),flushBuffer=serialize.flush(),syncBuffer=serialize.sync(),endBuffer=serialize.end();class Connection extends EventEmitter{constructor(config){super();if(config=config||{},this.stream=config.stream||getStream(config.ssl),typeof this.stream==="function")this.stream=this.stream(config);this._keepAlive=config.keepAlive,this._keepAliveInitialDelayMillis=config.keepAliveInitialDelayMillis,this.parsedStatements={},this.ssl=config.ssl||!1,this._ending=!1,this._emitMessage=!1;let self=this;this.on("newListener",function(eventName){if(eventName==="message")self._emitMessage=!0})}connect(port,host){let self=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(port,host),this.stream.once("connect",function(){if(self._keepAlive)self.stream.setKeepAlive(!0,self._keepAliveInitialDelayMillis);self.emit("connect")});let reportStreamError=function(error){if(self._ending&&(error.code==="ECONNRESET"||error.code==="EPIPE"))return;self.emit("error",error)};if(this.stream.on("error",reportStreamError),this.stream.on("close",function(){self.emit("end")}),!this.ssl)return this.attachListeners(this.stream);this.stream.once("data",function(buffer){switch(buffer.toString("utf8")){case"S":break;case"N":return self.stream.end(),self.emit("error",Error("The server does not support SSL connections"));default:return self.stream.end(),self.emit("error",Error("There was an error establishing an SSL connection"))}let options={socket:self.stream};if(self.ssl!==!0){if(Object.assign(options,self.ssl),"key"in self.ssl)options.key=self.ssl.key}let net=__require("net");if(net.isIP&&net.isIP(host)===0)options.servername=host;try{self.stream=getSecureStream(options)}catch(err){return self.emit("error",err)}self.attachListeners(self.stream),self.stream.on("error",reportStreamError),self.emit("sslconnect")})}attachListeners(stream){parse(stream,(msg)=>{let eventName=msg.name==="error"?"errorMessage":msg.name;if(this._emitMessage)this.emit("message",msg);this.emit(eventName,msg)})}requestSsl(){this.stream.write(serialize.requestSsl())}startup(config){this.stream.write(serialize.startup(config))}cancel(processID,secretKey){this._send(serialize.cancel(processID,secretKey))}password(password){this._send(serialize.password(password))}sendSASLInitialResponseMessage(mechanism,initialResponse){this._send(serialize.sendSASLInitialResponseMessage(mechanism,initialResponse))}sendSCRAMClientFinalMessage(additionalData){this._send(serialize.sendSCRAMClientFinalMessage(additionalData))}_send(buffer){if(!this.stream.writable)return!1;return this.stream.write(buffer)}query(text){this._send(serialize.query(text))}parse(query){this._send(serialize.parse(query))}bind(config){this._send(serialize.bind(config))}execute(config){this._send(serialize.execute(config))}flush(){if(this.stream.writable)this.stream.write(flushBuffer)}sync(){this._ending=!0,this._send(syncBuffer)}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(endBuffer,()=>{this.stream.end()})}close(msg){this._send(serialize.close(msg))}describe(msg){this._send(serialize.describe(msg))}sendCopyFromChunk(chunk){this._send(serialize.copyData(chunk))}endCopyFrom(){this._send(serialize.copyDone())}sendCopyFail(msg){this._send(serialize.copyFail(msg))}}module.exports=Connection});var require_split2=__commonJS((exports,module)=>{var{Transform}=__require("stream"),{StringDecoder}=__require("string_decoder"),kLast=Symbol("last"),kDecoder=Symbol("decoder");function transform(chunk,enc,cb){let list;if(this.overflow){if(list=this[kDecoder].write(chunk).split(this.matcher),list.length===1)return cb();list.shift(),this.overflow=!1}else this[kLast]+=this[kDecoder].write(chunk),list=this[kLast].split(this.matcher);this[kLast]=list.pop();for(let i=0;i<list.length;i++)try{push(this,this.mapper(list[i]))}catch(error){return cb(error)}if(this.overflow=this[kLast].length>this.maxLength,this.overflow&&!this.skipOverflow){cb(Error("maximum buffer reached"));return}cb()}function flush(cb){if(this[kLast]+=this[kDecoder].end(),this[kLast])try{push(this,this.mapper(this[kLast]))}catch(error){return cb(error)}cb()}function push(self,val){if(val!==void 0)self.push(val)}function noop(incoming){return incoming}function split(matcher,mapper,options){switch(matcher=matcher||/\r?\n/,mapper=mapper||noop,options=options||{},arguments.length){case 1:if(typeof matcher==="function")mapper=matcher,matcher=/\r?\n/;else if(typeof matcher==="object"&&!(matcher instanceof RegExp)&&!matcher[Symbol.split])options=matcher,matcher=/\r?\n/;break;case 2:if(typeof matcher==="function")options=mapper,mapper=matcher,matcher=/\r?\n/;else if(typeof mapper==="object")options=mapper,mapper=noop}options=Object.assign({},options),options.autoDestroy=!0,options.transform=transform,options.flush=flush,options.readableObjectMode=!0;let stream=new Transform(options);return stream[kLast]="",stream[kDecoder]=new StringDecoder("utf8"),stream.matcher=matcher,stream.mapper=mapper,stream.maxLength=options.maxLength,stream.skipOverflow=options.skipOverflow||!1,stream.overflow=!1,stream._destroy=function(err,cb){this._writableState.errorEmitted=!1,cb(err)},stream}module.exports=split});var require_helper=__commonJS((exports,module)=>{var path=__require("path"),Stream=__require("stream").Stream,split=require_split2(),util=__require("util"),defaultPort=5432,isWin=process.platform==="win32",warnStream=process.stderr,S_IRWXG=56,S_IRWXO=7,S_IFMT=61440,S_IFREG=32768;function isRegFile(mode){return(mode&S_IFMT)==S_IFREG}var fieldNames=["host","port","database","user","password"],nrOfFields=fieldNames.length,passKey=fieldNames[nrOfFields-1];function warn(){var isWritable=warnStream instanceof Stream&&warnStream.writable===!0;if(isWritable){var args=Array.prototype.slice.call(arguments).concat(`
|
|
10
|
-
`);warnStream.write(util.format.apply(util,args))}}Object.defineProperty(exports,"isWin",{get:function(){return isWin},set:function(val){isWin=val}});exports.warnTo=function(stream){var old=warnStream;return warnStream=stream,old};exports.getFileName=function(rawEnv){var env=rawEnv||process.env,file=env.PGPASSFILE||(isWin?path.join(env.APPDATA||"./","postgresql","pgpass.conf"):path.join(env.HOME||"./",".pgpass"));return file};exports.usePgPass=function(stats,fname){if(Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD"))return!1;if(isWin)return!0;if(fname=fname||"<unkn>",!isRegFile(stats.mode))return warn('WARNING: password file "%s" is not a plain file',fname),!1;if(stats.mode&(S_IRWXG|S_IRWXO))return warn('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',fname),!1;return!0};var matcher=exports.match=function(connInfo,entry){return fieldNames.slice(0,-1).reduce(function(prev,field,idx){if(idx==1){if(Number(connInfo[field]||defaultPort)===Number(entry[field]))return prev&&!0}return prev&&(entry[field]==="*"||entry[field]===connInfo[field])},!0)};exports.getPassword=function(connInfo,stream,cb){var pass,lineStream=stream.pipe(split());function onLine(line){var entry=parseLine(line);if(entry&&isValidEntry(entry)&&matcher(connInfo,entry))pass=entry[passKey],lineStream.end()}var onEnd=function(){stream.destroy(),cb(pass)},onErr=function(err){stream.destroy(),warn("WARNING: error on reading file: %s",err),cb(void 0)};stream.on("error",onErr),lineStream.on("data",onLine).on("end",onEnd).on("error",onErr)};var parseLine=exports.parseLine=function(line){if(line.length<11||line.match(/^\s+#/))return null;var curChar="",prevChar="",fieldIdx=0,startIdx=0,endIdx=0,obj={},isLastField=!1,addToObj=function(idx,i0,i1){var field=line.substring(i0,i1);if(!Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE"))field=field.replace(/\\([:\\])/g,"$1");obj[fieldNames[idx]]=field};for(var i=0;i<line.length-1;i+=1){if(curChar=line.charAt(i+1),prevChar=line.charAt(i),isLastField=fieldIdx==nrOfFields-1,isLastField){addToObj(fieldIdx,startIdx);break}if(i>=0&&curChar==":"&&prevChar!=="\\")addToObj(fieldIdx,startIdx,i+1),startIdx=i+2,fieldIdx+=1}return obj=Object.keys(obj).length===nrOfFields?obj:null,obj},isValidEntry=exports.isValidEntry=function(entry){var rules={0:function(x){return x.length>0},1:function(x){if(x==="*")return!0;return x=Number(x),isFinite(x)&&x>0&&x<9007199254740992&&Math.floor(x)===x},2:function(x){return x.length>0},3:function(x){return x.length>0},4:function(x){return x.length>0}};for(var idx=0;idx<fieldNames.length;idx+=1){var rule=rules[idx],value=entry[fieldNames[idx]]||"",res=rule(value);if(!res)return!1}return!0}});var require_lib=__commonJS((exports,module)=>{var path=__require("path"),fs=__require("fs"),helper=require_helper();module.exports=function(connInfo,cb){var file=helper.getFileName();fs.stat(file,function(err,stat){if(err||!helper.usePgPass(stat,file))return cb(void 0);var st=fs.createReadStream(file);helper.getPassword(connInfo,st,cb)})};module.exports.warnTo=helper.warnTo});var require_client=__commonJS((exports,module)=>{var EventEmitter=__require("events").EventEmitter,utils=require_utils(),nodeUtils=__require("util"),sasl=require_sasl(),TypeOverrides=require_type_overrides(),ConnectionParameters=require_connection_parameters(),Query=require_query(),defaults=require_defaults(),Connection=require_connection(),crypto=require_utils2(),activeQueryDeprecationNotice=nodeUtils.deprecate(()=>{},"Client.activeQuery is deprecated and will be removed in pg@9.0"),queryQueueDeprecationNotice=nodeUtils.deprecate(()=>{},"Client.queryQueue is deprecated and will be removed in pg@9.0."),pgPassDeprecationNotice=nodeUtils.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."),byoPromiseDeprecationNotice=nodeUtils.deprecate(()=>{},"Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0."),queryQueueLengthDeprecationNotice=nodeUtils.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.");class Client extends EventEmitter{constructor(config){super();this.connectionParameters=new ConnectionParameters(config),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 c=config||{};if(c.Promise)byoPromiseDeprecationNotice();if(this._Promise=c.Promise||global.Promise,this._types=new TypeOverrides(c.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this._activeQuery=null,this.enableChannelBinding=Boolean(c.enableChannelBinding),this.connection=c.connection||new Connection({stream:c.stream,ssl:this.connectionParameters.ssl,keepAlive:c.keepAlive||!1,keepAliveInitialDelayMillis:c.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this._queryQueue=[],this.binary=c.binary||defaults.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=c.connectionTimeoutMillis||0}get activeQuery(){return activeQueryDeprecationNotice(),this._activeQuery}set activeQuery(val){activeQueryDeprecationNotice(),this._activeQuery=val}_getActiveQuery(){return this._activeQuery}_errorAllQueries(err){let enqueueError=(query)=>{process.nextTick(()=>{query.handleError(err,this.connection)})},activeQuery=this._getActiveQuery();if(activeQuery)enqueueError(activeQuery),this._activeQuery=null;this._queryQueue.forEach(enqueueError),this._queryQueue.length=0}_connect(callback){let self=this,con=this.connection;if(this._connectionCallback=callback,this._connecting||this._connected){let err=Error("Client has already been connected. You cannot reuse a client.");process.nextTick(()=>{callback(err)});return}if(this._connecting=!0,this._connectionTimeoutMillis>0){if(this.connectionTimeoutHandle=setTimeout(()=>{con._ending=!0,con.stream.destroy(Error("timeout expired"))},this._connectionTimeoutMillis),this.connectionTimeoutHandle.unref)this.connectionTimeoutHandle.unref()}if(this.host&&this.host.indexOf("/")===0)con.connect(this.host+"/.s.PGSQL."+this.port);else con.connect(this.port,this.host);con.on("connect",function(){if(self.ssl)con.requestSsl();else con.startup(self.getStartupConf())}),con.on("sslconnect",function(){con.startup(self.getStartupConf())}),this._attachListeners(con),con.once("end",()=>{let error=this._ending?Error("Connection terminated"):Error("Connection terminated unexpectedly");if(clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(error),this._ended=!0,!this._ending){if(this._connecting&&!this._connectionError)if(this._connectionCallback)this._connectionCallback(error);else this._handleErrorEvent(error);else if(!this._connectionError)this._handleErrorEvent(error)}process.nextTick(()=>{this.emit("end")})})}connect(callback){if(callback){this._connect(callback);return}return new this._Promise((resolve,reject)=>{this._connect((error)=>{if(error)reject(error);else resolve(this)})})}_attachListeners(con){con.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),con.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),con.on("authenticationSASL",this._handleAuthSASL.bind(this)),con.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),con.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),con.on("backendKeyData",this._handleBackendKeyData.bind(this)),con.on("error",this._handleErrorEvent.bind(this)),con.on("errorMessage",this._handleErrorMessage.bind(this)),con.on("readyForQuery",this._handleReadyForQuery.bind(this)),con.on("notice",this._handleNotice.bind(this)),con.on("rowDescription",this._handleRowDescription.bind(this)),con.on("dataRow",this._handleDataRow.bind(this)),con.on("portalSuspended",this._handlePortalSuspended.bind(this)),con.on("emptyQuery",this._handleEmptyQuery.bind(this)),con.on("commandComplete",this._handleCommandComplete.bind(this)),con.on("parseComplete",this._handleParseComplete.bind(this)),con.on("copyInResponse",this._handleCopyInResponse.bind(this)),con.on("copyData",this._handleCopyData.bind(this)),con.on("notification",this._handleNotification.bind(this))}_getPassword(cb){let con=this.connection;if(typeof this.password==="function")this._Promise.resolve().then(()=>this.password(this.connectionParameters)).then((pass)=>{if(pass!==void 0){if(typeof pass!=="string"){con.emit("error",TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=pass}else this.connectionParameters.password=this.password=null;cb()}).catch((err)=>{con.emit("error",err)});else if(this.password!==null)cb();else try{require_lib()(this.connectionParameters,(pass)=>{if(pass!==void 0)pgPassDeprecationNotice(),this.connectionParameters.password=this.password=pass;cb()})}catch(e){this.emit("error",e)}}_handleAuthCleartextPassword(msg){this._getPassword(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(msg){this._getPassword(async()=>{try{let hashedPassword=await crypto.postgresMd5PasswordHash(this.user,this.password,msg.salt);this.connection.password(hashedPassword)}catch(e){this.emit("error",e)}})}_handleAuthSASL(msg){this._getPassword(()=>{try{this.saslSession=sasl.startSession(msg.mechanisms,this.enableChannelBinding&&this.connection.stream),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(err){this.connection.emit("error",err)}})}async _handleAuthSASLContinue(msg){try{await sasl.continueSession(this.saslSession,this.password,msg.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(err){this.connection.emit("error",err)}}_handleAuthSASLFinal(msg){try{sasl.finalizeSession(this.saslSession,msg.data),this.saslSession=null}catch(err){this.connection.emit("error",err)}}_handleBackendKeyData(msg){this.processID=msg.processID,this.secretKey=msg.secretKey}_handleReadyForQuery(msg){if(this._connecting){if(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)this._connectionCallback(null,this),this._connectionCallback=null;this.emit("connect")}let activeQuery=this._getActiveQuery();if(this._activeQuery=null,this.readyForQuery=!0,activeQuery)activeQuery.handleReadyForQuery(this.connection);this._pulseQueryQueue()}_handleErrorWhileConnecting(err){if(this._connectionError)return;if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(err);this.emit("error",err)}_handleErrorEvent(err){if(this._connecting)return this._handleErrorWhileConnecting(err);this._queryable=!1,this._errorAllQueries(err),this.emit("error",err)}_handleErrorMessage(msg){if(this._connecting)return this._handleErrorWhileConnecting(msg);let activeQuery=this._getActiveQuery();if(!activeQuery){this._handleErrorEvent(msg);return}this._activeQuery=null,activeQuery.handleError(msg,this.connection)}_handleRowDescription(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error=Error("Received unexpected rowDescription message from backend.");this._handleErrorEvent(error);return}activeQuery.handleRowDescription(msg)}_handleDataRow(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error=Error("Received unexpected dataRow message from backend.");this._handleErrorEvent(error);return}activeQuery.handleDataRow(msg)}_handlePortalSuspended(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error=Error("Received unexpected portalSuspended message from backend.");this._handleErrorEvent(error);return}activeQuery.handlePortalSuspended(this.connection)}_handleEmptyQuery(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error=Error("Received unexpected emptyQuery message from backend.");this._handleErrorEvent(error);return}activeQuery.handleEmptyQuery(this.connection)}_handleCommandComplete(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error=Error("Received unexpected commandComplete message from backend.");this._handleErrorEvent(error);return}activeQuery.handleCommandComplete(msg,this.connection)}_handleParseComplete(){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error=Error("Received unexpected parseComplete message from backend.");this._handleErrorEvent(error);return}if(activeQuery.name)this.connection.parsedStatements[activeQuery.name]=activeQuery.text}_handleCopyInResponse(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error=Error("Received unexpected copyInResponse message from backend.");this._handleErrorEvent(error);return}activeQuery.handleCopyInResponse(this.connection)}_handleCopyData(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error=Error("Received unexpected copyData message from backend.");this._handleErrorEvent(error);return}activeQuery.handleCopyData(msg,this.connection)}_handleNotification(msg){this.emit("notification",msg)}_handleNotice(msg){this.emit("notice",msg)}getStartupConf(){let params=this.connectionParameters,data={user:params.user,database:params.database},appName=params.application_name||params.fallback_application_name;if(appName)data.application_name=appName;if(params.replication)data.replication=""+params.replication;if(params.statement_timeout)data.statement_timeout=String(parseInt(params.statement_timeout,10));if(params.lock_timeout)data.lock_timeout=String(parseInt(params.lock_timeout,10));if(params.idle_in_transaction_session_timeout)data.idle_in_transaction_session_timeout=String(parseInt(params.idle_in_transaction_session_timeout,10));if(params.options)data.options=params.options;return data}cancel(client,query){if(client.activeQuery===query){let con=this.connection;if(this.host&&this.host.indexOf("/")===0)con.connect(this.host+"/.s.PGSQL."+this.port);else con.connect(this.port,this.host);con.on("connect",function(){con.cancel(client.processID,client.secretKey)})}else if(client._queryQueue.indexOf(query)!==-1)client._queryQueue.splice(client._queryQueue.indexOf(query),1)}setTypeParser(oid,format,parseFn){return this._types.setTypeParser(oid,format,parseFn)}getTypeParser(oid,format){return this._types.getTypeParser(oid,format)}escapeIdentifier(str){return utils.escapeIdentifier(str)}escapeLiteral(str){return utils.escapeLiteral(str)}_pulseQueryQueue(){if(this.readyForQuery===!0){this._activeQuery=this._queryQueue.shift();let activeQuery=this._getActiveQuery();if(activeQuery){this.readyForQuery=!1,this.hasExecuted=!0;let queryError=activeQuery.submit(this.connection);if(queryError)process.nextTick(()=>{activeQuery.handleError(queryError,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else if(this.hasExecuted)this._activeQuery=null,this.emit("drain")}}query(config,values,callback){let query,result,readTimeout,readTimeoutTimer,queryCallback;if(config===null||config===void 0)throw TypeError("Client was passed a null or undefined query");else if(typeof config.submit==="function"){if(readTimeout=config.query_timeout||this.connectionParameters.query_timeout,result=query=config,!query.callback){if(typeof values==="function")query.callback=values;else if(callback)query.callback=callback}}else if(readTimeout=config.query_timeout||this.connectionParameters.query_timeout,query=new Query(config,values,callback),!query.callback)result=new this._Promise((resolve,reject)=>{query.callback=(err,res)=>err?reject(err):resolve(res)}).catch((err)=>{throw Error.captureStackTrace(err),err});if(readTimeout)queryCallback=query.callback||(()=>{}),readTimeoutTimer=setTimeout(()=>{let error=Error("Query read timeout");process.nextTick(()=>{query.handleError(error,this.connection)}),queryCallback(error),query.callback=()=>{};let index=this._queryQueue.indexOf(query);if(index>-1)this._queryQueue.splice(index,1);this._pulseQueryQueue()},readTimeout),query.callback=(err,res)=>{clearTimeout(readTimeoutTimer),queryCallback(err,res)};if(this.binary&&!query.binary)query.binary=!0;if(query._result&&!query._result._types)query._result._types=this._types;if(!this._queryable)return process.nextTick(()=>{query.handleError(Error("Client has encountered a connection error and is not queryable"),this.connection)}),result;if(this._ending)return process.nextTick(()=>{query.handleError(Error("Client was closed and is not queryable"),this.connection)}),result;if(this._queryQueue.length>0)queryQueueLengthDeprecationNotice();return this._queryQueue.push(query),this._pulseQueryQueue(),result}ref(){this.connection.ref()}unref(){this.connection.unref()}end(cb){if(this._ending=!0,!this.connection._connecting||this._ended)if(cb)cb();else return this._Promise.resolve();if(this._getActiveQuery()||!this._queryable)this.connection.stream.destroy();else this.connection.end();if(cb)this.connection.once("end",cb);else return new this._Promise((resolve)=>{this.connection.once("end",resolve)})}get queryQueue(){return queryQueueDeprecationNotice(),this._queryQueue}}Client.Query=Query;module.exports=Client});var require_pg_pool=__commonJS((exports,module)=>{var EventEmitter=__require("events").EventEmitter,NOOP=function(){},removeWhere=(list,predicate)=>{let i=list.findIndex(predicate);return i===-1?void 0:list.splice(i,1)[0]};class IdleItem{constructor(client,idleListener,timeoutId){this.client=client,this.idleListener=idleListener,this.timeoutId=timeoutId}}class PendingItem{constructor(callback){this.callback=callback}}function throwOnDoubleRelease(){throw Error("Release called on client which has already been released to the pool.")}function promisify(Promise2,callback){if(callback)return{callback,result:void 0};let rej,res,cb=function(err,client){err?rej(err):res(client)},result=new Promise2(function(resolve,reject){res=resolve,rej=reject}).catch((err)=>{throw Error.captureStackTrace(err),err});return{callback:cb,result}}function makeIdleListener(pool,client){return function idleListener(err){err.client=client,client.removeListener("error",idleListener),client.on("error",()=>{pool.log("additional client error after disconnection due to error",err)}),pool._remove(client),pool.emit("error",err,client)}}class Pool extends EventEmitter{constructor(options,Client){super();if(this.options=Object.assign({},options),options!=null&&"password"in options)Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:options.password});if(options!=null&&options.ssl&&options.ssl.key)Object.defineProperty(this.options.ssl,"key",{enumerable:!1});if(this.options.max=this.options.max||this.options.poolSize||10,this.options.min=this.options.min||0,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||Client||require_lib2().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(f){let Promise2=this.Promise;if(typeof Promise2.try==="function")return Promise2.try(f);return new Promise2((resolve)=>resolve(f()))}_isFull(){return this._clients.length>=this.options.max}_isAboveMin(){return this._clients.length>this.options.min}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){if(this.log("pulse queue on ending"),this._idle.length)this._idle.slice().map((item)=>{this._remove(item.client)});if(!this._clients.length)this.ended=!0,this._endCallback();return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let pendingItem=this._pendingQueue.shift();if(this._idle.length){let idleItem=this._idle.pop();clearTimeout(idleItem.timeoutId);let client=idleItem.client;client.ref&&client.ref();let idleListener=idleItem.idleListener;return this._acquireClient(client,pendingItem,idleListener,!1)}if(!this._isFull())return this.newClient(pendingItem);throw Error("unexpected condition")}_remove(client,callback){let removed=removeWhere(this._idle,(item)=>item.client===client);if(removed!==void 0)clearTimeout(removed.timeoutId);this._clients=this._clients.filter((c)=>c!==client);let context=this;client.end(()=>{if(context.emit("remove",client),typeof callback==="function")callback()})}connect(cb){if(this.ending){let err=Error("Cannot use a pool after calling end on the pool");return cb?cb(err):this.Promise.reject(err)}let response=promisify(this.Promise,cb),result=response.result;if(this._isFull()||this._idle.length){if(this._idle.length)process.nextTick(()=>this._pulseQueue());if(!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new PendingItem(response.callback)),result;let queueCallback=(err,res,done)=>{clearTimeout(tid),response.callback(err,res,done)},pendingItem=new PendingItem(queueCallback),tid=setTimeout(()=>{removeWhere(this._pendingQueue,(i)=>i.callback===queueCallback),pendingItem.timedOut=!0,response.callback(Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);if(tid.unref)tid.unref();return this._pendingQueue.push(pendingItem),result}return this.newClient(new PendingItem(response.callback)),result}newClient(pendingItem){let client=new this.Client(this.options);this._clients.push(client);let idleListener=makeIdleListener(this,client);this.log("checking client timeout");let tid,timeoutHit=!1;if(this.options.connectionTimeoutMillis)tid=setTimeout(()=>{if(client.connection)this.log("ending client due to timeout"),timeoutHit=!0,client.connection.stream.destroy();else if(!client.isConnected())this.log("ending client due to timeout"),timeoutHit=!0,client.end()},this.options.connectionTimeoutMillis);this.log("connecting new client"),client.connect((err)=>{if(tid)clearTimeout(tid);if(client.on("error",idleListener),err){if(this.log("client failed to connect",err),this._clients=this._clients.filter((c)=>c!==client),timeoutHit)err=Error("Connection terminated due to connection timeout",{cause:err});if(this._pulseQueue(),!pendingItem.timedOut)pendingItem.callback(err,void 0,NOOP)}else{if(this.log("new client connected"),this.options.onConnect){this._promiseTry(()=>this.options.onConnect(client)).then(()=>{this._afterConnect(client,pendingItem,idleListener)},(hookErr)=>{this._clients=this._clients.filter((c)=>c!==client),client.end(()=>{if(this._pulseQueue(),!pendingItem.timedOut)pendingItem.callback(hookErr,void 0,NOOP)})});return}return this._afterConnect(client,pendingItem,idleListener)}})}_afterConnect(client,pendingItem,idleListener){if(this.options.maxLifetimeSeconds!==0){let maxLifetimeTimeout=setTimeout(()=>{if(this.log("ending client due to expired lifetime"),this._expired.add(client),this._idle.findIndex((idleItem)=>idleItem.client===client)!==-1)this._acquireClient(client,new PendingItem((err,client2,clientRelease)=>clientRelease()),idleListener,!1)},this.options.maxLifetimeSeconds*1000);maxLifetimeTimeout.unref(),client.once("end",()=>clearTimeout(maxLifetimeTimeout))}return this._acquireClient(client,pendingItem,idleListener,!0)}_acquireClient(client,pendingItem,idleListener,isNew){if(isNew)this.emit("connect",client);if(this.emit("acquire",client),client.release=this._releaseOnce(client,idleListener),client.removeListener("error",idleListener),!pendingItem.timedOut)if(isNew&&this.options.verify)this.options.verify(client,(err)=>{if(err)return client.release(err),pendingItem.callback(err,void 0,NOOP);pendingItem.callback(void 0,client,client.release)});else pendingItem.callback(void 0,client,client.release);else if(isNew&&this.options.verify)this.options.verify(client,client.release);else client.release()}_releaseOnce(client,idleListener){let released=!1;return(err)=>{if(released)throwOnDoubleRelease();released=!0,this._release(client,idleListener,err)}}_release(client,idleListener,err){if(client.on("error",idleListener),client._poolUseCount=(client._poolUseCount||0)+1,this.emit("release",err,client),err||this.ending||!client._queryable||client._ending||client._poolUseCount>=this.options.maxUses){if(client._poolUseCount>=this.options.maxUses)this.log("remove expended client");return this._remove(client,this._pulseQueue.bind(this))}if(this._expired.has(client))return this.log("remove expired client"),this._expired.delete(client),this._remove(client,this._pulseQueue.bind(this));let tid;if(this.options.idleTimeoutMillis&&this._isAboveMin()){if(tid=setTimeout(()=>{if(this._isAboveMin())this.log("remove idle client"),this._remove(client,this._pulseQueue.bind(this))},this.options.idleTimeoutMillis),this.options.allowExitOnIdle)tid.unref()}if(this.options.allowExitOnIdle)client.unref();this._idle.push(new IdleItem(client,idleListener,tid)),this._pulseQueue()}query(text,values,cb){if(typeof text==="function"){let response2=promisify(this.Promise,text);return setImmediate(function(){return response2.callback(Error("Passing a function as the first parameter to pool.query is not supported"))}),response2.result}if(typeof values==="function")cb=values,values=void 0;let response=promisify(this.Promise,cb);return cb=response.callback,this.connect((err,client)=>{if(err)return cb(err);let clientReleased=!1,onError=(err2)=>{if(clientReleased)return;clientReleased=!0,client.release(err2),cb(err2)};client.once("error",onError),this.log("dispatching query");try{client.query(text,values,(err2,res)=>{if(this.log("query dispatched"),client.removeListener("error",onError),clientReleased)return;if(clientReleased=!0,client.release(err2),err2)return cb(err2);return cb(void 0,res)})}catch(err2){return client.release(err2),cb(err2)}}),response.result}end(cb){if(this.log("ending"),this.ending){let err=Error("Called end on pool more than once");return cb?cb(err):this.Promise.reject(err)}this.ending=!0;let promised=promisify(this.Promise,cb);return this._endCallback=promised.callback,this._pulseQueue(),promised.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((acc,client)=>acc+(this._expired.has(client)?1:0),0)}get totalCount(){return this._clients.length}}module.exports=Pool});var require_query2=__commonJS((exports,module)=>{var EventEmitter=__require("events").EventEmitter,util=__require("util"),utils=require_utils(),NativeQuery=module.exports=function(config,values,callback){EventEmitter.call(this),config=utils.normalizeQueryConfig(config,values,callback),this.text=config.text,this.values=config.values,this.name=config.name,this.queryMode=config.queryMode,this.callback=config.callback,this.state="new",this._arrayMode=config.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(event){if(event==="row")this._emitRowEvents=!0}.bind(this))};util.inherits(NativeQuery,EventEmitter);var errorFieldMap={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};NativeQuery.prototype.handleError=function(err){let fields=this.native.pq.resultErrorFields();if(fields)for(let key in fields){let normalizedFieldName=errorFieldMap[key]||key;err[normalizedFieldName]=fields[key]}if(this.callback)this.callback(err);else this.emit("error",err);this.state="error"};NativeQuery.prototype.then=function(onSuccess,onFailure){return this._getPromise().then(onSuccess,onFailure)};NativeQuery.prototype.catch=function(callback){return this._getPromise().catch(callback)};NativeQuery.prototype._getPromise=function(){if(this._promise)return this._promise;return this._promise=new Promise(function(resolve,reject){this._once("end",resolve),this._once("error",reject)}.bind(this)),this._promise};NativeQuery.prototype.submit=function(client){this.state="running";let self=this;this.native=client.native,client.native.arrayMode=this._arrayMode;let after=function(err,rows,results){if(client.native.arrayMode=!1,setImmediate(function(){self.emit("_done")}),err)return self.handleError(err);if(self._emitRowEvents)if(results.length>1)rows.forEach((rowOfRows,i)=>{rowOfRows.forEach((row)=>{self.emit("row",row,results[i])})});else rows.forEach(function(row){self.emit("row",row,results)});if(self.state="end",self.emit("end",results),self.callback)self.callback(null,results)};if(process.domain)after=process.domain.bind(after);if(this.name){if(this.name.length>63)console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries");let values=(this.values||[]).map(utils.prepareValue);if(client.namedQueries[this.name]){if(this.text&&client.namedQueries[this.name]!==this.text){let err=Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return after(err)}return client.native.execute(this.name,values,after)}return client.native.prepare(this.name,this.text,values.length,function(err){if(err)return after(err);return client.namedQueries[self.name]=self.text,self.native.execute(self.name,values,after)})}else if(this.values){if(!Array.isArray(this.values)){let err=Error("Query values must be an array");return after(err)}let vals=this.values.map(utils.prepareValue);client.native.query(this.text,vals,after)}else if(this.queryMode==="extended")client.native.query(this.text,[],after);else client.native.query(this.text,after)}});var require_client2=__commonJS((exports,module)=>{var nodeUtils=__require("util"),Native;try{Native=(()=>{throw new Error("Cannot require module "+"pg-native");})()}catch(e){throw e}var TypeOverrides=require_type_overrides(),EventEmitter=__require("events").EventEmitter,util=__require("util"),ConnectionParameters=require_connection_parameters(),NativeQuery=require_query2(),queryQueueLengthDeprecationNotice=nodeUtils.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."),Client=module.exports=function(config){EventEmitter.call(this),config=config||{},this._Promise=config.Promise||global.Promise,this._types=new TypeOverrides(config.types),this.native=new Native({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;let cp=this.connectionParameters=new ConnectionParameters(config);if(config.nativeConnectionString)cp.nativeConnectionString=config.nativeConnectionString;this.user=cp.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:cp.password}),this.database=cp.database,this.host=cp.host,this.port=cp.port,this.namedQueries={}};Client.Query=NativeQuery;util.inherits(Client,EventEmitter);Client.prototype._errorAllQueries=function(err){let enqueueError=(query)=>{process.nextTick(()=>{query.native=this.native,query.handleError(err)})};if(this._hasActiveQuery())enqueueError(this._activeQuery),this._activeQuery=null;this._queryQueue.forEach(enqueueError),this._queryQueue.length=0};Client.prototype._connect=function(cb){let self=this;if(this._connecting){process.nextTick(()=>cb(Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(err,conString){if(self.connectionParameters.nativeConnectionString)conString=self.connectionParameters.nativeConnectionString;if(err)return cb(err);self.native.connect(conString,function(err2){if(err2)return self.native.end(),cb(err2);self._connected=!0,self.native.on("error",function(err3){self._queryable=!1,self._errorAllQueries(err3),self.emit("error",err3)}),self.native.on("notification",function(msg){self.emit("notification",{channel:msg.relname,payload:msg.extra})}),self.emit("connect"),self._pulseQueryQueue(!0),cb(null,this)})})};Client.prototype.connect=function(callback){if(callback){this._connect(callback);return}return new this._Promise((resolve,reject)=>{this._connect((error)=>{if(error)reject(error);else resolve(this)})})};Client.prototype.query=function(config,values,callback){let query,result,readTimeout,readTimeoutTimer,queryCallback;if(config===null||config===void 0)throw TypeError("Client was passed a null or undefined query");else if(typeof config.submit==="function"){if(readTimeout=config.query_timeout||this.connectionParameters.query_timeout,result=query=config,typeof values==="function")config.callback=values}else if(readTimeout=config.query_timeout||this.connectionParameters.query_timeout,query=new NativeQuery(config,values,callback),!query.callback){let resolveOut,rejectOut;result=new this._Promise((resolve,reject)=>{resolveOut=resolve,rejectOut=reject}).catch((err)=>{throw Error.captureStackTrace(err),err}),query.callback=(err,res)=>err?rejectOut(err):resolveOut(res)}if(readTimeout)queryCallback=query.callback||(()=>{}),readTimeoutTimer=setTimeout(()=>{let error=Error("Query read timeout");process.nextTick(()=>{query.handleError(error,this.connection)}),queryCallback(error),query.callback=()=>{};let index=this._queryQueue.indexOf(query);if(index>-1)this._queryQueue.splice(index,1);this._pulseQueryQueue()},readTimeout),query.callback=(err,res)=>{clearTimeout(readTimeoutTimer),queryCallback(err,res)};if(!this._queryable)return query.native=this.native,process.nextTick(()=>{query.handleError(Error("Client has encountered a connection error and is not queryable"))}),result;if(this._ending)return query.native=this.native,process.nextTick(()=>{query.handleError(Error("Client was closed and is not queryable"))}),result;if(this._queryQueue.length>0)queryQueueLengthDeprecationNotice();return this._queryQueue.push(query),this._pulseQueryQueue(),result};Client.prototype.end=function(cb){let self=this;if(this._ending=!0,!this._connected)this.once("connect",this.end.bind(this,cb));let result;if(!cb)result=new this._Promise(function(resolve,reject){cb=(err)=>err?reject(err):resolve()});return this.native.end(function(){self._connected=!1,self._errorAllQueries(Error("Connection terminated")),process.nextTick(()=>{if(self.emit("end"),cb)cb()})}),result};Client.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};Client.prototype._pulseQueryQueue=function(initialConnection){if(!this._connected)return;if(this._hasActiveQuery())return;let query=this._queryQueue.shift();if(!query){if(!initialConnection)this.emit("drain");return}this._activeQuery=query,query.submit(this);let self=this;query.once("_done",function(){self._pulseQueryQueue()})};Client.prototype.cancel=function(query){if(this._activeQuery===query)this.native.cancel(function(){});else if(this._queryQueue.indexOf(query)!==-1)this._queryQueue.splice(this._queryQueue.indexOf(query),1)};Client.prototype.ref=function(){};Client.prototype.unref=function(){};Client.prototype.setTypeParser=function(oid,format,parseFn){return this._types.setTypeParser(oid,format,parseFn)};Client.prototype.getTypeParser=function(oid,format){return this._types.getTypeParser(oid,format)};Client.prototype.isConnected=function(){return this._connected}});var require_lib2=__commonJS((exports,module)=>{var Client=require_client(),defaults=require_defaults(),Connection=require_connection(),Result=require_result(),utils=require_utils(),Pool=require_pg_pool(),TypeOverrides=require_type_overrides(),{DatabaseError}=require_dist(),{escapeIdentifier,escapeLiteral}=require_utils(),poolFactory=(Client2)=>{return class extends Pool{constructor(options){super(options,Client2)}}},PG=function(clientConstructor2){this.defaults=defaults,this.Client=clientConstructor2,this.Query=this.Client.Query,this.Pool=poolFactory(this.Client),this._pools=[],this.Connection=Connection,this.types=require_pg_types(),this.DatabaseError=DatabaseError,this.TypeOverrides=TypeOverrides,this.escapeIdentifier=escapeIdentifier,this.escapeLiteral=escapeLiteral,this.Result=Result,this.utils=utils},clientConstructor=Client,forceNative=!1;try{forceNative=!!process.env.NODE_PG_FORCE_NATIVE}catch{}if(forceNative)clientConstructor=require_client2();module.exports=new PG(clientConstructor);Object.defineProperty(module.exports,"native",{configurable:!0,enumerable:!1,get(){let native=null;try{native=new PG(require_client2())}catch(err){if(err.code!=="MODULE_NOT_FOUND")throw err}return Object.defineProperty(module.exports,"native",{value:native}),native}})});var exports_esm={};__export(exports_esm,{types:()=>types,escapeLiteral:()=>escapeLiteral,escapeIdentifier:()=>escapeIdentifier,defaults:()=>defaults,default:()=>esm_default,TypeOverrides:()=>TypeOverrides,Result:()=>Result,Query:()=>Query,Pool:()=>Pool,DatabaseError:()=>DatabaseError,Connection:()=>Connection,Client:()=>Client});var import_lib,Client,Pool,Connection,types,Query,DatabaseError,escapeIdentifier,escapeLiteral,Result,TypeOverrides,defaults,esm_default;var init_esm=__esm(()=>{import_lib=__toESM(require_lib2(),1),Client=import_lib.default.Client,Pool=import_lib.default.Pool,Connection=import_lib.default.Connection,types=import_lib.default.types,Query=import_lib.default.Query,DatabaseError=import_lib.default.DatabaseError,escapeIdentifier=import_lib.default.escapeIdentifier,escapeLiteral=import_lib.default.escapeLiteral,Result=import_lib.default.Result,TypeOverrides=import_lib.default.TypeOverrides,defaults=import_lib.default.defaults,esm_default=import_lib.default});import{createCipheriv,createDecipheriv,randomBytes}from"crypto";class AgentDatabase{}var registry=new Map;function registerAdapter(name,factory){registry.set(name,factory)}var COLLECTIONS={tasks:"tasks",config:"config",gitRepos:"git_repositories",bookmarks:"bookmarked_commands",notifications:"notifications",pluginState:"plugin_state"},nowIso=()=>new Date().toISOString();function pluginStateId(pluginName,key){return`${pluginName}::${key}`}function deriveKey(hex){if(!/^[0-9a-fA-F]{64}$/.test(hex))throw Error("vibe-plugin-storage-postgres: encryption key must be a 64-character hex string (32 bytes)");return Buffer.from(hex,"hex")}function encrypt(plaintext,key){let iv=randomBytes(12),cipher=createCipheriv("aes-256-gcm",key,iv);return{ciphertext:Buffer.concat([cipher.update(plaintext,"utf8"),cipher.final()]),iv,tag:cipher.getAuthTag()}}function decrypt(blob,key){let decipher=createDecipheriv("aes-256-gcm",key,blob.iv);return decipher.setAuthTag(blob.tag),Buffer.concat([decipher.update(blob.ciphertext),decipher.final()]).toString("utf8")}class PostgresAgentDatabase extends AgentDatabase{pool;key;connStr;constructor(pool,key,connStr){super();this.pool=pool,this.key=key,this.connStr=connStr}async init(){await this.pool.query(`
|
|
10
|
+
`);warnStream.write(util.format.apply(util,args))}}Object.defineProperty(exports,"isWin",{get:function(){return isWin},set:function(val){isWin=val}});exports.warnTo=function(stream){var old=warnStream;return warnStream=stream,old};exports.getFileName=function(rawEnv){var env=rawEnv||process.env,file=env.PGPASSFILE||(isWin?path.join(env.APPDATA||"./","postgresql","pgpass.conf"):path.join(env.HOME||"./",".pgpass"));return file};exports.usePgPass=function(stats,fname){if(Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD"))return!1;if(isWin)return!0;if(fname=fname||"<unkn>",!isRegFile(stats.mode))return warn('WARNING: password file "%s" is not a plain file',fname),!1;if(stats.mode&(S_IRWXG|S_IRWXO))return warn('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',fname),!1;return!0};var matcher=exports.match=function(connInfo,entry){return fieldNames.slice(0,-1).reduce(function(prev,field,idx){if(idx==1){if(Number(connInfo[field]||defaultPort)===Number(entry[field]))return prev&&!0}return prev&&(entry[field]==="*"||entry[field]===connInfo[field])},!0)};exports.getPassword=function(connInfo,stream,cb){var pass,lineStream=stream.pipe(split());function onLine(line){var entry=parseLine(line);if(entry&&isValidEntry(entry)&&matcher(connInfo,entry))pass=entry[passKey],lineStream.end()}var onEnd=function(){stream.destroy(),cb(pass)},onErr=function(err){stream.destroy(),warn("WARNING: error on reading file: %s",err),cb(void 0)};stream.on("error",onErr),lineStream.on("data",onLine).on("end",onEnd).on("error",onErr)};var parseLine=exports.parseLine=function(line){if(line.length<11||line.match(/^\s+#/))return null;var curChar="",prevChar="",fieldIdx=0,startIdx=0,endIdx=0,obj={},isLastField=!1,addToObj=function(idx,i0,i1){var field=line.substring(i0,i1);if(!Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE"))field=field.replace(/\\([:\\])/g,"$1");obj[fieldNames[idx]]=field};for(var i=0;i<line.length-1;i+=1){if(curChar=line.charAt(i+1),prevChar=line.charAt(i),isLastField=fieldIdx==nrOfFields-1,isLastField){addToObj(fieldIdx,startIdx);break}if(i>=0&&curChar==":"&&prevChar!=="\\")addToObj(fieldIdx,startIdx,i+1),startIdx=i+2,fieldIdx+=1}return obj=Object.keys(obj).length===nrOfFields?obj:null,obj},isValidEntry=exports.isValidEntry=function(entry){var rules={0:function(x){return x.length>0},1:function(x){if(x==="*")return!0;return x=Number(x),isFinite(x)&&x>0&&x<9007199254740992&&Math.floor(x)===x},2:function(x){return x.length>0},3:function(x){return x.length>0},4:function(x){return x.length>0}};for(var idx=0;idx<fieldNames.length;idx+=1){var rule=rules[idx],value=entry[fieldNames[idx]]||"",res=rule(value);if(!res)return!1}return!0}});var require_lib=__commonJS((exports,module)=>{var path=__require("path"),fs=__require("fs"),helper=require_helper();module.exports=function(connInfo,cb){var file=helper.getFileName();fs.stat(file,function(err,stat){if(err||!helper.usePgPass(stat,file))return cb(void 0);var st=fs.createReadStream(file);helper.getPassword(connInfo,st,cb)})};module.exports.warnTo=helper.warnTo});var require_client=__commonJS((exports,module)=>{var EventEmitter=__require("events").EventEmitter,utils=require_utils(),nodeUtils=__require("util"),sasl=require_sasl(),TypeOverrides=require_type_overrides(),ConnectionParameters=require_connection_parameters(),Query=require_query(),defaults=require_defaults(),Connection=require_connection(),crypto=require_utils2(),activeQueryDeprecationNotice=nodeUtils.deprecate(()=>{},"Client.activeQuery is deprecated and will be removed in pg@9.0"),queryQueueDeprecationNotice=nodeUtils.deprecate(()=>{},"Client.queryQueue is deprecated and will be removed in pg@9.0."),pgPassDeprecationNotice=nodeUtils.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."),byoPromiseDeprecationNotice=nodeUtils.deprecate(()=>{},"Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0."),queryQueueLengthDeprecationNotice=nodeUtils.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.");class Client extends EventEmitter{constructor(config){super();this.connectionParameters=new ConnectionParameters(config),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 c=config||{};if(c.Promise)byoPromiseDeprecationNotice();if(this._Promise=c.Promise||global.Promise,this._types=new TypeOverrides(c.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this._activeQuery=null,this.enableChannelBinding=Boolean(c.enableChannelBinding),this.connection=c.connection||new Connection({stream:c.stream,ssl:this.connectionParameters.ssl,keepAlive:c.keepAlive||!1,keepAliveInitialDelayMillis:c.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this._queryQueue=[],this.binary=c.binary||defaults.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=c.connectionTimeoutMillis||0}get activeQuery(){return activeQueryDeprecationNotice(),this._activeQuery}set activeQuery(val){activeQueryDeprecationNotice(),this._activeQuery=val}_getActiveQuery(){return this._activeQuery}_errorAllQueries(err){let enqueueError=(query)=>{process.nextTick(()=>{query.handleError(err,this.connection)})},activeQuery=this._getActiveQuery();if(activeQuery)enqueueError(activeQuery),this._activeQuery=null;this._queryQueue.forEach(enqueueError),this._queryQueue.length=0}_connect(callback){let self=this,con=this.connection;if(this._connectionCallback=callback,this._connecting||this._connected){let err=Error("Client has already been connected. You cannot reuse a client.");process.nextTick(()=>{callback(err)});return}if(this._connecting=!0,this._connectionTimeoutMillis>0){if(this.connectionTimeoutHandle=setTimeout(()=>{con._ending=!0,con.stream.destroy(Error("timeout expired"))},this._connectionTimeoutMillis),this.connectionTimeoutHandle.unref)this.connectionTimeoutHandle.unref()}if(this.host&&this.host.indexOf("/")===0)con.connect(this.host+"/.s.PGSQL."+this.port);else con.connect(this.port,this.host);con.on("connect",function(){if(self.ssl)con.requestSsl();else con.startup(self.getStartupConf())}),con.on("sslconnect",function(){con.startup(self.getStartupConf())}),this._attachListeners(con),con.once("end",()=>{let error=this._ending?Error("Connection terminated"):Error("Connection terminated unexpectedly");if(clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(error),this._ended=!0,!this._ending){if(this._connecting&&!this._connectionError)if(this._connectionCallback)this._connectionCallback(error);else this._handleErrorEvent(error);else if(!this._connectionError)this._handleErrorEvent(error)}process.nextTick(()=>{this.emit("end")})})}connect(callback){if(callback){this._connect(callback);return}return new this._Promise((resolve,reject)=>{this._connect((error)=>{if(error)reject(error);else resolve(this)})})}_attachListeners(con){con.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),con.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),con.on("authenticationSASL",this._handleAuthSASL.bind(this)),con.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),con.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),con.on("backendKeyData",this._handleBackendKeyData.bind(this)),con.on("error",this._handleErrorEvent.bind(this)),con.on("errorMessage",this._handleErrorMessage.bind(this)),con.on("readyForQuery",this._handleReadyForQuery.bind(this)),con.on("notice",this._handleNotice.bind(this)),con.on("rowDescription",this._handleRowDescription.bind(this)),con.on("dataRow",this._handleDataRow.bind(this)),con.on("portalSuspended",this._handlePortalSuspended.bind(this)),con.on("emptyQuery",this._handleEmptyQuery.bind(this)),con.on("commandComplete",this._handleCommandComplete.bind(this)),con.on("parseComplete",this._handleParseComplete.bind(this)),con.on("copyInResponse",this._handleCopyInResponse.bind(this)),con.on("copyData",this._handleCopyData.bind(this)),con.on("notification",this._handleNotification.bind(this))}_getPassword(cb){let con=this.connection;if(typeof this.password==="function")this._Promise.resolve().then(()=>this.password(this.connectionParameters)).then((pass)=>{if(pass!==void 0){if(typeof pass!=="string"){con.emit("error",TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=pass}else this.connectionParameters.password=this.password=null;cb()}).catch((err)=>{con.emit("error",err)});else if(this.password!==null)cb();else try{require_lib()(this.connectionParameters,(pass)=>{if(pass!==void 0)pgPassDeprecationNotice(),this.connectionParameters.password=this.password=pass;cb()})}catch(e){this.emit("error",e)}}_handleAuthCleartextPassword(msg){this._getPassword(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(msg){this._getPassword(async()=>{try{let hashedPassword=await crypto.postgresMd5PasswordHash(this.user,this.password,msg.salt);this.connection.password(hashedPassword)}catch(e){this.emit("error",e)}})}_handleAuthSASL(msg){this._getPassword(()=>{try{this.saslSession=sasl.startSession(msg.mechanisms,this.enableChannelBinding&&this.connection.stream),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(err){this.connection.emit("error",err)}})}async _handleAuthSASLContinue(msg){try{await sasl.continueSession(this.saslSession,this.password,msg.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(err){this.connection.emit("error",err)}}_handleAuthSASLFinal(msg){try{sasl.finalizeSession(this.saslSession,msg.data),this.saslSession=null}catch(err){this.connection.emit("error",err)}}_handleBackendKeyData(msg){this.processID=msg.processID,this.secretKey=msg.secretKey}_handleReadyForQuery(msg){if(this._connecting){if(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)this._connectionCallback(null,this),this._connectionCallback=null;this.emit("connect")}let activeQuery=this._getActiveQuery();if(this._activeQuery=null,this.readyForQuery=!0,activeQuery)activeQuery.handleReadyForQuery(this.connection);this._pulseQueryQueue()}_handleErrorWhileConnecting(err){if(this._connectionError)return;if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(err);this.emit("error",err)}_handleErrorEvent(err){if(this._connecting)return this._handleErrorWhileConnecting(err);this._queryable=!1,this._errorAllQueries(err),this.emit("error",err)}_handleErrorMessage(msg){if(this._connecting)return this._handleErrorWhileConnecting(msg);let activeQuery=this._getActiveQuery();if(!activeQuery){this._handleErrorEvent(msg);return}this._activeQuery=null,activeQuery.handleError(msg,this.connection)}_handleRowDescription(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error=Error("Received unexpected rowDescription message from backend.");this._handleErrorEvent(error);return}activeQuery.handleRowDescription(msg)}_handleDataRow(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error=Error("Received unexpected dataRow message from backend.");this._handleErrorEvent(error);return}activeQuery.handleDataRow(msg)}_handlePortalSuspended(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error=Error("Received unexpected portalSuspended message from backend.");this._handleErrorEvent(error);return}activeQuery.handlePortalSuspended(this.connection)}_handleEmptyQuery(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error=Error("Received unexpected emptyQuery message from backend.");this._handleErrorEvent(error);return}activeQuery.handleEmptyQuery(this.connection)}_handleCommandComplete(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error=Error("Received unexpected commandComplete message from backend.");this._handleErrorEvent(error);return}activeQuery.handleCommandComplete(msg,this.connection)}_handleParseComplete(){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error=Error("Received unexpected parseComplete message from backend.");this._handleErrorEvent(error);return}if(activeQuery.name)this.connection.parsedStatements[activeQuery.name]=activeQuery.text}_handleCopyInResponse(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error=Error("Received unexpected copyInResponse message from backend.");this._handleErrorEvent(error);return}activeQuery.handleCopyInResponse(this.connection)}_handleCopyData(msg){let activeQuery=this._getActiveQuery();if(activeQuery==null){let error=Error("Received unexpected copyData message from backend.");this._handleErrorEvent(error);return}activeQuery.handleCopyData(msg,this.connection)}_handleNotification(msg){this.emit("notification",msg)}_handleNotice(msg){this.emit("notice",msg)}getStartupConf(){let params=this.connectionParameters,data={user:params.user,database:params.database},appName=params.application_name||params.fallback_application_name;if(appName)data.application_name=appName;if(params.replication)data.replication=""+params.replication;if(params.statement_timeout)data.statement_timeout=String(parseInt(params.statement_timeout,10));if(params.lock_timeout)data.lock_timeout=String(parseInt(params.lock_timeout,10));if(params.idle_in_transaction_session_timeout)data.idle_in_transaction_session_timeout=String(parseInt(params.idle_in_transaction_session_timeout,10));if(params.options)data.options=params.options;return data}cancel(client,query){if(client.activeQuery===query){let con=this.connection;if(this.host&&this.host.indexOf("/")===0)con.connect(this.host+"/.s.PGSQL."+this.port);else con.connect(this.port,this.host);con.on("connect",function(){con.cancel(client.processID,client.secretKey)})}else if(client._queryQueue.indexOf(query)!==-1)client._queryQueue.splice(client._queryQueue.indexOf(query),1)}setTypeParser(oid,format,parseFn){return this._types.setTypeParser(oid,format,parseFn)}getTypeParser(oid,format){return this._types.getTypeParser(oid,format)}escapeIdentifier(str){return utils.escapeIdentifier(str)}escapeLiteral(str){return utils.escapeLiteral(str)}_pulseQueryQueue(){if(this.readyForQuery===!0){this._activeQuery=this._queryQueue.shift();let activeQuery=this._getActiveQuery();if(activeQuery){this.readyForQuery=!1,this.hasExecuted=!0;let queryError=activeQuery.submit(this.connection);if(queryError)process.nextTick(()=>{activeQuery.handleError(queryError,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else if(this.hasExecuted)this._activeQuery=null,this.emit("drain")}}query(config,values,callback){let query,result,readTimeout,readTimeoutTimer,queryCallback;if(config===null||config===void 0)throw TypeError("Client was passed a null or undefined query");else if(typeof config.submit==="function"){if(readTimeout=config.query_timeout||this.connectionParameters.query_timeout,result=query=config,!query.callback){if(typeof values==="function")query.callback=values;else if(callback)query.callback=callback}}else if(readTimeout=config.query_timeout||this.connectionParameters.query_timeout,query=new Query(config,values,callback),!query.callback)result=new this._Promise((resolve,reject)=>{query.callback=(err,res)=>err?reject(err):resolve(res)}).catch((err)=>{throw Error.captureStackTrace(err),err});if(readTimeout)queryCallback=query.callback||(()=>{}),readTimeoutTimer=setTimeout(()=>{let error=Error("Query read timeout");process.nextTick(()=>{query.handleError(error,this.connection)}),queryCallback(error),query.callback=()=>{};let index=this._queryQueue.indexOf(query);if(index>-1)this._queryQueue.splice(index,1);this._pulseQueryQueue()},readTimeout),query.callback=(err,res)=>{clearTimeout(readTimeoutTimer),queryCallback(err,res)};if(this.binary&&!query.binary)query.binary=!0;if(query._result&&!query._result._types)query._result._types=this._types;if(!this._queryable)return process.nextTick(()=>{query.handleError(Error("Client has encountered a connection error and is not queryable"),this.connection)}),result;if(this._ending)return process.nextTick(()=>{query.handleError(Error("Client was closed and is not queryable"),this.connection)}),result;if(this._queryQueue.length>0)queryQueueLengthDeprecationNotice();return this._queryQueue.push(query),this._pulseQueryQueue(),result}ref(){this.connection.ref()}unref(){this.connection.unref()}end(cb){if(this._ending=!0,!this.connection._connecting||this._ended)if(cb)cb();else return this._Promise.resolve();if(this._getActiveQuery()||!this._queryable)this.connection.stream.destroy();else this.connection.end();if(cb)this.connection.once("end",cb);else return new this._Promise((resolve)=>{this.connection.once("end",resolve)})}get queryQueue(){return queryQueueDeprecationNotice(),this._queryQueue}}Client.Query=Query;module.exports=Client});var require_pg_pool=__commonJS((exports,module)=>{var EventEmitter=__require("events").EventEmitter,NOOP=function(){},removeWhere=(list,predicate)=>{let i=list.findIndex(predicate);return i===-1?void 0:list.splice(i,1)[0]};class IdleItem{constructor(client,idleListener,timeoutId){this.client=client,this.idleListener=idleListener,this.timeoutId=timeoutId}}class PendingItem{constructor(callback){this.callback=callback}}function throwOnDoubleRelease(){throw Error("Release called on client which has already been released to the pool.")}function promisify(Promise2,callback){if(callback)return{callback,result:void 0};let rej,res,cb=function(err,client){err?rej(err):res(client)},result=new Promise2(function(resolve,reject){res=resolve,rej=reject}).catch((err)=>{throw Error.captureStackTrace(err),err});return{callback:cb,result}}function makeIdleListener(pool,client){return function idleListener(err){err.client=client,client.removeListener("error",idleListener),client.on("error",()=>{pool.log("additional client error after disconnection due to error",err)}),pool._remove(client),pool.emit("error",err,client)}}class Pool extends EventEmitter{constructor(options,Client){super();if(this.options=Object.assign({},options),options!=null&&"password"in options)Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:options.password});if(options!=null&&options.ssl&&options.ssl.key)Object.defineProperty(this.options.ssl,"key",{enumerable:!1});if(this.options.max=this.options.max||this.options.poolSize||10,this.options.min=this.options.min||0,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||Client||require_lib2().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(f){let Promise2=this.Promise;if(typeof Promise2.try==="function")return Promise2.try(f);return new Promise2((resolve)=>resolve(f()))}_isFull(){return this._clients.length>=this.options.max}_isAboveMin(){return this._clients.length>this.options.min}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){if(this.log("pulse queue on ending"),this._idle.length)this._idle.slice().map((item)=>{this._remove(item.client)});if(!this._clients.length)this.ended=!0,this._endCallback();return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let pendingItem=this._pendingQueue.shift();if(this._idle.length){let idleItem=this._idle.pop();clearTimeout(idleItem.timeoutId);let client=idleItem.client;client.ref&&client.ref();let idleListener=idleItem.idleListener;return this._acquireClient(client,pendingItem,idleListener,!1)}if(!this._isFull())return this.newClient(pendingItem);throw Error("unexpected condition")}_remove(client,callback){let removed=removeWhere(this._idle,(item)=>item.client===client);if(removed!==void 0)clearTimeout(removed.timeoutId);this._clients=this._clients.filter((c)=>c!==client);let context=this;client.end(()=>{if(context.emit("remove",client),typeof callback==="function")callback()})}connect(cb){if(this.ending){let err=Error("Cannot use a pool after calling end on the pool");return cb?cb(err):this.Promise.reject(err)}let response=promisify(this.Promise,cb),result=response.result;if(this._isFull()||this._idle.length){if(this._idle.length)process.nextTick(()=>this._pulseQueue());if(!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new PendingItem(response.callback)),result;let queueCallback=(err,res,done)=>{clearTimeout(tid),response.callback(err,res,done)},pendingItem=new PendingItem(queueCallback),tid=setTimeout(()=>{removeWhere(this._pendingQueue,(i)=>i.callback===queueCallback),pendingItem.timedOut=!0,response.callback(Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);if(tid.unref)tid.unref();return this._pendingQueue.push(pendingItem),result}return this.newClient(new PendingItem(response.callback)),result}newClient(pendingItem){let client=new this.Client(this.options);this._clients.push(client);let idleListener=makeIdleListener(this,client);this.log("checking client timeout");let tid,timeoutHit=!1;if(this.options.connectionTimeoutMillis)tid=setTimeout(()=>{if(client.connection)this.log("ending client due to timeout"),timeoutHit=!0,client.connection.stream.destroy();else if(!client.isConnected())this.log("ending client due to timeout"),timeoutHit=!0,client.end()},this.options.connectionTimeoutMillis);this.log("connecting new client"),client.connect((err)=>{if(tid)clearTimeout(tid);if(client.on("error",idleListener),err){if(this.log("client failed to connect",err),this._clients=this._clients.filter((c)=>c!==client),timeoutHit)err=Error("Connection terminated due to connection timeout",{cause:err});if(this._pulseQueue(),!pendingItem.timedOut)pendingItem.callback(err,void 0,NOOP)}else{if(this.log("new client connected"),this.options.onConnect){this._promiseTry(()=>this.options.onConnect(client)).then(()=>{this._afterConnect(client,pendingItem,idleListener)},(hookErr)=>{this._clients=this._clients.filter((c)=>c!==client),client.end(()=>{if(this._pulseQueue(),!pendingItem.timedOut)pendingItem.callback(hookErr,void 0,NOOP)})});return}return this._afterConnect(client,pendingItem,idleListener)}})}_afterConnect(client,pendingItem,idleListener){if(this.options.maxLifetimeSeconds!==0){let maxLifetimeTimeout=setTimeout(()=>{if(this.log("ending client due to expired lifetime"),this._expired.add(client),this._idle.findIndex((idleItem)=>idleItem.client===client)!==-1)this._acquireClient(client,new PendingItem((err,client2,clientRelease)=>clientRelease()),idleListener,!1)},this.options.maxLifetimeSeconds*1000);maxLifetimeTimeout.unref(),client.once("end",()=>clearTimeout(maxLifetimeTimeout))}return this._acquireClient(client,pendingItem,idleListener,!0)}_acquireClient(client,pendingItem,idleListener,isNew){if(isNew)this.emit("connect",client);if(this.emit("acquire",client),client.release=this._releaseOnce(client,idleListener),client.removeListener("error",idleListener),!pendingItem.timedOut)if(isNew&&this.options.verify)this.options.verify(client,(err)=>{if(err)return client.release(err),pendingItem.callback(err,void 0,NOOP);pendingItem.callback(void 0,client,client.release)});else pendingItem.callback(void 0,client,client.release);else if(isNew&&this.options.verify)this.options.verify(client,client.release);else client.release()}_releaseOnce(client,idleListener){let released=!1;return(err)=>{if(released)throwOnDoubleRelease();released=!0,this._release(client,idleListener,err)}}_release(client,idleListener,err){if(client.on("error",idleListener),client._poolUseCount=(client._poolUseCount||0)+1,this.emit("release",err,client),err||this.ending||!client._queryable||client._ending||client._poolUseCount>=this.options.maxUses){if(client._poolUseCount>=this.options.maxUses)this.log("remove expended client");return this._remove(client,this._pulseQueue.bind(this))}if(this._expired.has(client))return this.log("remove expired client"),this._expired.delete(client),this._remove(client,this._pulseQueue.bind(this));let tid;if(this.options.idleTimeoutMillis&&this._isAboveMin()){if(tid=setTimeout(()=>{if(this._isAboveMin())this.log("remove idle client"),this._remove(client,this._pulseQueue.bind(this))},this.options.idleTimeoutMillis),this.options.allowExitOnIdle)tid.unref()}if(this.options.allowExitOnIdle)client.unref();this._idle.push(new IdleItem(client,idleListener,tid)),this._pulseQueue()}query(text,values,cb){if(typeof text==="function"){let response2=promisify(this.Promise,text);return setImmediate(function(){return response2.callback(Error("Passing a function as the first parameter to pool.query is not supported"))}),response2.result}if(typeof values==="function")cb=values,values=void 0;let response=promisify(this.Promise,cb);return cb=response.callback,this.connect((err,client)=>{if(err)return cb(err);let clientReleased=!1,onError=(err2)=>{if(clientReleased)return;clientReleased=!0,client.release(err2),cb(err2)};client.once("error",onError),this.log("dispatching query");try{client.query(text,values,(err2,res)=>{if(this.log("query dispatched"),client.removeListener("error",onError),clientReleased)return;if(clientReleased=!0,client.release(err2),err2)return cb(err2);return cb(void 0,res)})}catch(err2){return client.release(err2),cb(err2)}}),response.result}end(cb){if(this.log("ending"),this.ending){let err=Error("Called end on pool more than once");return cb?cb(err):this.Promise.reject(err)}this.ending=!0;let promised=promisify(this.Promise,cb);return this._endCallback=promised.callback,this._pulseQueue(),promised.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((acc,client)=>acc+(this._expired.has(client)?1:0),0)}get totalCount(){return this._clients.length}}module.exports=Pool});var require_query2=__commonJS((exports,module)=>{var EventEmitter=__require("events").EventEmitter,util=__require("util"),utils=require_utils(),NativeQuery=module.exports=function(config,values,callback){EventEmitter.call(this),config=utils.normalizeQueryConfig(config,values,callback),this.text=config.text,this.values=config.values,this.name=config.name,this.queryMode=config.queryMode,this.callback=config.callback,this.state="new",this._arrayMode=config.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(event){if(event==="row")this._emitRowEvents=!0}.bind(this))};util.inherits(NativeQuery,EventEmitter);var errorFieldMap={sqlState:"code",statementPosition:"position",messagePrimary:"message",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};NativeQuery.prototype.handleError=function(err){let fields=this.native.pq.resultErrorFields();if(fields)for(let key in fields){let normalizedFieldName=errorFieldMap[key]||key;err[normalizedFieldName]=fields[key]}if(this.callback)this.callback(err);else this.emit("error",err);this.state="error"};NativeQuery.prototype.then=function(onSuccess,onFailure){return this._getPromise().then(onSuccess,onFailure)};NativeQuery.prototype.catch=function(callback){return this._getPromise().catch(callback)};NativeQuery.prototype._getPromise=function(){if(this._promise)return this._promise;return this._promise=new Promise(function(resolve,reject){this._once("end",resolve),this._once("error",reject)}.bind(this)),this._promise};NativeQuery.prototype.submit=function(client){this.state="running";let self=this;this.native=client.native,client.native.arrayMode=this._arrayMode;let after=function(err,rows,results){if(client.native.arrayMode=!1,setImmediate(function(){self.emit("_done")}),err)return self.handleError(err);if(self._emitRowEvents)if(results.length>1)rows.forEach((rowOfRows,i)=>{rowOfRows.forEach((row)=>{self.emit("row",row,results[i])})});else rows.forEach(function(row){self.emit("row",row,results)});if(self.state="end",self.emit("end",results),self.callback)self.callback(null,results)};if(process.domain)after=process.domain.bind(after);if(this.name){if(this.name.length>63)console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries");let values=(this.values||[]).map(utils.prepareValue);if(client.namedQueries[this.name]){if(this.text&&client.namedQueries[this.name]!==this.text){let err=Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return after(err)}return client.native.execute(this.name,values,after)}return client.native.prepare(this.name,this.text,values.length,function(err){if(err)return after(err);return client.namedQueries[self.name]=self.text,self.native.execute(self.name,values,after)})}else if(this.values){if(!Array.isArray(this.values)){let err=Error("Query values must be an array");return after(err)}let vals=this.values.map(utils.prepareValue);client.native.query(this.text,vals,after)}else if(this.queryMode==="extended")client.native.query(this.text,[],after);else client.native.query(this.text,after)}});var require_client2=__commonJS((exports,module)=>{var nodeUtils=__require("util"),Native;try{Native=(()=>{throw new Error("Cannot require module "+"pg-native");})()}catch(e){throw e}var TypeOverrides=require_type_overrides(),EventEmitter=__require("events").EventEmitter,util=__require("util"),ConnectionParameters=require_connection_parameters(),NativeQuery=require_query2(),queryQueueLengthDeprecationNotice=nodeUtils.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."),Client=module.exports=function(config){EventEmitter.call(this),config=config||{},this._Promise=config.Promise||global.Promise,this._types=new TypeOverrides(config.types),this.native=new Native({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0;let cp=this.connectionParameters=new ConnectionParameters(config);if(config.nativeConnectionString)cp.nativeConnectionString=config.nativeConnectionString;this.user=cp.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:cp.password}),this.database=cp.database,this.host=cp.host,this.port=cp.port,this.namedQueries={}};Client.Query=NativeQuery;util.inherits(Client,EventEmitter);Client.prototype._errorAllQueries=function(err){let enqueueError=(query)=>{process.nextTick(()=>{query.native=this.native,query.handleError(err)})};if(this._hasActiveQuery())enqueueError(this._activeQuery),this._activeQuery=null;this._queryQueue.forEach(enqueueError),this._queryQueue.length=0};Client.prototype._connect=function(cb){let self=this;if(this._connecting){process.nextTick(()=>cb(Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(err,conString){if(self.connectionParameters.nativeConnectionString)conString=self.connectionParameters.nativeConnectionString;if(err)return cb(err);self.native.connect(conString,function(err2){if(err2)return self.native.end(),cb(err2);self._connected=!0,self.native.on("error",function(err3){self._queryable=!1,self._errorAllQueries(err3),self.emit("error",err3)}),self.native.on("notification",function(msg){self.emit("notification",{channel:msg.relname,payload:msg.extra})}),self.emit("connect"),self._pulseQueryQueue(!0),cb(null,this)})})};Client.prototype.connect=function(callback){if(callback){this._connect(callback);return}return new this._Promise((resolve,reject)=>{this._connect((error)=>{if(error)reject(error);else resolve(this)})})};Client.prototype.query=function(config,values,callback){let query,result,readTimeout,readTimeoutTimer,queryCallback;if(config===null||config===void 0)throw TypeError("Client was passed a null or undefined query");else if(typeof config.submit==="function"){if(readTimeout=config.query_timeout||this.connectionParameters.query_timeout,result=query=config,typeof values==="function")config.callback=values}else if(readTimeout=config.query_timeout||this.connectionParameters.query_timeout,query=new NativeQuery(config,values,callback),!query.callback){let resolveOut,rejectOut;result=new this._Promise((resolve,reject)=>{resolveOut=resolve,rejectOut=reject}).catch((err)=>{throw Error.captureStackTrace(err),err}),query.callback=(err,res)=>err?rejectOut(err):resolveOut(res)}if(readTimeout)queryCallback=query.callback||(()=>{}),readTimeoutTimer=setTimeout(()=>{let error=Error("Query read timeout");process.nextTick(()=>{query.handleError(error,this.connection)}),queryCallback(error),query.callback=()=>{};let index=this._queryQueue.indexOf(query);if(index>-1)this._queryQueue.splice(index,1);this._pulseQueryQueue()},readTimeout),query.callback=(err,res)=>{clearTimeout(readTimeoutTimer),queryCallback(err,res)};if(!this._queryable)return query.native=this.native,process.nextTick(()=>{query.handleError(Error("Client has encountered a connection error and is not queryable"))}),result;if(this._ending)return query.native=this.native,process.nextTick(()=>{query.handleError(Error("Client was closed and is not queryable"))}),result;if(this._queryQueue.length>0)queryQueueLengthDeprecationNotice();return this._queryQueue.push(query),this._pulseQueryQueue(),result};Client.prototype.end=function(cb){let self=this;if(this._ending=!0,!this._connected)this.once("connect",this.end.bind(this,cb));let result;if(!cb)result=new this._Promise(function(resolve,reject){cb=(err)=>err?reject(err):resolve()});return this.native.end(function(){self._connected=!1,self._errorAllQueries(Error("Connection terminated")),process.nextTick(()=>{if(self.emit("end"),cb)cb()})}),result};Client.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};Client.prototype._pulseQueryQueue=function(initialConnection){if(!this._connected)return;if(this._hasActiveQuery())return;let query=this._queryQueue.shift();if(!query){if(!initialConnection)this.emit("drain");return}this._activeQuery=query,query.submit(this);let self=this;query.once("_done",function(){self._pulseQueryQueue()})};Client.prototype.cancel=function(query){if(this._activeQuery===query)this.native.cancel(function(){});else if(this._queryQueue.indexOf(query)!==-1)this._queryQueue.splice(this._queryQueue.indexOf(query),1)};Client.prototype.ref=function(){};Client.prototype.unref=function(){};Client.prototype.setTypeParser=function(oid,format,parseFn){return this._types.setTypeParser(oid,format,parseFn)};Client.prototype.getTypeParser=function(oid,format){return this._types.getTypeParser(oid,format)};Client.prototype.isConnected=function(){return this._connected}});var require_lib2=__commonJS((exports,module)=>{var Client=require_client(),defaults=require_defaults(),Connection=require_connection(),Result=require_result(),utils=require_utils(),Pool=require_pg_pool(),TypeOverrides=require_type_overrides(),{DatabaseError}=require_dist(),{escapeIdentifier,escapeLiteral}=require_utils(),poolFactory=(Client2)=>{return class extends Pool{constructor(options){super(options,Client2)}}},PG=function(clientConstructor2){this.defaults=defaults,this.Client=clientConstructor2,this.Query=this.Client.Query,this.Pool=poolFactory(this.Client),this._pools=[],this.Connection=Connection,this.types=require_pg_types(),this.DatabaseError=DatabaseError,this.TypeOverrides=TypeOverrides,this.escapeIdentifier=escapeIdentifier,this.escapeLiteral=escapeLiteral,this.Result=Result,this.utils=utils},clientConstructor=Client,forceNative=!1;try{forceNative=!!process.env.NODE_PG_FORCE_NATIVE}catch{}if(forceNative)clientConstructor=require_client2();module.exports=new PG(clientConstructor);Object.defineProperty(module.exports,"native",{configurable:!0,enumerable:!1,get(){let native=null;try{native=new PG(require_client2())}catch(err){if(err.code!=="MODULE_NOT_FOUND")throw err}return Object.defineProperty(module.exports,"native",{value:native}),native}})});var exports_esm={};__export(exports_esm,{types:()=>types,escapeLiteral:()=>escapeLiteral,escapeIdentifier:()=>escapeIdentifier,defaults:()=>defaults,default:()=>esm_default,TypeOverrides:()=>TypeOverrides,Result:()=>Result,Query:()=>Query,Pool:()=>Pool,DatabaseError:()=>DatabaseError,Connection:()=>Connection,Client:()=>Client});var import_lib,Client,Pool,Connection,types,Query,DatabaseError,escapeIdentifier,escapeLiteral,Result,TypeOverrides,defaults,esm_default;var init_esm=__esm(()=>{import_lib=__toESM(require_lib2(),1),Client=import_lib.default.Client,Pool=import_lib.default.Pool,Connection=import_lib.default.Connection,types=import_lib.default.types,Query=import_lib.default.Query,DatabaseError=import_lib.default.DatabaseError,escapeIdentifier=import_lib.default.escapeIdentifier,escapeLiteral=import_lib.default.escapeLiteral,Result=import_lib.default.Result,TypeOverrides=import_lib.default.TypeOverrides,defaults=import_lib.default.defaults,esm_default=import_lib.default});function createLifecycleHooks(spec){let{name,onInit,onShutdown,telemetryEventName,skipPlatforms}=spec;return{onServerStart:async(_app,hostServices)=>{if(skipPlatforms&&skipPlatforms.includes(process.platform)){process.stderr.write(`[${name}] skipping init on unsupported platform '${process.platform}'
|
|
11
|
+
`);return}if(onInit)await onInit(hostServices);if(telemetryEventName)hostServices.telemetry?.emit(telemetryEventName,{plugin:name})},onServerStop:async(hostServices)=>{if(onShutdown)await onShutdown(hostServices)}}}var BoundLogger=class{constructor(logger,source){this.logger=logger,this.source=source}logger;source;info(message,meta){this.logger?.info?.(this.source,message,meta)}warn(message,meta){this.logger?.warn?.(this.source,message,meta)}error(message,meta){this.logger?.error?.(this.source,message,meta)}debug(message,meta){this.logger?.debug?.(this.source,message,meta)}};var ProviderRegistry=class{constructor(hostServices){this.hostServices=hostServices}hostServices;getServiceRegistry(){return this.hostServices?.serviceRegistry}registerProvider(type,name,provider){this.hostServices?.serviceRegistry?.registerService(type,name,provider)}getProvider(type,name){return this.hostServices?.serviceRegistry?.getService(type,name)}listProviders(type){return this.hostServices?.serviceRegistry?.listProvidersForType?.(type)??[]}withCliContribution(contribution){let contributors=this.hostServices?.cliContributors;if(!contributors)return;for(let section of contribution.statusSections??[])contributors.addStatusSection?.(section);for(let check of contribution.doctorChecks??[])contributors.addDoctorCheck?.(check)}};var TelemetryEmitter=class{constructor(pluginName,pluginVersion,hostServices){this.pluginName=pluginName,this.pluginVersion=pluginVersion,this.hostServices=hostServices}pluginName;pluginVersion;hostServices;emit(eventName,payload){let target=this.hostServices?.telemetry;if(!target)return;target.emit(eventName,{plugin:this.pluginName,version:this.pluginVersion,timestamp:new Date().toISOString(),...payload??{}})}emitReady(context){this.emit(`${this.pluginName}.ready`,context)}emitError(error,context){this.emit(`${this.pluginName}.error`,{message:error.message,...context??{}})}emitEvent(type,payload){this.emit(type,payload)}};import{createCipheriv,createDecipheriv,randomBytes}from"crypto";class AgentDatabase{}var registry=new Map;function registerAdapter(name,factory){registry.set(name,factory)}var COLLECTIONS={tasks:"tasks",config:"config",gitRepos:"git_repositories",bookmarks:"bookmarked_commands",notifications:"notifications",pluginState:"plugin_state"},nowIso=()=>new Date().toISOString();function pluginStateId(pluginName,key){return`${pluginName}::${key}`}function deriveKey(hex){if(!/^[0-9a-fA-F]{64}$/.test(hex))throw Error("vibe-plugin-storage-postgres: encryption key must be a 64-character hex string (32 bytes)");return Buffer.from(hex,"hex")}function encrypt(plaintext,key){let iv=randomBytes(12),cipher=createCipheriv("aes-256-gcm",key,iv);return{ciphertext:Buffer.concat([cipher.update(plaintext,"utf8"),cipher.final()]),iv,tag:cipher.getAuthTag()}}function decrypt(blob,key){let decipher=createDecipheriv("aes-256-gcm",key,blob.iv);return decipher.setAuthTag(blob.tag),Buffer.concat([decipher.update(blob.ciphertext),decipher.final()]).toString("utf8")}class PostgresAgentDatabase extends AgentDatabase{pool;key;connStr;constructor(pool,key,connStr){super();this.pool=pool,this.key=key,this.connStr=connStr}async init(){await this.pool.query(`
|
|
11
12
|
CREATE TABLE IF NOT EXISTS documents (
|
|
12
13
|
collection text NOT NULL,
|
|
13
14
|
id text NOT NULL,
|
|
@@ -22,4 +23,4 @@ See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode de
|
|
|
22
23
|
CREATE INDEX IF NOT EXISTS idx_doc_updated_at ON documents (updated_at);
|
|
23
24
|
`)}async putDoc(collection,id,value,options){let json=JSON.stringify(value),blob=encrypt(json,this.key);if(options?.keepCreatedAt)await this.pool.query(`INSERT INTO documents (collection, id, ciphertext, iv, tag) VALUES ($1, $2, $3, $4, $5)
|
|
24
25
|
ON CONFLICT (collection, id) DO UPDATE SET ciphertext = EXCLUDED.ciphertext, iv = EXCLUDED.iv, tag = EXCLUDED.tag, updated_at = now()`,[collection,id,blob.ciphertext,blob.iv,blob.tag]);else await this.pool.query(`INSERT INTO documents (collection, id, ciphertext, iv, tag) VALUES ($1, $2, $3, $4, $5)
|
|
25
|
-
ON CONFLICT (collection, id) DO UPDATE SET ciphertext = EXCLUDED.ciphertext, iv = EXCLUDED.iv, tag = EXCLUDED.tag, updated_at = now()`,[collection,id,blob.ciphertext,blob.iv,blob.tag])}async getDoc(collection,id){let row=(await this.pool.query("SELECT id, ciphertext, iv, tag, created_at, updated_at FROM documents WHERE collection = $1 AND id = $2",[collection,id])).rows[0];if(!row)return null;let json=decrypt({ciphertext:row.ciphertext,iv:row.iv,tag:row.tag},this.key);return{collection,id:row.id,value:JSON.parse(json),createdAt:row.created_at.toISOString(),updatedAt:row.updated_at.toISOString()}}async listDocs(collection){return(await this.pool.query("SELECT id, ciphertext, iv, tag, created_at, updated_at FROM documents WHERE collection = $1 ORDER BY created_at DESC",[collection])).rows.map((row)=>{let r2=row,json=decrypt({ciphertext:r2.ciphertext,iv:r2.iv,tag:r2.tag},this.key);return{collection,id:r2.id,value:JSON.parse(json),createdAt:r2.created_at.toISOString(),updatedAt:r2.updated_at.toISOString()}})}async deleteDoc(collection,id){return((await this.pool.query("DELETE FROM documents WHERE collection = $1 AND id = $2",[collection,id])).rowCount??0)>0}async close(){await this.pool.end()}getDbPath(){return this.connStr}async createTask(task){let now=nowIso(),value={...task,createdAt:now,updatedAt:now};return await this.putDoc(COLLECTIONS.tasks,task.id,value),value}async getTask(id){return(await this.getDoc(COLLECTIONS.tasks,id))?.value}async getAllTasks(){return(await this.listDocs(COLLECTIONS.tasks)).map((d)=>d.value)}async getPendingTasks(){return(await this.getAllTasks()).filter((t)=>t.status==="pending")}async updateTask(id,updates){let existing=await this.getDoc(COLLECTIONS.tasks,id);if(!existing)return;let next={...existing.value,...updates,updatedAt:nowIso()};await this.putDoc(COLLECTIONS.tasks,id,next,{keepCreatedAt:!0})}async cancelTask(id){let existing=await this.getDoc(COLLECTIONS.tasks,id);if(!existing)return!1;if(existing.value.status==="completed"||existing.value.status==="failed")return!1;let next={...existing.value,status:"failed",error:"Cancelled by user",updatedAt:nowIso()};return await this.putDoc(COLLECTIONS.tasks,id,next,{keepCreatedAt:!0}),!0}async getConfig(key){return(await this.getDoc(COLLECTIONS.config,key))?.value.value}async setConfig(key,value){await this.putDoc(COLLECTIONS.config,key,{key,value})}async deleteConfig(key){return this.deleteDoc(COLLECTIONS.config,key)}async getAllConfig(){let docs=await this.listDocs(COLLECTIONS.config),out={};for(let d of docs)out[d.value.key]=d.value.value;return out}async bulkSetConfig(entries){for(let[k,v]of Object.entries(entries))await this.setConfig(k,v)}async getConfigStatus(){let row=(await this.pool.query("SELECT COUNT(*)::int AS n, MAX(updated_at) AS last_updated FROM documents WHERE collection = $1",[COLLECTIONS.config])).rows[0];return{totalKeys:row.n,lastUpdated:row.last_updated?row.last_updated.toISOString():null}}async createGitRepository(repo){let now=nowIso(),value={...repo,createdAt:now,lastScanned:now};return await this.putDoc(COLLECTIONS.gitRepos,repo.id,value),value}async getGitRepository(id){return(await this.getDoc(COLLECTIONS.gitRepos,id))?.value}async getGitRepositoryByPath(path){return(await this.listDocs(COLLECTIONS.gitRepos)).find((d)=>d.value.path===path)?.value}async getAllGitRepositories(){return(await this.listDocs(COLLECTIONS.gitRepos)).map((d)=>d.value)}async updateGitRepository(id,updates){let existing=await this.getDoc(COLLECTIONS.gitRepos,id);if(!existing)return;let next={...existing.value,...updates,lastScanned:nowIso()};await this.putDoc(COLLECTIONS.gitRepos,id,next,{keepCreatedAt:!0})}async deleteGitRepository(id){return this.deleteDoc(COLLECTIONS.gitRepos,id)}async fixGitHierarchy(){let all=await this.getAllGitRepositories(),byPath=new Map(all.map((r)=>[r.path,r])),fixed=0;for(let repo of all){let segments=repo.path.split("/").filter(Boolean),parent;for(let i=segments.length-1;i>0;i--){let candidate="/"+segments.slice(0,i).join("/");if(byPath.has(candidate)&&candidate!==repo.path){parent=candidate;break}}if(parent!==repo.parentPath)await this.updateGitRepository(repo.id,{parentPath:parent}),fixed+=1}return{fixed}}async createBookmarkedCommand(cmd){let value={...cmd,createdAt:nowIso()};return await this.putDoc(COLLECTIONS.bookmarks,cmd.id,value),value}async getBookmarkedCommand(id){return(await this.getDoc(COLLECTIONS.bookmarks,id))?.value}async getAllBookmarkedCommands(){return(await this.listDocs(COLLECTIONS.bookmarks)).map((d)=>d.value)}async getBookmarkedCommandsByProject(projectId){return(await this.getAllBookmarkedCommands()).filter((c)=>projectId===null?c.projectId===void 0||c.projectId===null:c.projectId===projectId)}async getBookmarkedCommandsByCategory(category){return(await this.getAllBookmarkedCommands()).filter((c)=>c.category===category)}async updateBookmarkedCommand(id,updates){let existing=await this.getDoc(COLLECTIONS.bookmarks,id);if(!existing)return;let next={...existing.value,...updates};await this.putDoc(COLLECTIONS.bookmarks,id,next,{keepCreatedAt:!0})}async deleteBookmarkedCommand(id){return this.deleteDoc(COLLECTIONS.bookmarks,id)}async executeBookmarkedCommand(id){return this.getBookmarkedCommand(id)}async createNotification(notification){let value={...notification,createdAt:nowIso()};return await this.putDoc(COLLECTIONS.notifications,notification.id,value),value}async getNotification(id){return(await this.getDoc(COLLECTIONS.notifications,id))?.value}async getAllNotifications(){return(await this.listDocs(COLLECTIONS.notifications)).map((d)=>d.value)}async getNotificationsByProject(projectId){return(await this.getAllNotifications()).filter((n)=>projectId===null?n.projectId===void 0||n.projectId===null:n.projectId===projectId)}async getGlobalNotifications(){return(await this.getAllNotifications()).filter((n)=>!n.projectId)}async getUnreadNotifications(){return(await this.getAllNotifications()).filter((n)=>n.status==="unread")}async updateNotificationStatus(id,status){let existing=await this.getDoc(COLLECTIONS.notifications,id);if(!existing)return;let next={...existing.value,status};await this.putDoc(COLLECTIONS.notifications,id,next,{keepCreatedAt:!0})}async markAllNotificationsRead(){let all=await this.getAllNotifications(),count=0;for(let n of all)if(n.status==="unread")await this.updateNotificationStatus(n.id,"read"),count+=1;return count}async deleteNotification(id){return this.deleteDoc(COLLECTIONS.notifications,id)}async clearOldNotifications(olderThanDays=30){let cutoff=Date.now()-olderThanDays*86400000,all=await this.getAllNotifications(),count=0;for(let n of all)if(Date.parse(n.createdAt)<cutoff)await this.deleteDoc(COLLECTIONS.notifications,n.id),count+=1;return count}async getPluginState(pluginName,key){return(await this.getDoc(COLLECTIONS.pluginState,pluginStateId(pluginName,key)))?.value.value}async setPluginState(pluginName,key,value){await this.putDoc(COLLECTIONS.pluginState,pluginStateId(pluginName,key),{pluginName,key,value})}async deletePluginState(pluginName,key){return this.deleteDoc(COLLECTIONS.pluginState,pluginStateId(pluginName,key))}async getAllPluginState(pluginName){return(await this.listDocs(COLLECTIONS.pluginState)).filter((d)=>d.value.pluginName===pluginName).map((d)=>({key:d.value.key,value:d.value.value,updatedAt:d.updatedAt}))}async deleteAllPluginState(pluginName){return(await this.pool.query("DELETE FROM documents WHERE collection = $1 AND id LIKE $2",[COLLECTIONS.pluginState,`${pluginName}::%`])).rowCount??0}}var createPostgresAgentDatabase=async(opts)=>{let connStr,fromOptions=opts.adapterOptions?.connectionString;if(fromOptions)connStr=fromOptions;else if(opts.dataDir&&/^(postgres|postgresql):\/\//.test(opts.dataDir))connStr=opts.dataDir;else if(process.env.VIBE_POSTGRES_URL)connStr=process.env.VIBE_POSTGRES_URL;if(!connStr)throw Error("vibe-plugin-storage-postgres: connection string required. Pass via adapterOptions.connectionString (preferred), set VIBE_POSTGRES_URL, or pass a postgres:// URL as dbPath.");let key=deriveKey(opts.encryptionKey),pgModule=await Promise.resolve().then(() => (init_esm(),exports_esm)),PoolCtor=pgModule.Pool??pgModule.default?.Pool;if(!PoolCtor)throw Error("vibe-plugin-storage-postgres: failed to load 'pg' module");let pool=new PoolCtor({connectionString:connStr}),adapter=new PostgresAgentDatabase(pool,key,connStr);return await adapter.init(),adapter};registerAdapter("postgres",createPostgresAgentDatabase);var
|
|
26
|
+
ON CONFLICT (collection, id) DO UPDATE SET ciphertext = EXCLUDED.ciphertext, iv = EXCLUDED.iv, tag = EXCLUDED.tag, updated_at = now()`,[collection,id,blob.ciphertext,blob.iv,blob.tag])}async getDoc(collection,id){let row=(await this.pool.query("SELECT id, ciphertext, iv, tag, created_at, updated_at FROM documents WHERE collection = $1 AND id = $2",[collection,id])).rows[0];if(!row)return null;let json=decrypt({ciphertext:row.ciphertext,iv:row.iv,tag:row.tag},this.key);return{collection,id:row.id,value:JSON.parse(json),createdAt:row.created_at.toISOString(),updatedAt:row.updated_at.toISOString()}}async listDocs(collection){return(await this.pool.query("SELECT id, ciphertext, iv, tag, created_at, updated_at FROM documents WHERE collection = $1 ORDER BY created_at DESC",[collection])).rows.map((row)=>{let r2=row,json=decrypt({ciphertext:r2.ciphertext,iv:r2.iv,tag:r2.tag},this.key);return{collection,id:r2.id,value:JSON.parse(json),createdAt:r2.created_at.toISOString(),updatedAt:r2.updated_at.toISOString()}})}async deleteDoc(collection,id){return((await this.pool.query("DELETE FROM documents WHERE collection = $1 AND id = $2",[collection,id])).rowCount??0)>0}async close(){await this.pool.end()}getDbPath(){return this.connStr}async createTask(task){let now=nowIso(),value={...task,createdAt:now,updatedAt:now};return await this.putDoc(COLLECTIONS.tasks,task.id,value),value}async getTask(id){return(await this.getDoc(COLLECTIONS.tasks,id))?.value}async getAllTasks(){return(await this.listDocs(COLLECTIONS.tasks)).map((d)=>d.value)}async getPendingTasks(){return(await this.getAllTasks()).filter((t)=>t.status==="pending")}async updateTask(id,updates){let existing=await this.getDoc(COLLECTIONS.tasks,id);if(!existing)return;let next={...existing.value,...updates,updatedAt:nowIso()};await this.putDoc(COLLECTIONS.tasks,id,next,{keepCreatedAt:!0})}async cancelTask(id){let existing=await this.getDoc(COLLECTIONS.tasks,id);if(!existing)return!1;if(existing.value.status==="completed"||existing.value.status==="failed")return!1;let next={...existing.value,status:"failed",error:"Cancelled by user",updatedAt:nowIso()};return await this.putDoc(COLLECTIONS.tasks,id,next,{keepCreatedAt:!0}),!0}async getConfig(key){return(await this.getDoc(COLLECTIONS.config,key))?.value.value}async setConfig(key,value){await this.putDoc(COLLECTIONS.config,key,{key,value})}async deleteConfig(key){return this.deleteDoc(COLLECTIONS.config,key)}async getAllConfig(){let docs=await this.listDocs(COLLECTIONS.config),out={};for(let d of docs)out[d.value.key]=d.value.value;return out}async bulkSetConfig(entries){for(let[k,v]of Object.entries(entries))await this.setConfig(k,v)}async getConfigStatus(){let row=(await this.pool.query("SELECT COUNT(*)::int AS n, MAX(updated_at) AS last_updated FROM documents WHERE collection = $1",[COLLECTIONS.config])).rows[0];return{totalKeys:row.n,lastUpdated:row.last_updated?row.last_updated.toISOString():null}}async createGitRepository(repo){let now=nowIso(),value={...repo,createdAt:now,lastScanned:now};return await this.putDoc(COLLECTIONS.gitRepos,repo.id,value),value}async getGitRepository(id){return(await this.getDoc(COLLECTIONS.gitRepos,id))?.value}async getGitRepositoryByPath(path){return(await this.listDocs(COLLECTIONS.gitRepos)).find((d)=>d.value.path===path)?.value}async getAllGitRepositories(){return(await this.listDocs(COLLECTIONS.gitRepos)).map((d)=>d.value)}async updateGitRepository(id,updates){let existing=await this.getDoc(COLLECTIONS.gitRepos,id);if(!existing)return;let next={...existing.value,...updates,lastScanned:nowIso()};await this.putDoc(COLLECTIONS.gitRepos,id,next,{keepCreatedAt:!0})}async deleteGitRepository(id){return this.deleteDoc(COLLECTIONS.gitRepos,id)}async fixGitHierarchy(){let all=await this.getAllGitRepositories(),byPath=new Map(all.map((r)=>[r.path,r])),fixed=0;for(let repo of all){let segments=repo.path.split("/").filter(Boolean),parent;for(let i=segments.length-1;i>0;i--){let candidate="/"+segments.slice(0,i).join("/");if(byPath.has(candidate)&&candidate!==repo.path){parent=candidate;break}}if(parent!==repo.parentPath)await this.updateGitRepository(repo.id,{parentPath:parent}),fixed+=1}return{fixed}}async createBookmarkedCommand(cmd){let value={...cmd,createdAt:nowIso()};return await this.putDoc(COLLECTIONS.bookmarks,cmd.id,value),value}async getBookmarkedCommand(id){return(await this.getDoc(COLLECTIONS.bookmarks,id))?.value}async getAllBookmarkedCommands(){return(await this.listDocs(COLLECTIONS.bookmarks)).map((d)=>d.value)}async getBookmarkedCommandsByProject(projectId){return(await this.getAllBookmarkedCommands()).filter((c)=>projectId===null?c.projectId===void 0||c.projectId===null:c.projectId===projectId)}async getBookmarkedCommandsByCategory(category){return(await this.getAllBookmarkedCommands()).filter((c)=>c.category===category)}async updateBookmarkedCommand(id,updates){let existing=await this.getDoc(COLLECTIONS.bookmarks,id);if(!existing)return;let next={...existing.value,...updates};await this.putDoc(COLLECTIONS.bookmarks,id,next,{keepCreatedAt:!0})}async deleteBookmarkedCommand(id){return this.deleteDoc(COLLECTIONS.bookmarks,id)}async executeBookmarkedCommand(id){return this.getBookmarkedCommand(id)}async createNotification(notification){let value={...notification,createdAt:nowIso()};return await this.putDoc(COLLECTIONS.notifications,notification.id,value),value}async getNotification(id){return(await this.getDoc(COLLECTIONS.notifications,id))?.value}async getAllNotifications(){return(await this.listDocs(COLLECTIONS.notifications)).map((d)=>d.value)}async getNotificationsByProject(projectId){return(await this.getAllNotifications()).filter((n)=>projectId===null?n.projectId===void 0||n.projectId===null:n.projectId===projectId)}async getGlobalNotifications(){return(await this.getAllNotifications()).filter((n)=>!n.projectId)}async getUnreadNotifications(){return(await this.getAllNotifications()).filter((n)=>n.status==="unread")}async updateNotificationStatus(id,status){let existing=await this.getDoc(COLLECTIONS.notifications,id);if(!existing)return;let next={...existing.value,status};await this.putDoc(COLLECTIONS.notifications,id,next,{keepCreatedAt:!0})}async markAllNotificationsRead(){let all=await this.getAllNotifications(),count=0;for(let n of all)if(n.status==="unread")await this.updateNotificationStatus(n.id,"read"),count+=1;return count}async deleteNotification(id){return this.deleteDoc(COLLECTIONS.notifications,id)}async clearOldNotifications(olderThanDays=30){let cutoff=Date.now()-olderThanDays*86400000,all=await this.getAllNotifications(),count=0;for(let n of all)if(Date.parse(n.createdAt)<cutoff)await this.deleteDoc(COLLECTIONS.notifications,n.id),count+=1;return count}async getPluginState(pluginName,key){return(await this.getDoc(COLLECTIONS.pluginState,pluginStateId(pluginName,key)))?.value.value}async setPluginState(pluginName,key,value){await this.putDoc(COLLECTIONS.pluginState,pluginStateId(pluginName,key),{pluginName,key,value})}async deletePluginState(pluginName,key){return this.deleteDoc(COLLECTIONS.pluginState,pluginStateId(pluginName,key))}async getAllPluginState(pluginName){return(await this.listDocs(COLLECTIONS.pluginState)).filter((d)=>d.value.pluginName===pluginName).map((d)=>({key:d.value.key,value:d.value.value,updatedAt:d.updatedAt}))}async deleteAllPluginState(pluginName){return(await this.pool.query("DELETE FROM documents WHERE collection = $1 AND id LIKE $2",[COLLECTIONS.pluginState,`${pluginName}::%`])).rowCount??0}}var createPostgresAgentDatabase=async(opts)=>{let connStr,fromOptions=opts.adapterOptions?.connectionString;if(fromOptions)connStr=fromOptions;else if(opts.dataDir&&/^(postgres|postgresql):\/\//.test(opts.dataDir))connStr=opts.dataDir;else if(process.env.VIBE_POSTGRES_URL)connStr=process.env.VIBE_POSTGRES_URL;if(!connStr)throw Error("vibe-plugin-storage-postgres: connection string required. Pass via adapterOptions.connectionString (preferred), set VIBE_POSTGRES_URL, or pass a postgres:// URL as dbPath.");let key=deriveKey(opts.encryptionKey),pgModule=await Promise.resolve().then(() => (init_esm(),exports_esm)),PoolCtor=pgModule.Pool??pgModule.default?.Pool;if(!PoolCtor)throw Error("vibe-plugin-storage-postgres: failed to load 'pg' module");let pool=new PoolCtor({connectionString:connStr}),adapter=new PostgresAgentDatabase(pool,key,connStr);return await adapter.init(),adapter};registerAdapter("postgres",createPostgresAgentDatabase);var PLUGIN_NAME="storage-postgres",PLUGIN_VERSION="2026.509.2",createPlugin=(ctx)=>{let log=new BoundLogger(ctx.logger,PLUGIN_NAME),lifecycle=createLifecycleHooks({name:PLUGIN_NAME,telemetryEventName:"storage-postgres.ready",onInit:(hostServices)=>{new ProviderRegistry(hostServices).registerProvider("storage","postgres",createPostgresAgentDatabase),new TelemetryEmitter(PLUGIN_NAME,PLUGIN_VERSION,hostServices).emit("storage-postgres.registered",{adapter:"postgres"}),log.info("postgres storage adapter registered with host ProviderRegistry")}});return{name:PLUGIN_NAME,version:PLUGIN_VERSION,description:"PostgreSQL encrypted storage adapter (registers via side-effect import).",tags:["backend","adapter","provider"],capabilities:{storage:"rw",secrets:"read"},onServerStart:lifecycle.onServerStart,onServerStop:lifecycle.onServerStop}},vibePlugin={name:PLUGIN_NAME,version:PLUGIN_VERSION,description:"PostgreSQL encrypted storage adapter (registers via side-effect import).",tags:["backend","adapter","provider"],capabilities:{storage:"rw",secrets:"read"}},src_default=createPlugin;export{vibePlugin,src_default as default,createPostgresAgentDatabase,createPlugin};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vibecontrols/vibe-plugin-storage-postgres",
|
|
3
|
-
"version": "2026.509.
|
|
3
|
+
"version": "2026.509.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -21,13 +21,14 @@
|
|
|
21
21
|
"format": "bunx prettier . --write",
|
|
22
22
|
"format:check": "bunx prettier . --check",
|
|
23
23
|
"type:check": "tsc --noEmit",
|
|
24
|
-
"test": "bun test tests
|
|
24
|
+
"test": "bun test tests/",
|
|
25
25
|
"clean": "rimraf dist",
|
|
26
26
|
"prebuild": "bun run clean",
|
|
27
27
|
"prepublishOnly": "bun run build",
|
|
28
28
|
"sanity": "bun run format:check && bun run lint && bun run type:check && bun run test && bun run build"
|
|
29
29
|
},
|
|
30
30
|
"dependencies": {
|
|
31
|
+
"@vibecontrols/plugin-sdk": "2026.509.1",
|
|
31
32
|
"pg": "^8.13.1"
|
|
32
33
|
},
|
|
33
34
|
"devDependencies": {
|
|
@@ -43,7 +44,7 @@
|
|
|
43
44
|
"typescript-eslint": "^8.56.0"
|
|
44
45
|
},
|
|
45
46
|
"peerDependencies": {
|
|
46
|
-
"@vibecontrols/vibe-plugin-storage": "2026.509.
|
|
47
|
+
"@vibecontrols/vibe-plugin-storage": "2026.509.2",
|
|
47
48
|
"@vibecontrols/agent": ">=2026.428.0"
|
|
48
49
|
},
|
|
49
50
|
"peerDependenciesMeta": {
|