@vibecontrols/vibe-plugin-storage-postgres 2026.510.1 → 2026.1109.1
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/LICENSE +25 -0
- package/README.md +69 -0
- package/dist/index.js +5 -5
- package/package.json +40 -25
package/LICENSE
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Burdenoff Consultancy Services Private Limited,
|
|
4
|
+
Algoshred Technologies Private Limited,
|
|
5
|
+
and all its sister companies.
|
|
6
|
+
|
|
7
|
+
Maintainer: Vignesh T.V <https://github.com/tvvignesh>
|
|
8
|
+
|
|
9
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
10
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
11
|
+
in the Software without restriction, including without limitation the rights
|
|
12
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
13
|
+
copies of the Software, and to permit persons to whom the Software is furnished
|
|
14
|
+
to do so, subject to the following conditions:
|
|
15
|
+
|
|
16
|
+
The above copyright notice and this permission notice shall be included in all
|
|
17
|
+
copies or substantial portions of the Software.
|
|
18
|
+
|
|
19
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
21
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
22
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
23
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
24
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
25
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# @vibecontrols/vibe-plugin-storage-postgres
|
|
2
|
+
|
|
3
|
+
<!-- VIBECONTROLS_OSS_BODY_START -->
|
|
4
|
+
|
|
5
|
+
> Full-parity PostgreSQL storage provider with AES-256-GCM encryption — share state across multiple agents.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
vibe plugin install @vibecontrols/vibe-plugin-storage-postgres
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Or install the npm package directly into an existing project that hosts the VibeControls agent:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
bun add @vibecontrols/vibe-plugin-storage-postgres
|
|
17
|
+
# or
|
|
18
|
+
npm install @vibecontrols/vibe-plugin-storage-postgres
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## How it works
|
|
22
|
+
|
|
23
|
+
Storage **providers** implement the `AgentDatabase` contract from `@vibecontrols/vibe-plugin-storage` (meta) so the agent's persistence layer is pluggable across embedded and server backends.
|
|
24
|
+
|
|
25
|
+
This package is a **provider** registered against the `@vibecontrols/vibe-plugin-storage` meta plugin. Install the meta plugin first; this provider plugs into it.
|
|
26
|
+
|
|
27
|
+
## Upstream
|
|
28
|
+
|
|
29
|
+
- **PostgreSQL** — <https://www.postgresql.org/>
|
|
30
|
+
|
|
31
|
+
## More
|
|
32
|
+
|
|
33
|
+
- npm: <https://www.npmjs.com/package/@vibecontrols/vibe-plugin-storage-postgres>
|
|
34
|
+
- Source: <https://github.com/algoshred/vibe-plugin-storage-postgres>
|
|
35
|
+
- Plugin contract / SDK: <https://github.com/algoshred/vibecontrols-plugin-sdk>
|
|
36
|
+
- Plugin catalogue: <https://vibecontrols.com/plugins/storage-postgres>
|
|
37
|
+
|
|
38
|
+
<!-- VIBECONTROLS_OSS_BODY_END -->
|
|
39
|
+
|
|
40
|
+
<!-- VIBECONTROLS_OSS_FOOTER_START -->
|
|
41
|
+
|
|
42
|
+
---
|
|
43
|
+
|
|
44
|
+
## About VibeControls
|
|
45
|
+
|
|
46
|
+
**VibeControls** is the agentic engineering mission control for AI-native teams. Vibe-plugins extend the VibeControls agent with new providers, tools, sessions, tunnels, storage backends, and security stages.
|
|
47
|
+
|
|
48
|
+
- Website: <https://vibecontrols.com>
|
|
49
|
+
- Documentation: <https://docs.vibecontrols.com>
|
|
50
|
+
- Plugin SDK: <https://github.com/algoshred/vibecontrols-plugin-sdk>
|
|
51
|
+
- All plugins: <https://github.com/algoshred?q=vibe-plugin-&type=all>
|
|
52
|
+
|
|
53
|
+
## Credits
|
|
54
|
+
|
|
55
|
+
This plugin builds on the following upstream open-source projects. All trademarks and copyrights remain with their respective owners.
|
|
56
|
+
|
|
57
|
+
- **PostgreSQL** — <https://www.postgresql.org/>
|
|
58
|
+
|
|
59
|
+
## License
|
|
60
|
+
|
|
61
|
+
Released under the [MIT License](./LICENSE).
|
|
62
|
+
|
|
63
|
+
Copyright (c) 2026 Burdenoff Consultancy Services Private Limited, Algoshred Technologies Private Limited, and all its sister companies.
|
|
64
|
+
|
|
65
|
+
Maintainer: **Vignesh T.V** — <https://github.com/tvvignesh>
|
|
66
|
+
|
|
67
|
+
**Note**: this plugin is open source under MIT. The `@vibecontrols/agent` runtime that loads and orchestrates plugins is **closed source** and proprietary to Burdenoff Consultancy Services Pvt. Ltd. If you want a fully self-hostable agent, please open an issue or contact the maintainer.
|
|
68
|
+
|
|
69
|
+
<!-- VIBECONTROLS_OSS_FOOTER_END -->
|
package/dist/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames}=Object;var __hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to};var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn,res)=>()=>(fn&&(res=fn(fn=0)),res);var __require=import.meta.require;var require_postgres_array=__commonJS((exports)=>{exports.parse=function(source,transform){return new ArrayParser(source,transform).parse()};class ArrayParser{constructor(source,transform){this.source=source,this.transform=transform||identity,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var character=this.source[this.position++];if(character==="\\")return{value:this.source[this.position++],escaped:!0};return{value:character,escaped:!1}}record(character){this.recorded.push(character)}newEntry(includeEmpty){var entry;if(this.recorded.length>0||includeEmpty){if(entry=this.recorded.join(""),entry==="NULL"&&!includeEmpty)entry=null;if(entry!==null)entry=this.transform(entry);this.entries.push(entry),this.recorded=[]}}consumeDimensions(){if(this.source[0]==="[")while(!this.isEof()){var char=this.nextCharacter();if(char.value==="=")break}}parse(nested){var character,parser,quote;this.consumeDimensions();while(!this.isEof())if(character=this.nextCharacter(),character.value==="{"&&!quote){if(this.dimension++,this.dimension>1)parser=new ArrayParser(this.source.substr(this.position-1),this.transform),this.entries.push(parser.parse(!0)),this.position+=parser.position-2}else if(character.value==="}"&&!quote){if(this.dimension--,!this.dimension){if(this.newEntry(),nested)return this.entries}}else if(character.value==='"'&&!character.escaped){if(quote)this.newEntry(!0);quote=!quote}else if(character.value===","&&!quote)this.newEntry();else this.record(character.value);if(this.dimension!==0)throw Error("array dimension not balanced");return this.entries}}function identity(value){return value}});var require_arrayParser=__commonJS((exports,module)=>{var array=require_postgres_array();module.exports={create:function(source,transform){return{parse:function(){return array.parse(source,transform)}}}}});var require_postgres_date=__commonJS((exports,module)=>{var DATE_TIME=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,DATE=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,TIME_ZONE=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,INFINITY=/^-?infinity$/;module.exports=function(isoDate){if(INFINITY.test(isoDate))return Number(isoDate.replace("i","I"));var matches=DATE_TIME.exec(isoDate);if(!matches)return getDate(isoDate)||null;var isBC=!!matches[8],year=parseInt(matches[1],10);if(isBC)year=bcYearToNegativeYear(year);var month=parseInt(matches[2],10)-1,day=matches[3],hour=parseInt(matches[4],10),minute=parseInt(matches[5],10),second=parseInt(matches[6],10),ms=matches[7];ms=ms?1000*parseFloat(ms):0;var date,offset=timeZoneOffset(isoDate);if(offset!=null){if(date=new Date(Date.UTC(year,month,day,hour,minute,second,ms)),is0To99(year))date.setUTCFullYear(year);if(offset!==0)date.setTime(date.getTime()-offset)}else if(date=new Date(year,month,day,hour,minute,second,ms),is0To99(year))date.setFullYear(year);return date};function getDate(isoDate){var matches=DATE.exec(isoDate);if(!matches)return;var year=parseInt(matches[1],10),isBC=!!matches[4];if(isBC)year=bcYearToNegativeYear(year);var month=parseInt(matches[2],10)-1,day=matches[3],date=new Date(year,month,day);if(is0To99(year))date.setFullYear(year);return date}function timeZoneOffset(isoDate){if(isoDate.endsWith("+00"))return 0;var zone=TIME_ZONE.exec(isoDate.split(" ")[1]);if(!zone)return;var type=zone[1];if(type==="Z")return 0;var sign=type==="-"?-1:1,offset=parseInt(zone[2],10)*3600+parseInt(zone[3]||0,10)*60+parseInt(zone[4]||0,10);return offset*sign*1000}function bcYearToNegativeYear(year){return-(year-1)}function is0To99(num){return num>=0&&num<100}});var require_mutable=__commonJS((exports,module)=>{module.exports=extend;var hasOwnProperty=Object.prototype.hasOwnProperty;function extend(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)if(hasOwnProperty.call(source,key))target[key]=source[key]}return target}});var require_postgres_interval=__commonJS((exports,module)=>{var extend=require_mutable();module.exports=PostgresInterval;function PostgresInterval(raw){if(!(this instanceof PostgresInterval))return new PostgresInterval(raw);extend(this,parse(raw))}var properties=["seconds","minutes","hours","days","months","years"];PostgresInterval.prototype.toPostgres=function(){var filtered=properties.filter(this.hasOwnProperty,this);if(this.milliseconds&&filtered.indexOf("seconds")<0)filtered.push("seconds");if(filtered.length===0)return"0";return filtered.map(function(property){var value=this[property]||0;if(property==="seconds"&&this.milliseconds)value=(value+this.milliseconds/1000).toFixed(6).replace(/\.?0+$/,"");return value+" "+property},this).join(" ")};var propertiesISOEquivalent={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},dateProperties=["years","months","days"],timeProperties=["hours","minutes","seconds"];PostgresInterval.prototype.toISOString=PostgresInterval.prototype.toISO=function(){var datePart=dateProperties.map(buildProperty,this).join(""),timePart=timeProperties.map(buildProperty,this).join("");return"P"+datePart+"T"+timePart;function buildProperty(property){var value=this[property]||0;if(property==="seconds"&&this.milliseconds)value=(value+this.milliseconds/1000).toFixed(6).replace(/0+$/,"");return value+propertiesISOEquivalent[property]}};var NUMBER="([+-]?\\d+)",YEAR=NUMBER+"\\s+years?",MONTH=NUMBER+"\\s+mons?",DAY=NUMBER+"\\s+days?",TIME="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",INTERVAL=new RegExp([YEAR,MONTH,DAY,TIME].map(function(regexString){return"("+regexString+")?"}).join("\\s*")),positions={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},negatives=["hours","minutes","seconds","milliseconds"];function parseMilliseconds(fraction){var microseconds=fraction+"000000".slice(fraction.length);return parseInt(microseconds,10)/1000}function parse(interval){if(!interval)return{};var matches=INTERVAL.exec(interval),isNegative=matches[8]==="-";return Object.keys(positions).reduce(function(parsed,property){var position=positions[property],value=matches[position];if(!value)return parsed;if(value=property==="milliseconds"?parseMilliseconds(value):parseInt(value,10),!value)return parsed;if(isNegative&&~negatives.indexOf(property))value*=-1;return parsed[property]=value,parsed},{})}});var require_postgres_bytea=__commonJS((exports,module)=>{var bufferFrom=Buffer.from||Buffer;module.exports=function(input){if(/^\\x/.test(input))return bufferFrom(input.substr(2),"hex");var output="",i=0;while(i<input.length)if(input[i]!=="\\")output+=input[i],++i;else if(/[0-7]{3}/.test(input.substr(i+1,3)))output+=String.fromCharCode(parseInt(input.substr(i+1,3),8)),i+=4;else{var backslashes=1;while(i+backslashes<input.length&&input[i+backslashes]==="\\")backslashes++;for(var k=0;k<Math.floor(backslashes/2);++k)output+="\\";i+=Math.floor(backslashes/2)*2}return bufferFrom(output,"binary")}});var require_textParsers=__commonJS((exports,module)=>{var array=require_postgres_array(),arrayParser=require_arrayParser(),parseDate=require_postgres_date(),parseInterval=require_postgres_interval(),parseByteA=require_postgres_bytea();function allowNull(fn){return function(value){if(value===null)return value;return fn(value)}}function parseBool(value){if(value===null)return value;return value==="TRUE"||value==="t"||value==="true"||value==="y"||value==="yes"||value==="on"||value==="1"}function parseBoolArray(value){if(!value)return null;return array.parse(value,parseBool)}function parseBaseTenInt(string){return parseInt(string,10)}function parseIntegerArray(value){if(!value)return null;return array.parse(value,allowNull(parseBaseTenInt))}function parseBigIntegerArray(value){if(!value)return null;return array.parse(value,allowNull(function(entry){return parseBigInteger(entry).trim()}))}var parsePointArray=function(value){if(!value)return null;var p=arrayParser.create(value,function(entry){if(entry!==null)entry=parsePoint(entry);return entry});return p.parse()},parseFloatArray=function(value){if(!value)return null;var p=arrayParser.create(value,function(entry){if(entry!==null)entry=parseFloat(entry);return entry});return p.parse()},parseStringArray=function(value){if(!value)return null;var p=arrayParser.create(value);return p.parse()},parseDateArray=function(value){if(!value)return null;var p=arrayParser.create(value,function(entry){if(entry!==null)entry=parseDate(entry);return entry});return p.parse()},parseIntervalArray=function(value){if(!value)return null;var p=arrayParser.create(value,function(entry){if(entry!==null)entry=parseInterval(entry);return entry});return p.parse()},parseByteAArray=function(value){if(!value)return null;return array.parse(value,allowNull(parseByteA))},parseInteger=function(value){return parseInt(value,10)},parseBigInteger=function(value){var valStr=String(value);if(/^\d+$/.test(valStr))return valStr;return value},parseJsonArray=function(value){if(!value)return null;return array.parse(value,allowNull(JSON.parse))},parsePoint=function(value){if(value[0]!=="(")return null;return value=value.substring(1,value.length-1).split(","),{x:parseFloat(value[0]),y:parseFloat(value[1])}},parseCircle=function(value){if(value[0]!=="<"&&value[1]!=="(")return null;var point="(",radius="",pointParsed=!1;for(var i=2;i<value.length-1;i++){if(!pointParsed)point+=value[i];if(value[i]===")"){pointParsed=!0;continue}else if(!pointParsed)continue;if(value[i]===",")continue;radius+=value[i]}var result=parsePoint(point);return result.radius=parseFloat(radius),result},init=function(register){register(20,parseBigInteger),register(21,parseInteger),register(23,parseInteger),register(26,parseInteger),register(700,parseFloat),register(701,parseFloat),register(16,parseBool),register(1082,parseDate),register(1114,parseDate),register(1184,parseDate),register(600,parsePoint),register(651,parseStringArray),register(718,parseCircle),register(1000,parseBoolArray),register(1001,parseByteAArray),register(1005,parseIntegerArray),register(1007,parseIntegerArray),register(1028,parseIntegerArray),register(1016,parseBigIntegerArray),register(1017,parsePointArray),register(1021,parseFloatArray),register(1022,parseFloatArray),register(1231,parseFloatArray),register(1014,parseStringArray),register(1015,parseStringArray),register(1008,parseStringArray),register(1009,parseStringArray),register(1040,parseStringArray),register(1041,parseStringArray),register(1115,parseDateArray),register(1182,parseDateArray),register(1185,parseDateArray),register(1186,parseInterval),register(1187,parseIntervalArray),register(17,parseByteA),register(114,JSON.parse.bind(JSON)),register(3802,JSON.parse.bind(JSON)),register(199,parseJsonArray),register(3807,parseJsonArray),register(3907,parseStringArray),register(2951,parseStringArray),register(791,parseStringArray),register(1183,parseStringArray),register(1270,parseStringArray)};module.exports={init}});var require_pg_int8=__commonJS((exports,module)=>{var BASE=1e6;function readInt8(buffer){var high=buffer.readInt32BE(0),low=buffer.readUInt32BE(4),sign="";if(high<0)high=~high+(low===0),low=~low+1>>>0,sign="-";var result="",carry,t,digits,pad,l,i;{if(carry=high%BASE,high=high/BASE>>>0,t=4294967296*carry+low,low=t/BASE>>>0,digits=""+(t-BASE*low),low===0&&high===0)return sign+digits+result;pad="",l=6-digits.length;for(i=0;i<l;i++)pad+="0";result=pad+digits+result}{if(carry=high%BASE,high=high/BASE>>>0,t=4294967296*carry+low,low=t/BASE>>>0,digits=""+(t-BASE*low),low===0&&high===0)return sign+digits+result;pad="",l=6-digits.length;for(i=0;i<l;i++)pad+="0";result=pad+digits+result}{if(carry=high%BASE,high=high/BASE>>>0,t=4294967296*carry+low,low=t/BASE>>>0,digits=""+(t-BASE*low),low===0&&high===0)return sign+digits+result;pad="",l=6-digits.length;for(i=0;i<l;i++)pad+="0";result=pad+digits+result}return carry=high%BASE,t=4294967296*carry+low,digits=""+t%BASE,sign+digits+result}module.exports=readInt8});var require_binaryParsers=__commonJS((exports,module)=>{var parseInt64=require_pg_int8(),parseBits=function(data,bits,offset,invert,callback){offset=offset||0,invert=invert||!1,callback=callback||function(lastValue,newValue,bits2){return lastValue*Math.pow(2,bits2)+newValue};var offsetBytes=offset>>3,inv=function(value){if(invert)return~value&255;return value},mask=255,firstBits=8-offset%8;if(bits<firstBits)mask=255<<8-bits&255,firstBits=bits;if(offset)mask=mask>>offset%8;var result=0;if(offset%8+bits>=8)result=callback(0,inv(data[offsetBytes])&mask,firstBits);var bytes=bits+offset>>3;for(var i=offsetBytes+1;i<bytes;i++)result=callback(result,inv(data[i]),8);var lastBits=(bits+offset)%8;if(lastBits>0)result=callback(result,inv(data[bytes])>>8-lastBits,lastBits);return result},parseFloatFromBits=function(data,precisionBits,exponentBits){var bias=Math.pow(2,exponentBits-1)-1,sign=parseBits(data,1),exponent=parseBits(data,exponentBits,1);if(exponent===0)return 0;var precisionBitsCounter=1,parsePrecisionBits=function(lastValue,newValue,bits){if(lastValue===0)lastValue=1;for(var i=1;i<=bits;i++)if(precisionBitsCounter/=2,(newValue&1<<bits-i)>0)lastValue+=precisionBitsCounter;return lastValue},mantissa=parseBits(data,precisionBits,exponentBits+1,!1,parsePrecisionBits);if(exponent==Math.pow(2,exponentBits+1)-1){if(mantissa===0)return sign===0?1/0:-1/0;return NaN}return(sign===0?1:-1)*Math.pow(2,exponent-bias)*mantissa},parseInt16=function(value){if(parseBits(value,1)==1)return-1*(parseBits(value,15,1,!0)+1);return parseBits(value,15,1)},parseInt32=function(value){if(parseBits(value,1)==1)return-1*(parseBits(value,31,1,!0)+1);return parseBits(value,31,1)},parseFloat32=function(value){return parseFloatFromBits(value,23,8)},parseFloat64=function(value){return parseFloatFromBits(value,52,11)},parseNumeric=function(value){var sign=parseBits(value,16,32);if(sign==49152)return NaN;var weight=Math.pow(1e4,parseBits(value,16,16)),result=0,digits=[],ndigits=parseBits(value,16);for(var i=0;i<ndigits;i++)result+=parseBits(value,16,64+16*i)*weight,weight/=1e4;var scale=Math.pow(10,parseBits(value,16,48));return(sign===0?1:-1)*Math.round(result*scale)/scale},parseDate=function(isUTC,value){var sign=parseBits(value,1),rawValue=parseBits(value,63,1),result=new Date((sign===0?1:-1)*rawValue/1000+946684800000);if(!isUTC)result.setTime(result.getTime()+result.getTimezoneOffset()*60000);return result.usec=rawValue%1000,result.getMicroSeconds=function(){return this.usec},result.setMicroSeconds=function(value2){this.usec=value2},result.getUTCMicroSeconds=function(){return this.usec},result},parseArray=function(value){var dim=parseBits(value,32),flags=parseBits(value,32,32),elementType=parseBits(value,32,64),offset=96,dims=[];for(var i=0;i<dim;i++)dims[i]=parseBits(value,32,offset),offset+=32,offset+=32;var parseElement=function(elementType2){var length=parseBits(value,32,offset);if(offset+=32,length==4294967295)return null;var result;if(elementType2==23||elementType2==20)return result=parseBits(value,length*8,offset),offset+=length*8,result;else if(elementType2==25)return result=value.toString(this.encoding,offset>>3,(offset+=length<<3)>>3),result;else console.log("ERROR: ElementType not implemented: "+elementType2)},parse=function(dimension,elementType2){var array=[],i2;if(dimension.length>1){var count=dimension.shift();for(i2=0;i2<count;i2++)array[i2]=parse(dimension,elementType2);dimension.unshift(count)}else for(i2=0;i2<dimension[0];i2++)array[i2]=parseElement(elementType2);return array};return parse(dims,elementType)},parseText=function(value){return value.toString("utf8")},parseBool=function(value){if(value===null)return null;return parseBits(value,8)>0},init=function(register){register(20,parseInt64),register(21,parseInt16),register(23,parseInt32),register(26,parseInt32),register(1700,parseNumeric),register(700,parseFloat32),register(701,parseFloat64),register(16,parseBool),register(1114,parseDate.bind(null,!1)),register(1184,parseDate.bind(null,!0)),register(1000,parseArray),register(1007,parseArray),register(1016,parseArray),register(1008,parseArray),register(1009,parseArray),register(25,parseText)};module.exports={init}});var require_builtins=__commonJS((exports,module)=>{module.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}});var require_pg_types=__commonJS((exports)=>{var textParsers=require_textParsers(),binaryParsers=require_binaryParsers(),arrayParser=require_arrayParser(),builtinTypes=require_builtins();exports.getTypeParser=getTypeParser;exports.setTypeParser=setTypeParser;exports.arrayParser=arrayParser;exports.builtins=builtinTypes;var typeParsers={text:{},binary:{}};function noParse(val){return String(val)}function getTypeParser(oid,format){if(format=format||"text",!typeParsers[format])return noParse;return typeParsers[format][oid]||noParse}function setTypeParser(oid,format,parseFn){if(typeof format=="function")parseFn=format,format="text";typeParsers[format][oid]=parseFn}textParsers.init(function(oid,converter){typeParsers.text[oid]=converter});binaryParsers.init(function(oid,converter){typeParsers.binary[oid]=converter})});var require_defaults=__commonJS((exports,module)=>{var user;try{user=process.platform==="win32"?process.env.USERNAME:process.env.USER}catch{}module.exports={host:"localhost",user,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:30000,client_encoding:"",ssl:!1,application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,connect_timeout:0,keepalives:1,keepalives_idle:0};var pgTypes=require_pg_types(),parseBigInteger=pgTypes.getTypeParser(20,"text"),parseBigIntegerArray=pgTypes.getTypeParser(1016,"text");module.exports.__defineSetter__("parseInt8",function(val){pgTypes.setTypeParser(20,"text",val?pgTypes.getTypeParser(23,"text"):parseBigInteger),pgTypes.setTypeParser(1016,"text",val?pgTypes.getTypeParser(1007,"text"):parseBigIntegerArray)})});var require_utils=__commonJS((exports,module)=>{var defaults=require_defaults(),util=__require("util"),{isDate}=util.types||util;function escapeElement(elementRepresentation){return'"'+elementRepresentation.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")+'"'}function arrayString(val){let result="{";for(let i=0;i<val.length;i++){if(i>0)result=result+",";if(val[i]===null||typeof val[i]>"u")result=result+"NULL";else if(Array.isArray(val[i]))result=result+arrayString(val[i]);else if(ArrayBuffer.isView(val[i])){let item=val[i];if(!(item instanceof Buffer)){let buf=Buffer.from(item.buffer,item.byteOffset,item.byteLength);if(buf.length===item.byteLength)item=buf;else item=buf.slice(item.byteOffset,item.byteOffset+item.byteLength)}result+="\\\\x"+item.toString("hex")}else result+=escapeElement(prepareValue(val[i]))}return result=result+"}",result}var prepareValue=function(val,seen){if(val==null)return null;if(typeof val==="object"){if(val instanceof Buffer)return val;if(ArrayBuffer.isView(val)){let buf=Buffer.from(val.buffer,val.byteOffset,val.byteLength);if(buf.length===val.byteLength)return buf;return buf.slice(val.byteOffset,val.byteOffset+val.byteLength)}if(isDate(val))if(defaults.parseInputDatesAsUTC)return dateToStringUTC(val);else return dateToString(val);if(Array.isArray(val))return arrayString(val);return prepareObject(val,seen)}return val.toString()};function prepareObject(val,seen){if(val&&typeof val.toPostgres==="function"){if(seen=seen||[],seen.indexOf(val)!==-1)throw Error('circular reference detected while preparing "'+val+'" for query');return seen.push(val),prepareValue(val.toPostgres(prepareValue),seen)}return JSON.stringify(val)}function dateToString(date){let offset=-date.getTimezoneOffset(),year=date.getFullYear(),isBCYear=year<1;if(isBCYear)year=Math.abs(year)+1;let ret=String(year).padStart(4,"0")+"-"+String(date.getMonth()+1).padStart(2,"0")+"-"+String(date.getDate()).padStart(2,"0")+"T"+String(date.getHours()).padStart(2,"0")+":"+String(date.getMinutes()).padStart(2,"0")+":"+String(date.getSeconds()).padStart(2,"0")+"."+String(date.getMilliseconds()).padStart(3,"0");if(offset<0)ret+="-",offset*=-1;else ret+="+";if(ret+=String(Math.floor(offset/60)).padStart(2,"0")+":"+String(offset%60).padStart(2,"0"),isBCYear)ret+=" BC";return ret}function dateToStringUTC(date){let year=date.getUTCFullYear(),isBCYear=year<1;if(isBCYear)year=Math.abs(year)+1;let ret=String(year).padStart(4,"0")+"-"+String(date.getUTCMonth()+1).padStart(2,"0")+"-"+String(date.getUTCDate()).padStart(2,"0")+"T"+String(date.getUTCHours()).padStart(2,"0")+":"+String(date.getUTCMinutes()).padStart(2,"0")+":"+String(date.getUTCSeconds()).padStart(2,"0")+"."+String(date.getUTCMilliseconds()).padStart(3,"0");if(ret+="+00:00",isBCYear)ret+=" BC";return ret}function normalizeQueryConfig(config,values,callback){if(config=typeof config==="string"?{text:config}:config,values)if(typeof values==="function")config.callback=values;else config.values=values;if(callback)config.callback=callback;return config}var escapeIdentifier=function(str){return'"'+str.replace(/"/g,'""')+'"'},escapeLiteral=function(str){let hasBackslash=!1,escaped="'";if(str==null)return"''";if(typeof str!=="string")return"''";for(let i=0;i<str.length;i++){let c=str[i];if(c==="'")escaped+=c+c;else if(c==="\\")escaped+=c+c,hasBackslash=!0;else escaped+=c}if(escaped+="'",hasBackslash===!0)escaped=" E"+escaped;return escaped};module.exports={prepareValue:function(value){return prepareValue(value)},normalizeQueryConfig,escapeIdentifier,escapeLiteral}});var require_utils_legacy=__commonJS((exports,module)=>{var nodeCrypto=__require("crypto");function md5(string){return nodeCrypto.createHash("md5").update(string,"utf-8").digest("hex")}function postgresMd5PasswordHash(user,password,salt){let inner=md5(password+user);return"md5"+md5(Buffer.concat([Buffer.from(inner),salt]))}function sha256(text){return nodeCrypto.createHash("sha256").update(text).digest()}function hashByName(hashName,text){return hashName=hashName.replace(/(\D)-/,"$1"),nodeCrypto.createHash(hashName).update(text).digest()}function hmacSha256(key,msg){return nodeCrypto.createHmac("sha256",key).update(msg).digest()}async function deriveKey(password,salt,iterations){return nodeCrypto.pbkdf2Sync(password,salt,iterations,32,"sha256")}module.exports={postgresMd5PasswordHash,randomBytes:nodeCrypto.randomBytes,deriveKey,sha256,hashByName,hmacSha256,md5}});var require_utils_webcrypto=__commonJS((exports,module)=>{var nodeCrypto=__require("crypto");module.exports={postgresMd5PasswordHash,randomBytes,deriveKey,sha256,hashByName,hmacSha256,md5};var webCrypto=nodeCrypto.webcrypto||globalThis.crypto,subtleCrypto=webCrypto.subtle,textEncoder=new TextEncoder;function randomBytes(length){return webCrypto.getRandomValues(Buffer.alloc(length))}async function md5(string){try{return nodeCrypto.createHash("md5").update(string,"utf-8").digest("hex")}catch(e){let data=typeof string==="string"?textEncoder.encode(string):string,hash=await subtleCrypto.digest("MD5",data);return Array.from(new Uint8Array(hash)).map((b)=>b.toString(16).padStart(2,"0")).join("")}}async function postgresMd5PasswordHash(user,password,salt){let inner=await md5(password+user);return"md5"+await md5(Buffer.concat([Buffer.from(inner),salt]))}async function sha256(text){return await subtleCrypto.digest("SHA-256",text)}async function hashByName(hashName,text){return await subtleCrypto.digest(hashName,text)}async function hmacSha256(keyBuffer,msg){let key=await subtleCrypto.importKey("raw",keyBuffer,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return await subtleCrypto.sign("HMAC",key,textEncoder.encode(msg))}async function deriveKey(password,salt,iterations){let key=await subtleCrypto.importKey("raw",textEncoder.encode(password),"PBKDF2",!1,["deriveBits"]),params={name:"PBKDF2",hash:"SHA-256",salt,iterations};return await subtleCrypto.deriveBits(params,key,256,["deriveBits"])}});var require_utils2=__commonJS((exports,module)=>{var useLegacyCrypto=parseInt(process.versions&&process.versions.node&&process.versions.node.split(".")[0])<15;if(useLegacyCrypto)module.exports=require_utils_legacy();else module.exports=require_utils_webcrypto()});var require_cert_signatures=__commonJS((exports,module)=>{function x509Error(msg,cert){return Error("SASL channel binding: "+msg+" when parsing public certificate "+cert.toString("base64"))}function readASN1Length(data,index){let length=data[index++];if(length<128)return{length,index};let lengthBytes=length&127;if(lengthBytes>4)throw x509Error("bad length",data);length=0;for(let i=0;i<lengthBytes;i++)length=length<<8|data[index++];return{length,index}}function readASN1OID(data,index){if(data[index++]!==6)throw x509Error("non-OID data",data);let{length:OIDLength,index:indexAfterOIDLength}=readASN1Length(data,index);index=indexAfterOIDLength;let lastIndex=index+OIDLength,byte1=data[index++],oid=(byte1/40>>0)+"."+byte1%40;while(index<lastIndex){let value=0;while(index<lastIndex){let nextByte=data[index++];if(value=value<<7|nextByte&127,nextByte<128)break}oid+="."+value}return{oid,index}}function expectASN1Seq(data,index){if(data[index++]!==48)throw x509Error("non-sequence data",data);return readASN1Length(data,index)}function signatureAlgorithmHashFromCertificate(data,index){if(index===void 0)index=0;index=expectASN1Seq(data,index).index;let{length:certInfoLength,index:indexAfterCertInfoLength}=expectASN1Seq(data,index);index=indexAfterCertInfoLength+certInfoLength,index=expectASN1Seq(data,index).index;let{oid,index:indexAfterOID}=readASN1OID(data,index);switch(oid){case"1.2.840.113549.1.1.4":return"MD5";case"1.2.840.113549.1.1.5":return"SHA-1";case"1.2.840.113549.1.1.11":return"SHA-256";case"1.2.840.113549.1.1.12":return"SHA-384";case"1.2.840.113549.1.1.13":return"SHA-512";case"1.2.840.113549.1.1.14":return"SHA-224";case"1.2.840.113549.1.1.15":return"SHA512-224";case"1.2.840.113549.1.1.16":return"SHA512-256";case"1.2.840.10045.4.1":return"SHA-1";case"1.2.840.10045.4.3.1":return"SHA-224";case"1.2.840.10045.4.3.2":return"SHA-256";case"1.2.840.10045.4.3.3":return"SHA-384";case"1.2.840.10045.4.3.4":return"SHA-512";case"1.2.840.113549.1.1.10":{if(index=indexAfterOID,index=expectASN1Seq(data,index).index,data[index++]!==160)throw x509Error("non-tag data",data);index=readASN1Length(data,index).index,index=expectASN1Seq(data,index).index;let{oid:hashOID}=readASN1OID(data,index);switch(hashOID){case"1.2.840.113549.2.5":return"MD5";case"1.3.14.3.2.26":return"SHA-1";case"2.16.840.1.101.3.4.2.1":return"SHA-256";case"2.16.840.1.101.3.4.2.2":return"SHA-384";case"2.16.840.1.101.3.4.2.3":return"SHA-512"}throw x509Error("unknown hash OID "+hashOID,data)}case"1.3.101.110":case"1.3.101.112":return"SHA-512";case"1.3.101.111":case"1.3.101.113":throw x509Error("Ed448 certificate channel binding is not currently supported by Postgres")}throw x509Error("unknown OID "+oid,data)}module.exports={signatureAlgorithmHashFromCertificate}});var require_sasl=__commonJS((exports,module)=>{var crypto=require_utils2(),{signatureAlgorithmHashFromCertificate}=require_cert_signatures();function startSession(mechanisms,stream){let candidates=["SCRAM-SHA-256"];if(stream)candidates.unshift("SCRAM-SHA-256-PLUS");let mechanism=candidates.find((candidate)=>mechanisms.includes(candidate));if(!mechanism)throw Error("SASL: Only mechanism(s) "+candidates.join(" and ")+" are supported");if(mechanism==="SCRAM-SHA-256-PLUS"&&typeof stream.getPeerCertificate!=="function")throw Error("SASL: Mechanism SCRAM-SHA-256-PLUS requires a certificate");let clientNonce=crypto.randomBytes(18).toString("base64");return{mechanism,clientNonce,response:(mechanism==="SCRAM-SHA-256-PLUS"?"p=tls-server-end-point":stream?"y":"n")+",,n=*,r="+clientNonce,message:"SASLInitialResponse"}}async function continueSession(session,password,serverData,stream){if(session.message!=="SASLInitialResponse")throw Error("SASL: Last message was not SASLInitialResponse");if(typeof password!=="string")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(password==="")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string");if(typeof serverData!=="string")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let sv=parseServerFirstMessage(serverData);if(!sv.nonce.startsWith(session.clientNonce))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");else if(sv.nonce.length===session.clientNonce.length)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short");let clientFirstMessageBare="n=*,r="+session.clientNonce,serverFirstMessage="r="+sv.nonce+",s="+sv.salt+",i="+sv.iteration,channelBinding=stream?"eSws":"biws";if(session.mechanism==="SCRAM-SHA-256-PLUS"){let peerCert=stream.getPeerCertificate().raw,hashName=signatureAlgorithmHashFromCertificate(peerCert);if(hashName==="MD5"||hashName==="SHA-1")hashName="SHA-256";let certHash=await crypto.hashByName(hashName,peerCert);channelBinding=Buffer.concat([Buffer.from("p=tls-server-end-point,,"),Buffer.from(certHash)]).toString("base64")}let clientFinalMessageWithoutProof="c="+channelBinding+",r="+sv.nonce,authMessage=clientFirstMessageBare+","+serverFirstMessage+","+clientFinalMessageWithoutProof,saltBytes=Buffer.from(sv.salt,"base64"),saltedPassword=await crypto.deriveKey(password,saltBytes,sv.iteration),clientKey=await crypto.hmacSha256(saltedPassword,"Client Key"),storedKey=await crypto.sha256(clientKey),clientSignature=await crypto.hmacSha256(storedKey,authMessage),clientProof=xorBuffers(Buffer.from(clientKey),Buffer.from(clientSignature)).toString("base64"),serverKey=await crypto.hmacSha256(saltedPassword,"Server Key"),serverSignatureBytes=await crypto.hmacSha256(serverKey,authMessage);session.message="SASLResponse",session.serverSignature=Buffer.from(serverSignatureBytes).toString("base64"),session.response=clientFinalMessageWithoutProof+",p="+clientProof}function finalizeSession(session,serverData){if(session.message!=="SASLResponse")throw Error("SASL: Last message was not SASLResponse");if(typeof serverData!=="string")throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature}=parseServerFinalMessage(serverData);if(serverSignature!==session.serverSignature)throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}function isPrintableChars(text){if(typeof text!=="string")throw TypeError("SASL: text must be a string");return text.split("").map((_,i)=>text.charCodeAt(i)).every((c)=>c>=33&&c<=43||c>=45&&c<=126)}function isBase64(text){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(text)}function parseAttributePairs(text){if(typeof text!=="string")throw TypeError("SASL: attribute pairs text must be a string");return new Map(text.split(",").map((attrValue)=>{if(!/^.=/.test(attrValue))throw Error("SASL: Invalid attribute pair entry");let name=attrValue[0],value=attrValue.substring(2);return[name,value]}))}function parseServerFirstMessage(data){let attrPairs=parseAttributePairs(data),nonce=attrPairs.get("r");if(!nonce)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");else if(!isPrintableChars(nonce))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters");let salt=attrPairs.get("s");if(!salt)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");else if(!isBase64(salt))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64");let iterationText=attrPairs.get("i");if(!iterationText)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");else if(!/^[1-9][0-9]*$/.test(iterationText))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count");let iteration=parseInt(iterationText,10);return{nonce,salt,iteration}}function parseServerFinalMessage(serverData){let serverSignature=parseAttributePairs(serverData).get("v");if(!serverSignature)throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");else if(!isBase64(serverSignature))throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64");return{serverSignature}}function xorBuffers(a,b){if(!Buffer.isBuffer(a))throw TypeError("first argument must be a Buffer");if(!Buffer.isBuffer(b))throw TypeError("second argument must be a Buffer");if(a.length!==b.length)throw Error("Buffer lengths must match");if(a.length===0)throw Error("Buffers cannot be empty");return Buffer.from(a.map((_,i)=>a[i]^b[i]))}module.exports={startSession,continueSession,finalizeSession}});var require_type_overrides=__commonJS((exports,module)=>{var types=require_pg_types();function TypeOverrides(userTypes){this._types=userTypes||types,this.text={},this.binary={}}TypeOverrides.prototype.getOverrides=function(format){switch(format){case"text":return this.text;case"binary":return this.binary;default:return{}}};TypeOverrides.prototype.setTypeParser=function(oid,format,parseFn){if(typeof format==="function")parseFn=format,format="text";this.getOverrides(format)[oid]=parseFn};TypeOverrides.prototype.getTypeParser=function(oid,format){return format=format||"text",this.getOverrides(format)[oid]||this._types.getTypeParser(oid,format)};module.exports=TypeOverrides});var require_pg_connection_string=__commonJS((exports,module)=>{function parse(str,options={}){if(str.charAt(0)==="/"){let config2=str.split(" ");return{host:config2[0],database:config2[1]}}let config={},result,dummyHost=!1;if(/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(str))str=encodeURI(str).replace(/%25(\d\d)/g,"%$1");try{try{result=new URL(str,"postgres://base")}catch(e){result=new URL(str.replace("@/","@___DUMMY___/"),"postgres://base"),dummyHost=!0}}catch(err){throw err.input&&(err.input="*****REDACTED*****"),err}for(let entry of result.searchParams.entries())config[entry[0]]=entry[1];if(config.user=config.user||decodeURIComponent(result.username),config.password=config.password||decodeURIComponent(result.password),result.protocol=="socket:")return config.host=decodeURI(result.pathname),config.database=result.searchParams.get("db"),config.client_encoding=result.searchParams.get("encoding"),config;let hostname=dummyHost?"":result.hostname;if(!config.host)config.host=decodeURIComponent(hostname);else if(hostname&&/^%2f/i.test(hostname))result.pathname=hostname+result.pathname;if(!config.port)config.port=result.port;let pathname=result.pathname.slice(1)||null;if(config.database=pathname?decodeURI(pathname):null,config.ssl==="true"||config.ssl==="1")config.ssl=!0;if(config.ssl==="0")config.ssl=!1;if(config.sslcert||config.sslkey||config.sslrootcert||config.sslmode)config.ssl={};let fs=config.sslcert||config.sslkey||config.sslrootcert?__require("fs"):null;if(config.sslcert)config.ssl.cert=fs.readFileSync(config.sslcert).toString();if(config.sslkey)config.ssl.key=fs.readFileSync(config.sslkey).toString();if(config.sslrootcert)config.ssl.ca=fs.readFileSync(config.sslrootcert).toString();if(options.useLibpqCompat&&config.uselibpqcompat)throw Error("Both useLibpqCompat and uselibpqcompat are set. Please use only one of them.");if(config.uselibpqcompat==="true"||options.useLibpqCompat)switch(config.sslmode){case"disable":{config.ssl=!1;break}case"prefer":{config.ssl.rejectUnauthorized=!1;break}case"require":{if(config.sslrootcert)config.ssl.checkServerIdentity=function(){};else config.ssl.rejectUnauthorized=!1;break}case"verify-ca":{if(!config.ssl.ca)throw Error("SECURITY WARNING: Using sslmode=verify-ca requires specifying a CA with sslrootcert. If a public CA is used, verify-ca allows connections to a server that somebody else may have registered with the CA, making you vulnerable to Man-in-the-Middle attacks. Either specify a custom CA certificate with sslrootcert parameter or use sslmode=verify-full for proper security.");config.ssl.checkServerIdentity=function(){};break}case"verify-full":break}else switch(config.sslmode){case"disable":{config.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":{if(config.sslmode!=="verify-full")deprecatedSslModeWarning(config.sslmode);break}case"no-verify":{config.ssl.rejectUnauthorized=!1;break}}return config}function toConnectionOptions(sslConfig){return Object.entries(sslConfig).reduce((c,[key,value])=>{if(value!==void 0&&value!==null)c[key]=value;return c},{})}function toClientConfig(config){return Object.entries(config).reduce((c,[key,value])=>{if(key==="ssl"){let sslConfig=value;if(typeof sslConfig==="boolean")c[key]=sslConfig;if(typeof sslConfig==="object")c[key]=toConnectionOptions(sslConfig)}else if(value!==void 0&&value!==null)if(key==="port"){if(value!==""){let v=parseInt(value,10);if(isNaN(v))throw Error(`Invalid ${key}: ${value}`);c[key]=v}}else c[key]=value;return c},{})}function parseIntoClientConfig(str){return toClientConfig(parse(str))}function deprecatedSslModeWarning(sslmode){if(!deprecatedSslModeWarning.warned&&typeof process<"u"&&process.emitWarning)deprecatedSslModeWarning.warned=!0,process.emitWarning(`SECURITY WARNING: The SSL modes 'prefer', 'require', and 'verify-ca' are treated as aliases for 'verify-full'.
|
|
2
|
+
var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames}=Object;var __hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule||!__hasOwnProp.call(mod,"default")?__defProp(target,"default",{value:mod,enumerable:!0}):target;if(mod&&typeof mod==="object"||typeof mod==="function"){for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0})}if(canCache)cache.set(mod,to);return to};var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};var __require=import.meta.require;var require_postgres_array=__commonJS(function(exports){exports.parse=function(source,transform){return new ArrayParser(source,transform).parse()};class ArrayParser{constructor(source,transform){this.source=source,this.transform=transform||identity,this.position=0,this.entries=[],this.recorded=[],this.dimension=0}isEof(){return this.position>=this.source.length}nextCharacter(){var character=this.source[this.position++];if(character==="\\")return{value:this.source[this.position++],escaped:!0};return{value:character,escaped:!1}}record(character){this.recorded.push(character)}newEntry(includeEmpty){var entry;if(this.recorded.length>0||includeEmpty){if(entry=this.recorded.join(""),entry==="NULL"&&!includeEmpty)entry=null;if(entry!==null)entry=this.transform(entry);this.entries.push(entry),this.recorded=[]}}consumeDimensions(){if(this.source[0]==="[")while(!this.isEof()){var char=this.nextCharacter();if(char.value==="=")break}}parse(nested){var character,parser,quote;this.consumeDimensions();while(!this.isEof())if(character=this.nextCharacter(),character.value==="{"&&!quote){if(this.dimension++,this.dimension>1)parser=new ArrayParser(this.source.substr(this.position-1),this.transform),this.entries.push(parser.parse(!0)),this.position+=parser.position-2}else if(character.value==="}"&&!quote){if(this.dimension--,!this.dimension){if(this.newEntry(),nested)return this.entries}}else if(character.value==='"'&&!character.escaped){if(quote)this.newEntry(!0);quote=!quote}else if(character.value===","&&!quote)this.newEntry();else this.record(character.value);if(this.dimension!==0)throw Error("array dimension not balanced");return this.entries}}function identity(value){return value}});var require_arrayParser=__commonJS(function(exports,module){var array=require_postgres_array();module.exports={create:function(source,transform){return{parse:function(){return array.parse(source,transform)}}}}});var require_postgres_date=__commonJS(function(exports,module){var DATE_TIME=/(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/,DATE=/^(\d{1,})-(\d{2})-(\d{2})( BC)?$/,TIME_ZONE=/([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/,INFINITY=/^-?infinity$/;module.exports=function(isoDate){if(INFINITY.test(isoDate))return Number(isoDate.replace("i","I"));var matches=DATE_TIME.exec(isoDate);if(!matches)return getDate(isoDate)||null;var isBC=!!matches[8],year=parseInt(matches[1],10);if(isBC)year=bcYearToNegativeYear(year);var month=parseInt(matches[2],10)-1,day=matches[3],hour=parseInt(matches[4],10),minute=parseInt(matches[5],10),second=parseInt(matches[6],10),ms=matches[7];ms=ms?1000*parseFloat(ms):0;var date,offset=timeZoneOffset(isoDate);if(offset!=null){if(date=new Date(Date.UTC(year,month,day,hour,minute,second,ms)),is0To99(year))date.setUTCFullYear(year);if(offset!==0)date.setTime(date.getTime()-offset)}else if(date=new Date(year,month,day,hour,minute,second,ms),is0To99(year))date.setFullYear(year);return date};function getDate(isoDate){var matches=DATE.exec(isoDate);if(!matches)return;var year=parseInt(matches[1],10),isBC=!!matches[4];if(isBC)year=bcYearToNegativeYear(year);var month=parseInt(matches[2],10)-1,day=matches[3],date=new Date(year,month,day);if(is0To99(year))date.setFullYear(year);return date}function timeZoneOffset(isoDate){if(isoDate.endsWith("+00"))return 0;var zone=TIME_ZONE.exec(isoDate.split(" ")[1]);if(!zone)return;var type=zone[1];if(type==="Z")return 0;var sign=type==="-"?-1:1,offset=parseInt(zone[2],10)*3600+parseInt(zone[3]||0,10)*60+parseInt(zone[4]||0,10);return offset*sign*1000}function bcYearToNegativeYear(year){return-(year-1)}function is0To99(num){return num>=0&&num<100}});var require_mutable=__commonJS(function(exports,module){module.exports=extend;var hasOwnProperty=Object.prototype.hasOwnProperty;function extend(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)if(hasOwnProperty.call(source,key))target[key]=source[key]}return target}});var require_postgres_interval=__commonJS(function(exports,module){var extend=require_mutable();module.exports=PostgresInterval;function PostgresInterval(raw){if(!(this instanceof PostgresInterval))return new PostgresInterval(raw);extend(this,parse(raw))}var properties=["seconds","minutes","hours","days","months","years"];PostgresInterval.prototype.toPostgres=function(){var filtered=properties.filter(this.hasOwnProperty,this);if(this.milliseconds&&filtered.indexOf("seconds")<0)filtered.push("seconds");if(filtered.length===0)return"0";return filtered.map(function(property){var value=this[property]||0;if(property==="seconds"&&this.milliseconds)value=(value+this.milliseconds/1000).toFixed(6).replace(/\.?0+$/,"");return value+" "+property},this).join(" ")};var propertiesISOEquivalent={years:"Y",months:"M",days:"D",hours:"H",minutes:"M",seconds:"S"},dateProperties=["years","months","days"],timeProperties=["hours","minutes","seconds"];PostgresInterval.prototype.toISOString=PostgresInterval.prototype.toISO=function(){var datePart=dateProperties.map(buildProperty,this).join(""),timePart=timeProperties.map(buildProperty,this).join("");return"P"+datePart+"T"+timePart;function buildProperty(property){var value=this[property]||0;if(property==="seconds"&&this.milliseconds)value=(value+this.milliseconds/1000).toFixed(6).replace(/0+$/,"");return value+propertiesISOEquivalent[property]}};var NUMBER="([+-]?\\d+)",YEAR=NUMBER+"\\s+years?",MONTH=NUMBER+"\\s+mons?",DAY=NUMBER+"\\s+days?",TIME="([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?",INTERVAL=new RegExp([YEAR,MONTH,DAY,TIME].map(function(regexString){return"("+regexString+")?"}).join("\\s*")),positions={years:2,months:4,days:6,hours:9,minutes:10,seconds:11,milliseconds:12},negatives=["hours","minutes","seconds","milliseconds"];function parseMilliseconds(fraction){var microseconds=fraction+"000000".slice(fraction.length);return parseInt(microseconds,10)/1000}function parse(interval){if(!interval)return{};var matches=INTERVAL.exec(interval),isNegative=matches[8]==="-";return Object.keys(positions).reduce(function(parsed,property){var position=positions[property],value=matches[position];if(!value)return parsed;if(value=property==="milliseconds"?parseMilliseconds(value):parseInt(value,10),!value)return parsed;if(isNegative&&~negatives.indexOf(property))value*=-1;return parsed[property]=value,parsed},{})}});var require_postgres_bytea=__commonJS(function(exports,module){var bufferFrom=Buffer.from||Buffer;module.exports=function(input){if(/^\\x/.test(input))return bufferFrom(input.substr(2),"hex");var output="",i=0;while(i<input.length)if(input[i]!=="\\")output+=input[i],++i;else if(/[0-7]{3}/.test(input.substr(i+1,3)))output+=String.fromCharCode(parseInt(input.substr(i+1,3),8)),i+=4;else{var backslashes=1;while(i+backslashes<input.length&&input[i+backslashes]==="\\")backslashes++;for(var k=0;k<Math.floor(backslashes/2);++k)output+="\\";i+=Math.floor(backslashes/2)*2}return bufferFrom(output,"binary")}});var require_textParsers=__commonJS(function(exports,module){var array=require_postgres_array(),arrayParser=require_arrayParser(),parseDate=require_postgres_date(),parseInterval=require_postgres_interval(),parseByteA=require_postgres_bytea();function allowNull(fn){return function(value){if(value===null)return value;return fn(value)}}function parseBool(value){if(value===null)return value;return value==="TRUE"||value==="t"||value==="true"||value==="y"||value==="yes"||value==="on"||value==="1"}function parseBoolArray(value){if(!value)return null;return array.parse(value,parseBool)}function parseBaseTenInt(string){return parseInt(string,10)}function parseIntegerArray(value){if(!value)return null;return array.parse(value,allowNull(parseBaseTenInt))}function parseBigIntegerArray(value){if(!value)return null;return array.parse(value,allowNull(function(entry){return parseBigInteger(entry).trim()}))}var parsePointArray=function(value){if(!value)return null;var p=arrayParser.create(value,function(entry){if(entry!==null)entry=parsePoint(entry);return entry});return p.parse()},parseFloatArray=function(value){if(!value)return null;var p=arrayParser.create(value,function(entry){if(entry!==null)entry=parseFloat(entry);return entry});return p.parse()},parseStringArray=function(value){if(!value)return null;var p=arrayParser.create(value);return p.parse()},parseDateArray=function(value){if(!value)return null;var p=arrayParser.create(value,function(entry){if(entry!==null)entry=parseDate(entry);return entry});return p.parse()},parseIntervalArray=function(value){if(!value)return null;var p=arrayParser.create(value,function(entry){if(entry!==null)entry=parseInterval(entry);return entry});return p.parse()},parseByteAArray=function(value){if(!value)return null;return array.parse(value,allowNull(parseByteA))},parseInteger=function(value){return parseInt(value,10)},parseBigInteger=function(value){var valStr=String(value);if(/^\d+$/.test(valStr))return valStr;return value},parseJsonArray=function(value){if(!value)return null;return array.parse(value,allowNull(JSON.parse))},parsePoint=function(value){if(value[0]!=="(")return null;return value=value.substring(1,value.length-1).split(","),{x:parseFloat(value[0]),y:parseFloat(value[1])}},parseCircle=function(value){if(value[0]!=="<"&&value[1]!=="(")return null;var point="(",radius="",pointParsed=!1;for(var i=2;i<value.length-1;i++){if(!pointParsed)point+=value[i];if(value[i]===")"){pointParsed=!0;continue}else if(!pointParsed)continue;if(value[i]===",")continue;radius+=value[i]}var result=parsePoint(point);return result.radius=parseFloat(radius),result},init=function(register){register(20,parseBigInteger),register(21,parseInteger),register(23,parseInteger),register(26,parseInteger),register(700,parseFloat),register(701,parseFloat),register(16,parseBool),register(1082,parseDate),register(1114,parseDate),register(1184,parseDate),register(600,parsePoint),register(651,parseStringArray),register(718,parseCircle),register(1000,parseBoolArray),register(1001,parseByteAArray),register(1005,parseIntegerArray),register(1007,parseIntegerArray),register(1028,parseIntegerArray),register(1016,parseBigIntegerArray),register(1017,parsePointArray),register(1021,parseFloatArray),register(1022,parseFloatArray),register(1231,parseFloatArray),register(1014,parseStringArray),register(1015,parseStringArray),register(1008,parseStringArray),register(1009,parseStringArray),register(1040,parseStringArray),register(1041,parseStringArray),register(1115,parseDateArray),register(1182,parseDateArray),register(1185,parseDateArray),register(1186,parseInterval),register(1187,parseIntervalArray),register(17,parseByteA),register(114,JSON.parse.bind(JSON)),register(3802,JSON.parse.bind(JSON)),register(199,parseJsonArray),register(3807,parseJsonArray),register(3907,parseStringArray),register(2951,parseStringArray),register(791,parseStringArray),register(1183,parseStringArray),register(1270,parseStringArray)};module.exports={init}});var require_pg_int8=__commonJS(function(exports,module){var BASE=1e6;function readInt8(buffer){var high=buffer.readInt32BE(0),low=buffer.readUInt32BE(4),sign="";if(high<0)high=~high+(low===0),low=~low+1>>>0,sign="-";var result="",carry,t,digits,pad,l,i;{if(carry=high%BASE,high=high/BASE>>>0,t=4294967296*carry+low,low=t/BASE>>>0,digits=""+(t-BASE*low),low===0&&high===0)return sign+digits+result;pad="",l=6-digits.length;for(i=0;i<l;i++)pad+="0";result=pad+digits+result}{if(carry=high%BASE,high=high/BASE>>>0,t=4294967296*carry+low,low=t/BASE>>>0,digits=""+(t-BASE*low),low===0&&high===0)return sign+digits+result;pad="",l=6-digits.length;for(i=0;i<l;i++)pad+="0";result=pad+digits+result}{if(carry=high%BASE,high=high/BASE>>>0,t=4294967296*carry+low,low=t/BASE>>>0,digits=""+(t-BASE*low),low===0&&high===0)return sign+digits+result;pad="",l=6-digits.length;for(i=0;i<l;i++)pad+="0";result=pad+digits+result}return carry=high%BASE,t=4294967296*carry+low,digits=""+t%BASE,sign+digits+result}module.exports=readInt8});var require_binaryParsers=__commonJS(function(exports,module){var parseInt64=require_pg_int8(),parseBits=function(data,bits,offset,invert,callback){offset=offset||0,invert=invert||!1,callback=callback||function(lastValue,newValue,bits){return lastValue*Math.pow(2,bits)+newValue};var offsetBytes=offset>>3,inv=function(value){if(invert)return~value&255;return value},mask=255,firstBits=8-offset%8;if(bits<firstBits)mask=255<<8-bits&255,firstBits=bits;if(offset)mask=mask>>offset%8;var result=0;if(offset%8+bits>=8)result=callback(0,inv(data[offsetBytes])&mask,firstBits);var bytes=bits+offset>>3;for(var i=offsetBytes+1;i<bytes;i++)result=callback(result,inv(data[i]),8);var lastBits=(bits+offset)%8;if(lastBits>0)result=callback(result,inv(data[bytes])>>8-lastBits,lastBits);return result},parseFloatFromBits=function(data,precisionBits,exponentBits){var bias=Math.pow(2,exponentBits-1)-1,sign=parseBits(data,1),exponent=parseBits(data,exponentBits,1);if(exponent===0)return 0;var precisionBitsCounter=1,parsePrecisionBits=function(lastValue,newValue,bits){if(lastValue===0)lastValue=1;for(var i=1;i<=bits;i++)if(precisionBitsCounter/=2,(newValue&1<<bits-i)>0)lastValue+=precisionBitsCounter;return lastValue},mantissa=parseBits(data,precisionBits,exponentBits+1,!1,parsePrecisionBits);if(exponent==Math.pow(2,exponentBits+1)-1){if(mantissa===0)return sign===0?1/0:-1/0;return NaN}return(sign===0?1:-1)*Math.pow(2,exponent-bias)*mantissa},parseInt16=function(value){if(parseBits(value,1)==1)return-1*(parseBits(value,15,1,!0)+1);return parseBits(value,15,1)},parseInt32=function(value){if(parseBits(value,1)==1)return-1*(parseBits(value,31,1,!0)+1);return parseBits(value,31,1)},parseFloat32=function(value){return parseFloatFromBits(value,23,8)},parseFloat64=function(value){return parseFloatFromBits(value,52,11)},parseNumeric=function(value){var sign=parseBits(value,16,32);if(sign==49152)return NaN;var weight=Math.pow(1e4,parseBits(value,16,16)),result=0,digits=[],ndigits=parseBits(value,16);for(var i=0;i<ndigits;i++)result+=parseBits(value,16,64+16*i)*weight,weight/=1e4;var scale=Math.pow(10,parseBits(value,16,48));return(sign===0?1:-1)*Math.round(result*scale)/scale},parseDate=function(isUTC,value){var sign=parseBits(value,1),rawValue=parseBits(value,63,1),result=new Date((sign===0?1:-1)*rawValue/1000+946684800000);if(!isUTC)result.setTime(result.getTime()+result.getTimezoneOffset()*60000);return result.usec=rawValue%1000,result.getMicroSeconds=function(){return this.usec},result.setMicroSeconds=function(value){this.usec=value},result.getUTCMicroSeconds=function(){return this.usec},result},parseArray=function(value){var dim=parseBits(value,32),flags=parseBits(value,32,32),elementType=parseBits(value,32,64),offset=96,dims=[];for(var i=0;i<dim;i++)dims[i]=parseBits(value,32,offset),offset+=32,offset+=32;var parseElement=function(elementType){var length=parseBits(value,32,offset);if(offset+=32,length==4294967295)return null;var result;if(elementType==23||elementType==20)return result=parseBits(value,length*8,offset),offset+=length*8,result;else if(elementType==25)return result=value.toString(this.encoding,offset>>3,(offset+=length<<3)>>3),result;else console.log("ERROR: ElementType not implemented: "+elementType)},parse=function(dimension,elementType){var array=[],i;if(dimension.length>1){var count=dimension.shift();for(i=0;i<count;i++)array[i]=parse(dimension,elementType);dimension.unshift(count)}else for(i=0;i<dimension[0];i++)array[i]=parseElement(elementType);return array};return parse(dims,elementType)},parseText=function(value){return value.toString("utf8")},parseBool=function(value){if(value===null)return null;return parseBits(value,8)>0},init=function(register){register(20,parseInt64),register(21,parseInt16),register(23,parseInt32),register(26,parseInt32),register(1700,parseNumeric),register(700,parseFloat32),register(701,parseFloat64),register(16,parseBool),register(1114,parseDate.bind(null,!1)),register(1184,parseDate.bind(null,!0)),register(1000,parseArray),register(1007,parseArray),register(1016,parseArray),register(1008,parseArray),register(1009,parseArray),register(25,parseText)};module.exports={init}});var require_builtins=__commonJS(function(exports,module){module.exports={BOOL:16,BYTEA:17,CHAR:18,INT8:20,INT2:21,INT4:23,REGPROC:24,TEXT:25,OID:26,TID:27,XID:28,CID:29,JSON:114,XML:142,PG_NODE_TREE:194,SMGR:210,PATH:602,POLYGON:604,CIDR:650,FLOAT4:700,FLOAT8:701,ABSTIME:702,RELTIME:703,TINTERVAL:704,CIRCLE:718,MACADDR8:774,MONEY:790,MACADDR:829,INET:869,ACLITEM:1033,BPCHAR:1042,VARCHAR:1043,DATE:1082,TIME:1083,TIMESTAMP:1114,TIMESTAMPTZ:1184,INTERVAL:1186,TIMETZ:1266,BIT:1560,VARBIT:1562,NUMERIC:1700,REFCURSOR:1790,REGPROCEDURE:2202,REGOPER:2203,REGOPERATOR:2204,REGCLASS:2205,REGTYPE:2206,UUID:2950,TXID_SNAPSHOT:2970,PG_LSN:3220,PG_NDISTINCT:3361,PG_DEPENDENCIES:3402,TSVECTOR:3614,TSQUERY:3615,GTSVECTOR:3642,REGCONFIG:3734,REGDICTIONARY:3769,JSONB:3802,REGNAMESPACE:4089,REGROLE:4096}});var require_pg_types=__commonJS(function(exports){var textParsers=require_textParsers(),binaryParsers=require_binaryParsers(),arrayParser=require_arrayParser(),builtinTypes=require_builtins();exports.getTypeParser=getTypeParser;exports.setTypeParser=setTypeParser;exports.arrayParser=arrayParser;exports.builtins=builtinTypes;var typeParsers={text:{},binary:{}};function noParse(val){return String(val)}function getTypeParser(oid,format){if(format=format||"text",!typeParsers[format])return noParse;return typeParsers[format][oid]||noParse}function setTypeParser(oid,format,parseFn){if(typeof format=="function")parseFn=format,format="text";typeParsers[format][oid]=parseFn}textParsers.init(function(oid,converter){typeParsers.text[oid]=converter});binaryParsers.init(function(oid,converter){typeParsers.binary[oid]=converter})});var require_defaults=__commonJS(function(exports,module){var user;try{user=process.platform==="win32"?process.env.USERNAME:process.env.USER}catch{}module.exports={host:"localhost",user,database:void 0,password:null,connectionString:void 0,port:5432,rows:0,binary:!1,max:10,idleTimeoutMillis:30000,client_encoding:"",ssl:!1,sslnegotiation:void 0,application_name:void 0,fallback_application_name:void 0,options:void 0,parseInputDatesAsUTC:!1,statement_timeout:!1,lock_timeout:!1,idle_in_transaction_session_timeout:!1,query_timeout:!1,connect_timeout:0,keepalives:1,keepalives_idle:0};var pgTypes=require_pg_types(),parseBigInteger=pgTypes.getTypeParser(20,"text"),parseBigIntegerArray=pgTypes.getTypeParser(1016,"text");module.exports.__defineSetter__("parseInt8",function(val){pgTypes.setTypeParser(20,"text",val?pgTypes.getTypeParser(23,"text"):parseBigInteger),pgTypes.setTypeParser(1016,"text",val?pgTypes.getTypeParser(1007,"text"):parseBigIntegerArray)})});var require_utils=__commonJS(function(exports,module){var defaults=require_defaults(),nodeUtils=__require("util"),{isDate}=__require("util/types"),invalidDateDeprecationNotice=nodeUtils.deprecate(()=>{},"Sending an invalid date to Postgres is deprecated and will throw an error in the next major version of pg. Ensure any Date object passed as a query parameter is valid.","PG_INVALID_DATE");function escapeElement(elementRepresentation){return'"'+elementRepresentation.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")+'"'}function arrayString(val){let result="{";for(let i=0;i<val.length;i++){if(i>0)result+=",";let item=val[i];if(item==null)result+="NULL";else if(Array.isArray(item))result+=arrayString(item);else if(ArrayBuffer.isView(item)){if(!(item instanceof Buffer))item=Buffer.from(item.buffer,item.byteOffset,item.byteLength);result+="\\\\x"+item.toString("hex")}else result+=escapeElement(prepareValue(item))}return result+="}",result}var prepareValue=function(val,seen){if(val==null)return null;if(typeof val==="object"){if(val instanceof Buffer)return val;if(ArrayBuffer.isView(val))return Buffer.from(val.buffer,val.byteOffset,val.byteLength);if(isDate(val)){if(isNaN(val.getTime()))invalidDateDeprecationNotice();if(defaults.parseInputDatesAsUTC)return dateToStringUTC(val);else return dateToString(val)}if(Array.isArray(val))return arrayString(val);return prepareObject(val,seen)}return val.toString()};function prepareObject(val,seen){if(val&&typeof val.toPostgres==="function"){if(seen=seen||[],seen.indexOf(val)!==-1)throw Error('circular reference detected while preparing "'+val+'" for query');return seen.push(val),prepareValue(val.toPostgres(prepareValue),seen)}return JSON.stringify(val)}function dateToString(date){let offset=-date.getTimezoneOffset(),year=date.getFullYear(),isBCYear=year<1;if(isBCYear)year=Math.abs(year)+1;let ret=String(year).padStart(4,"0")+"-"+String(date.getMonth()+1).padStart(2,"0")+"-"+String(date.getDate()).padStart(2,"0")+"T"+String(date.getHours()).padStart(2,"0")+":"+String(date.getMinutes()).padStart(2,"0")+":"+String(date.getSeconds()).padStart(2,"0")+"."+String(date.getMilliseconds()).padStart(3,"0");if(offset<0)ret+="-",offset*=-1;else ret+="+";if(ret+=String(Math.floor(offset/60)).padStart(2,"0")+":"+String(offset%60).padStart(2,"0"),isBCYear)ret+=" BC";return ret}function dateToStringUTC(date){let year=date.getUTCFullYear(),isBCYear=year<1;if(isBCYear)year=Math.abs(year)+1;let ret=String(year).padStart(4,"0")+"-"+String(date.getUTCMonth()+1).padStart(2,"0")+"-"+String(date.getUTCDate()).padStart(2,"0")+"T"+String(date.getUTCHours()).padStart(2,"0")+":"+String(date.getUTCMinutes()).padStart(2,"0")+":"+String(date.getUTCSeconds()).padStart(2,"0")+"."+String(date.getUTCMilliseconds()).padStart(3,"0");if(ret+="+00:00",isBCYear)ret+=" BC";return ret}function normalizeQueryConfig(config,values,callback){if(config=typeof config==="string"?{text:config}:cloneQueryConfig(config),values)if(typeof values==="function")config.callback=values;else config.values=values;if(callback)config.callback=callback;return config}function cloneQueryConfig(config){if(config==null)return config;return Object.defineProperties(Object.create(Object.getPrototypeOf(config)),Object.getOwnPropertyDescriptors(config))}var escapeIdentifier=function(str){return'"'+str.replace(/"/g,'""')+'"'},escapeLiteral=function(str){let hasBackslash=!1,escaped="'";if(str==null)return"''";if(typeof str!=="string")return"''";for(let i=0;i<str.length;i++){let c=str[i];if(c==="'")escaped+=c+c;else if(c==="\\")escaped+=c+c,hasBackslash=!0;else escaped+=c}if(escaped+="'",hasBackslash===!0)escaped=" E"+escaped;return escaped};module.exports={prepareValue:function(value){return prepareValue(value)},normalizeQueryConfig,escapeIdentifier,escapeLiteral}});var require_utils2=__commonJS(function(exports,module){var nodeCrypto=__require("crypto");module.exports={postgresMd5PasswordHash,randomBytes,deriveKey,sha256,hashByName,hmacSha256,md5};var webCrypto=nodeCrypto.webcrypto||globalThis.crypto,subtleCrypto=webCrypto.subtle,textEncoder=new TextEncoder;function randomBytes(length){return webCrypto.getRandomValues(Buffer.alloc(length))}async function md5(string){try{return nodeCrypto.createHash("md5").update(string,"utf-8").digest("hex")}catch(e){let data=typeof string==="string"?textEncoder.encode(string):string,hash=await subtleCrypto.digest("MD5",data);return Array.from(new Uint8Array(hash)).map((b)=>b.toString(16).padStart(2,"0")).join("")}}async function postgresMd5PasswordHash(user,password,salt){let inner=await md5(password+user);return"md5"+await md5(Buffer.concat([Buffer.from(inner),salt]))}async function sha256(text){return await subtleCrypto.digest("SHA-256",text)}async function hashByName(hashName,text){return await subtleCrypto.digest(hashName,text)}async function hmacSha256(keyBuffer,msg){let key=await subtleCrypto.importKey("raw",keyBuffer,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return await subtleCrypto.sign("HMAC",key,textEncoder.encode(msg))}async function deriveKey(password,salt,iterations){let key=await subtleCrypto.importKey("raw",textEncoder.encode(password),"PBKDF2",!1,["deriveBits"]),params={name:"PBKDF2",hash:"SHA-256",salt,iterations};return await subtleCrypto.deriveBits(params,key,256,["deriveBits"])}});var require_cert_signatures=__commonJS(function(exports,module){function x509Error(msg,cert){return Error("SASL channel binding: "+msg+" when parsing public certificate "+cert.toString("base64"))}function readASN1Length(data,index){let length=data[index++];if(length<128)return{length,index};let lengthBytes=length&127;if(lengthBytes>4)throw x509Error("bad length",data);length=0;for(let i=0;i<lengthBytes;i++)length=length<<8|data[index++];return{length,index}}function readASN1OID(data,index){if(data[index++]!==6)throw x509Error("non-OID data",data);let{length:OIDLength,index:indexAfterOIDLength}=readASN1Length(data,index);index=indexAfterOIDLength;let lastIndex=index+OIDLength,byte1=data[index++],oid=(byte1/40>>0)+"."+byte1%40;while(index<lastIndex){let value=0;while(index<lastIndex){let nextByte=data[index++];if(value=value<<7|nextByte&127,nextByte<128)break}oid+="."+value}return{oid,index}}function expectASN1Seq(data,index){if(data[index++]!==48)throw x509Error("non-sequence data",data);return readASN1Length(data,index)}function signatureAlgorithmHashFromCertificate(data,index){if(index===void 0)index=0;index=expectASN1Seq(data,index).index;let{length:certInfoLength,index:indexAfterCertInfoLength}=expectASN1Seq(data,index);index=indexAfterCertInfoLength+certInfoLength,index=expectASN1Seq(data,index).index;let{oid,index:indexAfterOID}=readASN1OID(data,index);switch(oid){case"1.2.840.113549.1.1.4":return"MD5";case"1.2.840.113549.1.1.5":return"SHA-1";case"1.2.840.113549.1.1.11":return"SHA-256";case"1.2.840.113549.1.1.12":return"SHA-384";case"1.2.840.113549.1.1.13":return"SHA-512";case"1.2.840.113549.1.1.14":return"SHA-224";case"1.2.840.113549.1.1.15":return"SHA512-224";case"1.2.840.113549.1.1.16":return"SHA512-256";case"1.2.840.10045.4.1":return"SHA-1";case"1.2.840.10045.4.3.1":return"SHA-224";case"1.2.840.10045.4.3.2":return"SHA-256";case"1.2.840.10045.4.3.3":return"SHA-384";case"1.2.840.10045.4.3.4":return"SHA-512";case"1.2.840.113549.1.1.10":{if(index=indexAfterOID,index=expectASN1Seq(data,index).index,data[index++]!==160)throw x509Error("non-tag data",data);index=readASN1Length(data,index).index,index=expectASN1Seq(data,index).index;let{oid:hashOID}=readASN1OID(data,index);switch(hashOID){case"1.2.840.113549.2.5":return"MD5";case"1.3.14.3.2.26":return"SHA-1";case"2.16.840.1.101.3.4.2.1":return"SHA-256";case"2.16.840.1.101.3.4.2.2":return"SHA-384";case"2.16.840.1.101.3.4.2.3":return"SHA-512"}throw x509Error("unknown hash OID "+hashOID,data)}case"1.3.101.110":case"1.3.101.112":return"SHA-512";case"1.3.101.111":case"1.3.101.113":throw x509Error("Ed448 certificate channel binding is not currently supported by Postgres")}throw x509Error("unknown OID "+oid,data)}module.exports={signatureAlgorithmHashFromCertificate}});var require_sasl=__commonJS(function(exports,module){var crypto=require_utils2(),{signatureAlgorithmHashFromCertificate}=require_cert_signatures();function saslprep(password){let nonAsciiSpace=/[\u00A0\u1680\u2000-\u200B\u202F\u205F\u3000]/g,mappedToNothing=/[\u00AD\u034F\u1806\u180B\u180C\u180D\u200C\u200D\u2060\uFE00-\uFE0F\uFEFF]/g;return password.replace(nonAsciiSpace," ").replace(mappedToNothing,"").normalize("NFKC")}var DEFAULT_MAX_SCRAM_ITERATIONS=1e5;function startSession(mechanisms,stream,scramMaxIterations=DEFAULT_MAX_SCRAM_ITERATIONS){let candidates=["SCRAM-SHA-256"];if(stream)candidates.unshift("SCRAM-SHA-256-PLUS");let mechanism=candidates.find((candidate)=>mechanisms.includes(candidate));if(!mechanism)throw Error("SASL: Only mechanism(s) "+candidates.join(" and ")+" are supported");if(mechanism==="SCRAM-SHA-256-PLUS"&&typeof stream.getPeerCertificate!=="function")throw Error("SASL: Mechanism SCRAM-SHA-256-PLUS requires a certificate");let clientNonce=crypto.randomBytes(18).toString("base64");return{mechanism,clientNonce,response:(mechanism==="SCRAM-SHA-256-PLUS"?"p=tls-server-end-point":stream?"y":"n")+",,n=*,r="+clientNonce,message:"SASLInitialResponse",scramMaxIterations}}async function continueSession(session,password,serverData,stream){if(session.message!=="SASLInitialResponse")throw Error("SASL: Last message was not SASLInitialResponse");if(typeof password!=="string")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");if(password==="")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string");if(typeof serverData!=="string")throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");let sv=parseServerFirstMessage(serverData);if(!sv.nonce.startsWith(session.clientNonce))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");else if(sv.nonce.length===session.clientNonce.length)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short");let scramMaxIterations=typeof session.scramMaxIterations==="number"?session.scramMaxIterations:DEFAULT_MAX_SCRAM_ITERATIONS;if(scramMaxIterations!==0&&sv.iteration>scramMaxIterations)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration count "+sv.iteration+" exceeds scramMaxIterations of "+scramMaxIterations);let clientFirstMessageBare="n=*,r="+session.clientNonce,serverFirstMessage="r="+sv.nonce+",s="+sv.salt+",i="+sv.iteration,channelBinding=stream?"eSws":"biws";if(session.mechanism==="SCRAM-SHA-256-PLUS"){let peerCert=stream.getPeerCertificate().raw,hashName=signatureAlgorithmHashFromCertificate(peerCert);if(hashName==="MD5"||hashName==="SHA-1")hashName="SHA-256";let certHash=await crypto.hashByName(hashName,peerCert);channelBinding=Buffer.concat([Buffer.from("p=tls-server-end-point,,"),Buffer.from(certHash)]).toString("base64")}let clientFinalMessageWithoutProof="c="+channelBinding+",r="+sv.nonce,authMessage=clientFirstMessageBare+","+serverFirstMessage+","+clientFinalMessageWithoutProof,saltBytes=Buffer.from(sv.salt,"base64"),saltedPassword=await crypto.deriveKey(saslprep(password),saltBytes,sv.iteration),clientKey=await crypto.hmacSha256(saltedPassword,"Client Key"),storedKey=await crypto.sha256(clientKey),clientSignature=await crypto.hmacSha256(storedKey,authMessage),clientProof=xorBuffers(Buffer.from(clientKey),Buffer.from(clientSignature)).toString("base64"),serverKey=await crypto.hmacSha256(saltedPassword,"Server Key"),serverSignatureBytes=await crypto.hmacSha256(serverKey,authMessage);session.message="SASLResponse",session.serverSignature=Buffer.from(serverSignatureBytes).toString("base64"),session.response=clientFinalMessageWithoutProof+",p="+clientProof}function finalizeSession(session,serverData){if(session.message!=="SASLResponse")throw Error("SASL: Last message was not SASLResponse");if(typeof serverData!=="string")throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");let{serverSignature}=parseServerFinalMessage(serverData);if(serverSignature!==session.serverSignature)throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match")}function isPrintableChars(text){if(typeof text!=="string")throw TypeError("SASL: text must be a string");return text.split("").map((_,i)=>text.charCodeAt(i)).every((c)=>c>=33&&c<=43||c>=45&&c<=126)}function isBase64(text){return/^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(text)}function parseAttributePairs(text){if(typeof text!=="string")throw TypeError("SASL: attribute pairs text must be a string");return new Map(text.split(",").map((attrValue)=>{if(!/^.=/.test(attrValue))throw Error("SASL: Invalid attribute pair entry");let name=attrValue[0],value=attrValue.substring(2);return[name,value]}))}function parseServerFirstMessage(data){let attrPairs=parseAttributePairs(data),nonce=attrPairs.get("r");if(!nonce)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");else if(!isPrintableChars(nonce))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters");let salt=attrPairs.get("s");if(!salt)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");else if(!isBase64(salt))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64");let iterationText=attrPairs.get("i");if(!iterationText)throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");else if(!/^[1-9][0-9]*$/.test(iterationText))throw Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count");let iteration=parseInt(iterationText,10);return{nonce,salt,iteration}}function parseServerFinalMessage(serverData){let attrPairs=parseAttributePairs(serverData),error=attrPairs.get("e"),serverSignature=attrPairs.get("v");if(error)throw Error(`SASL: SCRAM-SERVER-FINAL-MESSAGE: server returned error: "${error}"`);if(!serverSignature)throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");else if(!isBase64(serverSignature))throw Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64");return{serverSignature}}function xorBuffers(a,b){if(!Buffer.isBuffer(a))throw TypeError("first argument must be a Buffer");if(!Buffer.isBuffer(b))throw TypeError("second argument must be a Buffer");if(a.length!==b.length)throw Error("Buffer lengths must match");if(a.length===0)throw Error("Buffers cannot be empty");return Buffer.from(a.map((_,i)=>a[i]^b[i]))}module.exports={startSession,continueSession,finalizeSession,DEFAULT_MAX_SCRAM_ITERATIONS}});var require_type_overrides=__commonJS(function(exports,module){var types=require_pg_types();function TypeOverrides(userTypes){this._types=userTypes||types,this.text={},this.binary={}}TypeOverrides.prototype.getOverrides=function(format){switch(format){case"text":return this.text;case"binary":return this.binary;default:return{}}};TypeOverrides.prototype.setTypeParser=function(oid,format,parseFn){if(typeof format==="function")parseFn=format,format="text";this.getOverrides(format)[oid]=parseFn};TypeOverrides.prototype.getTypeParser=function(oid,format){return format=format||"text",this.getOverrides(format)[oid]||this._types.getTypeParser(oid,format)};module.exports=TypeOverrides});var require_pg_connection_string=__commonJS(function(exports,module){function parse(str,options={}){if(str.charAt(0)==="/"){let config=str.split(" ");return{host:config[0],database:config[1]}}let config=Object.create(null),result,dummyHost=!1;if(/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(str))str=encodeURI(str).replace(/%25(\d\d)/g,"%$1");try{try{result=new URL(str,"postgres://base")}catch(e){result=new URL(str.replace("@/","@___DUMMY___/"),"postgres://base"),dummyHost=!0}}catch(err){throw err.input&&(err.input="*****REDACTED*****"),err}for(let entry of result.searchParams.entries())config[entry[0]]=entry[1];if(config.user=config.user||decodeURIComponent(result.username),config.password=config.password||decodeURIComponent(result.password),result.protocol=="socket:")return config.host=decodeURI(result.pathname),config.database=result.searchParams.get("db"),config.client_encoding=result.searchParams.get("encoding"),config;let hostname=(dummyHost?"":result.hostname).replace(/^\[(.+)\]$/,"$1");if(!config.host)config.host=decodeURIComponent(hostname);else if(hostname&&/^%2f/i.test(hostname))result.pathname=hostname+result.pathname;if(!config.port)config.port=result.port;let pathname=result.pathname.slice(1)||null;if(config.database=pathname?decodeURI(pathname):null,config.ssl==="true"||config.ssl==="1")config.ssl=!0;if(config.ssl==="0")config.ssl=!1;if(config.sslcert||config.sslkey||config.sslrootcert||config.sslmode)config.ssl={};if(config.sslnegotiation==="direct"&&config.ssl===void 0)config.ssl=!0;let fs=config.sslcert||config.sslkey||config.sslrootcert?__require("fs"):null;if(config.sslcert)config.ssl.cert=fs.readFileSync(config.sslcert).toString();if(config.sslkey)config.ssl.key=fs.readFileSync(config.sslkey).toString();if(config.sslrootcert)config.ssl.ca=fs.readFileSync(config.sslrootcert).toString();if(options.useLibpqCompat&&config.uselibpqcompat)throw Error("Both useLibpqCompat and uselibpqcompat are set. Please use only one of them.");if(config.uselibpqcompat==="true"||options.useLibpqCompat)switch(config.sslmode){case"disable":{config.ssl=!1;break}case"prefer":{config.ssl.rejectUnauthorized=!1;break}case"require":{if(config.sslrootcert)config.ssl.checkServerIdentity=function(){};else config.ssl.rejectUnauthorized=!1;break}case"verify-ca":{if(!config.ssl.ca)throw Error("SECURITY WARNING: Using sslmode=verify-ca requires specifying a CA with sslrootcert. If a public CA is used, verify-ca allows connections to a server that somebody else may have registered with the CA, making you vulnerable to Man-in-the-Middle attacks. Either specify a custom CA certificate with sslrootcert parameter or use sslmode=verify-full for proper security.");config.ssl.checkServerIdentity=function(){};break}case"verify-full":break}else switch(config.sslmode){case"disable":{config.ssl=!1;break}case"prefer":case"require":case"verify-ca":case"verify-full":{if(config.sslmode!=="verify-full")deprecatedSslModeWarning(config.sslmode);break}case"no-verify":{config.ssl.rejectUnauthorized=!1;break}}return config}function toConnectionOptions(sslConfig){return Object.entries(sslConfig).reduce((c,[key,value])=>{if(value!==void 0&&value!==null)c[key]=value;return c},Object.create(null))}function toClientConfig(config){return Object.entries(config).reduce((c,[key,value])=>{if(key==="ssl"){let sslConfig=value;if(typeof sslConfig==="boolean")c[key]=sslConfig;if(typeof sslConfig==="object")c[key]=toConnectionOptions(sslConfig)}else if(value!==void 0&&value!==null)if(key==="port"){if(value!==""){let v=parseInt(value,10);if(isNaN(v))throw Error(`Invalid ${key}: ${value}`);c[key]=v}}else c[key]=value;return c},Object.create(null))}function parseIntoClientConfig(str){return toClientConfig(parse(str))}function deprecatedSslModeWarning(sslmode){if(!deprecatedSslModeWarning.warned&&typeof process<"u"&&process.emitWarning)deprecatedSslModeWarning.warned=!0,process.emitWarning(`SECURITY WARNING: The SSL modes 'prefer', 'require', and 'verify-ca' are treated as aliases for 'verify-full'.
|
|
3
3
|
In the next major version (pg-connection-string v3.0.0 and pg v9.0.0), these modes will adopt standard libpq semantics, which have weaker security guarantees.
|
|
4
4
|
|
|
5
5
|
To prepare for this change:
|
|
6
6
|
- If you want the current behavior, explicitly use 'sslmode=verify-full'
|
|
7
7
|
- If you want libpq compatibility now, use 'uselibpqcompat=true&sslmode=${sslmode}'
|
|
8
8
|
|
|
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});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?.registerProvider?.(type,provider,name)}getProvider(type,name){let reg=this.hostServices?.serviceRegistry;if(!reg)return;if(name===void 0)return reg.getProvider?.(type);if(!reg.listProvidersForType)return;if(!(reg.listProvidersForType(type)??[]).some((entry)=>typeof entry==="string"?entry===name:entry.pluginName===name))return;return reg.getProvider?.(type)}listProviders(type){return(this.hostServices?.serviceRegistry?.listProvidersForType?.(type)??[]).map((entry)=>typeof entry==="string"?entry:entry.pluginName)}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(`
|
|
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(function(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.sslnegotiation=val("sslnegotiation",config,"PGSSLNEGOTIATION"),this.sslnegotiation!==void 0&&this.sslnegotiation!=="postgres"&&this.sslnegotiation!=="direct")throw Error(`Invalid sslnegotiation value: "${this.sslnegotiation}". Valid values are "postgres" and "direct".`);if(this.sslnegotiation==="direct"&&!this.ssl)throw Error("sslnegotiation=direct requires SSL to be enabled");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"),add(params,this,"sslnegotiation"),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(function(exports,module){var types=require_pg_types(),matchRegexp=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/;class Result{constructor(rowMode,types){if(this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=types,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=Object.create(null);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(function(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]||connection.submittedNamedStatements[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]!==void 0||connection.submittedNamedStatements[this.name]!==void 0)}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)){if(connection.parse({text:this.text,name:this.name,types:this.types}),this.name)connection.submittedNamedStatements[this.name]=this.text}try{connection.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:utils.prepareValue})}catch(err){connection.close({type:"S",name:this.name}),connection.sync(),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(function(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(function(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,0,0,this.offset)}}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}addInt32PrefixedString(string){let len=Buffer.byteLength(string);this.ensure(4+len);let buffer=this.buffer,offset=this.offset;return buffer[offset++]=len>>>24&255,buffer[offset++]=len>>>16&255,buffer[offset++]=len>>>8&255,buffer[offset++]=len>>>0&255,buffer.write(string,offset,"utf-8"),this.offset=offset+len,this}add(otherBuffer){return this.ensure(otherBuffer.length),otherBuffer.copy(this.buffer,this.offset),this.offset+=otherBuffer.length,this}reserveUnsafe(size){let offset=this.offset;return this.ensure(size),this.offset+=size,offset}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}clear(){this.offset=5,this.headerPosition=0}}exports.Writer=Writer});var require_serializer=__commonJS(function(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=(password)=>writer.addCString(password).flush(112),sendSASLInitialResponseMessage=function(mechanism,initialResponse){return writer.addCString(mechanism).addInt32PrefixedString(initialResponse),writer.flush(112)},sendSCRAMClientFinalMessage=function(additionalData){return writer.addString(additionalData).flush(112)},query=(text)=>writer.addCString(text).flush(81),emptyArray=[],parse=(query)=>{let name=query.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=query.types||emptyArray,len=types.length,buffer=writer.addCString(name).addCString(query.text).addInt16(len);for(let i=0;i<len;i++)buffer.addInt32(types[i]);return writer.flush(80)},writeValues=function(values,valueMapper,formatsOffset){let len=values.length;for(let i=0;i<len;i++){let mappedVal=valueMapper?valueMapper(values[i],i):values[i],formatByte=0;if(mappedVal==null)writer.addInt32(-1);else if(mappedVal instanceof Buffer)formatByte=1,writer.addInt32(mappedVal.length),writer.add(mappedVal);else writer.addInt32PrefixedString(mappedVal);let buf=writer.buffer;buf[formatsOffset++]=0,buf[formatsOffset++]=formatByte}},bind=(config={})=>{let portal=config.portal||"",statement=config.statement||"",binary=config.binary||!1,values=config.values||emptyArray,len=values.length;writer.addCString(portal).addCString(statement),writer.addInt16(len);let formatsOffset=writer.reserveUnsafe(len*2);writer.addInt16(len);try{writeValues(values,config.valueMapper,formatsOffset)}catch(err){throw writer.clear(),err}return 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)=>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)=>writer.add(chunk).flush(100),copyFail=(message)=>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(function(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++]);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(function(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.uint32();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(function(exports){Object.defineProperty(exports,"__esModule",{value:!0});exports.DatabaseError=exports.serialize=void 0;exports.parse=parse;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()))}});var require_empty=__commonJS(function(exports){Object.defineProperty(exports,"__esModule",{value:!0});exports.default={}});var require_stream=__commonJS(function(exports,module){var{getStream,getSecureStream}=getStreamFuncs();module.exports={getStream,getSecureStream};function getNodejsStreamFuncs(){function getStream(ssl){let net=__require("net");return new net.Socket}function getSecureStream(options){let tls=__require("tls");return tls.connect(options)}return{getStream,getSecureStream}}function getCloudflareStreamFuncs(){function getStream(ssl){let{CloudflareSocket}=require_empty();return new CloudflareSocket(ssl)}function getSecureStream(options){return options.socket.startTls(options),options.socket}return{getStream,getSecureStream}}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(function(exports,module){var EventEmitter=__require("events").EventEmitter,{parse,serialize}=require_dist(),stream=require_stream(),{getStream}=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.submittedNamedStatements={},this.ssl=config.ssl||!1,this.sslNegotiation=config.sslNegotiation||"postgres",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);if(this.sslNegotiation==="direct")return this.stream.once("connect",function(){self.upgradeToSSL(host,reportStreamError)});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"))}self.upgradeToSSL(host,reportStreamError)})}upgradeToSSL(host,reportStreamError){let self=this,options={socket:self.stream,host};if(self.ssl!==!0){if(Object.assign(options,self.ssl),"key"in self.ssl)options.key=self.ssl.key}if(self.sslNegotiation==="direct")options.ALPNProtocols=["postgresql"];let net=__require("net");if(net.isIP&&net.isIP(host)===0)options.servername=host;try{self.stream=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._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(function(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(function(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(function(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(function(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.");function coerceNumberOrDefault(value,defaultValue){if(typeof value==="number")return Number.isFinite(value)?value:defaultValue;if(typeof value==="string"&&value.trim()!==""){let n=Number(value);return Number.isFinite(n)?n:defaultValue}return defaultValue}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._txStatus=null,this.enableChannelBinding=Boolean(c.enableChannelBinding),this.scramMaxIterations=coerceNumberOrDefault(c.scramMaxIterations,sasl.DEFAULT_MAX_SCRAM_ITERATIONS),this.connection=c.connection||new Connection({stream:c.stream,ssl:this.connectionParameters.ssl,sslNegotiation:this.connectionParameters.sslnegotiation,keepAlive:c.keepAlive||!1,keepAliveInitialDelayMillis:c.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this._queryQueue=[],this._sentQueryQueue=[],this.pipeline=Boolean(c.pipeline),this.binary=c.binary||defaults.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.sslNegotiation=this.connectionParameters.sslnegotiation||"postgres",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._sentQueryQueue.forEach(enqueueError),this._sentQueryQueue.length=0,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){if(self.sslNegotiation!=="direct")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.scramMaxIterations),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._txStatus=msg?.status??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}if(this._activeQuery=null,activeQuery.name)delete this.connection.submittedNamedStatements[activeQuery.name];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,delete this.connection.submittedNamedStatements[activeQuery.name]}_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);else if(client._sentQueryQueue.indexOf(query)!==-1)query.callback=()=>{}}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.pipeline){this._pulsePipelinedQueryQueue();return}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")}}_pulsePipelinedQueryQueue(){if(!this._connected||!this._queryable)return;while(this._queryQueue.length>0){let query=this._queryQueue.shift();this.hasExecuted=!0;let queryError=query.submit(this.connection);if(queryError){process.nextTick(()=>{query.handleError(queryError,this.connection)});continue}this._sentQueryQueue.push(query)}if(this.readyForQuery&&!this._activeQuery&&this._sentQueryQueue.length>0)this._activeQuery=this._sentQueryQueue.shift(),this.readyForQuery=!1;if(!this._activeQuery&&this._sentQueryQueue.length===0&&this._queryQueue.length===0&&this.hasExecuted)this.emit("drain")}query(config,values,callback){let query,result;if(config==null)throw TypeError("Client was passed a null or undefined query");if(typeof config.submit==="function"){if(result=query=config,!query.callback){if(typeof values==="function")query.callback=values;else if(callback)query.callback=callback}}else if(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});else if(typeof query.callback!=="function")throw TypeError("callback is not a function");let readTimeout=config.query_timeout||this.connectionParameters.query_timeout;if(readTimeout){let 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);else if(this.pipeline){this.connection.stream.destroy();return}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.pipeline){let portalQuery=typeof config.submit==="function"&&!(query instanceof Query)?"Custom query classes such as pg-cursor and pg-query-stream are":query.rows?"The `rows` option is":null;if(portalQuery)return process.nextTick(()=>{query.handleError(Error(`${portalQuery} not supported in pipeline mode`),this.connection)}),result}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&&!this.pipeline)queryQueueLengthDeprecationNotice();return this._queryQueue.push(query),this._pulseQueryQueue(),result}ref(){this.connection.ref()}unref(){this.connection.unref()}getTransactionStatus(){return this._txStatus}end(cb){if(this._ending=!0,!this.connection._connecting||this._ended)if(cb){cb();return}else return this._Promise.resolve();if(!this._queryable)this.connection.stream.destroy();else if(this.pipeline&&(this._getActiveQuery()||this._sentQueryQueue.length>0||this._queryQueue.length>0))this.once("drain",()=>this.connection.end());else if(this._getActiveQuery())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(function(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,client,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 response=promisify(this.Promise,text);return setImmediate(function(){return response.callback(Error("Passing a function as the first parameter to pool.query is not supported"))}),response.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=(err)=>{if(clientReleased)return;clientReleased=!0,client.release(err),cb(err)};client.once("error",onError),this.log("dispatching query");try{client.query(text,values,(err,res)=>{if(this.log("query dispatched"),client.removeListener("error",onError),clientReleased)return;if(clientReleased=!0,client.release(err),err)return cb(err);return cb(void 0,res)})}catch(err){return client.release(err),cb(err)}}),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(function(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",messageDetail:"detail",messageHint:"hint",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&&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]!==void 0){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(function(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,this.pipeline=Boolean(config.pipeline),this._pipelineInFlight=!1;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(err){if(err)return self.native.end(),cb(err);self._connected=!0,self.native.on("error",function(err){self._queryable=!1,self._errorAllQueries(err),self.emit("error",err)}),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&&!this.pipeline)queryQueueLengthDeprecationNotice();return this._queryQueue.push(query),this._pulseQueryQueue(),result};Client.prototype.end=function(cb){let self=this;if(this._ending=!0,this._connecting&&!this._connected)this.once("connect",()=>{this.end(()=>{})});let result;if(!cb)result=new this._Promise(function(resolve,reject){cb=(err)=>err?reject(err):resolve()});let doEnd=function(){self.native.end(function(){self._connected=!1,self._errorAllQueries(Error("Connection terminated")),process.nextTick(()=>{if(self.emit("end"),cb)cb()})})};if(this.pipeline&&(this._pipelineInFlight||this._queryQueue.length>0))this.once("drain",doEnd);else doEnd();return 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.pipeline&&!initialConnection)return this._pulsePipelinedQueryQueue();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._pulsePipelinedQueryQueue=function(){if(!this._connected||this._pipelineInFlight)return;if(this._queryQueue.length===0){if(this.hasExecuted)this.emit("drain");return}this._pipelineInFlight=!0;let self=this,queries=[],nativeQueries=[],utils=require_utils();while(this._queryQueue.length>0){let query=this._queryQueue.shift();this.hasExecuted=!0,nativeQueries.push(query);let values=query.values?query.values.map(utils.prepareValue):null,pipelineEntry={text:query.text,name:query.name,arrayMode:query._arrayMode};if(values)pipelineEntry.values=values;if(query.name&&this.namedQueries[query.name])pipelineEntry._alreadyPrepared=!0;queries.push(pipelineEntry)}this.native.pipeline(queries,function(err,results){if(self._pipelineInFlight=!1,err){self._connected=!1,self._queryable=!1;for(let i=0;i<nativeQueries.length;i++){let q=nativeQueries[i];q.native=self.native,q.handleError(err)}self._errorAllQueries(err),self.emit("error",err),self.emit("end");return}for(let i=0;i<nativeQueries.length;i++){let q=nativeQueries[i],r=results[i];if(q.native=self.native,r.err)q.handleError(r.err);else{if(q.name)self.namedQueries[q.name]=q.text;if(q.state="end",q.emit("end",r.result),q.callback)q.callback(null,r.result)}setImmediate(function(){q.emit("_done")})}self._pulsePipelinedQueryQueue()})};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};Client.prototype.getTransactionStatus=function(){return this.native.getTransactionStatus()}});var require_lib2=__commonJS(function(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=(Client)=>class extends Pool{constructor(options){super(options,Client)}},PG=function(clientConstructor){this.defaults=defaults,this.Client=clientConstructor,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 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,onNuke,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)},onNuke:async(hostServices,ctx)=>{if(onNuke)return onNuke(hostServices,ctx)}}}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 CONTEXT_PROVIDER_TYPE="context",REGISTRY_KEY=Symbol.for("@vibecontrols/plugin-sdk:contextProviders@1");function getRegistry(){let slots=globalThis,existing=slots[REGISTRY_KEY];if(existing)return existing;let created=new Map;return slots[REGISTRY_KEY]=created,created}function registerContextProvider(provider,hostServices){if(!provider||typeof provider.name!=="string"||provider.name.length===0)throw Error("ContextProvider.name is required");if(typeof provider.getContext!=="function")throw Error("ContextProvider.getContext must be a function");getRegistry().set(provider.name,provider),hostServices?.serviceRegistry?.registerProvider?.(CONTEXT_PROVIDER_TYPE,provider,provider.name)}function listContextProviders(){return Array.from(getRegistry().values())}function getContextProvider(name){return getRegistry().get(name)}var ProviderRegistry=class{constructor(hostServices){this.hostServices=hostServices}hostServices;registerContextProvider(provider){registerContextProvider(provider,this.hostServices)}listContextProviders(){return listContextProviders()}getContextProvider(name){return getContextProvider(name)}getServiceRegistry(){return this.hostServices?.serviceRegistry}registerProvider(type,name,provider){this.hostServices?.serviceRegistry?.registerProvider?.(type,provider,name)}getProvider(type,name){let reg=this.hostServices?.serviceRegistry;if(!reg)return;if(name===void 0)return reg.getProvider?.(type);if(reg.getProviderByName)return reg.getProviderByName(type,name);if(!reg.listProvidersForType)return;if(!(reg.listProvidersForType(type)??[]).some((entry)=>typeof entry==="string"?entry===name:entry.pluginName===name))return;return reg.getProvider?.(type)}listProviders(type){return(this.hostServices?.serviceRegistry?.listProvidersForType?.(type)??[]).map((entry)=>typeof entry==="string"?entry:entry.pluginName)}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";import{dirname,sep}from"path";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(`
|
|
12
12
|
CREATE TABLE IF NOT EXISTS documents (
|
|
13
13
|
collection text NOT NULL,
|
|
14
14
|
id text NOT NULL,
|
|
@@ -23,4 +23,4 @@ See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode de
|
|
|
23
23
|
CREATE INDEX IF NOT EXISTS idx_doc_updated_at ON documents (updated_at);
|
|
24
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)
|
|
25
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)
|
|
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
|
|
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 r=row,json=decrypt({ciphertext:r.ciphertext,iv:r.iv,tag:r.tag},this.key);return{collection,id:r.id,value:JSON.parse(json),createdAt:r.created_at.toISOString(),updatedAt:r.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 backup(targetPath){let pgDump=Bun.which("pg_dump",{PATH:process.env.PATH});if(pgDump===null)throw Error("Postgres backup failed: PostgreSQL client tools not found on PATH (could not locate `pg_dump`). Install the PostgreSQL client tools and ensure `pg_dump` is on PATH.");let proc=Bun.spawn([pgDump,"--format=custom","--file",targetPath,this.connStr],{stdout:"pipe",stderr:"pipe"}),exitCode=await proc.exited;if(exitCode!==0){let err=await new Response(proc.stderr).text();throw Error(`Postgres backup failed (exit ${exitCode}): ${err}`)}}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 parent,current=repo.path;for(;;){let candidate=dirname(current);if(candidate===current||candidate===sep||candidate===".")break;if(byPath.has(candidate)&&candidate!==repo.path){parent=candidate;break}current=candidate}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(),{})),PoolCtor=Pool??esm_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.4",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}},src_default=createPlugin;export{createPlugin,createPostgresAgentDatabase,src_default as default};
|
package/package.json
CHANGED
|
@@ -1,47 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vibecontrols/vibe-plugin-storage-postgres",
|
|
3
|
-
"version": "2026.
|
|
3
|
+
"version": "2026.1109.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
7
7
|
"description": "PostgreSQL storage provider for the VibeControls agent — full-parity adapter with AES-256-GCM encryption at rest.",
|
|
8
8
|
"engines": {
|
|
9
|
-
"bun": ">=1.
|
|
9
|
+
"bun": ">=1.4.4"
|
|
10
10
|
},
|
|
11
11
|
"author": {
|
|
12
12
|
"name": "Vignesh T.V",
|
|
13
|
-
"email": "vignesh@burdenoff.com",
|
|
14
13
|
"url": "https://github.com/tvvignesh"
|
|
15
14
|
},
|
|
16
|
-
"license": "
|
|
15
|
+
"license": "MIT",
|
|
17
16
|
"scripts": {
|
|
18
|
-
"build": "bun build ./src/index.ts --outdir ./dist --target bun --minify-syntax --minify-whitespace --external elysia && tsc
|
|
19
|
-
"dev": "tsc --watch",
|
|
20
|
-
"lint": "eslint
|
|
21
|
-
"format": "
|
|
22
|
-
"format:check": "
|
|
23
|
-
"type:check": "
|
|
24
|
-
"test": "bun test
|
|
17
|
+
"build": "bun build ./src/index.ts --outdir ./dist --target bun --minify-syntax --minify-whitespace --external elysia && tsc -p tsconfig.build.json",
|
|
18
|
+
"dev": "tsc -p tsconfig.build.json --watch",
|
|
19
|
+
"lint": "eslint .",
|
|
20
|
+
"format": "bun fmt",
|
|
21
|
+
"format:check": "bun fmt --check",
|
|
22
|
+
"type:check": "boff gate -- bun check --no-pretty",
|
|
23
|
+
"test": "bun test",
|
|
25
24
|
"clean": "rimraf dist",
|
|
26
25
|
"prebuild": "bun run clean",
|
|
27
26
|
"prepublishOnly": "bun run build",
|
|
28
|
-
"sanity": "
|
|
27
|
+
"sanity": "boff sanity",
|
|
28
|
+
"sanity:force": "boff sanity --force",
|
|
29
|
+
"audit": "bun audit --audit-level=high"
|
|
29
30
|
},
|
|
30
31
|
"dependencies": {
|
|
31
|
-
"@vibecontrols/plugin-sdk": "2026.
|
|
32
|
-
"pg": "^8.
|
|
32
|
+
"@vibecontrols/plugin-sdk": "2026.1108.1",
|
|
33
|
+
"pg": "^8.23.1"
|
|
33
34
|
},
|
|
34
35
|
"devDependencies": {
|
|
35
|
-
"@
|
|
36
|
-
"@types/
|
|
37
|
-
"@types/pg": "^8.
|
|
38
|
-
"
|
|
39
|
-
"
|
|
40
|
-
"
|
|
41
|
-
"
|
|
42
|
-
"rimraf": "^6.0.1",
|
|
43
|
-
"typescript": "^5.9.3",
|
|
44
|
-
"typescript-eslint": "^8.56.0"
|
|
36
|
+
"@burdenoff/toolchain": "2026.1107.14",
|
|
37
|
+
"@types/bun": "^1.4.4",
|
|
38
|
+
"@types/pg": "^8.23.1",
|
|
39
|
+
"eslint": "^9.39.5",
|
|
40
|
+
"knip": "^6.44.1",
|
|
41
|
+
"rimraf": "^6.1.4",
|
|
42
|
+
"typescript": "6.0.3"
|
|
45
43
|
},
|
|
46
44
|
"peerDependencies": {
|
|
47
45
|
"@vibecontrols/vibe-plugin-storage": "2026.509.2",
|
|
@@ -74,6 +72,23 @@
|
|
|
74
72
|
"homepage": "https://github.com/Algoshred/vibe-plugin-storage-postgres",
|
|
75
73
|
"repository": {
|
|
76
74
|
"type": "git",
|
|
77
|
-
"url": "https://github.com/Algoshred/vibe-plugin-storage-postgres"
|
|
75
|
+
"url": "git+https://github.com/Algoshred/vibe-plugin-storage-postgres.git"
|
|
76
|
+
},
|
|
77
|
+
"bugs": {
|
|
78
|
+
"url": "https://github.com/Algoshred/vibe-plugin-storage-postgres/issues"
|
|
79
|
+
},
|
|
80
|
+
"packageManager": "bun@1.4.4",
|
|
81
|
+
"boff": {
|
|
82
|
+
"type": "plugin",
|
|
83
|
+
"sanity": {
|
|
84
|
+
"steps": [
|
|
85
|
+
"format",
|
|
86
|
+
"lint",
|
|
87
|
+
"typecheck",
|
|
88
|
+
"build",
|
|
89
|
+
"test",
|
|
90
|
+
"knip"
|
|
91
|
+
]
|
|
92
|
+
}
|
|
78
93
|
}
|
|
79
94
|
}
|