relq 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (305) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +862 -0
  3. package/dist/addons/buffer.js +1869 -0
  4. package/dist/addons/pg-cursor.js +1425 -0
  5. package/dist/addons/pg-format.js +2248 -0
  6. package/dist/addons/pg.js +4790 -0
  7. package/dist/bin/relq.js +2 -0
  8. package/dist/cjs/cache/index.cjs +9 -0
  9. package/dist/cjs/cache/query-cache.cjs +311 -0
  10. package/dist/cjs/cli/commands/add.cjs +82 -0
  11. package/dist/cjs/cli/commands/commit.cjs +145 -0
  12. package/dist/cjs/cli/commands/diff.cjs +84 -0
  13. package/dist/cjs/cli/commands/export.cjs +333 -0
  14. package/dist/cjs/cli/commands/fetch.cjs +59 -0
  15. package/dist/cjs/cli/commands/generate.cjs +242 -0
  16. package/dist/cjs/cli/commands/history.cjs +165 -0
  17. package/dist/cjs/cli/commands/import.cjs +524 -0
  18. package/dist/cjs/cli/commands/init.cjs +437 -0
  19. package/dist/cjs/cli/commands/introspect.cjs +142 -0
  20. package/dist/cjs/cli/commands/log.cjs +62 -0
  21. package/dist/cjs/cli/commands/migrate.cjs +167 -0
  22. package/dist/cjs/cli/commands/pull.cjs +410 -0
  23. package/dist/cjs/cli/commands/push.cjs +165 -0
  24. package/dist/cjs/cli/commands/rollback.cjs +169 -0
  25. package/dist/cjs/cli/commands/status.cjs +110 -0
  26. package/dist/cjs/cli/commands/sync.cjs +79 -0
  27. package/dist/cjs/cli/index.cjs +275 -0
  28. package/dist/cjs/cli/utils/change-tracker.cjs +446 -0
  29. package/dist/cjs/cli/utils/commit-manager.cjs +239 -0
  30. package/dist/cjs/cli/utils/config-loader.cjs +127 -0
  31. package/dist/cjs/cli/utils/env-loader.cjs +62 -0
  32. package/dist/cjs/cli/utils/fast-introspect.cjs +398 -0
  33. package/dist/cjs/cli/utils/git-utils.cjs +404 -0
  34. package/dist/cjs/cli/utils/migration-generator.cjs +269 -0
  35. package/dist/cjs/cli/utils/relqignore.cjs +114 -0
  36. package/dist/cjs/cli/utils/repo-manager.cjs +515 -0
  37. package/dist/cjs/cli/utils/schema-comparator.cjs +313 -0
  38. package/dist/cjs/cli/utils/schema-diff.cjs +284 -0
  39. package/dist/cjs/cli/utils/schema-hash.cjs +108 -0
  40. package/dist/cjs/cli/utils/schema-introspect.cjs +455 -0
  41. package/dist/cjs/cli/utils/snapshot-manager.cjs +223 -0
  42. package/dist/cjs/cli/utils/spinner.cjs +108 -0
  43. package/dist/cjs/cli/utils/sql-generator.cjs +520 -0
  44. package/dist/cjs/cli/utils/sql-parser.cjs +999 -0
  45. package/dist/cjs/cli/utils/type-generator.cjs +2061 -0
  46. package/dist/cjs/condition/array-condition-builder.cjs +503 -0
  47. package/dist/cjs/condition/array-numeric-condition-builder.cjs +186 -0
  48. package/dist/cjs/condition/array-specialized-condition-builder.cjs +206 -0
  49. package/dist/cjs/condition/array-string-condition-builder.cjs +146 -0
  50. package/dist/cjs/condition/base-condition-builder.cjs +2 -0
  51. package/dist/cjs/condition/condition-collector.cjs +284 -0
  52. package/dist/cjs/condition/fulltext-condition-builder.cjs +61 -0
  53. package/dist/cjs/condition/geometric-condition-builder.cjs +208 -0
  54. package/dist/cjs/condition/index.cjs +25 -0
  55. package/dist/cjs/condition/jsonb-condition-builder.cjs +160 -0
  56. package/dist/cjs/condition/network-condition-builder.cjs +230 -0
  57. package/dist/cjs/condition/range-condition-builder.cjs +82 -0
  58. package/dist/cjs/config/config.cjs +190 -0
  59. package/dist/cjs/config/index.cjs +9 -0
  60. package/dist/cjs/constants/pg-values.cjs +68 -0
  61. package/dist/cjs/copy/copy-builder.cjs +316 -0
  62. package/dist/cjs/copy/index.cjs +6 -0
  63. package/dist/cjs/core/query-builder.cjs +440 -0
  64. package/dist/cjs/core/relq-client.cjs +1831 -0
  65. package/dist/cjs/core/typed-kuery-client.cjs +2 -0
  66. package/dist/cjs/count/count-builder.cjs +88 -0
  67. package/dist/cjs/count/index.cjs +5 -0
  68. package/dist/cjs/cte/cte-builder.cjs +89 -0
  69. package/dist/cjs/cte/index.cjs +5 -0
  70. package/dist/cjs/ddl/function.cjs +48 -0
  71. package/dist/cjs/ddl/index.cjs +7 -0
  72. package/dist/cjs/ddl/sql.cjs +54 -0
  73. package/dist/cjs/delete/delete-builder.cjs +135 -0
  74. package/dist/cjs/delete/index.cjs +5 -0
  75. package/dist/cjs/errors/relq-errors.cjs +329 -0
  76. package/dist/cjs/examples/fulltext-search-test.cjs +122 -0
  77. package/dist/cjs/explain/explain-builder.cjs +99 -0
  78. package/dist/cjs/explain/index.cjs +5 -0
  79. package/dist/cjs/function/create-function-builder.cjs +196 -0
  80. package/dist/cjs/function/index.cjs +6 -0
  81. package/dist/cjs/functions/advanced-functions.cjs +241 -0
  82. package/dist/cjs/functions/case-builder.cjs +66 -0
  83. package/dist/cjs/functions/geometric-functions.cjs +104 -0
  84. package/dist/cjs/functions/index.cjs +184 -0
  85. package/dist/cjs/functions/network-functions.cjs +86 -0
  86. package/dist/cjs/functions/sql-functions.cjs +431 -0
  87. package/dist/cjs/index.cjs +164 -0
  88. package/dist/cjs/indexing/create-index-builder.cjs +187 -0
  89. package/dist/cjs/indexing/drop-index-builder.cjs +89 -0
  90. package/dist/cjs/indexing/index-types.cjs +2 -0
  91. package/dist/cjs/indexing/index.cjs +8 -0
  92. package/dist/cjs/insert/conflict-builder.cjs +173 -0
  93. package/dist/cjs/insert/index.cjs +5 -0
  94. package/dist/cjs/insert/insert-builder.cjs +254 -0
  95. package/dist/cjs/introspect/index.cjs +229 -0
  96. package/dist/cjs/maintenance/index.cjs +6 -0
  97. package/dist/cjs/maintenance/vacuum-builder.cjs +166 -0
  98. package/dist/cjs/pubsub/index.cjs +7 -0
  99. package/dist/cjs/pubsub/listen-notify-builder.cjs +57 -0
  100. package/dist/cjs/pubsub/listener-connection.cjs +180 -0
  101. package/dist/cjs/raw/index.cjs +5 -0
  102. package/dist/cjs/raw/raw-query-builder.cjs +27 -0
  103. package/dist/cjs/schema/index.cjs +15 -0
  104. package/dist/cjs/schema/schema-builder.cjs +1167 -0
  105. package/dist/cjs/schema-builder.cjs +21 -0
  106. package/dist/cjs/schema-definition/column-types.cjs +829 -0
  107. package/dist/cjs/schema-definition/index.cjs +62 -0
  108. package/dist/cjs/schema-definition/introspection.cjs +620 -0
  109. package/dist/cjs/schema-definition/partitions.cjs +129 -0
  110. package/dist/cjs/schema-definition/pg-enum.cjs +76 -0
  111. package/dist/cjs/schema-definition/pg-function.cjs +91 -0
  112. package/dist/cjs/schema-definition/pg-sequence.cjs +56 -0
  113. package/dist/cjs/schema-definition/pg-trigger.cjs +108 -0
  114. package/dist/cjs/schema-definition/relations.cjs +98 -0
  115. package/dist/cjs/schema-definition/sql-expressions.cjs +202 -0
  116. package/dist/cjs/schema-definition/table-definition.cjs +636 -0
  117. package/dist/cjs/select/aggregate-builder.cjs +179 -0
  118. package/dist/cjs/select/index.cjs +5 -0
  119. package/dist/cjs/select/select-builder.cjs +233 -0
  120. package/dist/cjs/sequence/index.cjs +7 -0
  121. package/dist/cjs/sequence/sequence-builder.cjs +264 -0
  122. package/dist/cjs/table/alter-table-builder.cjs +146 -0
  123. package/dist/cjs/table/constraint-builder.cjs +102 -0
  124. package/dist/cjs/table/create-table-builder.cjs +248 -0
  125. package/dist/cjs/table/index.cjs +17 -0
  126. package/dist/cjs/table/partition-builder.cjs +131 -0
  127. package/dist/cjs/table/truncate-builder.cjs +70 -0
  128. package/dist/cjs/transaction/index.cjs +6 -0
  129. package/dist/cjs/transaction/transaction-builder.cjs +78 -0
  130. package/dist/cjs/trigger/create-trigger-builder.cjs +174 -0
  131. package/dist/cjs/trigger/index.cjs +6 -0
  132. package/dist/cjs/types/aggregate-types.cjs +2 -0
  133. package/dist/cjs/types/config-types.cjs +40 -0
  134. package/dist/cjs/types/inference-types.cjs +18 -0
  135. package/dist/cjs/types/pagination-types.cjs +7 -0
  136. package/dist/cjs/types/result-types.cjs +2 -0
  137. package/dist/cjs/types/schema-types.cjs +2 -0
  138. package/dist/cjs/types/subscription-types.cjs +2 -0
  139. package/dist/cjs/types.cjs +2 -0
  140. package/dist/cjs/update/array-update-builder.cjs +205 -0
  141. package/dist/cjs/update/index.cjs +13 -0
  142. package/dist/cjs/update/update-builder.cjs +195 -0
  143. package/dist/cjs/utils/case-converter.cjs +58 -0
  144. package/dist/cjs/utils/environment-detection.cjs +120 -0
  145. package/dist/cjs/utils/index.cjs +10 -0
  146. package/dist/cjs/utils/pool-defaults.cjs +106 -0
  147. package/dist/cjs/utils/type-coercion.cjs +118 -0
  148. package/dist/cjs/view/create-view-builder.cjs +180 -0
  149. package/dist/cjs/view/index.cjs +7 -0
  150. package/dist/cjs/window/index.cjs +5 -0
  151. package/dist/cjs/window/window-builder.cjs +80 -0
  152. package/dist/config.cjs +1 -0
  153. package/dist/config.d.ts +655 -0
  154. package/dist/config.js +1 -0
  155. package/dist/esm/cache/index.js +1 -0
  156. package/dist/esm/cache/query-cache.js +303 -0
  157. package/dist/esm/cli/commands/add.js +78 -0
  158. package/dist/esm/cli/commands/commit.js +109 -0
  159. package/dist/esm/cli/commands/diff.js +81 -0
  160. package/dist/esm/cli/commands/export.js +297 -0
  161. package/dist/esm/cli/commands/fetch.js +56 -0
  162. package/dist/esm/cli/commands/generate.js +206 -0
  163. package/dist/esm/cli/commands/history.js +129 -0
  164. package/dist/esm/cli/commands/import.js +488 -0
  165. package/dist/esm/cli/commands/init.js +401 -0
  166. package/dist/esm/cli/commands/introspect.js +106 -0
  167. package/dist/esm/cli/commands/log.js +59 -0
  168. package/dist/esm/cli/commands/migrate.js +131 -0
  169. package/dist/esm/cli/commands/pull.js +374 -0
  170. package/dist/esm/cli/commands/push.js +129 -0
  171. package/dist/esm/cli/commands/rollback.js +133 -0
  172. package/dist/esm/cli/commands/status.js +107 -0
  173. package/dist/esm/cli/commands/sync.js +76 -0
  174. package/dist/esm/cli/index.js +240 -0
  175. package/dist/esm/cli/utils/change-tracker.js +405 -0
  176. package/dist/esm/cli/utils/commit-manager.js +191 -0
  177. package/dist/esm/cli/utils/config-loader.js +86 -0
  178. package/dist/esm/cli/utils/env-loader.js +57 -0
  179. package/dist/esm/cli/utils/fast-introspect.js +362 -0
  180. package/dist/esm/cli/utils/git-utils.js +347 -0
  181. package/dist/esm/cli/utils/migration-generator.js +263 -0
  182. package/dist/esm/cli/utils/relqignore.js +74 -0
  183. package/dist/esm/cli/utils/repo-manager.js +444 -0
  184. package/dist/esm/cli/utils/schema-comparator.js +307 -0
  185. package/dist/esm/cli/utils/schema-diff.js +276 -0
  186. package/dist/esm/cli/utils/schema-hash.js +69 -0
  187. package/dist/esm/cli/utils/schema-introspect.js +418 -0
  188. package/dist/esm/cli/utils/snapshot-manager.js +179 -0
  189. package/dist/esm/cli/utils/spinner.js +101 -0
  190. package/dist/esm/cli/utils/sql-generator.js +504 -0
  191. package/dist/esm/cli/utils/sql-parser.js +992 -0
  192. package/dist/esm/cli/utils/type-generator.js +2058 -0
  193. package/dist/esm/condition/array-condition-builder.js +495 -0
  194. package/dist/esm/condition/array-numeric-condition-builder.js +182 -0
  195. package/dist/esm/condition/array-specialized-condition-builder.js +200 -0
  196. package/dist/esm/condition/array-string-condition-builder.js +142 -0
  197. package/dist/esm/condition/base-condition-builder.js +1 -0
  198. package/dist/esm/condition/condition-collector.js +275 -0
  199. package/dist/esm/condition/fulltext-condition-builder.js +53 -0
  200. package/dist/esm/condition/geometric-condition-builder.js +200 -0
  201. package/dist/esm/condition/index.js +7 -0
  202. package/dist/esm/condition/jsonb-condition-builder.js +152 -0
  203. package/dist/esm/condition/network-condition-builder.js +222 -0
  204. package/dist/esm/condition/range-condition-builder.js +74 -0
  205. package/dist/esm/config/config.js +150 -0
  206. package/dist/esm/config/index.js +1 -0
  207. package/dist/esm/constants/pg-values.js +63 -0
  208. package/dist/esm/copy/copy-builder.js +308 -0
  209. package/dist/esm/copy/index.js +1 -0
  210. package/dist/esm/core/query-builder.js +426 -0
  211. package/dist/esm/core/relq-client.js +1791 -0
  212. package/dist/esm/core/typed-kuery-client.js +1 -0
  213. package/dist/esm/count/count-builder.js +81 -0
  214. package/dist/esm/count/index.js +1 -0
  215. package/dist/esm/cte/cte-builder.js +82 -0
  216. package/dist/esm/cte/index.js +1 -0
  217. package/dist/esm/ddl/function.js +45 -0
  218. package/dist/esm/ddl/index.js +2 -0
  219. package/dist/esm/ddl/sql.js +51 -0
  220. package/dist/esm/delete/delete-builder.js +128 -0
  221. package/dist/esm/delete/index.js +1 -0
  222. package/dist/esm/errors/relq-errors.js +310 -0
  223. package/dist/esm/examples/fulltext-search-test.js +117 -0
  224. package/dist/esm/explain/explain-builder.js +95 -0
  225. package/dist/esm/explain/index.js +1 -0
  226. package/dist/esm/function/create-function-builder.js +188 -0
  227. package/dist/esm/function/index.js +1 -0
  228. package/dist/esm/functions/advanced-functions.js +231 -0
  229. package/dist/esm/functions/case-builder.js +58 -0
  230. package/dist/esm/functions/geometric-functions.js +97 -0
  231. package/dist/esm/functions/index.js +171 -0
  232. package/dist/esm/functions/network-functions.js +79 -0
  233. package/dist/esm/functions/sql-functions.js +421 -0
  234. package/dist/esm/index.js +34 -0
  235. package/dist/esm/indexing/create-index-builder.js +180 -0
  236. package/dist/esm/indexing/drop-index-builder.js +81 -0
  237. package/dist/esm/indexing/index-types.js +1 -0
  238. package/dist/esm/indexing/index.js +2 -0
  239. package/dist/esm/insert/conflict-builder.js +162 -0
  240. package/dist/esm/insert/index.js +1 -0
  241. package/dist/esm/insert/insert-builder.js +247 -0
  242. package/dist/esm/introspect/index.js +224 -0
  243. package/dist/esm/maintenance/index.js +1 -0
  244. package/dist/esm/maintenance/vacuum-builder.js +158 -0
  245. package/dist/esm/pubsub/index.js +1 -0
  246. package/dist/esm/pubsub/listen-notify-builder.js +48 -0
  247. package/dist/esm/pubsub/listener-connection.js +173 -0
  248. package/dist/esm/raw/index.js +1 -0
  249. package/dist/esm/raw/raw-query-builder.js +20 -0
  250. package/dist/esm/schema/index.js +1 -0
  251. package/dist/esm/schema/schema-builder.js +1150 -0
  252. package/dist/esm/schema-builder.js +2 -0
  253. package/dist/esm/schema-definition/column-types.js +738 -0
  254. package/dist/esm/schema-definition/index.js +10 -0
  255. package/dist/esm/schema-definition/introspection.js +614 -0
  256. package/dist/esm/schema-definition/partitions.js +123 -0
  257. package/dist/esm/schema-definition/pg-enum.js +70 -0
  258. package/dist/esm/schema-definition/pg-function.js +85 -0
  259. package/dist/esm/schema-definition/pg-sequence.js +50 -0
  260. package/dist/esm/schema-definition/pg-trigger.js +102 -0
  261. package/dist/esm/schema-definition/relations.js +90 -0
  262. package/dist/esm/schema-definition/sql-expressions.js +193 -0
  263. package/dist/esm/schema-definition/table-definition.js +630 -0
  264. package/dist/esm/select/aggregate-builder.js +172 -0
  265. package/dist/esm/select/index.js +1 -0
  266. package/dist/esm/select/select-builder.js +226 -0
  267. package/dist/esm/sequence/index.js +1 -0
  268. package/dist/esm/sequence/sequence-builder.js +255 -0
  269. package/dist/esm/table/alter-table-builder.js +138 -0
  270. package/dist/esm/table/constraint-builder.js +95 -0
  271. package/dist/esm/table/create-table-builder.js +241 -0
  272. package/dist/esm/table/index.js +5 -0
  273. package/dist/esm/table/partition-builder.js +121 -0
  274. package/dist/esm/table/truncate-builder.js +63 -0
  275. package/dist/esm/transaction/index.js +1 -0
  276. package/dist/esm/transaction/transaction-builder.js +70 -0
  277. package/dist/esm/trigger/create-trigger-builder.js +166 -0
  278. package/dist/esm/trigger/index.js +1 -0
  279. package/dist/esm/types/aggregate-types.js +1 -0
  280. package/dist/esm/types/config-types.js +36 -0
  281. package/dist/esm/types/inference-types.js +12 -0
  282. package/dist/esm/types/pagination-types.js +4 -0
  283. package/dist/esm/types/result-types.js +1 -0
  284. package/dist/esm/types/schema-types.js +1 -0
  285. package/dist/esm/types/subscription-types.js +1 -0
  286. package/dist/esm/types.js +1 -0
  287. package/dist/esm/update/array-update-builder.js +192 -0
  288. package/dist/esm/update/index.js +2 -0
  289. package/dist/esm/update/update-builder.js +188 -0
  290. package/dist/esm/utils/case-converter.js +55 -0
  291. package/dist/esm/utils/environment-detection.js +113 -0
  292. package/dist/esm/utils/index.js +2 -0
  293. package/dist/esm/utils/pool-defaults.js +100 -0
  294. package/dist/esm/utils/type-coercion.js +110 -0
  295. package/dist/esm/view/create-view-builder.js +171 -0
  296. package/dist/esm/view/index.js +1 -0
  297. package/dist/esm/window/index.js +1 -0
  298. package/dist/esm/window/window-builder.js +73 -0
  299. package/dist/index.cjs +1 -0
  300. package/dist/index.d.ts +10341 -0
  301. package/dist/index.js +1 -0
  302. package/dist/schema-builder.cjs +1 -0
  303. package/dist/schema-builder.d.ts +2272 -0
  304. package/dist/schema-builder.js +1 -0
  305. package/package.json +55 -0
@@ -0,0 +1,4790 @@
1
+ import { createRequire } from "node:module";
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __toESM = (mod, isNodeMode, target) => {
8
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
9
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
10
+ for (let key of __getOwnPropNames(mod))
11
+ if (!__hasOwnProp.call(to, key))
12
+ __defProp(to, key, {
13
+ get: () => mod[key],
14
+ enumerable: true
15
+ });
16
+ return to;
17
+ };
18
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
19
+ var __export = (target, all) => {
20
+ for (var name in all)
21
+ __defProp(target, name, {
22
+ get: all[name],
23
+ enumerable: true,
24
+ configurable: true,
25
+ set: (newValue) => all[name] = () => newValue
26
+ });
27
+ };
28
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
29
+
30
+ // node_modules/postgres-array/index.js
31
+ var require_postgres_array = __commonJS((exports) => {
32
+ exports.parse = function(source, transform) {
33
+ return new ArrayParser(source, transform).parse();
34
+ };
35
+
36
+ class ArrayParser {
37
+ constructor(source, transform) {
38
+ this.source = source;
39
+ this.transform = transform || identity;
40
+ this.position = 0;
41
+ this.entries = [];
42
+ this.recorded = [];
43
+ this.dimension = 0;
44
+ }
45
+ isEof() {
46
+ return this.position >= this.source.length;
47
+ }
48
+ nextCharacter() {
49
+ var character = this.source[this.position++];
50
+ if (character === "\\") {
51
+ return {
52
+ value: this.source[this.position++],
53
+ escaped: true
54
+ };
55
+ }
56
+ return {
57
+ value: character,
58
+ escaped: false
59
+ };
60
+ }
61
+ record(character) {
62
+ this.recorded.push(character);
63
+ }
64
+ newEntry(includeEmpty) {
65
+ var entry;
66
+ if (this.recorded.length > 0 || includeEmpty) {
67
+ entry = this.recorded.join("");
68
+ if (entry === "NULL" && !includeEmpty) {
69
+ entry = null;
70
+ }
71
+ if (entry !== null)
72
+ entry = this.transform(entry);
73
+ this.entries.push(entry);
74
+ this.recorded = [];
75
+ }
76
+ }
77
+ consumeDimensions() {
78
+ if (this.source[0] === "[") {
79
+ while (!this.isEof()) {
80
+ var char = this.nextCharacter();
81
+ if (char.value === "=")
82
+ break;
83
+ }
84
+ }
85
+ }
86
+ parse(nested) {
87
+ var character, parser, quote;
88
+ this.consumeDimensions();
89
+ while (!this.isEof()) {
90
+ character = this.nextCharacter();
91
+ if (character.value === "{" && !quote) {
92
+ this.dimension++;
93
+ if (this.dimension > 1) {
94
+ parser = new ArrayParser(this.source.substr(this.position - 1), this.transform);
95
+ this.entries.push(parser.parse(true));
96
+ this.position += parser.position - 2;
97
+ }
98
+ } else if (character.value === "}" && !quote) {
99
+ this.dimension--;
100
+ if (!this.dimension) {
101
+ this.newEntry();
102
+ if (nested)
103
+ return this.entries;
104
+ }
105
+ } else if (character.value === '"' && !character.escaped) {
106
+ if (quote)
107
+ this.newEntry(true);
108
+ quote = !quote;
109
+ } else if (character.value === "," && !quote) {
110
+ this.newEntry();
111
+ } else {
112
+ this.record(character.value);
113
+ }
114
+ }
115
+ if (this.dimension !== 0) {
116
+ throw new Error("array dimension not balanced");
117
+ }
118
+ return this.entries;
119
+ }
120
+ }
121
+ function identity(value) {
122
+ return value;
123
+ }
124
+ });
125
+
126
+ // node_modules/pg-types/lib/arrayParser.js
127
+ var require_arrayParser = __commonJS((exports, module) => {
128
+ var array = require_postgres_array();
129
+ module.exports = {
130
+ create: function(source, transform) {
131
+ return {
132
+ parse: function() {
133
+ return array.parse(source, transform);
134
+ }
135
+ };
136
+ }
137
+ };
138
+ });
139
+
140
+ // node_modules/postgres-date/index.js
141
+ var require_postgres_date = __commonJS((exports, module) => {
142
+ var DATE_TIME = /(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/;
143
+ var DATE = /^(\d{1,})-(\d{2})-(\d{2})( BC)?$/;
144
+ var TIME_ZONE = /([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/;
145
+ var INFINITY = /^-?infinity$/;
146
+ module.exports = function parseDate(isoDate) {
147
+ if (INFINITY.test(isoDate)) {
148
+ return Number(isoDate.replace("i", "I"));
149
+ }
150
+ var matches = DATE_TIME.exec(isoDate);
151
+ if (!matches) {
152
+ return getDate(isoDate) || null;
153
+ }
154
+ var isBC = !!matches[8];
155
+ var year = parseInt(matches[1], 10);
156
+ if (isBC) {
157
+ year = bcYearToNegativeYear(year);
158
+ }
159
+ var month = parseInt(matches[2], 10) - 1;
160
+ var day = matches[3];
161
+ var hour = parseInt(matches[4], 10);
162
+ var minute = parseInt(matches[5], 10);
163
+ var second = parseInt(matches[6], 10);
164
+ var ms = matches[7];
165
+ ms = ms ? 1000 * parseFloat(ms) : 0;
166
+ var date;
167
+ var offset = timeZoneOffset(isoDate);
168
+ if (offset != null) {
169
+ date = new Date(Date.UTC(year, month, day, hour, minute, second, ms));
170
+ if (is0To99(year)) {
171
+ date.setUTCFullYear(year);
172
+ }
173
+ if (offset !== 0) {
174
+ date.setTime(date.getTime() - offset);
175
+ }
176
+ } else {
177
+ date = new Date(year, month, day, hour, minute, second, ms);
178
+ if (is0To99(year)) {
179
+ date.setFullYear(year);
180
+ }
181
+ }
182
+ return date;
183
+ };
184
+ function getDate(isoDate) {
185
+ var matches = DATE.exec(isoDate);
186
+ if (!matches) {
187
+ return;
188
+ }
189
+ var year = parseInt(matches[1], 10);
190
+ var isBC = !!matches[4];
191
+ if (isBC) {
192
+ year = bcYearToNegativeYear(year);
193
+ }
194
+ var month = parseInt(matches[2], 10) - 1;
195
+ var day = matches[3];
196
+ var date = new Date(year, month, day);
197
+ if (is0To99(year)) {
198
+ date.setFullYear(year);
199
+ }
200
+ return date;
201
+ }
202
+ function timeZoneOffset(isoDate) {
203
+ if (isoDate.endsWith("+00")) {
204
+ return 0;
205
+ }
206
+ var zone = TIME_ZONE.exec(isoDate.split(" ")[1]);
207
+ if (!zone)
208
+ return;
209
+ var type = zone[1];
210
+ if (type === "Z") {
211
+ return 0;
212
+ }
213
+ var sign = type === "-" ? -1 : 1;
214
+ var offset = parseInt(zone[2], 10) * 3600 + parseInt(zone[3] || 0, 10) * 60 + parseInt(zone[4] || 0, 10);
215
+ return offset * sign * 1000;
216
+ }
217
+ function bcYearToNegativeYear(year) {
218
+ return -(year - 1);
219
+ }
220
+ function is0To99(num) {
221
+ return num >= 0 && num < 100;
222
+ }
223
+ });
224
+
225
+ // node_modules/xtend/mutable.js
226
+ var require_mutable = __commonJS((exports, module) => {
227
+ module.exports = extend;
228
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
229
+ function extend(target) {
230
+ for (var i = 1;i < arguments.length; i++) {
231
+ var source = arguments[i];
232
+ for (var key in source) {
233
+ if (hasOwnProperty.call(source, key)) {
234
+ target[key] = source[key];
235
+ }
236
+ }
237
+ }
238
+ return target;
239
+ }
240
+ });
241
+
242
+ // node_modules/postgres-interval/index.js
243
+ var require_postgres_interval = __commonJS((exports, module) => {
244
+ var extend = require_mutable();
245
+ module.exports = PostgresInterval;
246
+ function PostgresInterval(raw) {
247
+ if (!(this instanceof PostgresInterval)) {
248
+ return new PostgresInterval(raw);
249
+ }
250
+ extend(this, parse(raw));
251
+ }
252
+ var properties = ["seconds", "minutes", "hours", "days", "months", "years"];
253
+ PostgresInterval.prototype.toPostgres = function() {
254
+ var filtered = properties.filter(this.hasOwnProperty, this);
255
+ if (this.milliseconds && filtered.indexOf("seconds") < 0) {
256
+ filtered.push("seconds");
257
+ }
258
+ if (filtered.length === 0)
259
+ return "0";
260
+ return filtered.map(function(property) {
261
+ var value = this[property] || 0;
262
+ if (property === "seconds" && this.milliseconds) {
263
+ value = (value + this.milliseconds / 1000).toFixed(6).replace(/\.?0+$/, "");
264
+ }
265
+ return value + " " + property;
266
+ }, this).join(" ");
267
+ };
268
+ var propertiesISOEquivalent = {
269
+ years: "Y",
270
+ months: "M",
271
+ days: "D",
272
+ hours: "H",
273
+ minutes: "M",
274
+ seconds: "S"
275
+ };
276
+ var dateProperties = ["years", "months", "days"];
277
+ var timeProperties = ["hours", "minutes", "seconds"];
278
+ PostgresInterval.prototype.toISOString = PostgresInterval.prototype.toISO = function() {
279
+ var datePart = dateProperties.map(buildProperty, this).join("");
280
+ var timePart = timeProperties.map(buildProperty, this).join("");
281
+ return "P" + datePart + "T" + timePart;
282
+ function buildProperty(property) {
283
+ var value = this[property] || 0;
284
+ if (property === "seconds" && this.milliseconds) {
285
+ value = (value + this.milliseconds / 1000).toFixed(6).replace(/0+$/, "");
286
+ }
287
+ return value + propertiesISOEquivalent[property];
288
+ }
289
+ };
290
+ var NUMBER = "([+-]?\\d+)";
291
+ var YEAR = NUMBER + "\\s+years?";
292
+ var MONTH = NUMBER + "\\s+mons?";
293
+ var DAY = NUMBER + "\\s+days?";
294
+ var TIME = "([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?";
295
+ var INTERVAL = new RegExp([YEAR, MONTH, DAY, TIME].map(function(regexString) {
296
+ return "(" + regexString + ")?";
297
+ }).join("\\s*"));
298
+ var positions = {
299
+ years: 2,
300
+ months: 4,
301
+ days: 6,
302
+ hours: 9,
303
+ minutes: 10,
304
+ seconds: 11,
305
+ milliseconds: 12
306
+ };
307
+ var negatives = ["hours", "minutes", "seconds", "milliseconds"];
308
+ function parseMilliseconds(fraction) {
309
+ var microseconds = fraction + "000000".slice(fraction.length);
310
+ return parseInt(microseconds, 10) / 1000;
311
+ }
312
+ function parse(interval) {
313
+ if (!interval)
314
+ return {};
315
+ var matches = INTERVAL.exec(interval);
316
+ var isNegative = matches[8] === "-";
317
+ return Object.keys(positions).reduce(function(parsed, property) {
318
+ var position = positions[property];
319
+ var value = matches[position];
320
+ if (!value)
321
+ return parsed;
322
+ value = property === "milliseconds" ? parseMilliseconds(value) : parseInt(value, 10);
323
+ if (!value)
324
+ return parsed;
325
+ if (isNegative && ~negatives.indexOf(property)) {
326
+ value *= -1;
327
+ }
328
+ parsed[property] = value;
329
+ return parsed;
330
+ }, {});
331
+ }
332
+ });
333
+
334
+ // node_modules/postgres-bytea/index.js
335
+ var require_postgres_bytea = __commonJS((exports, module) => {
336
+ module.exports = function parseBytea(input) {
337
+ if (/^\\x/.test(input)) {
338
+ return new Buffer(input.substr(2), "hex");
339
+ }
340
+ var output = "";
341
+ var i = 0;
342
+ while (i < input.length) {
343
+ if (input[i] !== "\\") {
344
+ output += input[i];
345
+ ++i;
346
+ } else {
347
+ if (/[0-7]{3}/.test(input.substr(i + 1, 3))) {
348
+ output += String.fromCharCode(parseInt(input.substr(i + 1, 3), 8));
349
+ i += 4;
350
+ } else {
351
+ var backslashes = 1;
352
+ while (i + backslashes < input.length && input[i + backslashes] === "\\") {
353
+ backslashes++;
354
+ }
355
+ for (var k = 0;k < Math.floor(backslashes / 2); ++k) {
356
+ output += "\\";
357
+ }
358
+ i += Math.floor(backslashes / 2) * 2;
359
+ }
360
+ }
361
+ }
362
+ return new Buffer(output, "binary");
363
+ };
364
+ });
365
+
366
+ // node_modules/pg-types/lib/textParsers.js
367
+ var require_textParsers = __commonJS((exports, module) => {
368
+ var array = require_postgres_array();
369
+ var arrayParser = require_arrayParser();
370
+ var parseDate = require_postgres_date();
371
+ var parseInterval = require_postgres_interval();
372
+ var parseByteA = require_postgres_bytea();
373
+ function allowNull(fn) {
374
+ return function nullAllowed(value) {
375
+ if (value === null)
376
+ return value;
377
+ return fn(value);
378
+ };
379
+ }
380
+ function parseBool(value) {
381
+ if (value === null)
382
+ return value;
383
+ return value === "TRUE" || value === "t" || value === "true" || value === "y" || value === "yes" || value === "on" || value === "1";
384
+ }
385
+ function parseBoolArray(value) {
386
+ if (!value)
387
+ return null;
388
+ return array.parse(value, parseBool);
389
+ }
390
+ function parseBaseTenInt(string) {
391
+ return parseInt(string, 10);
392
+ }
393
+ function parseIntegerArray(value) {
394
+ if (!value)
395
+ return null;
396
+ return array.parse(value, allowNull(parseBaseTenInt));
397
+ }
398
+ function parseBigIntegerArray(value) {
399
+ if (!value)
400
+ return null;
401
+ return array.parse(value, allowNull(function(entry) {
402
+ return parseBigInteger(entry).trim();
403
+ }));
404
+ }
405
+ var parsePointArray = function(value) {
406
+ if (!value) {
407
+ return null;
408
+ }
409
+ var p = arrayParser.create(value, function(entry) {
410
+ if (entry !== null) {
411
+ entry = parsePoint(entry);
412
+ }
413
+ return entry;
414
+ });
415
+ return p.parse();
416
+ };
417
+ var parseFloatArray = function(value) {
418
+ if (!value) {
419
+ return null;
420
+ }
421
+ var p = arrayParser.create(value, function(entry) {
422
+ if (entry !== null) {
423
+ entry = parseFloat(entry);
424
+ }
425
+ return entry;
426
+ });
427
+ return p.parse();
428
+ };
429
+ var parseStringArray = function(value) {
430
+ if (!value) {
431
+ return null;
432
+ }
433
+ var p = arrayParser.create(value);
434
+ return p.parse();
435
+ };
436
+ var parseDateArray = function(value) {
437
+ if (!value) {
438
+ return null;
439
+ }
440
+ var p = arrayParser.create(value, function(entry) {
441
+ if (entry !== null) {
442
+ entry = parseDate(entry);
443
+ }
444
+ return entry;
445
+ });
446
+ return p.parse();
447
+ };
448
+ var parseIntervalArray = function(value) {
449
+ if (!value) {
450
+ return null;
451
+ }
452
+ var p = arrayParser.create(value, function(entry) {
453
+ if (entry !== null) {
454
+ entry = parseInterval(entry);
455
+ }
456
+ return entry;
457
+ });
458
+ return p.parse();
459
+ };
460
+ var parseByteAArray = function(value) {
461
+ if (!value) {
462
+ return null;
463
+ }
464
+ return array.parse(value, allowNull(parseByteA));
465
+ };
466
+ var parseInteger = function(value) {
467
+ return parseInt(value, 10);
468
+ };
469
+ var parseBigInteger = function(value) {
470
+ var valStr = String(value);
471
+ if (/^\d+$/.test(valStr)) {
472
+ return valStr;
473
+ }
474
+ return value;
475
+ };
476
+ var parseJsonArray = function(value) {
477
+ if (!value) {
478
+ return null;
479
+ }
480
+ return array.parse(value, allowNull(JSON.parse));
481
+ };
482
+ var parsePoint = function(value) {
483
+ if (value[0] !== "(") {
484
+ return null;
485
+ }
486
+ value = value.substring(1, value.length - 1).split(",");
487
+ return {
488
+ x: parseFloat(value[0]),
489
+ y: parseFloat(value[1])
490
+ };
491
+ };
492
+ var parseCircle = function(value) {
493
+ if (value[0] !== "<" && value[1] !== "(") {
494
+ return null;
495
+ }
496
+ var point = "(";
497
+ var radius = "";
498
+ var pointParsed = false;
499
+ for (var i = 2;i < value.length - 1; i++) {
500
+ if (!pointParsed) {
501
+ point += value[i];
502
+ }
503
+ if (value[i] === ")") {
504
+ pointParsed = true;
505
+ continue;
506
+ } else if (!pointParsed) {
507
+ continue;
508
+ }
509
+ if (value[i] === ",") {
510
+ continue;
511
+ }
512
+ radius += value[i];
513
+ }
514
+ var result = parsePoint(point);
515
+ result.radius = parseFloat(radius);
516
+ return result;
517
+ };
518
+ var init = function(register) {
519
+ register(20, parseBigInteger);
520
+ register(21, parseInteger);
521
+ register(23, parseInteger);
522
+ register(26, parseInteger);
523
+ register(700, parseFloat);
524
+ register(701, parseFloat);
525
+ register(16, parseBool);
526
+ register(1082, parseDate);
527
+ register(1114, parseDate);
528
+ register(1184, parseDate);
529
+ register(600, parsePoint);
530
+ register(651, parseStringArray);
531
+ register(718, parseCircle);
532
+ register(1000, parseBoolArray);
533
+ register(1001, parseByteAArray);
534
+ register(1005, parseIntegerArray);
535
+ register(1007, parseIntegerArray);
536
+ register(1028, parseIntegerArray);
537
+ register(1016, parseBigIntegerArray);
538
+ register(1017, parsePointArray);
539
+ register(1021, parseFloatArray);
540
+ register(1022, parseFloatArray);
541
+ register(1231, parseFloatArray);
542
+ register(1014, parseStringArray);
543
+ register(1015, parseStringArray);
544
+ register(1008, parseStringArray);
545
+ register(1009, parseStringArray);
546
+ register(1040, parseStringArray);
547
+ register(1041, parseStringArray);
548
+ register(1115, parseDateArray);
549
+ register(1182, parseDateArray);
550
+ register(1185, parseDateArray);
551
+ register(1186, parseInterval);
552
+ register(1187, parseIntervalArray);
553
+ register(17, parseByteA);
554
+ register(114, JSON.parse.bind(JSON));
555
+ register(3802, JSON.parse.bind(JSON));
556
+ register(199, parseJsonArray);
557
+ register(3807, parseJsonArray);
558
+ register(3907, parseStringArray);
559
+ register(2951, parseStringArray);
560
+ register(791, parseStringArray);
561
+ register(1183, parseStringArray);
562
+ register(1270, parseStringArray);
563
+ };
564
+ module.exports = {
565
+ init
566
+ };
567
+ });
568
+
569
+ // node_modules/pg-int8/index.js
570
+ var require_pg_int8 = __commonJS((exports, module) => {
571
+ var BASE = 1e6;
572
+ function readInt8(buffer) {
573
+ var high = buffer.readInt32BE(0);
574
+ var low = buffer.readUInt32BE(4);
575
+ var sign = "";
576
+ if (high < 0) {
577
+ high = ~high + (low === 0);
578
+ low = ~low + 1 >>> 0;
579
+ sign = "-";
580
+ }
581
+ var result = "";
582
+ var carry;
583
+ var t;
584
+ var digits;
585
+ var pad;
586
+ var l;
587
+ var i;
588
+ {
589
+ carry = high % BASE;
590
+ high = high / BASE >>> 0;
591
+ t = 4294967296 * carry + low;
592
+ low = t / BASE >>> 0;
593
+ digits = "" + (t - BASE * low);
594
+ if (low === 0 && high === 0) {
595
+ return sign + digits + result;
596
+ }
597
+ pad = "";
598
+ l = 6 - digits.length;
599
+ for (i = 0;i < l; i++) {
600
+ pad += "0";
601
+ }
602
+ result = pad + digits + result;
603
+ }
604
+ {
605
+ carry = high % BASE;
606
+ high = high / BASE >>> 0;
607
+ t = 4294967296 * carry + low;
608
+ low = t / BASE >>> 0;
609
+ digits = "" + (t - BASE * low);
610
+ if (low === 0 && high === 0) {
611
+ return sign + digits + result;
612
+ }
613
+ pad = "";
614
+ l = 6 - digits.length;
615
+ for (i = 0;i < l; i++) {
616
+ pad += "0";
617
+ }
618
+ result = pad + digits + result;
619
+ }
620
+ {
621
+ carry = high % BASE;
622
+ high = high / BASE >>> 0;
623
+ t = 4294967296 * carry + low;
624
+ low = t / BASE >>> 0;
625
+ digits = "" + (t - BASE * low);
626
+ if (low === 0 && high === 0) {
627
+ return sign + digits + result;
628
+ }
629
+ pad = "";
630
+ l = 6 - digits.length;
631
+ for (i = 0;i < l; i++) {
632
+ pad += "0";
633
+ }
634
+ result = pad + digits + result;
635
+ }
636
+ {
637
+ carry = high % BASE;
638
+ t = 4294967296 * carry + low;
639
+ digits = "" + t % BASE;
640
+ return sign + digits + result;
641
+ }
642
+ }
643
+ module.exports = readInt8;
644
+ });
645
+
646
+ // node_modules/pg-types/lib/binaryParsers.js
647
+ var require_binaryParsers = __commonJS((exports, module) => {
648
+ var parseInt64 = require_pg_int8();
649
+ var parseBits = function(data, bits, offset, invert, callback) {
650
+ offset = offset || 0;
651
+ invert = invert || false;
652
+ callback = callback || function(lastValue, newValue, bits2) {
653
+ return lastValue * Math.pow(2, bits2) + newValue;
654
+ };
655
+ var offsetBytes = offset >> 3;
656
+ var inv = function(value) {
657
+ if (invert) {
658
+ return ~value & 255;
659
+ }
660
+ return value;
661
+ };
662
+ var mask = 255;
663
+ var firstBits = 8 - offset % 8;
664
+ if (bits < firstBits) {
665
+ mask = 255 << 8 - bits & 255;
666
+ firstBits = bits;
667
+ }
668
+ if (offset) {
669
+ mask = mask >> offset % 8;
670
+ }
671
+ var result = 0;
672
+ if (offset % 8 + bits >= 8) {
673
+ result = callback(0, inv(data[offsetBytes]) & mask, firstBits);
674
+ }
675
+ var bytes = bits + offset >> 3;
676
+ for (var i = offsetBytes + 1;i < bytes; i++) {
677
+ result = callback(result, inv(data[i]), 8);
678
+ }
679
+ var lastBits = (bits + offset) % 8;
680
+ if (lastBits > 0) {
681
+ result = callback(result, inv(data[bytes]) >> 8 - lastBits, lastBits);
682
+ }
683
+ return result;
684
+ };
685
+ var parseFloatFromBits = function(data, precisionBits, exponentBits) {
686
+ var bias = Math.pow(2, exponentBits - 1) - 1;
687
+ var sign = parseBits(data, 1);
688
+ var exponent = parseBits(data, exponentBits, 1);
689
+ if (exponent === 0) {
690
+ return 0;
691
+ }
692
+ var precisionBitsCounter = 1;
693
+ var parsePrecisionBits = function(lastValue, newValue, bits) {
694
+ if (lastValue === 0) {
695
+ lastValue = 1;
696
+ }
697
+ for (var i = 1;i <= bits; i++) {
698
+ precisionBitsCounter /= 2;
699
+ if ((newValue & 1 << bits - i) > 0) {
700
+ lastValue += precisionBitsCounter;
701
+ }
702
+ }
703
+ return lastValue;
704
+ };
705
+ var mantissa = parseBits(data, precisionBits, exponentBits + 1, false, parsePrecisionBits);
706
+ if (exponent == Math.pow(2, exponentBits + 1) - 1) {
707
+ if (mantissa === 0) {
708
+ return sign === 0 ? Infinity : -Infinity;
709
+ }
710
+ return NaN;
711
+ }
712
+ return (sign === 0 ? 1 : -1) * Math.pow(2, exponent - bias) * mantissa;
713
+ };
714
+ var parseInt16 = function(value) {
715
+ if (parseBits(value, 1) == 1) {
716
+ return -1 * (parseBits(value, 15, 1, true) + 1);
717
+ }
718
+ return parseBits(value, 15, 1);
719
+ };
720
+ var parseInt32 = function(value) {
721
+ if (parseBits(value, 1) == 1) {
722
+ return -1 * (parseBits(value, 31, 1, true) + 1);
723
+ }
724
+ return parseBits(value, 31, 1);
725
+ };
726
+ var parseFloat32 = function(value) {
727
+ return parseFloatFromBits(value, 23, 8);
728
+ };
729
+ var parseFloat64 = function(value) {
730
+ return parseFloatFromBits(value, 52, 11);
731
+ };
732
+ var parseNumeric = function(value) {
733
+ var sign = parseBits(value, 16, 32);
734
+ if (sign == 49152) {
735
+ return NaN;
736
+ }
737
+ var weight = Math.pow(1e4, parseBits(value, 16, 16));
738
+ var result = 0;
739
+ var digits = [];
740
+ var ndigits = parseBits(value, 16);
741
+ for (var i = 0;i < ndigits; i++) {
742
+ result += parseBits(value, 16, 64 + 16 * i) * weight;
743
+ weight /= 1e4;
744
+ }
745
+ var scale = Math.pow(10, parseBits(value, 16, 48));
746
+ return (sign === 0 ? 1 : -1) * Math.round(result * scale) / scale;
747
+ };
748
+ var parseDate = function(isUTC, value) {
749
+ var sign = parseBits(value, 1);
750
+ var rawValue = parseBits(value, 63, 1);
751
+ var result = new Date((sign === 0 ? 1 : -1) * rawValue / 1000 + 946684800000);
752
+ if (!isUTC) {
753
+ result.setTime(result.getTime() + result.getTimezoneOffset() * 60000);
754
+ }
755
+ result.usec = rawValue % 1000;
756
+ result.getMicroSeconds = function() {
757
+ return this.usec;
758
+ };
759
+ result.setMicroSeconds = function(value2) {
760
+ this.usec = value2;
761
+ };
762
+ result.getUTCMicroSeconds = function() {
763
+ return this.usec;
764
+ };
765
+ return result;
766
+ };
767
+ var parseArray = function(value) {
768
+ var dim = parseBits(value, 32);
769
+ var flags = parseBits(value, 32, 32);
770
+ var elementType = parseBits(value, 32, 64);
771
+ var offset = 96;
772
+ var dims = [];
773
+ for (var i = 0;i < dim; i++) {
774
+ dims[i] = parseBits(value, 32, offset);
775
+ offset += 32;
776
+ offset += 32;
777
+ }
778
+ var parseElement = function(elementType2) {
779
+ var length = parseBits(value, 32, offset);
780
+ offset += 32;
781
+ if (length == 4294967295) {
782
+ return null;
783
+ }
784
+ var result;
785
+ if (elementType2 == 23 || elementType2 == 20) {
786
+ result = parseBits(value, length * 8, offset);
787
+ offset += length * 8;
788
+ return result;
789
+ } else if (elementType2 == 25) {
790
+ result = value.toString(this.encoding, offset >> 3, (offset += length << 3) >> 3);
791
+ return result;
792
+ } else {
793
+ console.log("ERROR: ElementType not implemented: " + elementType2);
794
+ }
795
+ };
796
+ var parse = function(dimension, elementType2) {
797
+ var array = [];
798
+ var i2;
799
+ if (dimension.length > 1) {
800
+ var count = dimension.shift();
801
+ for (i2 = 0;i2 < count; i2++) {
802
+ array[i2] = parse(dimension, elementType2);
803
+ }
804
+ dimension.unshift(count);
805
+ } else {
806
+ for (i2 = 0;i2 < dimension[0]; i2++) {
807
+ array[i2] = parseElement(elementType2);
808
+ }
809
+ }
810
+ return array;
811
+ };
812
+ return parse(dims, elementType);
813
+ };
814
+ var parseText = function(value) {
815
+ return value.toString("utf8");
816
+ };
817
+ var parseBool = function(value) {
818
+ if (value === null)
819
+ return null;
820
+ return parseBits(value, 8) > 0;
821
+ };
822
+ var init = function(register) {
823
+ register(20, parseInt64);
824
+ register(21, parseInt16);
825
+ register(23, parseInt32);
826
+ register(26, parseInt32);
827
+ register(1700, parseNumeric);
828
+ register(700, parseFloat32);
829
+ register(701, parseFloat64);
830
+ register(16, parseBool);
831
+ register(1114, parseDate.bind(null, false));
832
+ register(1184, parseDate.bind(null, true));
833
+ register(1000, parseArray);
834
+ register(1007, parseArray);
835
+ register(1016, parseArray);
836
+ register(1008, parseArray);
837
+ register(1009, parseArray);
838
+ register(25, parseText);
839
+ };
840
+ module.exports = {
841
+ init
842
+ };
843
+ });
844
+
845
+ // node_modules/pg-types/lib/builtins.js
846
+ var require_builtins = __commonJS((exports, module) => {
847
+ module.exports = {
848
+ BOOL: 16,
849
+ BYTEA: 17,
850
+ CHAR: 18,
851
+ INT8: 20,
852
+ INT2: 21,
853
+ INT4: 23,
854
+ REGPROC: 24,
855
+ TEXT: 25,
856
+ OID: 26,
857
+ TID: 27,
858
+ XID: 28,
859
+ CID: 29,
860
+ JSON: 114,
861
+ XML: 142,
862
+ PG_NODE_TREE: 194,
863
+ SMGR: 210,
864
+ PATH: 602,
865
+ POLYGON: 604,
866
+ CIDR: 650,
867
+ FLOAT4: 700,
868
+ FLOAT8: 701,
869
+ ABSTIME: 702,
870
+ RELTIME: 703,
871
+ TINTERVAL: 704,
872
+ CIRCLE: 718,
873
+ MACADDR8: 774,
874
+ MONEY: 790,
875
+ MACADDR: 829,
876
+ INET: 869,
877
+ ACLITEM: 1033,
878
+ BPCHAR: 1042,
879
+ VARCHAR: 1043,
880
+ DATE: 1082,
881
+ TIME: 1083,
882
+ TIMESTAMP: 1114,
883
+ TIMESTAMPTZ: 1184,
884
+ INTERVAL: 1186,
885
+ TIMETZ: 1266,
886
+ BIT: 1560,
887
+ VARBIT: 1562,
888
+ NUMERIC: 1700,
889
+ REFCURSOR: 1790,
890
+ REGPROCEDURE: 2202,
891
+ REGOPER: 2203,
892
+ REGOPERATOR: 2204,
893
+ REGCLASS: 2205,
894
+ REGTYPE: 2206,
895
+ UUID: 2950,
896
+ TXID_SNAPSHOT: 2970,
897
+ PG_LSN: 3220,
898
+ PG_NDISTINCT: 3361,
899
+ PG_DEPENDENCIES: 3402,
900
+ TSVECTOR: 3614,
901
+ TSQUERY: 3615,
902
+ GTSVECTOR: 3642,
903
+ REGCONFIG: 3734,
904
+ REGDICTIONARY: 3769,
905
+ JSONB: 3802,
906
+ REGNAMESPACE: 4089,
907
+ REGROLE: 4096
908
+ };
909
+ });
910
+
911
+ // node_modules/pg-types/index.js
912
+ var require_pg_types = __commonJS((exports) => {
913
+ var textParsers = require_textParsers();
914
+ var binaryParsers = require_binaryParsers();
915
+ var arrayParser = require_arrayParser();
916
+ var builtinTypes = require_builtins();
917
+ exports.getTypeParser = getTypeParser;
918
+ exports.setTypeParser = setTypeParser;
919
+ exports.arrayParser = arrayParser;
920
+ exports.builtins = builtinTypes;
921
+ var typeParsers = {
922
+ text: {},
923
+ binary: {}
924
+ };
925
+ function noParse(val) {
926
+ return String(val);
927
+ }
928
+ function getTypeParser(oid, format) {
929
+ format = format || "text";
930
+ if (!typeParsers[format]) {
931
+ return noParse;
932
+ }
933
+ return typeParsers[format][oid] || noParse;
934
+ }
935
+ function setTypeParser(oid, format, parseFn) {
936
+ if (typeof format == "function") {
937
+ parseFn = format;
938
+ format = "text";
939
+ }
940
+ typeParsers[format][oid] = parseFn;
941
+ }
942
+ textParsers.init(function(oid, converter) {
943
+ typeParsers.text[oid] = converter;
944
+ });
945
+ binaryParsers.init(function(oid, converter) {
946
+ typeParsers.binary[oid] = converter;
947
+ });
948
+ });
949
+
950
+ // node_modules/pg/lib/defaults.js
951
+ var require_defaults = __commonJS((exports, module) => {
952
+ module.exports = {
953
+ host: "localhost",
954
+ user: process.platform === "win32" ? process.env.USERNAME : process.env.USER,
955
+ database: undefined,
956
+ password: null,
957
+ connectionString: undefined,
958
+ port: 5432,
959
+ rows: 0,
960
+ binary: false,
961
+ max: 10,
962
+ idleTimeoutMillis: 30000,
963
+ client_encoding: "",
964
+ ssl: false,
965
+ application_name: undefined,
966
+ fallback_application_name: undefined,
967
+ options: undefined,
968
+ parseInputDatesAsUTC: false,
969
+ statement_timeout: false,
970
+ lock_timeout: false,
971
+ idle_in_transaction_session_timeout: false,
972
+ query_timeout: false,
973
+ connect_timeout: 0,
974
+ keepalives: 1,
975
+ keepalives_idle: 0
976
+ };
977
+ var pgTypes = require_pg_types();
978
+ var parseBigInteger = pgTypes.getTypeParser(20, "text");
979
+ var parseBigIntegerArray = pgTypes.getTypeParser(1016, "text");
980
+ module.exports.__defineSetter__("parseInt8", function(val) {
981
+ pgTypes.setTypeParser(20, "text", val ? pgTypes.getTypeParser(23, "text") : parseBigInteger);
982
+ pgTypes.setTypeParser(1016, "text", val ? pgTypes.getTypeParser(1007, "text") : parseBigIntegerArray);
983
+ });
984
+ });
985
+
986
+ // node_modules/pg/lib/utils.js
987
+ var require_utils = __commonJS((exports, module) => {
988
+ var defaults = require_defaults();
989
+ var util = __require("util");
990
+ var { isDate } = util.types || util;
991
+ function escapeElement(elementRepresentation) {
992
+ const escaped = elementRepresentation.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
993
+ return '"' + escaped + '"';
994
+ }
995
+ function arrayString(val) {
996
+ let result = "{";
997
+ for (let i = 0;i < val.length; i++) {
998
+ if (i > 0) {
999
+ result = result + ",";
1000
+ }
1001
+ if (val[i] === null || typeof val[i] === "undefined") {
1002
+ result = result + "NULL";
1003
+ } else if (Array.isArray(val[i])) {
1004
+ result = result + arrayString(val[i]);
1005
+ } else if (ArrayBuffer.isView(val[i])) {
1006
+ let item = val[i];
1007
+ if (!(item instanceof Buffer)) {
1008
+ const buf = Buffer.from(item.buffer, item.byteOffset, item.byteLength);
1009
+ if (buf.length === item.byteLength) {
1010
+ item = buf;
1011
+ } else {
1012
+ item = buf.slice(item.byteOffset, item.byteOffset + item.byteLength);
1013
+ }
1014
+ }
1015
+ result += "\\\\x" + item.toString("hex");
1016
+ } else {
1017
+ result += escapeElement(prepareValue(val[i]));
1018
+ }
1019
+ }
1020
+ result = result + "}";
1021
+ return result;
1022
+ }
1023
+ var prepareValue = function(val, seen) {
1024
+ if (val == null) {
1025
+ return null;
1026
+ }
1027
+ if (typeof val === "object") {
1028
+ if (val instanceof Buffer) {
1029
+ return val;
1030
+ }
1031
+ if (ArrayBuffer.isView(val)) {
1032
+ const buf = Buffer.from(val.buffer, val.byteOffset, val.byteLength);
1033
+ if (buf.length === val.byteLength) {
1034
+ return buf;
1035
+ }
1036
+ return buf.slice(val.byteOffset, val.byteOffset + val.byteLength);
1037
+ }
1038
+ if (isDate(val)) {
1039
+ if (defaults.parseInputDatesAsUTC) {
1040
+ return dateToStringUTC(val);
1041
+ } else {
1042
+ return dateToString(val);
1043
+ }
1044
+ }
1045
+ if (Array.isArray(val)) {
1046
+ return arrayString(val);
1047
+ }
1048
+ return prepareObject(val, seen);
1049
+ }
1050
+ return val.toString();
1051
+ };
1052
+ function prepareObject(val, seen) {
1053
+ if (val && typeof val.toPostgres === "function") {
1054
+ seen = seen || [];
1055
+ if (seen.indexOf(val) !== -1) {
1056
+ throw new Error('circular reference detected while preparing "' + val + '" for query');
1057
+ }
1058
+ seen.push(val);
1059
+ return prepareValue(val.toPostgres(prepareValue), seen);
1060
+ }
1061
+ return JSON.stringify(val);
1062
+ }
1063
+ function dateToString(date) {
1064
+ let offset = -date.getTimezoneOffset();
1065
+ let year = date.getFullYear();
1066
+ const isBCYear = year < 1;
1067
+ if (isBCYear)
1068
+ year = Math.abs(year) + 1;
1069
+ 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");
1070
+ if (offset < 0) {
1071
+ ret += "-";
1072
+ offset *= -1;
1073
+ } else {
1074
+ ret += "+";
1075
+ }
1076
+ ret += String(Math.floor(offset / 60)).padStart(2, "0") + ":" + String(offset % 60).padStart(2, "0");
1077
+ if (isBCYear)
1078
+ ret += " BC";
1079
+ return ret;
1080
+ }
1081
+ function dateToStringUTC(date) {
1082
+ let year = date.getUTCFullYear();
1083
+ const isBCYear = year < 1;
1084
+ if (isBCYear)
1085
+ year = Math.abs(year) + 1;
1086
+ 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");
1087
+ ret += "+00:00";
1088
+ if (isBCYear)
1089
+ ret += " BC";
1090
+ return ret;
1091
+ }
1092
+ function normalizeQueryConfig(config, values, callback) {
1093
+ config = typeof config === "string" ? { text: config } : config;
1094
+ if (values) {
1095
+ if (typeof values === "function") {
1096
+ config.callback = values;
1097
+ } else {
1098
+ config.values = values;
1099
+ }
1100
+ }
1101
+ if (callback) {
1102
+ config.callback = callback;
1103
+ }
1104
+ return config;
1105
+ }
1106
+ var escapeIdentifier = function(str) {
1107
+ return '"' + str.replace(/"/g, '""') + '"';
1108
+ };
1109
+ var escapeLiteral = function(str) {
1110
+ let hasBackslash = false;
1111
+ let escaped = "'";
1112
+ if (str == null) {
1113
+ return "''";
1114
+ }
1115
+ if (typeof str !== "string") {
1116
+ return "''";
1117
+ }
1118
+ for (let i = 0;i < str.length; i++) {
1119
+ const c = str[i];
1120
+ if (c === "'") {
1121
+ escaped += c + c;
1122
+ } else if (c === "\\") {
1123
+ escaped += c + c;
1124
+ hasBackslash = true;
1125
+ } else {
1126
+ escaped += c;
1127
+ }
1128
+ }
1129
+ escaped += "'";
1130
+ if (hasBackslash === true) {
1131
+ escaped = " E" + escaped;
1132
+ }
1133
+ return escaped;
1134
+ };
1135
+ module.exports = {
1136
+ prepareValue: function prepareValueWrapper(value) {
1137
+ return prepareValue(value);
1138
+ },
1139
+ normalizeQueryConfig,
1140
+ escapeIdentifier,
1141
+ escapeLiteral
1142
+ };
1143
+ });
1144
+
1145
+ // node_modules/pg/lib/crypto/utils-legacy.js
1146
+ var require_utils_legacy = __commonJS((exports, module) => {
1147
+ var nodeCrypto = __require("crypto");
1148
+ function md5(string) {
1149
+ return nodeCrypto.createHash("md5").update(string, "utf-8").digest("hex");
1150
+ }
1151
+ function postgresMd5PasswordHash(user, password, salt) {
1152
+ const inner = md5(password + user);
1153
+ const outer = md5(Buffer.concat([Buffer.from(inner), salt]));
1154
+ return "md5" + outer;
1155
+ }
1156
+ function sha256(text) {
1157
+ return nodeCrypto.createHash("sha256").update(text).digest();
1158
+ }
1159
+ function hashByName(hashName, text) {
1160
+ hashName = hashName.replace(/(\D)-/, "$1");
1161
+ return nodeCrypto.createHash(hashName).update(text).digest();
1162
+ }
1163
+ function hmacSha256(key, msg) {
1164
+ return nodeCrypto.createHmac("sha256", key).update(msg).digest();
1165
+ }
1166
+ async function deriveKey(password, salt, iterations) {
1167
+ return nodeCrypto.pbkdf2Sync(password, salt, iterations, 32, "sha256");
1168
+ }
1169
+ module.exports = {
1170
+ postgresMd5PasswordHash,
1171
+ randomBytes: nodeCrypto.randomBytes,
1172
+ deriveKey,
1173
+ sha256,
1174
+ hashByName,
1175
+ hmacSha256,
1176
+ md5
1177
+ };
1178
+ });
1179
+
1180
+ // node_modules/pg/lib/crypto/utils-webcrypto.js
1181
+ var require_utils_webcrypto = __commonJS((exports, module) => {
1182
+ var nodeCrypto = __require("crypto");
1183
+ module.exports = {
1184
+ postgresMd5PasswordHash,
1185
+ randomBytes,
1186
+ deriveKey,
1187
+ sha256,
1188
+ hashByName,
1189
+ hmacSha256,
1190
+ md5
1191
+ };
1192
+ var webCrypto = nodeCrypto.webcrypto || globalThis.crypto;
1193
+ var subtleCrypto = webCrypto.subtle;
1194
+ var textEncoder = new TextEncoder;
1195
+ function randomBytes(length) {
1196
+ return webCrypto.getRandomValues(Buffer.alloc(length));
1197
+ }
1198
+ async function md5(string) {
1199
+ try {
1200
+ return nodeCrypto.createHash("md5").update(string, "utf-8").digest("hex");
1201
+ } catch (e) {
1202
+ const data = typeof string === "string" ? textEncoder.encode(string) : string;
1203
+ const hash = await subtleCrypto.digest("MD5", data);
1204
+ return Array.from(new Uint8Array(hash)).map((b) => b.toString(16).padStart(2, "0")).join("");
1205
+ }
1206
+ }
1207
+ async function postgresMd5PasswordHash(user, password, salt) {
1208
+ const inner = await md5(password + user);
1209
+ const outer = await md5(Buffer.concat([Buffer.from(inner), salt]));
1210
+ return "md5" + outer;
1211
+ }
1212
+ async function sha256(text) {
1213
+ return await subtleCrypto.digest("SHA-256", text);
1214
+ }
1215
+ async function hashByName(hashName, text) {
1216
+ return await subtleCrypto.digest(hashName, text);
1217
+ }
1218
+ async function hmacSha256(keyBuffer, msg) {
1219
+ const key = await subtleCrypto.importKey("raw", keyBuffer, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
1220
+ return await subtleCrypto.sign("HMAC", key, textEncoder.encode(msg));
1221
+ }
1222
+ async function deriveKey(password, salt, iterations) {
1223
+ const key = await subtleCrypto.importKey("raw", textEncoder.encode(password), "PBKDF2", false, ["deriveBits"]);
1224
+ const params = { name: "PBKDF2", hash: "SHA-256", salt, iterations };
1225
+ return await subtleCrypto.deriveBits(params, key, 32 * 8, ["deriveBits"]);
1226
+ }
1227
+ });
1228
+
1229
+ // node_modules/pg/lib/crypto/utils.js
1230
+ var require_utils2 = __commonJS((exports, module) => {
1231
+ var useLegacyCrypto = parseInt(process.versions && process.versions.node && process.versions.node.split(".")[0]) < 15;
1232
+ if (useLegacyCrypto) {
1233
+ module.exports = require_utils_legacy();
1234
+ } else {
1235
+ module.exports = require_utils_webcrypto();
1236
+ }
1237
+ });
1238
+
1239
+ // node_modules/pg/lib/crypto/cert-signatures.js
1240
+ var require_cert_signatures = __commonJS((exports, module) => {
1241
+ function x509Error(msg, cert) {
1242
+ return new Error("SASL channel binding: " + msg + " when parsing public certificate " + cert.toString("base64"));
1243
+ }
1244
+ function readASN1Length(data, index) {
1245
+ let length = data[index++];
1246
+ if (length < 128)
1247
+ return { length, index };
1248
+ const lengthBytes = length & 127;
1249
+ if (lengthBytes > 4)
1250
+ throw x509Error("bad length", data);
1251
+ length = 0;
1252
+ for (let i = 0;i < lengthBytes; i++) {
1253
+ length = length << 8 | data[index++];
1254
+ }
1255
+ return { length, index };
1256
+ }
1257
+ function readASN1OID(data, index) {
1258
+ if (data[index++] !== 6)
1259
+ throw x509Error("non-OID data", data);
1260
+ const { length: OIDLength, index: indexAfterOIDLength } = readASN1Length(data, index);
1261
+ index = indexAfterOIDLength;
1262
+ const lastIndex = index + OIDLength;
1263
+ const byte1 = data[index++];
1264
+ let oid = (byte1 / 40 >> 0) + "." + byte1 % 40;
1265
+ while (index < lastIndex) {
1266
+ let value = 0;
1267
+ while (index < lastIndex) {
1268
+ const nextByte = data[index++];
1269
+ value = value << 7 | nextByte & 127;
1270
+ if (nextByte < 128)
1271
+ break;
1272
+ }
1273
+ oid += "." + value;
1274
+ }
1275
+ return { oid, index };
1276
+ }
1277
+ function expectASN1Seq(data, index) {
1278
+ if (data[index++] !== 48)
1279
+ throw x509Error("non-sequence data", data);
1280
+ return readASN1Length(data, index);
1281
+ }
1282
+ function signatureAlgorithmHashFromCertificate(data, index) {
1283
+ if (index === undefined)
1284
+ index = 0;
1285
+ index = expectASN1Seq(data, index).index;
1286
+ const { length: certInfoLength, index: indexAfterCertInfoLength } = expectASN1Seq(data, index);
1287
+ index = indexAfterCertInfoLength + certInfoLength;
1288
+ index = expectASN1Seq(data, index).index;
1289
+ const { oid, index: indexAfterOID } = readASN1OID(data, index);
1290
+ switch (oid) {
1291
+ case "1.2.840.113549.1.1.4":
1292
+ return "MD5";
1293
+ case "1.2.840.113549.1.1.5":
1294
+ return "SHA-1";
1295
+ case "1.2.840.113549.1.1.11":
1296
+ return "SHA-256";
1297
+ case "1.2.840.113549.1.1.12":
1298
+ return "SHA-384";
1299
+ case "1.2.840.113549.1.1.13":
1300
+ return "SHA-512";
1301
+ case "1.2.840.113549.1.1.14":
1302
+ return "SHA-224";
1303
+ case "1.2.840.113549.1.1.15":
1304
+ return "SHA512-224";
1305
+ case "1.2.840.113549.1.1.16":
1306
+ return "SHA512-256";
1307
+ case "1.2.840.10045.4.1":
1308
+ return "SHA-1";
1309
+ case "1.2.840.10045.4.3.1":
1310
+ return "SHA-224";
1311
+ case "1.2.840.10045.4.3.2":
1312
+ return "SHA-256";
1313
+ case "1.2.840.10045.4.3.3":
1314
+ return "SHA-384";
1315
+ case "1.2.840.10045.4.3.4":
1316
+ return "SHA-512";
1317
+ case "1.2.840.113549.1.1.10": {
1318
+ index = indexAfterOID;
1319
+ index = expectASN1Seq(data, index).index;
1320
+ if (data[index++] !== 160)
1321
+ throw x509Error("non-tag data", data);
1322
+ index = readASN1Length(data, index).index;
1323
+ index = expectASN1Seq(data, index).index;
1324
+ const { oid: hashOID } = readASN1OID(data, index);
1325
+ switch (hashOID) {
1326
+ case "1.2.840.113549.2.5":
1327
+ return "MD5";
1328
+ case "1.3.14.3.2.26":
1329
+ return "SHA-1";
1330
+ case "2.16.840.1.101.3.4.2.1":
1331
+ return "SHA-256";
1332
+ case "2.16.840.1.101.3.4.2.2":
1333
+ return "SHA-384";
1334
+ case "2.16.840.1.101.3.4.2.3":
1335
+ return "SHA-512";
1336
+ }
1337
+ throw x509Error("unknown hash OID " + hashOID, data);
1338
+ }
1339
+ case "1.3.101.110":
1340
+ case "1.3.101.112":
1341
+ return "SHA-512";
1342
+ case "1.3.101.111":
1343
+ case "1.3.101.113":
1344
+ throw x509Error("Ed448 certificate channel binding is not currently supported by Postgres");
1345
+ }
1346
+ throw x509Error("unknown OID " + oid, data);
1347
+ }
1348
+ module.exports = { signatureAlgorithmHashFromCertificate };
1349
+ });
1350
+
1351
+ // node_modules/pg/lib/crypto/sasl.js
1352
+ var require_sasl = __commonJS((exports, module) => {
1353
+ var crypto = require_utils2();
1354
+ var { signatureAlgorithmHashFromCertificate } = require_cert_signatures();
1355
+ function startSession(mechanisms, stream) {
1356
+ const candidates = ["SCRAM-SHA-256"];
1357
+ if (stream)
1358
+ candidates.unshift("SCRAM-SHA-256-PLUS");
1359
+ const mechanism = candidates.find((candidate) => mechanisms.includes(candidate));
1360
+ if (!mechanism) {
1361
+ throw new Error("SASL: Only mechanism(s) " + candidates.join(" and ") + " are supported");
1362
+ }
1363
+ if (mechanism === "SCRAM-SHA-256-PLUS" && typeof stream.getPeerCertificate !== "function") {
1364
+ throw new Error("SASL: Mechanism SCRAM-SHA-256-PLUS requires a certificate");
1365
+ }
1366
+ const clientNonce = crypto.randomBytes(18).toString("base64");
1367
+ const gs2Header = mechanism === "SCRAM-SHA-256-PLUS" ? "p=tls-server-end-point" : stream ? "y" : "n";
1368
+ return {
1369
+ mechanism,
1370
+ clientNonce,
1371
+ response: gs2Header + ",,n=*,r=" + clientNonce,
1372
+ message: "SASLInitialResponse"
1373
+ };
1374
+ }
1375
+ async function continueSession(session, password, serverData, stream) {
1376
+ if (session.message !== "SASLInitialResponse") {
1377
+ throw new Error("SASL: Last message was not SASLInitialResponse");
1378
+ }
1379
+ if (typeof password !== "string") {
1380
+ throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string");
1381
+ }
1382
+ if (password === "") {
1383
+ throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string");
1384
+ }
1385
+ if (typeof serverData !== "string") {
1386
+ throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string");
1387
+ }
1388
+ const sv = parseServerFirstMessage(serverData);
1389
+ if (!sv.nonce.startsWith(session.clientNonce)) {
1390
+ throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce");
1391
+ } else if (sv.nonce.length === session.clientNonce.length) {
1392
+ throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short");
1393
+ }
1394
+ const clientFirstMessageBare = "n=*,r=" + session.clientNonce;
1395
+ const serverFirstMessage = "r=" + sv.nonce + ",s=" + sv.salt + ",i=" + sv.iteration;
1396
+ let channelBinding = stream ? "eSws" : "biws";
1397
+ if (session.mechanism === "SCRAM-SHA-256-PLUS") {
1398
+ const peerCert = stream.getPeerCertificate().raw;
1399
+ let hashName = signatureAlgorithmHashFromCertificate(peerCert);
1400
+ if (hashName === "MD5" || hashName === "SHA-1")
1401
+ hashName = "SHA-256";
1402
+ const certHash = await crypto.hashByName(hashName, peerCert);
1403
+ const bindingData = Buffer.concat([Buffer.from("p=tls-server-end-point,,"), Buffer.from(certHash)]);
1404
+ channelBinding = bindingData.toString("base64");
1405
+ }
1406
+ const clientFinalMessageWithoutProof = "c=" + channelBinding + ",r=" + sv.nonce;
1407
+ const authMessage = clientFirstMessageBare + "," + serverFirstMessage + "," + clientFinalMessageWithoutProof;
1408
+ const saltBytes = Buffer.from(sv.salt, "base64");
1409
+ const saltedPassword = await crypto.deriveKey(password, saltBytes, sv.iteration);
1410
+ const clientKey = await crypto.hmacSha256(saltedPassword, "Client Key");
1411
+ const storedKey = await crypto.sha256(clientKey);
1412
+ const clientSignature = await crypto.hmacSha256(storedKey, authMessage);
1413
+ const clientProof = xorBuffers(Buffer.from(clientKey), Buffer.from(clientSignature)).toString("base64");
1414
+ const serverKey = await crypto.hmacSha256(saltedPassword, "Server Key");
1415
+ const serverSignatureBytes = await crypto.hmacSha256(serverKey, authMessage);
1416
+ session.message = "SASLResponse";
1417
+ session.serverSignature = Buffer.from(serverSignatureBytes).toString("base64");
1418
+ session.response = clientFinalMessageWithoutProof + ",p=" + clientProof;
1419
+ }
1420
+ function finalizeSession(session, serverData) {
1421
+ if (session.message !== "SASLResponse") {
1422
+ throw new Error("SASL: Last message was not SASLResponse");
1423
+ }
1424
+ if (typeof serverData !== "string") {
1425
+ throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string");
1426
+ }
1427
+ const { serverSignature } = parseServerFinalMessage(serverData);
1428
+ if (serverSignature !== session.serverSignature) {
1429
+ throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match");
1430
+ }
1431
+ }
1432
+ function isPrintableChars(text) {
1433
+ if (typeof text !== "string") {
1434
+ throw new TypeError("SASL: text must be a string");
1435
+ }
1436
+ return text.split("").map((_, i) => text.charCodeAt(i)).every((c) => c >= 33 && c <= 43 || c >= 45 && c <= 126);
1437
+ }
1438
+ function isBase64(text) {
1439
+ return /^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(text);
1440
+ }
1441
+ function parseAttributePairs(text) {
1442
+ if (typeof text !== "string") {
1443
+ throw new TypeError("SASL: attribute pairs text must be a string");
1444
+ }
1445
+ return new Map(text.split(",").map((attrValue) => {
1446
+ if (!/^.=/.test(attrValue)) {
1447
+ throw new Error("SASL: Invalid attribute pair entry");
1448
+ }
1449
+ const name = attrValue[0];
1450
+ const value = attrValue.substring(2);
1451
+ return [name, value];
1452
+ }));
1453
+ }
1454
+ function parseServerFirstMessage(data) {
1455
+ const attrPairs = parseAttributePairs(data);
1456
+ const nonce = attrPairs.get("r");
1457
+ if (!nonce) {
1458
+ throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing");
1459
+ } else if (!isPrintableChars(nonce)) {
1460
+ throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters");
1461
+ }
1462
+ const salt = attrPairs.get("s");
1463
+ if (!salt) {
1464
+ throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing");
1465
+ } else if (!isBase64(salt)) {
1466
+ throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64");
1467
+ }
1468
+ const iterationText = attrPairs.get("i");
1469
+ if (!iterationText) {
1470
+ throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing");
1471
+ } else if (!/^[1-9][0-9]*$/.test(iterationText)) {
1472
+ throw new Error("SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count");
1473
+ }
1474
+ const iteration = parseInt(iterationText, 10);
1475
+ return {
1476
+ nonce,
1477
+ salt,
1478
+ iteration
1479
+ };
1480
+ }
1481
+ function parseServerFinalMessage(serverData) {
1482
+ const attrPairs = parseAttributePairs(serverData);
1483
+ const serverSignature = attrPairs.get("v");
1484
+ if (!serverSignature) {
1485
+ throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing");
1486
+ } else if (!isBase64(serverSignature)) {
1487
+ throw new Error("SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64");
1488
+ }
1489
+ return {
1490
+ serverSignature
1491
+ };
1492
+ }
1493
+ function xorBuffers(a, b) {
1494
+ if (!Buffer.isBuffer(a)) {
1495
+ throw new TypeError("first argument must be a Buffer");
1496
+ }
1497
+ if (!Buffer.isBuffer(b)) {
1498
+ throw new TypeError("second argument must be a Buffer");
1499
+ }
1500
+ if (a.length !== b.length) {
1501
+ throw new Error("Buffer lengths must match");
1502
+ }
1503
+ if (a.length === 0) {
1504
+ throw new Error("Buffers cannot be empty");
1505
+ }
1506
+ return Buffer.from(a.map((_, i) => a[i] ^ b[i]));
1507
+ }
1508
+ module.exports = {
1509
+ startSession,
1510
+ continueSession,
1511
+ finalizeSession
1512
+ };
1513
+ });
1514
+
1515
+ // node_modules/pg/lib/type-overrides.js
1516
+ var require_type_overrides = __commonJS((exports, module) => {
1517
+ var types = require_pg_types();
1518
+ function TypeOverrides(userTypes) {
1519
+ this._types = userTypes || types;
1520
+ this.text = {};
1521
+ this.binary = {};
1522
+ }
1523
+ TypeOverrides.prototype.getOverrides = function(format) {
1524
+ switch (format) {
1525
+ case "text":
1526
+ return this.text;
1527
+ case "binary":
1528
+ return this.binary;
1529
+ default:
1530
+ return {};
1531
+ }
1532
+ };
1533
+ TypeOverrides.prototype.setTypeParser = function(oid, format, parseFn) {
1534
+ if (typeof format === "function") {
1535
+ parseFn = format;
1536
+ format = "text";
1537
+ }
1538
+ this.getOverrides(format)[oid] = parseFn;
1539
+ };
1540
+ TypeOverrides.prototype.getTypeParser = function(oid, format) {
1541
+ format = format || "text";
1542
+ return this.getOverrides(format)[oid] || this._types.getTypeParser(oid, format);
1543
+ };
1544
+ module.exports = TypeOverrides;
1545
+ });
1546
+
1547
+ // node_modules/pg-connection-string/index.js
1548
+ var require_pg_connection_string = __commonJS((exports, module) => {
1549
+ function parse(str, options = {}) {
1550
+ if (str.charAt(0) === "/") {
1551
+ const config2 = str.split(" ");
1552
+ return { host: config2[0], database: config2[1] };
1553
+ }
1554
+ const config = {};
1555
+ let result;
1556
+ let dummyHost = false;
1557
+ if (/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(str)) {
1558
+ str = encodeURI(str).replace(/%25(\d\d)/g, "%$1");
1559
+ }
1560
+ try {
1561
+ try {
1562
+ result = new URL(str, "postgres://base");
1563
+ } catch (e) {
1564
+ result = new URL(str.replace("@/", "@___DUMMY___/"), "postgres://base");
1565
+ dummyHost = true;
1566
+ }
1567
+ } catch (err) {
1568
+ err.input && (err.input = "*****REDACTED*****");
1569
+ }
1570
+ for (const entry of result.searchParams.entries()) {
1571
+ config[entry[0]] = entry[1];
1572
+ }
1573
+ config.user = config.user || decodeURIComponent(result.username);
1574
+ config.password = config.password || decodeURIComponent(result.password);
1575
+ if (result.protocol == "socket:") {
1576
+ config.host = decodeURI(result.pathname);
1577
+ config.database = result.searchParams.get("db");
1578
+ config.client_encoding = result.searchParams.get("encoding");
1579
+ return config;
1580
+ }
1581
+ const hostname = dummyHost ? "" : result.hostname;
1582
+ if (!config.host) {
1583
+ config.host = decodeURIComponent(hostname);
1584
+ } else if (hostname && /^%2f/i.test(hostname)) {
1585
+ result.pathname = hostname + result.pathname;
1586
+ }
1587
+ if (!config.port) {
1588
+ config.port = result.port;
1589
+ }
1590
+ const pathname = result.pathname.slice(1) || null;
1591
+ config.database = pathname ? decodeURI(pathname) : null;
1592
+ if (config.ssl === "true" || config.ssl === "1") {
1593
+ config.ssl = true;
1594
+ }
1595
+ if (config.ssl === "0") {
1596
+ config.ssl = false;
1597
+ }
1598
+ if (config.sslcert || config.sslkey || config.sslrootcert || config.sslmode) {
1599
+ config.ssl = {};
1600
+ }
1601
+ const fs = config.sslcert || config.sslkey || config.sslrootcert ? __require("fs") : null;
1602
+ if (config.sslcert) {
1603
+ config.ssl.cert = fs.readFileSync(config.sslcert).toString();
1604
+ }
1605
+ if (config.sslkey) {
1606
+ config.ssl.key = fs.readFileSync(config.sslkey).toString();
1607
+ }
1608
+ if (config.sslrootcert) {
1609
+ config.ssl.ca = fs.readFileSync(config.sslrootcert).toString();
1610
+ }
1611
+ if (options.useLibpqCompat && config.uselibpqcompat) {
1612
+ throw new Error("Both useLibpqCompat and uselibpqcompat are set. Please use only one of them.");
1613
+ }
1614
+ if (config.uselibpqcompat === "true" || options.useLibpqCompat) {
1615
+ switch (config.sslmode) {
1616
+ case "disable": {
1617
+ config.ssl = false;
1618
+ break;
1619
+ }
1620
+ case "prefer": {
1621
+ config.ssl.rejectUnauthorized = false;
1622
+ break;
1623
+ }
1624
+ case "require": {
1625
+ if (config.sslrootcert) {
1626
+ config.ssl.checkServerIdentity = function() {};
1627
+ } else {
1628
+ config.ssl.rejectUnauthorized = false;
1629
+ }
1630
+ break;
1631
+ }
1632
+ case "verify-ca": {
1633
+ if (!config.ssl.ca) {
1634
+ throw new Error("SECURITY WARNING: Using sslmode=verify-ca requires specifying a CA with sslrootcert. If a public CA is used, verify-ca allows connections to a server that somebody else may have registered with the CA, making you vulnerable to Man-in-the-Middle attacks. Either specify a custom CA certificate with sslrootcert parameter or use sslmode=verify-full for proper security.");
1635
+ }
1636
+ config.ssl.checkServerIdentity = function() {};
1637
+ break;
1638
+ }
1639
+ case "verify-full": {
1640
+ break;
1641
+ }
1642
+ }
1643
+ } else {
1644
+ switch (config.sslmode) {
1645
+ case "disable": {
1646
+ config.ssl = false;
1647
+ break;
1648
+ }
1649
+ case "prefer":
1650
+ case "require":
1651
+ case "verify-ca":
1652
+ case "verify-full": {
1653
+ break;
1654
+ }
1655
+ case "no-verify": {
1656
+ config.ssl.rejectUnauthorized = false;
1657
+ break;
1658
+ }
1659
+ }
1660
+ }
1661
+ return config;
1662
+ }
1663
+ function toConnectionOptions(sslConfig) {
1664
+ const connectionOptions = Object.entries(sslConfig).reduce((c, [key, value]) => {
1665
+ if (value !== undefined && value !== null) {
1666
+ c[key] = value;
1667
+ }
1668
+ return c;
1669
+ }, {});
1670
+ return connectionOptions;
1671
+ }
1672
+ function toClientConfig(config) {
1673
+ const poolConfig = Object.entries(config).reduce((c, [key, value]) => {
1674
+ if (key === "ssl") {
1675
+ const sslConfig = value;
1676
+ if (typeof sslConfig === "boolean") {
1677
+ c[key] = sslConfig;
1678
+ }
1679
+ if (typeof sslConfig === "object") {
1680
+ c[key] = toConnectionOptions(sslConfig);
1681
+ }
1682
+ } else if (value !== undefined && value !== null) {
1683
+ if (key === "port") {
1684
+ if (value !== "") {
1685
+ const v = parseInt(value, 10);
1686
+ if (isNaN(v)) {
1687
+ throw new Error(`Invalid ${key}: ${value}`);
1688
+ }
1689
+ c[key] = v;
1690
+ }
1691
+ } else {
1692
+ c[key] = value;
1693
+ }
1694
+ }
1695
+ return c;
1696
+ }, {});
1697
+ return poolConfig;
1698
+ }
1699
+ function parseIntoClientConfig(str) {
1700
+ return toClientConfig(parse(str));
1701
+ }
1702
+ module.exports = parse;
1703
+ parse.parse = parse;
1704
+ parse.toClientConfig = toClientConfig;
1705
+ parse.parseIntoClientConfig = parseIntoClientConfig;
1706
+ });
1707
+
1708
+ // node_modules/pg/lib/connection-parameters.js
1709
+ var require_connection_parameters = __commonJS((exports, module) => {
1710
+ var dns = __require("dns");
1711
+ var defaults = require_defaults();
1712
+ var parse = require_pg_connection_string().parse;
1713
+ var val = function(key, config, envVar) {
1714
+ if (envVar === undefined) {
1715
+ envVar = process.env["PG" + key.toUpperCase()];
1716
+ } else if (envVar === false) {} else {
1717
+ envVar = process.env[envVar];
1718
+ }
1719
+ return config[key] || envVar || defaults[key];
1720
+ };
1721
+ var readSSLConfigFromEnvironment = function() {
1722
+ switch (process.env.PGSSLMODE) {
1723
+ case "disable":
1724
+ return false;
1725
+ case "prefer":
1726
+ case "require":
1727
+ case "verify-ca":
1728
+ case "verify-full":
1729
+ return true;
1730
+ case "no-verify":
1731
+ return { rejectUnauthorized: false };
1732
+ }
1733
+ return defaults.ssl;
1734
+ };
1735
+ var quoteParamValue = function(value) {
1736
+ return "'" + ("" + value).replace(/\\/g, "\\\\").replace(/'/g, "\\'") + "'";
1737
+ };
1738
+ var add = function(params, config, paramName) {
1739
+ const value = config[paramName];
1740
+ if (value !== undefined && value !== null) {
1741
+ params.push(paramName + "=" + quoteParamValue(value));
1742
+ }
1743
+ };
1744
+
1745
+ class ConnectionParameters {
1746
+ constructor(config) {
1747
+ config = typeof config === "string" ? parse(config) : config || {};
1748
+ if (config.connectionString) {
1749
+ config = Object.assign({}, config, parse(config.connectionString));
1750
+ }
1751
+ this.user = val("user", config);
1752
+ this.database = val("database", config);
1753
+ if (this.database === undefined) {
1754
+ this.database = this.user;
1755
+ }
1756
+ this.port = parseInt(val("port", config), 10);
1757
+ this.host = val("host", config);
1758
+ Object.defineProperty(this, "password", {
1759
+ configurable: true,
1760
+ enumerable: false,
1761
+ writable: true,
1762
+ value: val("password", config)
1763
+ });
1764
+ this.binary = val("binary", config);
1765
+ this.options = val("options", config);
1766
+ this.ssl = typeof config.ssl === "undefined" ? readSSLConfigFromEnvironment() : config.ssl;
1767
+ if (typeof this.ssl === "string") {
1768
+ if (this.ssl === "true") {
1769
+ this.ssl = true;
1770
+ }
1771
+ }
1772
+ if (this.ssl === "no-verify") {
1773
+ this.ssl = { rejectUnauthorized: false };
1774
+ }
1775
+ if (this.ssl && this.ssl.key) {
1776
+ Object.defineProperty(this.ssl, "key", {
1777
+ enumerable: false
1778
+ });
1779
+ }
1780
+ this.client_encoding = val("client_encoding", config);
1781
+ this.replication = val("replication", config);
1782
+ this.isDomainSocket = !(this.host || "").indexOf("/");
1783
+ this.application_name = val("application_name", config, "PGAPPNAME");
1784
+ this.fallback_application_name = val("fallback_application_name", config, false);
1785
+ this.statement_timeout = val("statement_timeout", config, false);
1786
+ this.lock_timeout = val("lock_timeout", config, false);
1787
+ this.idle_in_transaction_session_timeout = val("idle_in_transaction_session_timeout", config, false);
1788
+ this.query_timeout = val("query_timeout", config, false);
1789
+ if (config.connectionTimeoutMillis === undefined) {
1790
+ this.connect_timeout = process.env.PGCONNECT_TIMEOUT || 0;
1791
+ } else {
1792
+ this.connect_timeout = Math.floor(config.connectionTimeoutMillis / 1000);
1793
+ }
1794
+ if (config.keepAlive === false) {
1795
+ this.keepalives = 0;
1796
+ } else if (config.keepAlive === true) {
1797
+ this.keepalives = 1;
1798
+ }
1799
+ if (typeof config.keepAliveInitialDelayMillis === "number") {
1800
+ this.keepalives_idle = Math.floor(config.keepAliveInitialDelayMillis / 1000);
1801
+ }
1802
+ }
1803
+ getLibpqConnectionString(cb) {
1804
+ const params = [];
1805
+ add(params, this, "user");
1806
+ add(params, this, "password");
1807
+ add(params, this, "port");
1808
+ add(params, this, "application_name");
1809
+ add(params, this, "fallback_application_name");
1810
+ add(params, this, "connect_timeout");
1811
+ add(params, this, "options");
1812
+ const ssl = typeof this.ssl === "object" ? this.ssl : this.ssl ? { sslmode: this.ssl } : {};
1813
+ add(params, ssl, "sslmode");
1814
+ add(params, ssl, "sslca");
1815
+ add(params, ssl, "sslkey");
1816
+ add(params, ssl, "sslcert");
1817
+ add(params, ssl, "sslrootcert");
1818
+ if (this.database) {
1819
+ params.push("dbname=" + quoteParamValue(this.database));
1820
+ }
1821
+ if (this.replication) {
1822
+ params.push("replication=" + quoteParamValue(this.replication));
1823
+ }
1824
+ if (this.host) {
1825
+ params.push("host=" + quoteParamValue(this.host));
1826
+ }
1827
+ if (this.isDomainSocket) {
1828
+ return cb(null, params.join(" "));
1829
+ }
1830
+ if (this.client_encoding) {
1831
+ params.push("client_encoding=" + quoteParamValue(this.client_encoding));
1832
+ }
1833
+ dns.lookup(this.host, function(err, address) {
1834
+ if (err)
1835
+ return cb(err, null);
1836
+ params.push("hostaddr=" + quoteParamValue(address));
1837
+ return cb(null, params.join(" "));
1838
+ });
1839
+ }
1840
+ }
1841
+ module.exports = ConnectionParameters;
1842
+ });
1843
+
1844
+ // node_modules/pg/lib/result.js
1845
+ var require_result = __commonJS((exports, module) => {
1846
+ var types = require_pg_types();
1847
+ var matchRegexp = /^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/;
1848
+
1849
+ class Result {
1850
+ constructor(rowMode, types2) {
1851
+ this.command = null;
1852
+ this.rowCount = null;
1853
+ this.oid = null;
1854
+ this.rows = [];
1855
+ this.fields = [];
1856
+ this._parsers = undefined;
1857
+ this._types = types2;
1858
+ this.RowCtor = null;
1859
+ this.rowAsArray = rowMode === "array";
1860
+ if (this.rowAsArray) {
1861
+ this.parseRow = this._parseRowAsArray;
1862
+ }
1863
+ this._prebuiltEmptyResultObject = null;
1864
+ }
1865
+ addCommandComplete(msg) {
1866
+ let match;
1867
+ if (msg.text) {
1868
+ match = matchRegexp.exec(msg.text);
1869
+ } else {
1870
+ match = matchRegexp.exec(msg.command);
1871
+ }
1872
+ if (match) {
1873
+ this.command = match[1];
1874
+ if (match[3]) {
1875
+ this.oid = parseInt(match[2], 10);
1876
+ this.rowCount = parseInt(match[3], 10);
1877
+ } else if (match[2]) {
1878
+ this.rowCount = parseInt(match[2], 10);
1879
+ }
1880
+ }
1881
+ }
1882
+ _parseRowAsArray(rowData) {
1883
+ const row = new Array(rowData.length);
1884
+ for (let i = 0, len = rowData.length;i < len; i++) {
1885
+ const rawValue = rowData[i];
1886
+ if (rawValue !== null) {
1887
+ row[i] = this._parsers[i](rawValue);
1888
+ } else {
1889
+ row[i] = null;
1890
+ }
1891
+ }
1892
+ return row;
1893
+ }
1894
+ parseRow(rowData) {
1895
+ const row = { ...this._prebuiltEmptyResultObject };
1896
+ for (let i = 0, len = rowData.length;i < len; i++) {
1897
+ const rawValue = rowData[i];
1898
+ const field = this.fields[i].name;
1899
+ if (rawValue !== null) {
1900
+ const v = this.fields[i].format === "binary" ? Buffer.from(rawValue) : rawValue;
1901
+ row[field] = this._parsers[i](v);
1902
+ } else {
1903
+ row[field] = null;
1904
+ }
1905
+ }
1906
+ return row;
1907
+ }
1908
+ addRow(row) {
1909
+ this.rows.push(row);
1910
+ }
1911
+ addFields(fieldDescriptions) {
1912
+ this.fields = fieldDescriptions;
1913
+ if (this.fields.length) {
1914
+ this._parsers = new Array(fieldDescriptions.length);
1915
+ }
1916
+ const row = {};
1917
+ for (let i = 0;i < fieldDescriptions.length; i++) {
1918
+ const desc = fieldDescriptions[i];
1919
+ row[desc.name] = null;
1920
+ if (this._types) {
1921
+ this._parsers[i] = this._types.getTypeParser(desc.dataTypeID, desc.format || "text");
1922
+ } else {
1923
+ this._parsers[i] = types.getTypeParser(desc.dataTypeID, desc.format || "text");
1924
+ }
1925
+ }
1926
+ this._prebuiltEmptyResultObject = { ...row };
1927
+ }
1928
+ }
1929
+ module.exports = Result;
1930
+ });
1931
+
1932
+ // node_modules/pg/lib/query.js
1933
+ var require_query = __commonJS((exports, module) => {
1934
+ var { EventEmitter } = __require("events");
1935
+ var Result = require_result();
1936
+ var utils = require_utils();
1937
+
1938
+ class Query extends EventEmitter {
1939
+ constructor(config, values, callback) {
1940
+ super();
1941
+ config = utils.normalizeQueryConfig(config, values, callback);
1942
+ this.text = config.text;
1943
+ this.values = config.values;
1944
+ this.rows = config.rows;
1945
+ this.types = config.types;
1946
+ this.name = config.name;
1947
+ this.queryMode = config.queryMode;
1948
+ this.binary = config.binary;
1949
+ this.portal = config.portal || "";
1950
+ this.callback = config.callback;
1951
+ this._rowMode = config.rowMode;
1952
+ if (process.domain && config.callback) {
1953
+ this.callback = process.domain.bind(config.callback);
1954
+ }
1955
+ this._result = new Result(this._rowMode, this.types);
1956
+ this._results = this._result;
1957
+ this._canceledDueToError = false;
1958
+ }
1959
+ requiresPreparation() {
1960
+ if (this.queryMode === "extended") {
1961
+ return true;
1962
+ }
1963
+ if (this.name) {
1964
+ return true;
1965
+ }
1966
+ if (this.rows) {
1967
+ return true;
1968
+ }
1969
+ if (!this.text) {
1970
+ return false;
1971
+ }
1972
+ if (!this.values) {
1973
+ return false;
1974
+ }
1975
+ return this.values.length > 0;
1976
+ }
1977
+ _checkForMultirow() {
1978
+ if (this._result.command) {
1979
+ if (!Array.isArray(this._results)) {
1980
+ this._results = [this._result];
1981
+ }
1982
+ this._result = new Result(this._rowMode, this._result._types);
1983
+ this._results.push(this._result);
1984
+ }
1985
+ }
1986
+ handleRowDescription(msg) {
1987
+ this._checkForMultirow();
1988
+ this._result.addFields(msg.fields);
1989
+ this._accumulateRows = this.callback || !this.listeners("row").length;
1990
+ }
1991
+ handleDataRow(msg) {
1992
+ let row;
1993
+ if (this._canceledDueToError) {
1994
+ return;
1995
+ }
1996
+ try {
1997
+ row = this._result.parseRow(msg.fields);
1998
+ } catch (err) {
1999
+ this._canceledDueToError = err;
2000
+ return;
2001
+ }
2002
+ this.emit("row", row, this._result);
2003
+ if (this._accumulateRows) {
2004
+ this._result.addRow(row);
2005
+ }
2006
+ }
2007
+ handleCommandComplete(msg, connection) {
2008
+ this._checkForMultirow();
2009
+ this._result.addCommandComplete(msg);
2010
+ if (this.rows) {
2011
+ connection.sync();
2012
+ }
2013
+ }
2014
+ handleEmptyQuery(connection) {
2015
+ if (this.rows) {
2016
+ connection.sync();
2017
+ }
2018
+ }
2019
+ handleError(err, connection) {
2020
+ if (this._canceledDueToError) {
2021
+ err = this._canceledDueToError;
2022
+ this._canceledDueToError = false;
2023
+ }
2024
+ if (this.callback) {
2025
+ return this.callback(err);
2026
+ }
2027
+ this.emit("error", err);
2028
+ }
2029
+ handleReadyForQuery(con) {
2030
+ if (this._canceledDueToError) {
2031
+ return this.handleError(this._canceledDueToError, con);
2032
+ }
2033
+ if (this.callback) {
2034
+ try {
2035
+ this.callback(null, this._results);
2036
+ } catch (err) {
2037
+ process.nextTick(() => {
2038
+ throw err;
2039
+ });
2040
+ }
2041
+ }
2042
+ this.emit("end", this._results);
2043
+ }
2044
+ submit(connection) {
2045
+ if (typeof this.text !== "string" && typeof this.name !== "string") {
2046
+ return new Error("A query must have either text or a name. Supplying neither is unsupported.");
2047
+ }
2048
+ const previous = connection.parsedStatements[this.name];
2049
+ if (this.text && previous && this.text !== previous) {
2050
+ return new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);
2051
+ }
2052
+ if (this.values && !Array.isArray(this.values)) {
2053
+ return new Error("Query values must be an array");
2054
+ }
2055
+ if (this.requiresPreparation()) {
2056
+ connection.stream.cork && connection.stream.cork();
2057
+ try {
2058
+ this.prepare(connection);
2059
+ } finally {
2060
+ connection.stream.uncork && connection.stream.uncork();
2061
+ }
2062
+ } else {
2063
+ connection.query(this.text);
2064
+ }
2065
+ return null;
2066
+ }
2067
+ hasBeenParsed(connection) {
2068
+ return this.name && connection.parsedStatements[this.name];
2069
+ }
2070
+ handlePortalSuspended(connection) {
2071
+ this._getRows(connection, this.rows);
2072
+ }
2073
+ _getRows(connection, rows) {
2074
+ connection.execute({
2075
+ portal: this.portal,
2076
+ rows
2077
+ });
2078
+ if (!rows) {
2079
+ connection.sync();
2080
+ } else {
2081
+ connection.flush();
2082
+ }
2083
+ }
2084
+ prepare(connection) {
2085
+ if (!this.hasBeenParsed(connection)) {
2086
+ connection.parse({
2087
+ text: this.text,
2088
+ name: this.name,
2089
+ types: this.types
2090
+ });
2091
+ }
2092
+ try {
2093
+ connection.bind({
2094
+ portal: this.portal,
2095
+ statement: this.name,
2096
+ values: this.values,
2097
+ binary: this.binary,
2098
+ valueMapper: utils.prepareValue
2099
+ });
2100
+ } catch (err) {
2101
+ this.handleError(err, connection);
2102
+ return;
2103
+ }
2104
+ connection.describe({
2105
+ type: "P",
2106
+ name: this.portal || ""
2107
+ });
2108
+ this._getRows(connection, this.rows);
2109
+ }
2110
+ handleCopyInResponse(connection) {
2111
+ connection.sendCopyFail("No source stream defined");
2112
+ }
2113
+ handleCopyData(msg, connection) {}
2114
+ }
2115
+ module.exports = Query;
2116
+ });
2117
+
2118
+ // node_modules/pg-protocol/dist/messages.js
2119
+ var require_messages = __commonJS((exports) => {
2120
+ Object.defineProperty(exports, "__esModule", { value: true });
2121
+ 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 = undefined;
2122
+ exports.parseComplete = {
2123
+ name: "parseComplete",
2124
+ length: 5
2125
+ };
2126
+ exports.bindComplete = {
2127
+ name: "bindComplete",
2128
+ length: 5
2129
+ };
2130
+ exports.closeComplete = {
2131
+ name: "closeComplete",
2132
+ length: 5
2133
+ };
2134
+ exports.noData = {
2135
+ name: "noData",
2136
+ length: 5
2137
+ };
2138
+ exports.portalSuspended = {
2139
+ name: "portalSuspended",
2140
+ length: 5
2141
+ };
2142
+ exports.replicationStart = {
2143
+ name: "replicationStart",
2144
+ length: 4
2145
+ };
2146
+ exports.emptyQuery = {
2147
+ name: "emptyQuery",
2148
+ length: 4
2149
+ };
2150
+ exports.copyDone = {
2151
+ name: "copyDone",
2152
+ length: 4
2153
+ };
2154
+
2155
+ class DatabaseError extends Error {
2156
+ constructor(message, length, name) {
2157
+ super(message);
2158
+ this.length = length;
2159
+ this.name = name;
2160
+ }
2161
+ }
2162
+ exports.DatabaseError = DatabaseError;
2163
+
2164
+ class CopyDataMessage {
2165
+ constructor(length, chunk) {
2166
+ this.length = length;
2167
+ this.chunk = chunk;
2168
+ this.name = "copyData";
2169
+ }
2170
+ }
2171
+ exports.CopyDataMessage = CopyDataMessage;
2172
+
2173
+ class CopyResponse {
2174
+ constructor(length, name, binary, columnCount) {
2175
+ this.length = length;
2176
+ this.name = name;
2177
+ this.binary = binary;
2178
+ this.columnTypes = new Array(columnCount);
2179
+ }
2180
+ }
2181
+ exports.CopyResponse = CopyResponse;
2182
+
2183
+ class Field {
2184
+ constructor(name, tableID, columnID, dataTypeID, dataTypeSize, dataTypeModifier, format) {
2185
+ this.name = name;
2186
+ this.tableID = tableID;
2187
+ this.columnID = columnID;
2188
+ this.dataTypeID = dataTypeID;
2189
+ this.dataTypeSize = dataTypeSize;
2190
+ this.dataTypeModifier = dataTypeModifier;
2191
+ this.format = format;
2192
+ }
2193
+ }
2194
+ exports.Field = Field;
2195
+
2196
+ class RowDescriptionMessage {
2197
+ constructor(length, fieldCount) {
2198
+ this.length = length;
2199
+ this.fieldCount = fieldCount;
2200
+ this.name = "rowDescription";
2201
+ this.fields = new Array(this.fieldCount);
2202
+ }
2203
+ }
2204
+ exports.RowDescriptionMessage = RowDescriptionMessage;
2205
+
2206
+ class ParameterDescriptionMessage {
2207
+ constructor(length, parameterCount) {
2208
+ this.length = length;
2209
+ this.parameterCount = parameterCount;
2210
+ this.name = "parameterDescription";
2211
+ this.dataTypeIDs = new Array(this.parameterCount);
2212
+ }
2213
+ }
2214
+ exports.ParameterDescriptionMessage = ParameterDescriptionMessage;
2215
+
2216
+ class ParameterStatusMessage {
2217
+ constructor(length, parameterName, parameterValue) {
2218
+ this.length = length;
2219
+ this.parameterName = parameterName;
2220
+ this.parameterValue = parameterValue;
2221
+ this.name = "parameterStatus";
2222
+ }
2223
+ }
2224
+ exports.ParameterStatusMessage = ParameterStatusMessage;
2225
+
2226
+ class AuthenticationMD5Password {
2227
+ constructor(length, salt) {
2228
+ this.length = length;
2229
+ this.salt = salt;
2230
+ this.name = "authenticationMD5Password";
2231
+ }
2232
+ }
2233
+ exports.AuthenticationMD5Password = AuthenticationMD5Password;
2234
+
2235
+ class BackendKeyDataMessage {
2236
+ constructor(length, processID, secretKey) {
2237
+ this.length = length;
2238
+ this.processID = processID;
2239
+ this.secretKey = secretKey;
2240
+ this.name = "backendKeyData";
2241
+ }
2242
+ }
2243
+ exports.BackendKeyDataMessage = BackendKeyDataMessage;
2244
+
2245
+ class NotificationResponseMessage {
2246
+ constructor(length, processId, channel, payload) {
2247
+ this.length = length;
2248
+ this.processId = processId;
2249
+ this.channel = channel;
2250
+ this.payload = payload;
2251
+ this.name = "notification";
2252
+ }
2253
+ }
2254
+ exports.NotificationResponseMessage = NotificationResponseMessage;
2255
+
2256
+ class ReadyForQueryMessage {
2257
+ constructor(length, status) {
2258
+ this.length = length;
2259
+ this.status = status;
2260
+ this.name = "readyForQuery";
2261
+ }
2262
+ }
2263
+ exports.ReadyForQueryMessage = ReadyForQueryMessage;
2264
+
2265
+ class CommandCompleteMessage {
2266
+ constructor(length, text) {
2267
+ this.length = length;
2268
+ this.text = text;
2269
+ this.name = "commandComplete";
2270
+ }
2271
+ }
2272
+ exports.CommandCompleteMessage = CommandCompleteMessage;
2273
+
2274
+ class DataRowMessage {
2275
+ constructor(length, fields) {
2276
+ this.length = length;
2277
+ this.fields = fields;
2278
+ this.name = "dataRow";
2279
+ this.fieldCount = fields.length;
2280
+ }
2281
+ }
2282
+ exports.DataRowMessage = DataRowMessage;
2283
+
2284
+ class NoticeMessage {
2285
+ constructor(length, message) {
2286
+ this.length = length;
2287
+ this.message = message;
2288
+ this.name = "notice";
2289
+ }
2290
+ }
2291
+ exports.NoticeMessage = NoticeMessage;
2292
+ });
2293
+
2294
+ // node_modules/pg-protocol/dist/buffer-writer.js
2295
+ var require_buffer_writer = __commonJS((exports) => {
2296
+ Object.defineProperty(exports, "__esModule", { value: true });
2297
+ exports.Writer = undefined;
2298
+
2299
+ class Writer {
2300
+ constructor(size = 256) {
2301
+ this.size = size;
2302
+ this.offset = 5;
2303
+ this.headerPosition = 0;
2304
+ this.buffer = Buffer.allocUnsafe(size);
2305
+ }
2306
+ ensure(size) {
2307
+ const remaining = this.buffer.length - this.offset;
2308
+ if (remaining < size) {
2309
+ const oldBuffer = this.buffer;
2310
+ const newSize = oldBuffer.length + (oldBuffer.length >> 1) + size;
2311
+ this.buffer = Buffer.allocUnsafe(newSize);
2312
+ oldBuffer.copy(this.buffer);
2313
+ }
2314
+ }
2315
+ addInt32(num) {
2316
+ this.ensure(4);
2317
+ this.buffer[this.offset++] = num >>> 24 & 255;
2318
+ this.buffer[this.offset++] = num >>> 16 & 255;
2319
+ this.buffer[this.offset++] = num >>> 8 & 255;
2320
+ this.buffer[this.offset++] = num >>> 0 & 255;
2321
+ return this;
2322
+ }
2323
+ addInt16(num) {
2324
+ this.ensure(2);
2325
+ this.buffer[this.offset++] = num >>> 8 & 255;
2326
+ this.buffer[this.offset++] = num >>> 0 & 255;
2327
+ return this;
2328
+ }
2329
+ addCString(string) {
2330
+ if (!string) {
2331
+ this.ensure(1);
2332
+ } else {
2333
+ const len = Buffer.byteLength(string);
2334
+ this.ensure(len + 1);
2335
+ this.buffer.write(string, this.offset, "utf-8");
2336
+ this.offset += len;
2337
+ }
2338
+ this.buffer[this.offset++] = 0;
2339
+ return this;
2340
+ }
2341
+ addString(string = "") {
2342
+ const len = Buffer.byteLength(string);
2343
+ this.ensure(len);
2344
+ this.buffer.write(string, this.offset);
2345
+ this.offset += len;
2346
+ return this;
2347
+ }
2348
+ add(otherBuffer) {
2349
+ this.ensure(otherBuffer.length);
2350
+ otherBuffer.copy(this.buffer, this.offset);
2351
+ this.offset += otherBuffer.length;
2352
+ return this;
2353
+ }
2354
+ join(code) {
2355
+ if (code) {
2356
+ this.buffer[this.headerPosition] = code;
2357
+ const length = this.offset - (this.headerPosition + 1);
2358
+ this.buffer.writeInt32BE(length, this.headerPosition + 1);
2359
+ }
2360
+ return this.buffer.slice(code ? 0 : 5, this.offset);
2361
+ }
2362
+ flush(code) {
2363
+ const result = this.join(code);
2364
+ this.offset = 5;
2365
+ this.headerPosition = 0;
2366
+ this.buffer = Buffer.allocUnsafe(this.size);
2367
+ return result;
2368
+ }
2369
+ }
2370
+ exports.Writer = Writer;
2371
+ });
2372
+
2373
+ // node_modules/pg-protocol/dist/serializer.js
2374
+ var require_serializer = __commonJS((exports) => {
2375
+ Object.defineProperty(exports, "__esModule", { value: true });
2376
+ exports.serialize = undefined;
2377
+ var buffer_writer_1 = require_buffer_writer();
2378
+ var writer = new buffer_writer_1.Writer;
2379
+ var startup = (opts) => {
2380
+ writer.addInt16(3).addInt16(0);
2381
+ for (const key of Object.keys(opts)) {
2382
+ writer.addCString(key).addCString(opts[key]);
2383
+ }
2384
+ writer.addCString("client_encoding").addCString("UTF8");
2385
+ const bodyBuffer = writer.addCString("").flush();
2386
+ const length = bodyBuffer.length + 4;
2387
+ return new buffer_writer_1.Writer().addInt32(length).add(bodyBuffer).flush();
2388
+ };
2389
+ var requestSsl = () => {
2390
+ const response = Buffer.allocUnsafe(8);
2391
+ response.writeInt32BE(8, 0);
2392
+ response.writeInt32BE(80877103, 4);
2393
+ return response;
2394
+ };
2395
+ var password = (password2) => {
2396
+ return writer.addCString(password2).flush(112);
2397
+ };
2398
+ var sendSASLInitialResponseMessage = function(mechanism, initialResponse) {
2399
+ writer.addCString(mechanism).addInt32(Buffer.byteLength(initialResponse)).addString(initialResponse);
2400
+ return writer.flush(112);
2401
+ };
2402
+ var sendSCRAMClientFinalMessage = function(additionalData) {
2403
+ return writer.addString(additionalData).flush(112);
2404
+ };
2405
+ var query = (text) => {
2406
+ return writer.addCString(text).flush(81);
2407
+ };
2408
+ var emptyArray = [];
2409
+ var parse = (query2) => {
2410
+ const name = query2.name || "";
2411
+ if (name.length > 63) {
2412
+ console.error("Warning! Postgres only supports 63 characters for query names.");
2413
+ console.error("You supplied %s (%s)", name, name.length);
2414
+ console.error("This can cause conflicts and silent errors executing queries");
2415
+ }
2416
+ const types = query2.types || emptyArray;
2417
+ const len = types.length;
2418
+ const buffer = writer.addCString(name).addCString(query2.text).addInt16(len);
2419
+ for (let i = 0;i < len; i++) {
2420
+ buffer.addInt32(types[i]);
2421
+ }
2422
+ return writer.flush(80);
2423
+ };
2424
+ var paramWriter = new buffer_writer_1.Writer;
2425
+ var writeValues = function(values, valueMapper) {
2426
+ for (let i = 0;i < values.length; i++) {
2427
+ const mappedVal = valueMapper ? valueMapper(values[i], i) : values[i];
2428
+ if (mappedVal == null) {
2429
+ writer.addInt16(0);
2430
+ paramWriter.addInt32(-1);
2431
+ } else if (mappedVal instanceof Buffer) {
2432
+ writer.addInt16(1);
2433
+ paramWriter.addInt32(mappedVal.length);
2434
+ paramWriter.add(mappedVal);
2435
+ } else {
2436
+ writer.addInt16(0);
2437
+ paramWriter.addInt32(Buffer.byteLength(mappedVal));
2438
+ paramWriter.addString(mappedVal);
2439
+ }
2440
+ }
2441
+ };
2442
+ var bind = (config = {}) => {
2443
+ const portal = config.portal || "";
2444
+ const statement = config.statement || "";
2445
+ const binary = config.binary || false;
2446
+ const values = config.values || emptyArray;
2447
+ const len = values.length;
2448
+ writer.addCString(portal).addCString(statement);
2449
+ writer.addInt16(len);
2450
+ writeValues(values, config.valueMapper);
2451
+ writer.addInt16(len);
2452
+ writer.add(paramWriter.flush());
2453
+ writer.addInt16(1);
2454
+ writer.addInt16(binary ? 1 : 0);
2455
+ return writer.flush(66);
2456
+ };
2457
+ var emptyExecute = Buffer.from([69, 0, 0, 0, 9, 0, 0, 0, 0, 0]);
2458
+ var execute = (config) => {
2459
+ if (!config || !config.portal && !config.rows) {
2460
+ return emptyExecute;
2461
+ }
2462
+ const portal = config.portal || "";
2463
+ const rows = config.rows || 0;
2464
+ const portalLength = Buffer.byteLength(portal);
2465
+ const len = 4 + portalLength + 1 + 4;
2466
+ const buff = Buffer.allocUnsafe(1 + len);
2467
+ buff[0] = 69;
2468
+ buff.writeInt32BE(len, 1);
2469
+ buff.write(portal, 5, "utf-8");
2470
+ buff[portalLength + 5] = 0;
2471
+ buff.writeUInt32BE(rows, buff.length - 4);
2472
+ return buff;
2473
+ };
2474
+ var cancel = (processID, secretKey) => {
2475
+ const buffer = Buffer.allocUnsafe(16);
2476
+ buffer.writeInt32BE(16, 0);
2477
+ buffer.writeInt16BE(1234, 4);
2478
+ buffer.writeInt16BE(5678, 6);
2479
+ buffer.writeInt32BE(processID, 8);
2480
+ buffer.writeInt32BE(secretKey, 12);
2481
+ return buffer;
2482
+ };
2483
+ var cstringMessage = (code, string) => {
2484
+ const stringLen = Buffer.byteLength(string);
2485
+ const len = 4 + stringLen + 1;
2486
+ const buffer = Buffer.allocUnsafe(1 + len);
2487
+ buffer[0] = code;
2488
+ buffer.writeInt32BE(len, 1);
2489
+ buffer.write(string, 5, "utf-8");
2490
+ buffer[len] = 0;
2491
+ return buffer;
2492
+ };
2493
+ var emptyDescribePortal = writer.addCString("P").flush(68);
2494
+ var emptyDescribeStatement = writer.addCString("S").flush(68);
2495
+ var describe = (msg) => {
2496
+ return msg.name ? cstringMessage(68, `${msg.type}${msg.name || ""}`) : msg.type === "P" ? emptyDescribePortal : emptyDescribeStatement;
2497
+ };
2498
+ var close = (msg) => {
2499
+ const text = `${msg.type}${msg.name || ""}`;
2500
+ return cstringMessage(67, text);
2501
+ };
2502
+ var copyData = (chunk) => {
2503
+ return writer.add(chunk).flush(100);
2504
+ };
2505
+ var copyFail = (message) => {
2506
+ return cstringMessage(102, message);
2507
+ };
2508
+ var codeOnlyBuffer = (code) => Buffer.from([code, 0, 0, 0, 4]);
2509
+ var flushBuffer = codeOnlyBuffer(72);
2510
+ var syncBuffer = codeOnlyBuffer(83);
2511
+ var endBuffer = codeOnlyBuffer(88);
2512
+ var copyDoneBuffer = codeOnlyBuffer(99);
2513
+ var serialize = {
2514
+ startup,
2515
+ password,
2516
+ requestSsl,
2517
+ sendSASLInitialResponseMessage,
2518
+ sendSCRAMClientFinalMessage,
2519
+ query,
2520
+ parse,
2521
+ bind,
2522
+ execute,
2523
+ describe,
2524
+ close,
2525
+ flush: () => flushBuffer,
2526
+ sync: () => syncBuffer,
2527
+ end: () => endBuffer,
2528
+ copyData,
2529
+ copyDone: () => copyDoneBuffer,
2530
+ copyFail,
2531
+ cancel
2532
+ };
2533
+ exports.serialize = serialize;
2534
+ });
2535
+
2536
+ // node_modules/pg-protocol/dist/buffer-reader.js
2537
+ var require_buffer_reader = __commonJS((exports) => {
2538
+ Object.defineProperty(exports, "__esModule", { value: true });
2539
+ exports.BufferReader = undefined;
2540
+ var emptyBuffer = Buffer.allocUnsafe(0);
2541
+
2542
+ class BufferReader {
2543
+ constructor(offset = 0) {
2544
+ this.offset = offset;
2545
+ this.buffer = emptyBuffer;
2546
+ this.encoding = "utf-8";
2547
+ }
2548
+ setBuffer(offset, buffer) {
2549
+ this.offset = offset;
2550
+ this.buffer = buffer;
2551
+ }
2552
+ int16() {
2553
+ const result = this.buffer.readInt16BE(this.offset);
2554
+ this.offset += 2;
2555
+ return result;
2556
+ }
2557
+ byte() {
2558
+ const result = this.buffer[this.offset];
2559
+ this.offset++;
2560
+ return result;
2561
+ }
2562
+ int32() {
2563
+ const result = this.buffer.readInt32BE(this.offset);
2564
+ this.offset += 4;
2565
+ return result;
2566
+ }
2567
+ uint32() {
2568
+ const result = this.buffer.readUInt32BE(this.offset);
2569
+ this.offset += 4;
2570
+ return result;
2571
+ }
2572
+ string(length) {
2573
+ const result = this.buffer.toString(this.encoding, this.offset, this.offset + length);
2574
+ this.offset += length;
2575
+ return result;
2576
+ }
2577
+ cstring() {
2578
+ const start = this.offset;
2579
+ let end = start;
2580
+ while (this.buffer[end++] !== 0) {}
2581
+ this.offset = end;
2582
+ return this.buffer.toString(this.encoding, start, end - 1);
2583
+ }
2584
+ bytes(length) {
2585
+ const result = this.buffer.slice(this.offset, this.offset + length);
2586
+ this.offset += length;
2587
+ return result;
2588
+ }
2589
+ }
2590
+ exports.BufferReader = BufferReader;
2591
+ });
2592
+
2593
+ // node_modules/pg-protocol/dist/parser.js
2594
+ var require_parser = __commonJS((exports) => {
2595
+ Object.defineProperty(exports, "__esModule", { value: true });
2596
+ exports.Parser = undefined;
2597
+ var messages_1 = require_messages();
2598
+ var buffer_reader_1 = require_buffer_reader();
2599
+ var CODE_LENGTH = 1;
2600
+ var LEN_LENGTH = 4;
2601
+ var HEADER_LENGTH = CODE_LENGTH + LEN_LENGTH;
2602
+ var emptyBuffer = Buffer.allocUnsafe(0);
2603
+
2604
+ class Parser {
2605
+ constructor(opts) {
2606
+ this.buffer = emptyBuffer;
2607
+ this.bufferLength = 0;
2608
+ this.bufferOffset = 0;
2609
+ this.reader = new buffer_reader_1.BufferReader;
2610
+ if ((opts === null || opts === undefined ? undefined : opts.mode) === "binary") {
2611
+ throw new Error("Binary mode not supported yet");
2612
+ }
2613
+ this.mode = (opts === null || opts === undefined ? undefined : opts.mode) || "text";
2614
+ }
2615
+ parse(buffer, callback) {
2616
+ this.mergeBuffer(buffer);
2617
+ const bufferFullLength = this.bufferOffset + this.bufferLength;
2618
+ let offset = this.bufferOffset;
2619
+ while (offset + HEADER_LENGTH <= bufferFullLength) {
2620
+ const code = this.buffer[offset];
2621
+ const length = this.buffer.readUInt32BE(offset + CODE_LENGTH);
2622
+ const fullMessageLength = CODE_LENGTH + length;
2623
+ if (fullMessageLength + offset <= bufferFullLength) {
2624
+ const message = this.handlePacket(offset + HEADER_LENGTH, code, length, this.buffer);
2625
+ callback(message);
2626
+ offset += fullMessageLength;
2627
+ } else {
2628
+ break;
2629
+ }
2630
+ }
2631
+ if (offset === bufferFullLength) {
2632
+ this.buffer = emptyBuffer;
2633
+ this.bufferLength = 0;
2634
+ this.bufferOffset = 0;
2635
+ } else {
2636
+ this.bufferLength = bufferFullLength - offset;
2637
+ this.bufferOffset = offset;
2638
+ }
2639
+ }
2640
+ mergeBuffer(buffer) {
2641
+ if (this.bufferLength > 0) {
2642
+ const newLength = this.bufferLength + buffer.byteLength;
2643
+ const newFullLength = newLength + this.bufferOffset;
2644
+ if (newFullLength > this.buffer.byteLength) {
2645
+ let newBuffer;
2646
+ if (newLength <= this.buffer.byteLength && this.bufferOffset >= this.bufferLength) {
2647
+ newBuffer = this.buffer;
2648
+ } else {
2649
+ let newBufferLength = this.buffer.byteLength * 2;
2650
+ while (newLength >= newBufferLength) {
2651
+ newBufferLength *= 2;
2652
+ }
2653
+ newBuffer = Buffer.allocUnsafe(newBufferLength);
2654
+ }
2655
+ this.buffer.copy(newBuffer, 0, this.bufferOffset, this.bufferOffset + this.bufferLength);
2656
+ this.buffer = newBuffer;
2657
+ this.bufferOffset = 0;
2658
+ }
2659
+ buffer.copy(this.buffer, this.bufferOffset + this.bufferLength);
2660
+ this.bufferLength = newLength;
2661
+ } else {
2662
+ this.buffer = buffer;
2663
+ this.bufferOffset = 0;
2664
+ this.bufferLength = buffer.byteLength;
2665
+ }
2666
+ }
2667
+ handlePacket(offset, code, length, bytes) {
2668
+ switch (code) {
2669
+ case 50:
2670
+ return messages_1.bindComplete;
2671
+ case 49:
2672
+ return messages_1.parseComplete;
2673
+ case 51:
2674
+ return messages_1.closeComplete;
2675
+ case 110:
2676
+ return messages_1.noData;
2677
+ case 115:
2678
+ return messages_1.portalSuspended;
2679
+ case 99:
2680
+ return messages_1.copyDone;
2681
+ case 87:
2682
+ return messages_1.replicationStart;
2683
+ case 73:
2684
+ return messages_1.emptyQuery;
2685
+ case 68:
2686
+ return this.parseDataRowMessage(offset, length, bytes);
2687
+ case 67:
2688
+ return this.parseCommandCompleteMessage(offset, length, bytes);
2689
+ case 90:
2690
+ return this.parseReadyForQueryMessage(offset, length, bytes);
2691
+ case 65:
2692
+ return this.parseNotificationMessage(offset, length, bytes);
2693
+ case 82:
2694
+ return this.parseAuthenticationResponse(offset, length, bytes);
2695
+ case 83:
2696
+ return this.parseParameterStatusMessage(offset, length, bytes);
2697
+ case 75:
2698
+ return this.parseBackendKeyData(offset, length, bytes);
2699
+ case 69:
2700
+ return this.parseErrorMessage(offset, length, bytes, "error");
2701
+ case 78:
2702
+ return this.parseErrorMessage(offset, length, bytes, "notice");
2703
+ case 84:
2704
+ return this.parseRowDescriptionMessage(offset, length, bytes);
2705
+ case 116:
2706
+ return this.parseParameterDescriptionMessage(offset, length, bytes);
2707
+ case 71:
2708
+ return this.parseCopyInMessage(offset, length, bytes);
2709
+ case 72:
2710
+ return this.parseCopyOutMessage(offset, length, bytes);
2711
+ case 100:
2712
+ return this.parseCopyData(offset, length, bytes);
2713
+ default:
2714
+ return new messages_1.DatabaseError("received invalid response: " + code.toString(16), length, "error");
2715
+ }
2716
+ }
2717
+ parseReadyForQueryMessage(offset, length, bytes) {
2718
+ this.reader.setBuffer(offset, bytes);
2719
+ const status = this.reader.string(1);
2720
+ return new messages_1.ReadyForQueryMessage(length, status);
2721
+ }
2722
+ parseCommandCompleteMessage(offset, length, bytes) {
2723
+ this.reader.setBuffer(offset, bytes);
2724
+ const text = this.reader.cstring();
2725
+ return new messages_1.CommandCompleteMessage(length, text);
2726
+ }
2727
+ parseCopyData(offset, length, bytes) {
2728
+ const chunk = bytes.slice(offset, offset + (length - 4));
2729
+ return new messages_1.CopyDataMessage(length, chunk);
2730
+ }
2731
+ parseCopyInMessage(offset, length, bytes) {
2732
+ return this.parseCopyMessage(offset, length, bytes, "copyInResponse");
2733
+ }
2734
+ parseCopyOutMessage(offset, length, bytes) {
2735
+ return this.parseCopyMessage(offset, length, bytes, "copyOutResponse");
2736
+ }
2737
+ parseCopyMessage(offset, length, bytes, messageName) {
2738
+ this.reader.setBuffer(offset, bytes);
2739
+ const isBinary = this.reader.byte() !== 0;
2740
+ const columnCount = this.reader.int16();
2741
+ const message = new messages_1.CopyResponse(length, messageName, isBinary, columnCount);
2742
+ for (let i = 0;i < columnCount; i++) {
2743
+ message.columnTypes[i] = this.reader.int16();
2744
+ }
2745
+ return message;
2746
+ }
2747
+ parseNotificationMessage(offset, length, bytes) {
2748
+ this.reader.setBuffer(offset, bytes);
2749
+ const processId = this.reader.int32();
2750
+ const channel = this.reader.cstring();
2751
+ const payload = this.reader.cstring();
2752
+ return new messages_1.NotificationResponseMessage(length, processId, channel, payload);
2753
+ }
2754
+ parseRowDescriptionMessage(offset, length, bytes) {
2755
+ this.reader.setBuffer(offset, bytes);
2756
+ const fieldCount = this.reader.int16();
2757
+ const message = new messages_1.RowDescriptionMessage(length, fieldCount);
2758
+ for (let i = 0;i < fieldCount; i++) {
2759
+ message.fields[i] = this.parseField();
2760
+ }
2761
+ return message;
2762
+ }
2763
+ parseField() {
2764
+ const name = this.reader.cstring();
2765
+ const tableID = this.reader.uint32();
2766
+ const columnID = this.reader.int16();
2767
+ const dataTypeID = this.reader.uint32();
2768
+ const dataTypeSize = this.reader.int16();
2769
+ const dataTypeModifier = this.reader.int32();
2770
+ const mode = this.reader.int16() === 0 ? "text" : "binary";
2771
+ return new messages_1.Field(name, tableID, columnID, dataTypeID, dataTypeSize, dataTypeModifier, mode);
2772
+ }
2773
+ parseParameterDescriptionMessage(offset, length, bytes) {
2774
+ this.reader.setBuffer(offset, bytes);
2775
+ const parameterCount = this.reader.int16();
2776
+ const message = new messages_1.ParameterDescriptionMessage(length, parameterCount);
2777
+ for (let i = 0;i < parameterCount; i++) {
2778
+ message.dataTypeIDs[i] = this.reader.int32();
2779
+ }
2780
+ return message;
2781
+ }
2782
+ parseDataRowMessage(offset, length, bytes) {
2783
+ this.reader.setBuffer(offset, bytes);
2784
+ const fieldCount = this.reader.int16();
2785
+ const fields = new Array(fieldCount);
2786
+ for (let i = 0;i < fieldCount; i++) {
2787
+ const len = this.reader.int32();
2788
+ fields[i] = len === -1 ? null : this.reader.string(len);
2789
+ }
2790
+ return new messages_1.DataRowMessage(length, fields);
2791
+ }
2792
+ parseParameterStatusMessage(offset, length, bytes) {
2793
+ this.reader.setBuffer(offset, bytes);
2794
+ const name = this.reader.cstring();
2795
+ const value = this.reader.cstring();
2796
+ return new messages_1.ParameterStatusMessage(length, name, value);
2797
+ }
2798
+ parseBackendKeyData(offset, length, bytes) {
2799
+ this.reader.setBuffer(offset, bytes);
2800
+ const processID = this.reader.int32();
2801
+ const secretKey = this.reader.int32();
2802
+ return new messages_1.BackendKeyDataMessage(length, processID, secretKey);
2803
+ }
2804
+ parseAuthenticationResponse(offset, length, bytes) {
2805
+ this.reader.setBuffer(offset, bytes);
2806
+ const code = this.reader.int32();
2807
+ const message = {
2808
+ name: "authenticationOk",
2809
+ length
2810
+ };
2811
+ switch (code) {
2812
+ case 0:
2813
+ break;
2814
+ case 3:
2815
+ if (message.length === 8) {
2816
+ message.name = "authenticationCleartextPassword";
2817
+ }
2818
+ break;
2819
+ case 5:
2820
+ if (message.length === 12) {
2821
+ message.name = "authenticationMD5Password";
2822
+ const salt = this.reader.bytes(4);
2823
+ return new messages_1.AuthenticationMD5Password(length, salt);
2824
+ }
2825
+ break;
2826
+ case 10:
2827
+ {
2828
+ message.name = "authenticationSASL";
2829
+ message.mechanisms = [];
2830
+ let mechanism;
2831
+ do {
2832
+ mechanism = this.reader.cstring();
2833
+ if (mechanism) {
2834
+ message.mechanisms.push(mechanism);
2835
+ }
2836
+ } while (mechanism);
2837
+ }
2838
+ break;
2839
+ case 11:
2840
+ message.name = "authenticationSASLContinue";
2841
+ message.data = this.reader.string(length - 8);
2842
+ break;
2843
+ case 12:
2844
+ message.name = "authenticationSASLFinal";
2845
+ message.data = this.reader.string(length - 8);
2846
+ break;
2847
+ default:
2848
+ throw new Error("Unknown authenticationOk message type " + code);
2849
+ }
2850
+ return message;
2851
+ }
2852
+ parseErrorMessage(offset, length, bytes, name) {
2853
+ this.reader.setBuffer(offset, bytes);
2854
+ const fields = {};
2855
+ let fieldType = this.reader.string(1);
2856
+ while (fieldType !== "\x00") {
2857
+ fields[fieldType] = this.reader.cstring();
2858
+ fieldType = this.reader.string(1);
2859
+ }
2860
+ const messageValue = fields.M;
2861
+ const message = name === "notice" ? new messages_1.NoticeMessage(length, messageValue) : new messages_1.DatabaseError(messageValue, length, name);
2862
+ message.severity = fields.S;
2863
+ message.code = fields.C;
2864
+ message.detail = fields.D;
2865
+ message.hint = fields.H;
2866
+ message.position = fields.P;
2867
+ message.internalPosition = fields.p;
2868
+ message.internalQuery = fields.q;
2869
+ message.where = fields.W;
2870
+ message.schema = fields.s;
2871
+ message.table = fields.t;
2872
+ message.column = fields.c;
2873
+ message.dataType = fields.d;
2874
+ message.constraint = fields.n;
2875
+ message.file = fields.F;
2876
+ message.line = fields.L;
2877
+ message.routine = fields.R;
2878
+ return message;
2879
+ }
2880
+ }
2881
+ exports.Parser = Parser;
2882
+ });
2883
+
2884
+ // node_modules/pg-protocol/dist/index.js
2885
+ var require_dist = __commonJS((exports) => {
2886
+ Object.defineProperty(exports, "__esModule", { value: true });
2887
+ exports.DatabaseError = exports.serialize = exports.parse = undefined;
2888
+ var messages_1 = require_messages();
2889
+ Object.defineProperty(exports, "DatabaseError", { enumerable: true, get: function() {
2890
+ return messages_1.DatabaseError;
2891
+ } });
2892
+ var serializer_1 = require_serializer();
2893
+ Object.defineProperty(exports, "serialize", { enumerable: true, get: function() {
2894
+ return serializer_1.serialize;
2895
+ } });
2896
+ var parser_1 = require_parser();
2897
+ function parse(stream, callback) {
2898
+ const parser = new parser_1.Parser;
2899
+ stream.on("data", (buffer) => parser.parse(buffer, callback));
2900
+ return new Promise((resolve) => stream.on("end", () => resolve()));
2901
+ }
2902
+ exports.parse = parse;
2903
+ });
2904
+
2905
+ // node_modules/pg-cloudflare/dist/empty.js
2906
+ var require_empty = __commonJS((exports) => {
2907
+ Object.defineProperty(exports, "__esModule", { value: true });
2908
+ exports.default = {};
2909
+ });
2910
+
2911
+ // node_modules/pg/lib/stream.js
2912
+ var require_stream = __commonJS((exports, module) => {
2913
+ var { getStream, getSecureStream } = getStreamFuncs();
2914
+ module.exports = {
2915
+ getStream,
2916
+ getSecureStream
2917
+ };
2918
+ function getNodejsStreamFuncs() {
2919
+ function getStream2(ssl) {
2920
+ const net = __require("net");
2921
+ return new net.Socket;
2922
+ }
2923
+ function getSecureStream2(options) {
2924
+ const tls = __require("tls");
2925
+ return tls.connect(options);
2926
+ }
2927
+ return {
2928
+ getStream: getStream2,
2929
+ getSecureStream: getSecureStream2
2930
+ };
2931
+ }
2932
+ function getCloudflareStreamFuncs() {
2933
+ function getStream2(ssl) {
2934
+ const { CloudflareSocket } = require_empty();
2935
+ return new CloudflareSocket(ssl);
2936
+ }
2937
+ function getSecureStream2(options) {
2938
+ options.socket.startTls(options);
2939
+ return options.socket;
2940
+ }
2941
+ return {
2942
+ getStream: getStream2,
2943
+ getSecureStream: getSecureStream2
2944
+ };
2945
+ }
2946
+ function isCloudflareRuntime() {
2947
+ if (typeof navigator === "object" && navigator !== null && typeof navigator.userAgent === "string") {
2948
+ return navigator.userAgent === "Cloudflare-Workers";
2949
+ }
2950
+ if (typeof Response === "function") {
2951
+ const resp = new Response(null, { cf: { thing: true } });
2952
+ if (typeof resp.cf === "object" && resp.cf !== null && resp.cf.thing) {
2953
+ return true;
2954
+ }
2955
+ }
2956
+ return false;
2957
+ }
2958
+ function getStreamFuncs() {
2959
+ if (isCloudflareRuntime()) {
2960
+ return getCloudflareStreamFuncs();
2961
+ }
2962
+ return getNodejsStreamFuncs();
2963
+ }
2964
+ });
2965
+
2966
+ // node_modules/pg/lib/connection.js
2967
+ var require_connection = __commonJS((exports, module) => {
2968
+ var EventEmitter = __require("events").EventEmitter;
2969
+ var { parse, serialize } = require_dist();
2970
+ var { getStream, getSecureStream } = require_stream();
2971
+ var flushBuffer = serialize.flush();
2972
+ var syncBuffer = serialize.sync();
2973
+ var endBuffer = serialize.end();
2974
+
2975
+ class Connection extends EventEmitter {
2976
+ constructor(config) {
2977
+ super();
2978
+ config = config || {};
2979
+ this.stream = config.stream || getStream(config.ssl);
2980
+ if (typeof this.stream === "function") {
2981
+ this.stream = this.stream(config);
2982
+ }
2983
+ this._keepAlive = config.keepAlive;
2984
+ this._keepAliveInitialDelayMillis = config.keepAliveInitialDelayMillis;
2985
+ this.lastBuffer = false;
2986
+ this.parsedStatements = {};
2987
+ this.ssl = config.ssl || false;
2988
+ this._ending = false;
2989
+ this._emitMessage = false;
2990
+ const self = this;
2991
+ this.on("newListener", function(eventName) {
2992
+ if (eventName === "message") {
2993
+ self._emitMessage = true;
2994
+ }
2995
+ });
2996
+ }
2997
+ connect(port, host) {
2998
+ const self = this;
2999
+ this._connecting = true;
3000
+ this.stream.setNoDelay(true);
3001
+ this.stream.connect(port, host);
3002
+ this.stream.once("connect", function() {
3003
+ if (self._keepAlive) {
3004
+ self.stream.setKeepAlive(true, self._keepAliveInitialDelayMillis);
3005
+ }
3006
+ self.emit("connect");
3007
+ });
3008
+ const reportStreamError = function(error) {
3009
+ if (self._ending && (error.code === "ECONNRESET" || error.code === "EPIPE")) {
3010
+ return;
3011
+ }
3012
+ self.emit("error", error);
3013
+ };
3014
+ this.stream.on("error", reportStreamError);
3015
+ this.stream.on("close", function() {
3016
+ self.emit("end");
3017
+ });
3018
+ if (!this.ssl) {
3019
+ return this.attachListeners(this.stream);
3020
+ }
3021
+ this.stream.once("data", function(buffer) {
3022
+ const responseCode = buffer.toString("utf8");
3023
+ switch (responseCode) {
3024
+ case "S":
3025
+ break;
3026
+ case "N":
3027
+ self.stream.end();
3028
+ return self.emit("error", new Error("The server does not support SSL connections"));
3029
+ default:
3030
+ self.stream.end();
3031
+ return self.emit("error", new Error("There was an error establishing an SSL connection"));
3032
+ }
3033
+ const options = {
3034
+ socket: self.stream
3035
+ };
3036
+ if (self.ssl !== true) {
3037
+ Object.assign(options, self.ssl);
3038
+ if ("key" in self.ssl) {
3039
+ options.key = self.ssl.key;
3040
+ }
3041
+ }
3042
+ const net = __require("net");
3043
+ if (net.isIP && net.isIP(host) === 0) {
3044
+ options.servername = host;
3045
+ }
3046
+ try {
3047
+ self.stream = getSecureStream(options);
3048
+ } catch (err) {
3049
+ return self.emit("error", err);
3050
+ }
3051
+ self.attachListeners(self.stream);
3052
+ self.stream.on("error", reportStreamError);
3053
+ self.emit("sslconnect");
3054
+ });
3055
+ }
3056
+ attachListeners(stream) {
3057
+ parse(stream, (msg) => {
3058
+ const eventName = msg.name === "error" ? "errorMessage" : msg.name;
3059
+ if (this._emitMessage) {
3060
+ this.emit("message", msg);
3061
+ }
3062
+ this.emit(eventName, msg);
3063
+ });
3064
+ }
3065
+ requestSsl() {
3066
+ this.stream.write(serialize.requestSsl());
3067
+ }
3068
+ startup(config) {
3069
+ this.stream.write(serialize.startup(config));
3070
+ }
3071
+ cancel(processID, secretKey) {
3072
+ this._send(serialize.cancel(processID, secretKey));
3073
+ }
3074
+ password(password) {
3075
+ this._send(serialize.password(password));
3076
+ }
3077
+ sendSASLInitialResponseMessage(mechanism, initialResponse) {
3078
+ this._send(serialize.sendSASLInitialResponseMessage(mechanism, initialResponse));
3079
+ }
3080
+ sendSCRAMClientFinalMessage(additionalData) {
3081
+ this._send(serialize.sendSCRAMClientFinalMessage(additionalData));
3082
+ }
3083
+ _send(buffer) {
3084
+ if (!this.stream.writable) {
3085
+ return false;
3086
+ }
3087
+ return this.stream.write(buffer);
3088
+ }
3089
+ query(text) {
3090
+ this._send(serialize.query(text));
3091
+ }
3092
+ parse(query) {
3093
+ this._send(serialize.parse(query));
3094
+ }
3095
+ bind(config) {
3096
+ this._send(serialize.bind(config));
3097
+ }
3098
+ execute(config) {
3099
+ this._send(serialize.execute(config));
3100
+ }
3101
+ flush() {
3102
+ if (this.stream.writable) {
3103
+ this.stream.write(flushBuffer);
3104
+ }
3105
+ }
3106
+ sync() {
3107
+ this._ending = true;
3108
+ this._send(syncBuffer);
3109
+ }
3110
+ ref() {
3111
+ this.stream.ref();
3112
+ }
3113
+ unref() {
3114
+ this.stream.unref();
3115
+ }
3116
+ end() {
3117
+ this._ending = true;
3118
+ if (!this._connecting || !this.stream.writable) {
3119
+ this.stream.end();
3120
+ return;
3121
+ }
3122
+ return this.stream.write(endBuffer, () => {
3123
+ this.stream.end();
3124
+ });
3125
+ }
3126
+ close(msg) {
3127
+ this._send(serialize.close(msg));
3128
+ }
3129
+ describe(msg) {
3130
+ this._send(serialize.describe(msg));
3131
+ }
3132
+ sendCopyFromChunk(chunk) {
3133
+ this._send(serialize.copyData(chunk));
3134
+ }
3135
+ endCopyFrom() {
3136
+ this._send(serialize.copyDone());
3137
+ }
3138
+ sendCopyFail(msg) {
3139
+ this._send(serialize.copyFail(msg));
3140
+ }
3141
+ }
3142
+ module.exports = Connection;
3143
+ });
3144
+
3145
+ // node_modules/split2/index.js
3146
+ var require_split2 = __commonJS((exports, module) => {
3147
+ var { Transform } = __require("stream");
3148
+ var { StringDecoder } = __require("string_decoder");
3149
+ var kLast = Symbol("last");
3150
+ var kDecoder = Symbol("decoder");
3151
+ function transform(chunk, enc, cb) {
3152
+ let list;
3153
+ if (this.overflow) {
3154
+ const buf = this[kDecoder].write(chunk);
3155
+ list = buf.split(this.matcher);
3156
+ if (list.length === 1)
3157
+ return cb();
3158
+ list.shift();
3159
+ this.overflow = false;
3160
+ } else {
3161
+ this[kLast] += this[kDecoder].write(chunk);
3162
+ list = this[kLast].split(this.matcher);
3163
+ }
3164
+ this[kLast] = list.pop();
3165
+ for (let i = 0;i < list.length; i++) {
3166
+ try {
3167
+ push(this, this.mapper(list[i]));
3168
+ } catch (error) {
3169
+ return cb(error);
3170
+ }
3171
+ }
3172
+ this.overflow = this[kLast].length > this.maxLength;
3173
+ if (this.overflow && !this.skipOverflow) {
3174
+ cb(new Error("maximum buffer reached"));
3175
+ return;
3176
+ }
3177
+ cb();
3178
+ }
3179
+ function flush(cb) {
3180
+ this[kLast] += this[kDecoder].end();
3181
+ if (this[kLast]) {
3182
+ try {
3183
+ push(this, this.mapper(this[kLast]));
3184
+ } catch (error) {
3185
+ return cb(error);
3186
+ }
3187
+ }
3188
+ cb();
3189
+ }
3190
+ function push(self, val) {
3191
+ if (val !== undefined) {
3192
+ self.push(val);
3193
+ }
3194
+ }
3195
+ function noop(incoming) {
3196
+ return incoming;
3197
+ }
3198
+ function split(matcher, mapper, options) {
3199
+ matcher = matcher || /\r?\n/;
3200
+ mapper = mapper || noop;
3201
+ options = options || {};
3202
+ switch (arguments.length) {
3203
+ case 1:
3204
+ if (typeof matcher === "function") {
3205
+ mapper = matcher;
3206
+ matcher = /\r?\n/;
3207
+ } else if (typeof matcher === "object" && !(matcher instanceof RegExp) && !matcher[Symbol.split]) {
3208
+ options = matcher;
3209
+ matcher = /\r?\n/;
3210
+ }
3211
+ break;
3212
+ case 2:
3213
+ if (typeof matcher === "function") {
3214
+ options = mapper;
3215
+ mapper = matcher;
3216
+ matcher = /\r?\n/;
3217
+ } else if (typeof mapper === "object") {
3218
+ options = mapper;
3219
+ mapper = noop;
3220
+ }
3221
+ }
3222
+ options = Object.assign({}, options);
3223
+ options.autoDestroy = true;
3224
+ options.transform = transform;
3225
+ options.flush = flush;
3226
+ options.readableObjectMode = true;
3227
+ const stream = new Transform(options);
3228
+ stream[kLast] = "";
3229
+ stream[kDecoder] = new StringDecoder("utf8");
3230
+ stream.matcher = matcher;
3231
+ stream.mapper = mapper;
3232
+ stream.maxLength = options.maxLength;
3233
+ stream.skipOverflow = options.skipOverflow || false;
3234
+ stream.overflow = false;
3235
+ stream._destroy = function(err, cb) {
3236
+ this._writableState.errorEmitted = false;
3237
+ cb(err);
3238
+ };
3239
+ return stream;
3240
+ }
3241
+ module.exports = split;
3242
+ });
3243
+
3244
+ // node_modules/pgpass/lib/helper.js
3245
+ var require_helper = __commonJS((exports, module) => {
3246
+ var path = __require("path");
3247
+ var Stream = __require("stream").Stream;
3248
+ var split = require_split2();
3249
+ var util = __require("util");
3250
+ var defaultPort = 5432;
3251
+ var isWin = process.platform === "win32";
3252
+ var warnStream = process.stderr;
3253
+ var S_IRWXG = 56;
3254
+ var S_IRWXO = 7;
3255
+ var S_IFMT = 61440;
3256
+ var S_IFREG = 32768;
3257
+ function isRegFile(mode) {
3258
+ return (mode & S_IFMT) == S_IFREG;
3259
+ }
3260
+ var fieldNames = ["host", "port", "database", "user", "password"];
3261
+ var nrOfFields = fieldNames.length;
3262
+ var passKey = fieldNames[nrOfFields - 1];
3263
+ function warn() {
3264
+ var isWritable = warnStream instanceof Stream && warnStream.writable === true;
3265
+ if (isWritable) {
3266
+ var args = Array.prototype.slice.call(arguments).concat(`
3267
+ `);
3268
+ warnStream.write(util.format.apply(util, args));
3269
+ }
3270
+ }
3271
+ Object.defineProperty(exports, "isWin", {
3272
+ get: function() {
3273
+ return isWin;
3274
+ },
3275
+ set: function(val) {
3276
+ isWin = val;
3277
+ }
3278
+ });
3279
+ exports.warnTo = function(stream) {
3280
+ var old = warnStream;
3281
+ warnStream = stream;
3282
+ return old;
3283
+ };
3284
+ exports.getFileName = function(rawEnv) {
3285
+ var env = rawEnv || process.env;
3286
+ var file = env.PGPASSFILE || (isWin ? path.join(env.APPDATA || "./", "postgresql", "pgpass.conf") : path.join(env.HOME || "./", ".pgpass"));
3287
+ return file;
3288
+ };
3289
+ exports.usePgPass = function(stats, fname) {
3290
+ if (Object.prototype.hasOwnProperty.call(process.env, "PGPASSWORD")) {
3291
+ return false;
3292
+ }
3293
+ if (isWin) {
3294
+ return true;
3295
+ }
3296
+ fname = fname || "<unkn>";
3297
+ if (!isRegFile(stats.mode)) {
3298
+ warn('WARNING: password file "%s" is not a plain file', fname);
3299
+ return false;
3300
+ }
3301
+ if (stats.mode & (S_IRWXG | S_IRWXO)) {
3302
+ warn('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less', fname);
3303
+ return false;
3304
+ }
3305
+ return true;
3306
+ };
3307
+ var matcher = exports.match = function(connInfo, entry) {
3308
+ return fieldNames.slice(0, -1).reduce(function(prev, field, idx) {
3309
+ if (idx == 1) {
3310
+ if (Number(connInfo[field] || defaultPort) === Number(entry[field])) {
3311
+ return prev && true;
3312
+ }
3313
+ }
3314
+ return prev && (entry[field] === "*" || entry[field] === connInfo[field]);
3315
+ }, true);
3316
+ };
3317
+ exports.getPassword = function(connInfo, stream, cb) {
3318
+ var pass;
3319
+ var lineStream = stream.pipe(split());
3320
+ function onLine(line) {
3321
+ var entry = parseLine(line);
3322
+ if (entry && isValidEntry(entry) && matcher(connInfo, entry)) {
3323
+ pass = entry[passKey];
3324
+ lineStream.end();
3325
+ }
3326
+ }
3327
+ var onEnd = function() {
3328
+ stream.destroy();
3329
+ cb(pass);
3330
+ };
3331
+ var onErr = function(err) {
3332
+ stream.destroy();
3333
+ warn("WARNING: error on reading file: %s", err);
3334
+ cb(undefined);
3335
+ };
3336
+ stream.on("error", onErr);
3337
+ lineStream.on("data", onLine).on("end", onEnd).on("error", onErr);
3338
+ };
3339
+ var parseLine = exports.parseLine = function(line) {
3340
+ if (line.length < 11 || line.match(/^\s+#/)) {
3341
+ return null;
3342
+ }
3343
+ var curChar = "";
3344
+ var prevChar = "";
3345
+ var fieldIdx = 0;
3346
+ var startIdx = 0;
3347
+ var endIdx = 0;
3348
+ var obj = {};
3349
+ var isLastField = false;
3350
+ var addToObj = function(idx, i0, i1) {
3351
+ var field = line.substring(i0, i1);
3352
+ if (!Object.hasOwnProperty.call(process.env, "PGPASS_NO_DEESCAPE")) {
3353
+ field = field.replace(/\\([:\\])/g, "$1");
3354
+ }
3355
+ obj[fieldNames[idx]] = field;
3356
+ };
3357
+ for (var i = 0;i < line.length - 1; i += 1) {
3358
+ curChar = line.charAt(i + 1);
3359
+ prevChar = line.charAt(i);
3360
+ isLastField = fieldIdx == nrOfFields - 1;
3361
+ if (isLastField) {
3362
+ addToObj(fieldIdx, startIdx);
3363
+ break;
3364
+ }
3365
+ if (i >= 0 && curChar == ":" && prevChar !== "\\") {
3366
+ addToObj(fieldIdx, startIdx, i + 1);
3367
+ startIdx = i + 2;
3368
+ fieldIdx += 1;
3369
+ }
3370
+ }
3371
+ obj = Object.keys(obj).length === nrOfFields ? obj : null;
3372
+ return obj;
3373
+ };
3374
+ var isValidEntry = exports.isValidEntry = function(entry) {
3375
+ var rules = {
3376
+ 0: function(x) {
3377
+ return x.length > 0;
3378
+ },
3379
+ 1: function(x) {
3380
+ if (x === "*") {
3381
+ return true;
3382
+ }
3383
+ x = Number(x);
3384
+ return isFinite(x) && x > 0 && x < 9007199254740992 && Math.floor(x) === x;
3385
+ },
3386
+ 2: function(x) {
3387
+ return x.length > 0;
3388
+ },
3389
+ 3: function(x) {
3390
+ return x.length > 0;
3391
+ },
3392
+ 4: function(x) {
3393
+ return x.length > 0;
3394
+ }
3395
+ };
3396
+ for (var idx = 0;idx < fieldNames.length; idx += 1) {
3397
+ var rule = rules[idx];
3398
+ var value = entry[fieldNames[idx]] || "";
3399
+ var res = rule(value);
3400
+ if (!res) {
3401
+ return false;
3402
+ }
3403
+ }
3404
+ return true;
3405
+ };
3406
+ });
3407
+
3408
+ // node_modules/pgpass/lib/index.js
3409
+ var require_lib = __commonJS((exports, module) => {
3410
+ var path = __require("path");
3411
+ var fs = __require("fs");
3412
+ var helper = require_helper();
3413
+ module.exports = function(connInfo, cb) {
3414
+ var file = helper.getFileName();
3415
+ fs.stat(file, function(err, stat) {
3416
+ if (err || !helper.usePgPass(stat, file)) {
3417
+ return cb(undefined);
3418
+ }
3419
+ var st = fs.createReadStream(file);
3420
+ helper.getPassword(connInfo, st, cb);
3421
+ });
3422
+ };
3423
+ module.exports.warnTo = helper.warnTo;
3424
+ });
3425
+
3426
+ // node_modules/pg/lib/client.js
3427
+ var require_client = __commonJS((exports, module) => {
3428
+ var EventEmitter = __require("events").EventEmitter;
3429
+ var utils = require_utils();
3430
+ var sasl = require_sasl();
3431
+ var TypeOverrides = require_type_overrides();
3432
+ var ConnectionParameters = require_connection_parameters();
3433
+ var Query = require_query();
3434
+ var defaults = require_defaults();
3435
+ var Connection = require_connection();
3436
+ var crypto = require_utils2();
3437
+
3438
+ class Client extends EventEmitter {
3439
+ constructor(config) {
3440
+ super();
3441
+ this.connectionParameters = new ConnectionParameters(config);
3442
+ this.user = this.connectionParameters.user;
3443
+ this.database = this.connectionParameters.database;
3444
+ this.port = this.connectionParameters.port;
3445
+ this.host = this.connectionParameters.host;
3446
+ Object.defineProperty(this, "password", {
3447
+ configurable: true,
3448
+ enumerable: false,
3449
+ writable: true,
3450
+ value: this.connectionParameters.password
3451
+ });
3452
+ this.replication = this.connectionParameters.replication;
3453
+ const c = config || {};
3454
+ this._Promise = c.Promise || global.Promise;
3455
+ this._types = new TypeOverrides(c.types);
3456
+ this._ending = false;
3457
+ this._ended = false;
3458
+ this._connecting = false;
3459
+ this._connected = false;
3460
+ this._connectionError = false;
3461
+ this._queryable = true;
3462
+ this.enableChannelBinding = Boolean(c.enableChannelBinding);
3463
+ this.connection = c.connection || new Connection({
3464
+ stream: c.stream,
3465
+ ssl: this.connectionParameters.ssl,
3466
+ keepAlive: c.keepAlive || false,
3467
+ keepAliveInitialDelayMillis: c.keepAliveInitialDelayMillis || 0,
3468
+ encoding: this.connectionParameters.client_encoding || "utf8"
3469
+ });
3470
+ this.queryQueue = [];
3471
+ this.binary = c.binary || defaults.binary;
3472
+ this.processID = null;
3473
+ this.secretKey = null;
3474
+ this.ssl = this.connectionParameters.ssl || false;
3475
+ if (this.ssl && this.ssl.key) {
3476
+ Object.defineProperty(this.ssl, "key", {
3477
+ enumerable: false
3478
+ });
3479
+ }
3480
+ this._connectionTimeoutMillis = c.connectionTimeoutMillis || 0;
3481
+ }
3482
+ _errorAllQueries(err) {
3483
+ const enqueueError = (query) => {
3484
+ process.nextTick(() => {
3485
+ query.handleError(err, this.connection);
3486
+ });
3487
+ };
3488
+ if (this.activeQuery) {
3489
+ enqueueError(this.activeQuery);
3490
+ this.activeQuery = null;
3491
+ }
3492
+ this.queryQueue.forEach(enqueueError);
3493
+ this.queryQueue.length = 0;
3494
+ }
3495
+ _connect(callback) {
3496
+ const self = this;
3497
+ const con = this.connection;
3498
+ this._connectionCallback = callback;
3499
+ if (this._connecting || this._connected) {
3500
+ const err = new Error("Client has already been connected. You cannot reuse a client.");
3501
+ process.nextTick(() => {
3502
+ callback(err);
3503
+ });
3504
+ return;
3505
+ }
3506
+ this._connecting = true;
3507
+ if (this._connectionTimeoutMillis > 0) {
3508
+ this.connectionTimeoutHandle = setTimeout(() => {
3509
+ con._ending = true;
3510
+ con.stream.destroy(new Error("timeout expired"));
3511
+ }, this._connectionTimeoutMillis);
3512
+ if (this.connectionTimeoutHandle.unref) {
3513
+ this.connectionTimeoutHandle.unref();
3514
+ }
3515
+ }
3516
+ if (this.host && this.host.indexOf("/") === 0) {
3517
+ con.connect(this.host + "/.s.PGSQL." + this.port);
3518
+ } else {
3519
+ con.connect(this.port, this.host);
3520
+ }
3521
+ con.on("connect", function() {
3522
+ if (self.ssl) {
3523
+ con.requestSsl();
3524
+ } else {
3525
+ con.startup(self.getStartupConf());
3526
+ }
3527
+ });
3528
+ con.on("sslconnect", function() {
3529
+ con.startup(self.getStartupConf());
3530
+ });
3531
+ this._attachListeners(con);
3532
+ con.once("end", () => {
3533
+ const error = this._ending ? new Error("Connection terminated") : new Error("Connection terminated unexpectedly");
3534
+ clearTimeout(this.connectionTimeoutHandle);
3535
+ this._errorAllQueries(error);
3536
+ this._ended = true;
3537
+ if (!this._ending) {
3538
+ if (this._connecting && !this._connectionError) {
3539
+ if (this._connectionCallback) {
3540
+ this._connectionCallback(error);
3541
+ } else {
3542
+ this._handleErrorEvent(error);
3543
+ }
3544
+ } else if (!this._connectionError) {
3545
+ this._handleErrorEvent(error);
3546
+ }
3547
+ }
3548
+ process.nextTick(() => {
3549
+ this.emit("end");
3550
+ });
3551
+ });
3552
+ }
3553
+ connect(callback) {
3554
+ if (callback) {
3555
+ this._connect(callback);
3556
+ return;
3557
+ }
3558
+ return new this._Promise((resolve, reject) => {
3559
+ this._connect((error) => {
3560
+ if (error) {
3561
+ reject(error);
3562
+ } else {
3563
+ resolve();
3564
+ }
3565
+ });
3566
+ });
3567
+ }
3568
+ _attachListeners(con) {
3569
+ con.on("authenticationCleartextPassword", this._handleAuthCleartextPassword.bind(this));
3570
+ con.on("authenticationMD5Password", this._handleAuthMD5Password.bind(this));
3571
+ con.on("authenticationSASL", this._handleAuthSASL.bind(this));
3572
+ con.on("authenticationSASLContinue", this._handleAuthSASLContinue.bind(this));
3573
+ con.on("authenticationSASLFinal", this._handleAuthSASLFinal.bind(this));
3574
+ con.on("backendKeyData", this._handleBackendKeyData.bind(this));
3575
+ con.on("error", this._handleErrorEvent.bind(this));
3576
+ con.on("errorMessage", this._handleErrorMessage.bind(this));
3577
+ con.on("readyForQuery", this._handleReadyForQuery.bind(this));
3578
+ con.on("notice", this._handleNotice.bind(this));
3579
+ con.on("rowDescription", this._handleRowDescription.bind(this));
3580
+ con.on("dataRow", this._handleDataRow.bind(this));
3581
+ con.on("portalSuspended", this._handlePortalSuspended.bind(this));
3582
+ con.on("emptyQuery", this._handleEmptyQuery.bind(this));
3583
+ con.on("commandComplete", this._handleCommandComplete.bind(this));
3584
+ con.on("parseComplete", this._handleParseComplete.bind(this));
3585
+ con.on("copyInResponse", this._handleCopyInResponse.bind(this));
3586
+ con.on("copyData", this._handleCopyData.bind(this));
3587
+ con.on("notification", this._handleNotification.bind(this));
3588
+ }
3589
+ _checkPgPass(cb) {
3590
+ const con = this.connection;
3591
+ if (typeof this.password === "function") {
3592
+ this._Promise.resolve().then(() => this.password()).then((pass) => {
3593
+ if (pass !== undefined) {
3594
+ if (typeof pass !== "string") {
3595
+ con.emit("error", new TypeError("Password must be a string"));
3596
+ return;
3597
+ }
3598
+ this.connectionParameters.password = this.password = pass;
3599
+ } else {
3600
+ this.connectionParameters.password = this.password = null;
3601
+ }
3602
+ cb();
3603
+ }).catch((err) => {
3604
+ con.emit("error", err);
3605
+ });
3606
+ } else if (this.password !== null) {
3607
+ cb();
3608
+ } else {
3609
+ try {
3610
+ const pgPass = require_lib();
3611
+ pgPass(this.connectionParameters, (pass) => {
3612
+ if (pass !== undefined) {
3613
+ this.connectionParameters.password = this.password = pass;
3614
+ }
3615
+ cb();
3616
+ });
3617
+ } catch (e) {
3618
+ this.emit("error", e);
3619
+ }
3620
+ }
3621
+ }
3622
+ _handleAuthCleartextPassword(msg) {
3623
+ this._checkPgPass(() => {
3624
+ this.connection.password(this.password);
3625
+ });
3626
+ }
3627
+ _handleAuthMD5Password(msg) {
3628
+ this._checkPgPass(async () => {
3629
+ try {
3630
+ const hashedPassword = await crypto.postgresMd5PasswordHash(this.user, this.password, msg.salt);
3631
+ this.connection.password(hashedPassword);
3632
+ } catch (e) {
3633
+ this.emit("error", e);
3634
+ }
3635
+ });
3636
+ }
3637
+ _handleAuthSASL(msg) {
3638
+ this._checkPgPass(() => {
3639
+ try {
3640
+ this.saslSession = sasl.startSession(msg.mechanisms, this.enableChannelBinding && this.connection.stream);
3641
+ this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism, this.saslSession.response);
3642
+ } catch (err) {
3643
+ this.connection.emit("error", err);
3644
+ }
3645
+ });
3646
+ }
3647
+ async _handleAuthSASLContinue(msg) {
3648
+ try {
3649
+ await sasl.continueSession(this.saslSession, this.password, msg.data, this.enableChannelBinding && this.connection.stream);
3650
+ this.connection.sendSCRAMClientFinalMessage(this.saslSession.response);
3651
+ } catch (err) {
3652
+ this.connection.emit("error", err);
3653
+ }
3654
+ }
3655
+ _handleAuthSASLFinal(msg) {
3656
+ try {
3657
+ sasl.finalizeSession(this.saslSession, msg.data);
3658
+ this.saslSession = null;
3659
+ } catch (err) {
3660
+ this.connection.emit("error", err);
3661
+ }
3662
+ }
3663
+ _handleBackendKeyData(msg) {
3664
+ this.processID = msg.processID;
3665
+ this.secretKey = msg.secretKey;
3666
+ }
3667
+ _handleReadyForQuery(msg) {
3668
+ if (this._connecting) {
3669
+ this._connecting = false;
3670
+ this._connected = true;
3671
+ clearTimeout(this.connectionTimeoutHandle);
3672
+ if (this._connectionCallback) {
3673
+ this._connectionCallback(null, this);
3674
+ this._connectionCallback = null;
3675
+ }
3676
+ this.emit("connect");
3677
+ }
3678
+ const { activeQuery } = this;
3679
+ this.activeQuery = null;
3680
+ this.readyForQuery = true;
3681
+ if (activeQuery) {
3682
+ activeQuery.handleReadyForQuery(this.connection);
3683
+ }
3684
+ this._pulseQueryQueue();
3685
+ }
3686
+ _handleErrorWhileConnecting(err) {
3687
+ if (this._connectionError) {
3688
+ return;
3689
+ }
3690
+ this._connectionError = true;
3691
+ clearTimeout(this.connectionTimeoutHandle);
3692
+ if (this._connectionCallback) {
3693
+ return this._connectionCallback(err);
3694
+ }
3695
+ this.emit("error", err);
3696
+ }
3697
+ _handleErrorEvent(err) {
3698
+ if (this._connecting) {
3699
+ return this._handleErrorWhileConnecting(err);
3700
+ }
3701
+ this._queryable = false;
3702
+ this._errorAllQueries(err);
3703
+ this.emit("error", err);
3704
+ }
3705
+ _handleErrorMessage(msg) {
3706
+ if (this._connecting) {
3707
+ return this._handleErrorWhileConnecting(msg);
3708
+ }
3709
+ const activeQuery = this.activeQuery;
3710
+ if (!activeQuery) {
3711
+ this._handleErrorEvent(msg);
3712
+ return;
3713
+ }
3714
+ this.activeQuery = null;
3715
+ activeQuery.handleError(msg, this.connection);
3716
+ }
3717
+ _handleRowDescription(msg) {
3718
+ this.activeQuery.handleRowDescription(msg);
3719
+ }
3720
+ _handleDataRow(msg) {
3721
+ this.activeQuery.handleDataRow(msg);
3722
+ }
3723
+ _handlePortalSuspended(msg) {
3724
+ this.activeQuery.handlePortalSuspended(this.connection);
3725
+ }
3726
+ _handleEmptyQuery(msg) {
3727
+ this.activeQuery.handleEmptyQuery(this.connection);
3728
+ }
3729
+ _handleCommandComplete(msg) {
3730
+ if (this.activeQuery == null) {
3731
+ const error = new Error("Received unexpected commandComplete message from backend.");
3732
+ this._handleErrorEvent(error);
3733
+ return;
3734
+ }
3735
+ this.activeQuery.handleCommandComplete(msg, this.connection);
3736
+ }
3737
+ _handleParseComplete() {
3738
+ if (this.activeQuery == null) {
3739
+ const error = new Error("Received unexpected parseComplete message from backend.");
3740
+ this._handleErrorEvent(error);
3741
+ return;
3742
+ }
3743
+ if (this.activeQuery.name) {
3744
+ this.connection.parsedStatements[this.activeQuery.name] = this.activeQuery.text;
3745
+ }
3746
+ }
3747
+ _handleCopyInResponse(msg) {
3748
+ this.activeQuery.handleCopyInResponse(this.connection);
3749
+ }
3750
+ _handleCopyData(msg) {
3751
+ this.activeQuery.handleCopyData(msg, this.connection);
3752
+ }
3753
+ _handleNotification(msg) {
3754
+ this.emit("notification", msg);
3755
+ }
3756
+ _handleNotice(msg) {
3757
+ this.emit("notice", msg);
3758
+ }
3759
+ getStartupConf() {
3760
+ const params = this.connectionParameters;
3761
+ const data = {
3762
+ user: params.user,
3763
+ database: params.database
3764
+ };
3765
+ const appName = params.application_name || params.fallback_application_name;
3766
+ if (appName) {
3767
+ data.application_name = appName;
3768
+ }
3769
+ if (params.replication) {
3770
+ data.replication = "" + params.replication;
3771
+ }
3772
+ if (params.statement_timeout) {
3773
+ data.statement_timeout = String(parseInt(params.statement_timeout, 10));
3774
+ }
3775
+ if (params.lock_timeout) {
3776
+ data.lock_timeout = String(parseInt(params.lock_timeout, 10));
3777
+ }
3778
+ if (params.idle_in_transaction_session_timeout) {
3779
+ data.idle_in_transaction_session_timeout = String(parseInt(params.idle_in_transaction_session_timeout, 10));
3780
+ }
3781
+ if (params.options) {
3782
+ data.options = params.options;
3783
+ }
3784
+ return data;
3785
+ }
3786
+ cancel(client, query) {
3787
+ if (client.activeQuery === query) {
3788
+ const con = this.connection;
3789
+ if (this.host && this.host.indexOf("/") === 0) {
3790
+ con.connect(this.host + "/.s.PGSQL." + this.port);
3791
+ } else {
3792
+ con.connect(this.port, this.host);
3793
+ }
3794
+ con.on("connect", function() {
3795
+ con.cancel(client.processID, client.secretKey);
3796
+ });
3797
+ } else if (client.queryQueue.indexOf(query) !== -1) {
3798
+ client.queryQueue.splice(client.queryQueue.indexOf(query), 1);
3799
+ }
3800
+ }
3801
+ setTypeParser(oid, format, parseFn) {
3802
+ return this._types.setTypeParser(oid, format, parseFn);
3803
+ }
3804
+ getTypeParser(oid, format) {
3805
+ return this._types.getTypeParser(oid, format);
3806
+ }
3807
+ escapeIdentifier(str) {
3808
+ return utils.escapeIdentifier(str);
3809
+ }
3810
+ escapeLiteral(str) {
3811
+ return utils.escapeLiteral(str);
3812
+ }
3813
+ _pulseQueryQueue() {
3814
+ if (this.readyForQuery === true) {
3815
+ this.activeQuery = this.queryQueue.shift();
3816
+ if (this.activeQuery) {
3817
+ this.readyForQuery = false;
3818
+ this.hasExecuted = true;
3819
+ const queryError = this.activeQuery.submit(this.connection);
3820
+ if (queryError) {
3821
+ process.nextTick(() => {
3822
+ this.activeQuery.handleError(queryError, this.connection);
3823
+ this.readyForQuery = true;
3824
+ this._pulseQueryQueue();
3825
+ });
3826
+ }
3827
+ } else if (this.hasExecuted) {
3828
+ this.activeQuery = null;
3829
+ this.emit("drain");
3830
+ }
3831
+ }
3832
+ }
3833
+ query(config, values, callback) {
3834
+ let query;
3835
+ let result;
3836
+ let readTimeout;
3837
+ let readTimeoutTimer;
3838
+ let queryCallback;
3839
+ if (config === null || config === undefined) {
3840
+ throw new TypeError("Client was passed a null or undefined query");
3841
+ } else if (typeof config.submit === "function") {
3842
+ readTimeout = config.query_timeout || this.connectionParameters.query_timeout;
3843
+ result = query = config;
3844
+ if (typeof values === "function") {
3845
+ query.callback = query.callback || values;
3846
+ }
3847
+ } else {
3848
+ readTimeout = config.query_timeout || this.connectionParameters.query_timeout;
3849
+ query = new Query(config, values, callback);
3850
+ if (!query.callback) {
3851
+ result = new this._Promise((resolve, reject) => {
3852
+ query.callback = (err, res) => err ? reject(err) : resolve(res);
3853
+ }).catch((err) => {
3854
+ Error.captureStackTrace(err);
3855
+ throw err;
3856
+ });
3857
+ }
3858
+ }
3859
+ if (readTimeout) {
3860
+ queryCallback = query.callback;
3861
+ readTimeoutTimer = setTimeout(() => {
3862
+ const error = new Error("Query read timeout");
3863
+ process.nextTick(() => {
3864
+ query.handleError(error, this.connection);
3865
+ });
3866
+ queryCallback(error);
3867
+ query.callback = () => {};
3868
+ const index = this.queryQueue.indexOf(query);
3869
+ if (index > -1) {
3870
+ this.queryQueue.splice(index, 1);
3871
+ }
3872
+ this._pulseQueryQueue();
3873
+ }, readTimeout);
3874
+ query.callback = (err, res) => {
3875
+ clearTimeout(readTimeoutTimer);
3876
+ queryCallback(err, res);
3877
+ };
3878
+ }
3879
+ if (this.binary && !query.binary) {
3880
+ query.binary = true;
3881
+ }
3882
+ if (query._result && !query._result._types) {
3883
+ query._result._types = this._types;
3884
+ }
3885
+ if (!this._queryable) {
3886
+ process.nextTick(() => {
3887
+ query.handleError(new Error("Client has encountered a connection error and is not queryable"), this.connection);
3888
+ });
3889
+ return result;
3890
+ }
3891
+ if (this._ending) {
3892
+ process.nextTick(() => {
3893
+ query.handleError(new Error("Client was closed and is not queryable"), this.connection);
3894
+ });
3895
+ return result;
3896
+ }
3897
+ this.queryQueue.push(query);
3898
+ this._pulseQueryQueue();
3899
+ return result;
3900
+ }
3901
+ ref() {
3902
+ this.connection.ref();
3903
+ }
3904
+ unref() {
3905
+ this.connection.unref();
3906
+ }
3907
+ end(cb) {
3908
+ this._ending = true;
3909
+ if (!this.connection._connecting || this._ended) {
3910
+ if (cb) {
3911
+ cb();
3912
+ } else {
3913
+ return this._Promise.resolve();
3914
+ }
3915
+ }
3916
+ if (this.activeQuery || !this._queryable) {
3917
+ this.connection.stream.destroy();
3918
+ } else {
3919
+ this.connection.end();
3920
+ }
3921
+ if (cb) {
3922
+ this.connection.once("end", cb);
3923
+ } else {
3924
+ return new this._Promise((resolve) => {
3925
+ this.connection.once("end", resolve);
3926
+ });
3927
+ }
3928
+ }
3929
+ }
3930
+ Client.Query = Query;
3931
+ module.exports = Client;
3932
+ });
3933
+
3934
+ // node_modules/pg-pool/index.js
3935
+ var require_pg_pool = __commonJS((exports, module) => {
3936
+ var EventEmitter = __require("events").EventEmitter;
3937
+ var NOOP = function() {};
3938
+ var removeWhere = (list, predicate) => {
3939
+ const i = list.findIndex(predicate);
3940
+ return i === -1 ? undefined : list.splice(i, 1)[0];
3941
+ };
3942
+
3943
+ class IdleItem {
3944
+ constructor(client, idleListener, timeoutId) {
3945
+ this.client = client;
3946
+ this.idleListener = idleListener;
3947
+ this.timeoutId = timeoutId;
3948
+ }
3949
+ }
3950
+
3951
+ class PendingItem {
3952
+ constructor(callback) {
3953
+ this.callback = callback;
3954
+ }
3955
+ }
3956
+ function throwOnDoubleRelease() {
3957
+ throw new Error("Release called on client which has already been released to the pool.");
3958
+ }
3959
+ function promisify(Promise2, callback) {
3960
+ if (callback) {
3961
+ return { callback, result: undefined };
3962
+ }
3963
+ let rej;
3964
+ let res;
3965
+ const cb = function(err, client) {
3966
+ err ? rej(err) : res(client);
3967
+ };
3968
+ const result = new Promise2(function(resolve, reject) {
3969
+ res = resolve;
3970
+ rej = reject;
3971
+ }).catch((err) => {
3972
+ Error.captureStackTrace(err);
3973
+ throw err;
3974
+ });
3975
+ return { callback: cb, result };
3976
+ }
3977
+ function makeIdleListener(pool, client) {
3978
+ return function idleListener(err) {
3979
+ err.client = client;
3980
+ client.removeListener("error", idleListener);
3981
+ client.on("error", () => {
3982
+ pool.log("additional client error after disconnection due to error", err);
3983
+ });
3984
+ pool._remove(client);
3985
+ pool.emit("error", err, client);
3986
+ };
3987
+ }
3988
+
3989
+ class Pool extends EventEmitter {
3990
+ constructor(options, Client) {
3991
+ super();
3992
+ this.options = Object.assign({}, options);
3993
+ if (options != null && "password" in options) {
3994
+ Object.defineProperty(this.options, "password", {
3995
+ configurable: true,
3996
+ enumerable: false,
3997
+ writable: true,
3998
+ value: options.password
3999
+ });
4000
+ }
4001
+ if (options != null && options.ssl && options.ssl.key) {
4002
+ Object.defineProperty(this.options.ssl, "key", {
4003
+ enumerable: false
4004
+ });
4005
+ }
4006
+ this.options.max = this.options.max || this.options.poolSize || 10;
4007
+ this.options.min = this.options.min || 0;
4008
+ this.options.maxUses = this.options.maxUses || Infinity;
4009
+ this.options.allowExitOnIdle = this.options.allowExitOnIdle || false;
4010
+ this.options.maxLifetimeSeconds = this.options.maxLifetimeSeconds || 0;
4011
+ this.log = this.options.log || function() {};
4012
+ this.Client = this.options.Client || Client || require_lib2().Client;
4013
+ this.Promise = this.options.Promise || global.Promise;
4014
+ if (typeof this.options.idleTimeoutMillis === "undefined") {
4015
+ this.options.idleTimeoutMillis = 1e4;
4016
+ }
4017
+ this._clients = [];
4018
+ this._idle = [];
4019
+ this._expired = new WeakSet;
4020
+ this._pendingQueue = [];
4021
+ this._endCallback = undefined;
4022
+ this.ending = false;
4023
+ this.ended = false;
4024
+ }
4025
+ _isFull() {
4026
+ return this._clients.length >= this.options.max;
4027
+ }
4028
+ _isAboveMin() {
4029
+ return this._clients.length > this.options.min;
4030
+ }
4031
+ _pulseQueue() {
4032
+ this.log("pulse queue");
4033
+ if (this.ended) {
4034
+ this.log("pulse queue ended");
4035
+ return;
4036
+ }
4037
+ if (this.ending) {
4038
+ this.log("pulse queue on ending");
4039
+ if (this._idle.length) {
4040
+ this._idle.slice().map((item) => {
4041
+ this._remove(item.client);
4042
+ });
4043
+ }
4044
+ if (!this._clients.length) {
4045
+ this.ended = true;
4046
+ this._endCallback();
4047
+ }
4048
+ return;
4049
+ }
4050
+ if (!this._pendingQueue.length) {
4051
+ this.log("no queued requests");
4052
+ return;
4053
+ }
4054
+ if (!this._idle.length && this._isFull()) {
4055
+ return;
4056
+ }
4057
+ const pendingItem = this._pendingQueue.shift();
4058
+ if (this._idle.length) {
4059
+ const idleItem = this._idle.pop();
4060
+ clearTimeout(idleItem.timeoutId);
4061
+ const client = idleItem.client;
4062
+ client.ref && client.ref();
4063
+ const idleListener = idleItem.idleListener;
4064
+ return this._acquireClient(client, pendingItem, idleListener, false);
4065
+ }
4066
+ if (!this._isFull()) {
4067
+ return this.newClient(pendingItem);
4068
+ }
4069
+ throw new Error("unexpected condition");
4070
+ }
4071
+ _remove(client, callback) {
4072
+ const removed = removeWhere(this._idle, (item) => item.client === client);
4073
+ if (removed !== undefined) {
4074
+ clearTimeout(removed.timeoutId);
4075
+ }
4076
+ this._clients = this._clients.filter((c) => c !== client);
4077
+ const context = this;
4078
+ client.end(() => {
4079
+ context.emit("remove", client);
4080
+ if (typeof callback === "function") {
4081
+ callback();
4082
+ }
4083
+ });
4084
+ }
4085
+ connect(cb) {
4086
+ if (this.ending) {
4087
+ const err = new Error("Cannot use a pool after calling end on the pool");
4088
+ return cb ? cb(err) : this.Promise.reject(err);
4089
+ }
4090
+ const response = promisify(this.Promise, cb);
4091
+ const result = response.result;
4092
+ if (this._isFull() || this._idle.length) {
4093
+ if (this._idle.length) {
4094
+ process.nextTick(() => this._pulseQueue());
4095
+ }
4096
+ if (!this.options.connectionTimeoutMillis) {
4097
+ this._pendingQueue.push(new PendingItem(response.callback));
4098
+ return result;
4099
+ }
4100
+ const queueCallback = (err, res, done) => {
4101
+ clearTimeout(tid);
4102
+ response.callback(err, res, done);
4103
+ };
4104
+ const pendingItem = new PendingItem(queueCallback);
4105
+ const tid = setTimeout(() => {
4106
+ removeWhere(this._pendingQueue, (i) => i.callback === queueCallback);
4107
+ pendingItem.timedOut = true;
4108
+ response.callback(new Error("timeout exceeded when trying to connect"));
4109
+ }, this.options.connectionTimeoutMillis);
4110
+ if (tid.unref) {
4111
+ tid.unref();
4112
+ }
4113
+ this._pendingQueue.push(pendingItem);
4114
+ return result;
4115
+ }
4116
+ this.newClient(new PendingItem(response.callback));
4117
+ return result;
4118
+ }
4119
+ newClient(pendingItem) {
4120
+ const client = new this.Client(this.options);
4121
+ this._clients.push(client);
4122
+ const idleListener = makeIdleListener(this, client);
4123
+ this.log("checking client timeout");
4124
+ let tid;
4125
+ let timeoutHit = false;
4126
+ if (this.options.connectionTimeoutMillis) {
4127
+ tid = setTimeout(() => {
4128
+ this.log("ending client due to timeout");
4129
+ timeoutHit = true;
4130
+ client.connection ? client.connection.stream.destroy() : client.end();
4131
+ }, this.options.connectionTimeoutMillis);
4132
+ }
4133
+ this.log("connecting new client");
4134
+ client.connect((err) => {
4135
+ if (tid) {
4136
+ clearTimeout(tid);
4137
+ }
4138
+ client.on("error", idleListener);
4139
+ if (err) {
4140
+ this.log("client failed to connect", err);
4141
+ this._clients = this._clients.filter((c) => c !== client);
4142
+ if (timeoutHit) {
4143
+ err = new Error("Connection terminated due to connection timeout", { cause: err });
4144
+ }
4145
+ this._pulseQueue();
4146
+ if (!pendingItem.timedOut) {
4147
+ pendingItem.callback(err, undefined, NOOP);
4148
+ }
4149
+ } else {
4150
+ this.log("new client connected");
4151
+ if (this.options.maxLifetimeSeconds !== 0) {
4152
+ const maxLifetimeTimeout = setTimeout(() => {
4153
+ this.log("ending client due to expired lifetime");
4154
+ this._expired.add(client);
4155
+ const idleIndex = this._idle.findIndex((idleItem) => idleItem.client === client);
4156
+ if (idleIndex !== -1) {
4157
+ this._acquireClient(client, new PendingItem((err2, client2, clientRelease) => clientRelease()), idleListener, false);
4158
+ }
4159
+ }, this.options.maxLifetimeSeconds * 1000);
4160
+ maxLifetimeTimeout.unref();
4161
+ client.once("end", () => clearTimeout(maxLifetimeTimeout));
4162
+ }
4163
+ return this._acquireClient(client, pendingItem, idleListener, true);
4164
+ }
4165
+ });
4166
+ }
4167
+ _acquireClient(client, pendingItem, idleListener, isNew) {
4168
+ if (isNew) {
4169
+ this.emit("connect", client);
4170
+ }
4171
+ this.emit("acquire", client);
4172
+ client.release = this._releaseOnce(client, idleListener);
4173
+ client.removeListener("error", idleListener);
4174
+ if (!pendingItem.timedOut) {
4175
+ if (isNew && this.options.verify) {
4176
+ this.options.verify(client, (err) => {
4177
+ if (err) {
4178
+ client.release(err);
4179
+ return pendingItem.callback(err, undefined, NOOP);
4180
+ }
4181
+ pendingItem.callback(undefined, client, client.release);
4182
+ });
4183
+ } else {
4184
+ pendingItem.callback(undefined, client, client.release);
4185
+ }
4186
+ } else {
4187
+ if (isNew && this.options.verify) {
4188
+ this.options.verify(client, client.release);
4189
+ } else {
4190
+ client.release();
4191
+ }
4192
+ }
4193
+ }
4194
+ _releaseOnce(client, idleListener) {
4195
+ let released = false;
4196
+ return (err) => {
4197
+ if (released) {
4198
+ throwOnDoubleRelease();
4199
+ }
4200
+ released = true;
4201
+ this._release(client, idleListener, err);
4202
+ };
4203
+ }
4204
+ _release(client, idleListener, err) {
4205
+ client.on("error", idleListener);
4206
+ client._poolUseCount = (client._poolUseCount || 0) + 1;
4207
+ this.emit("release", err, client);
4208
+ if (err || this.ending || !client._queryable || client._ending || client._poolUseCount >= this.options.maxUses) {
4209
+ if (client._poolUseCount >= this.options.maxUses) {
4210
+ this.log("remove expended client");
4211
+ }
4212
+ return this._remove(client, this._pulseQueue.bind(this));
4213
+ }
4214
+ const isExpired = this._expired.has(client);
4215
+ if (isExpired) {
4216
+ this.log("remove expired client");
4217
+ this._expired.delete(client);
4218
+ return this._remove(client, this._pulseQueue.bind(this));
4219
+ }
4220
+ let tid;
4221
+ if (this.options.idleTimeoutMillis && this._isAboveMin()) {
4222
+ tid = setTimeout(() => {
4223
+ this.log("remove idle client");
4224
+ this._remove(client, this._pulseQueue.bind(this));
4225
+ }, this.options.idleTimeoutMillis);
4226
+ if (this.options.allowExitOnIdle) {
4227
+ tid.unref();
4228
+ }
4229
+ }
4230
+ if (this.options.allowExitOnIdle) {
4231
+ client.unref();
4232
+ }
4233
+ this._idle.push(new IdleItem(client, idleListener, tid));
4234
+ this._pulseQueue();
4235
+ }
4236
+ query(text, values, cb) {
4237
+ if (typeof text === "function") {
4238
+ const response2 = promisify(this.Promise, text);
4239
+ setImmediate(function() {
4240
+ return response2.callback(new Error("Passing a function as the first parameter to pool.query is not supported"));
4241
+ });
4242
+ return response2.result;
4243
+ }
4244
+ if (typeof values === "function") {
4245
+ cb = values;
4246
+ values = undefined;
4247
+ }
4248
+ const response = promisify(this.Promise, cb);
4249
+ cb = response.callback;
4250
+ this.connect((err, client) => {
4251
+ if (err) {
4252
+ return cb(err);
4253
+ }
4254
+ let clientReleased = false;
4255
+ const onError = (err2) => {
4256
+ if (clientReleased) {
4257
+ return;
4258
+ }
4259
+ clientReleased = true;
4260
+ client.release(err2);
4261
+ cb(err2);
4262
+ };
4263
+ client.once("error", onError);
4264
+ this.log("dispatching query");
4265
+ try {
4266
+ client.query(text, values, (err2, res) => {
4267
+ this.log("query dispatched");
4268
+ client.removeListener("error", onError);
4269
+ if (clientReleased) {
4270
+ return;
4271
+ }
4272
+ clientReleased = true;
4273
+ client.release(err2);
4274
+ if (err2) {
4275
+ return cb(err2);
4276
+ }
4277
+ return cb(undefined, res);
4278
+ });
4279
+ } catch (err2) {
4280
+ client.release(err2);
4281
+ return cb(err2);
4282
+ }
4283
+ });
4284
+ return response.result;
4285
+ }
4286
+ end(cb) {
4287
+ this.log("ending");
4288
+ if (this.ending) {
4289
+ const err = new Error("Called end on pool more than once");
4290
+ return cb ? cb(err) : this.Promise.reject(err);
4291
+ }
4292
+ this.ending = true;
4293
+ const promised = promisify(this.Promise, cb);
4294
+ this._endCallback = promised.callback;
4295
+ this._pulseQueue();
4296
+ return promised.result;
4297
+ }
4298
+ get waitingCount() {
4299
+ return this._pendingQueue.length;
4300
+ }
4301
+ get idleCount() {
4302
+ return this._idle.length;
4303
+ }
4304
+ get expiredCount() {
4305
+ return this._clients.reduce((acc, client) => acc + (this._expired.has(client) ? 1 : 0), 0);
4306
+ }
4307
+ get totalCount() {
4308
+ return this._clients.length;
4309
+ }
4310
+ }
4311
+ module.exports = Pool;
4312
+ });
4313
+
4314
+ // node_modules/pg/lib/native/query.js
4315
+ var require_query2 = __commonJS((exports, module) => {
4316
+ var EventEmitter = __require("events").EventEmitter;
4317
+ var util = __require("util");
4318
+ var utils = require_utils();
4319
+ var NativeQuery = module.exports = function(config, values, callback) {
4320
+ EventEmitter.call(this);
4321
+ config = utils.normalizeQueryConfig(config, values, callback);
4322
+ this.text = config.text;
4323
+ this.values = config.values;
4324
+ this.name = config.name;
4325
+ this.queryMode = config.queryMode;
4326
+ this.callback = config.callback;
4327
+ this.state = "new";
4328
+ this._arrayMode = config.rowMode === "array";
4329
+ this._emitRowEvents = false;
4330
+ this.on("newListener", function(event) {
4331
+ if (event === "row")
4332
+ this._emitRowEvents = true;
4333
+ }.bind(this));
4334
+ };
4335
+ util.inherits(NativeQuery, EventEmitter);
4336
+ var errorFieldMap = {
4337
+ sqlState: "code",
4338
+ statementPosition: "position",
4339
+ messagePrimary: "message",
4340
+ context: "where",
4341
+ schemaName: "schema",
4342
+ tableName: "table",
4343
+ columnName: "column",
4344
+ dataTypeName: "dataType",
4345
+ constraintName: "constraint",
4346
+ sourceFile: "file",
4347
+ sourceLine: "line",
4348
+ sourceFunction: "routine"
4349
+ };
4350
+ NativeQuery.prototype.handleError = function(err) {
4351
+ const fields = this.native.pq.resultErrorFields();
4352
+ if (fields) {
4353
+ for (const key in fields) {
4354
+ const normalizedFieldName = errorFieldMap[key] || key;
4355
+ err[normalizedFieldName] = fields[key];
4356
+ }
4357
+ }
4358
+ if (this.callback) {
4359
+ this.callback(err);
4360
+ } else {
4361
+ this.emit("error", err);
4362
+ }
4363
+ this.state = "error";
4364
+ };
4365
+ NativeQuery.prototype.then = function(onSuccess, onFailure) {
4366
+ return this._getPromise().then(onSuccess, onFailure);
4367
+ };
4368
+ NativeQuery.prototype.catch = function(callback) {
4369
+ return this._getPromise().catch(callback);
4370
+ };
4371
+ NativeQuery.prototype._getPromise = function() {
4372
+ if (this._promise)
4373
+ return this._promise;
4374
+ this._promise = new Promise(function(resolve, reject) {
4375
+ this._once("end", resolve);
4376
+ this._once("error", reject);
4377
+ }.bind(this));
4378
+ return this._promise;
4379
+ };
4380
+ NativeQuery.prototype.submit = function(client) {
4381
+ this.state = "running";
4382
+ const self = this;
4383
+ this.native = client.native;
4384
+ client.native.arrayMode = this._arrayMode;
4385
+ let after = function(err, rows, results) {
4386
+ client.native.arrayMode = false;
4387
+ setImmediate(function() {
4388
+ self.emit("_done");
4389
+ });
4390
+ if (err) {
4391
+ return self.handleError(err);
4392
+ }
4393
+ if (self._emitRowEvents) {
4394
+ if (results.length > 1) {
4395
+ rows.forEach((rowOfRows, i) => {
4396
+ rowOfRows.forEach((row) => {
4397
+ self.emit("row", row, results[i]);
4398
+ });
4399
+ });
4400
+ } else {
4401
+ rows.forEach(function(row) {
4402
+ self.emit("row", row, results);
4403
+ });
4404
+ }
4405
+ }
4406
+ self.state = "end";
4407
+ self.emit("end", results);
4408
+ if (self.callback) {
4409
+ self.callback(null, results);
4410
+ }
4411
+ };
4412
+ if (process.domain) {
4413
+ after = process.domain.bind(after);
4414
+ }
4415
+ if (this.name) {
4416
+ if (this.name.length > 63) {
4417
+ console.error("Warning! Postgres only supports 63 characters for query names.");
4418
+ console.error("You supplied %s (%s)", this.name, this.name.length);
4419
+ console.error("This can cause conflicts and silent errors executing queries");
4420
+ }
4421
+ const values = (this.values || []).map(utils.prepareValue);
4422
+ if (client.namedQueries[this.name]) {
4423
+ if (this.text && client.namedQueries[this.name] !== this.text) {
4424
+ const err = new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);
4425
+ return after(err);
4426
+ }
4427
+ return client.native.execute(this.name, values, after);
4428
+ }
4429
+ return client.native.prepare(this.name, this.text, values.length, function(err) {
4430
+ if (err)
4431
+ return after(err);
4432
+ client.namedQueries[self.name] = self.text;
4433
+ return self.native.execute(self.name, values, after);
4434
+ });
4435
+ } else if (this.values) {
4436
+ if (!Array.isArray(this.values)) {
4437
+ const err = new Error("Query values must be an array");
4438
+ return after(err);
4439
+ }
4440
+ const vals = this.values.map(utils.prepareValue);
4441
+ client.native.query(this.text, vals, after);
4442
+ } else if (this.queryMode === "extended") {
4443
+ client.native.query(this.text, [], after);
4444
+ } else {
4445
+ client.native.query(this.text, after);
4446
+ }
4447
+ };
4448
+ });
4449
+
4450
+ // node_modules/pg/lib/native/client.js
4451
+ var require_client2 = __commonJS((exports, module) => {
4452
+ var Native;
4453
+ try {
4454
+ Native = (()=>{throw new Error("Cannot require module "+"pg-native");})();
4455
+ } catch (e) {
4456
+ throw e;
4457
+ }
4458
+ var TypeOverrides = require_type_overrides();
4459
+ var EventEmitter = __require("events").EventEmitter;
4460
+ var util = __require("util");
4461
+ var ConnectionParameters = require_connection_parameters();
4462
+ var NativeQuery = require_query2();
4463
+ var Client = module.exports = function(config) {
4464
+ EventEmitter.call(this);
4465
+ config = config || {};
4466
+ this._Promise = config.Promise || global.Promise;
4467
+ this._types = new TypeOverrides(config.types);
4468
+ this.native = new Native({
4469
+ types: this._types
4470
+ });
4471
+ this._queryQueue = [];
4472
+ this._ending = false;
4473
+ this._connecting = false;
4474
+ this._connected = false;
4475
+ this._queryable = true;
4476
+ const cp = this.connectionParameters = new ConnectionParameters(config);
4477
+ if (config.nativeConnectionString)
4478
+ cp.nativeConnectionString = config.nativeConnectionString;
4479
+ this.user = cp.user;
4480
+ Object.defineProperty(this, "password", {
4481
+ configurable: true,
4482
+ enumerable: false,
4483
+ writable: true,
4484
+ value: cp.password
4485
+ });
4486
+ this.database = cp.database;
4487
+ this.host = cp.host;
4488
+ this.port = cp.port;
4489
+ this.namedQueries = {};
4490
+ };
4491
+ Client.Query = NativeQuery;
4492
+ util.inherits(Client, EventEmitter);
4493
+ Client.prototype._errorAllQueries = function(err) {
4494
+ const enqueueError = (query) => {
4495
+ process.nextTick(() => {
4496
+ query.native = this.native;
4497
+ query.handleError(err);
4498
+ });
4499
+ };
4500
+ if (this._hasActiveQuery()) {
4501
+ enqueueError(this._activeQuery);
4502
+ this._activeQuery = null;
4503
+ }
4504
+ this._queryQueue.forEach(enqueueError);
4505
+ this._queryQueue.length = 0;
4506
+ };
4507
+ Client.prototype._connect = function(cb) {
4508
+ const self = this;
4509
+ if (this._connecting) {
4510
+ process.nextTick(() => cb(new Error("Client has already been connected. You cannot reuse a client.")));
4511
+ return;
4512
+ }
4513
+ this._connecting = true;
4514
+ this.connectionParameters.getLibpqConnectionString(function(err, conString) {
4515
+ if (self.connectionParameters.nativeConnectionString)
4516
+ conString = self.connectionParameters.nativeConnectionString;
4517
+ if (err)
4518
+ return cb(err);
4519
+ self.native.connect(conString, function(err2) {
4520
+ if (err2) {
4521
+ self.native.end();
4522
+ return cb(err2);
4523
+ }
4524
+ self._connected = true;
4525
+ self.native.on("error", function(err3) {
4526
+ self._queryable = false;
4527
+ self._errorAllQueries(err3);
4528
+ self.emit("error", err3);
4529
+ });
4530
+ self.native.on("notification", function(msg) {
4531
+ self.emit("notification", {
4532
+ channel: msg.relname,
4533
+ payload: msg.extra
4534
+ });
4535
+ });
4536
+ self.emit("connect");
4537
+ self._pulseQueryQueue(true);
4538
+ cb();
4539
+ });
4540
+ });
4541
+ };
4542
+ Client.prototype.connect = function(callback) {
4543
+ if (callback) {
4544
+ this._connect(callback);
4545
+ return;
4546
+ }
4547
+ return new this._Promise((resolve, reject) => {
4548
+ this._connect((error) => {
4549
+ if (error) {
4550
+ reject(error);
4551
+ } else {
4552
+ resolve();
4553
+ }
4554
+ });
4555
+ });
4556
+ };
4557
+ Client.prototype.query = function(config, values, callback) {
4558
+ let query;
4559
+ let result;
4560
+ let readTimeout;
4561
+ let readTimeoutTimer;
4562
+ let queryCallback;
4563
+ if (config === null || config === undefined) {
4564
+ throw new TypeError("Client was passed a null or undefined query");
4565
+ } else if (typeof config.submit === "function") {
4566
+ readTimeout = config.query_timeout || this.connectionParameters.query_timeout;
4567
+ result = query = config;
4568
+ if (typeof values === "function") {
4569
+ config.callback = values;
4570
+ }
4571
+ } else {
4572
+ readTimeout = config.query_timeout || this.connectionParameters.query_timeout;
4573
+ query = new NativeQuery(config, values, callback);
4574
+ if (!query.callback) {
4575
+ let resolveOut, rejectOut;
4576
+ result = new this._Promise((resolve, reject) => {
4577
+ resolveOut = resolve;
4578
+ rejectOut = reject;
4579
+ }).catch((err) => {
4580
+ Error.captureStackTrace(err);
4581
+ throw err;
4582
+ });
4583
+ query.callback = (err, res) => err ? rejectOut(err) : resolveOut(res);
4584
+ }
4585
+ }
4586
+ if (readTimeout) {
4587
+ queryCallback = query.callback;
4588
+ readTimeoutTimer = setTimeout(() => {
4589
+ const error = new Error("Query read timeout");
4590
+ process.nextTick(() => {
4591
+ query.handleError(error, this.connection);
4592
+ });
4593
+ queryCallback(error);
4594
+ query.callback = () => {};
4595
+ const index = this._queryQueue.indexOf(query);
4596
+ if (index > -1) {
4597
+ this._queryQueue.splice(index, 1);
4598
+ }
4599
+ this._pulseQueryQueue();
4600
+ }, readTimeout);
4601
+ query.callback = (err, res) => {
4602
+ clearTimeout(readTimeoutTimer);
4603
+ queryCallback(err, res);
4604
+ };
4605
+ }
4606
+ if (!this._queryable) {
4607
+ query.native = this.native;
4608
+ process.nextTick(() => {
4609
+ query.handleError(new Error("Client has encountered a connection error and is not queryable"));
4610
+ });
4611
+ return result;
4612
+ }
4613
+ if (this._ending) {
4614
+ query.native = this.native;
4615
+ process.nextTick(() => {
4616
+ query.handleError(new Error("Client was closed and is not queryable"));
4617
+ });
4618
+ return result;
4619
+ }
4620
+ this._queryQueue.push(query);
4621
+ this._pulseQueryQueue();
4622
+ return result;
4623
+ };
4624
+ Client.prototype.end = function(cb) {
4625
+ const self = this;
4626
+ this._ending = true;
4627
+ if (!this._connected) {
4628
+ this.once("connect", this.end.bind(this, cb));
4629
+ }
4630
+ let result;
4631
+ if (!cb) {
4632
+ result = new this._Promise(function(resolve, reject) {
4633
+ cb = (err) => err ? reject(err) : resolve();
4634
+ });
4635
+ }
4636
+ this.native.end(function() {
4637
+ self._errorAllQueries(new Error("Connection terminated"));
4638
+ process.nextTick(() => {
4639
+ self.emit("end");
4640
+ if (cb)
4641
+ cb();
4642
+ });
4643
+ });
4644
+ return result;
4645
+ };
4646
+ Client.prototype._hasActiveQuery = function() {
4647
+ return this._activeQuery && this._activeQuery.state !== "error" && this._activeQuery.state !== "end";
4648
+ };
4649
+ Client.prototype._pulseQueryQueue = function(initialConnection) {
4650
+ if (!this._connected) {
4651
+ return;
4652
+ }
4653
+ if (this._hasActiveQuery()) {
4654
+ return;
4655
+ }
4656
+ const query = this._queryQueue.shift();
4657
+ if (!query) {
4658
+ if (!initialConnection) {
4659
+ this.emit("drain");
4660
+ }
4661
+ return;
4662
+ }
4663
+ this._activeQuery = query;
4664
+ query.submit(this);
4665
+ const self = this;
4666
+ query.once("_done", function() {
4667
+ self._pulseQueryQueue();
4668
+ });
4669
+ };
4670
+ Client.prototype.cancel = function(query) {
4671
+ if (this._activeQuery === query) {
4672
+ this.native.cancel(function() {});
4673
+ } else if (this._queryQueue.indexOf(query) !== -1) {
4674
+ this._queryQueue.splice(this._queryQueue.indexOf(query), 1);
4675
+ }
4676
+ };
4677
+ Client.prototype.ref = function() {};
4678
+ Client.prototype.unref = function() {};
4679
+ Client.prototype.setTypeParser = function(oid, format, parseFn) {
4680
+ return this._types.setTypeParser(oid, format, parseFn);
4681
+ };
4682
+ Client.prototype.getTypeParser = function(oid, format) {
4683
+ return this._types.getTypeParser(oid, format);
4684
+ };
4685
+ });
4686
+
4687
+ // node_modules/pg/lib/index.js
4688
+ var require_lib2 = __commonJS((exports, module) => {
4689
+ var Client = require_client();
4690
+ var defaults = require_defaults();
4691
+ var Connection = require_connection();
4692
+ var Result = require_result();
4693
+ var utils = require_utils();
4694
+ var Pool = require_pg_pool();
4695
+ var TypeOverrides = require_type_overrides();
4696
+ var { DatabaseError } = require_dist();
4697
+ var { escapeIdentifier, escapeLiteral } = require_utils();
4698
+ var poolFactory = (Client2) => {
4699
+ return class BoundPool extends Pool {
4700
+ constructor(options) {
4701
+ super(options, Client2);
4702
+ }
4703
+ };
4704
+ };
4705
+ var PG = function(clientConstructor) {
4706
+ this.defaults = defaults;
4707
+ this.Client = clientConstructor;
4708
+ this.Query = this.Client.Query;
4709
+ this.Pool = poolFactory(this.Client);
4710
+ this._pools = [];
4711
+ this.Connection = Connection;
4712
+ this.types = require_pg_types();
4713
+ this.DatabaseError = DatabaseError;
4714
+ this.TypeOverrides = TypeOverrides;
4715
+ this.escapeIdentifier = escapeIdentifier;
4716
+ this.escapeLiteral = escapeLiteral;
4717
+ this.Result = Result;
4718
+ this.utils = utils;
4719
+ };
4720
+ if (typeof process.env.NODE_PG_FORCE_NATIVE !== "undefined") {
4721
+ module.exports = new PG(require_client2());
4722
+ } else {
4723
+ module.exports = new PG(Client);
4724
+ Object.defineProperty(module.exports, "native", {
4725
+ configurable: true,
4726
+ enumerable: false,
4727
+ get() {
4728
+ let native = null;
4729
+ try {
4730
+ native = new PG(require_client2());
4731
+ } catch (err) {
4732
+ if (err.code !== "MODULE_NOT_FOUND") {
4733
+ throw err;
4734
+ }
4735
+ }
4736
+ Object.defineProperty(module.exports, "native", {
4737
+ value: native
4738
+ });
4739
+ return native;
4740
+ }
4741
+ });
4742
+ }
4743
+ });
4744
+
4745
+ // node_modules/pg/esm/index.mjs
4746
+ var exports_esm = {};
4747
+ __export(exports_esm, {
4748
+ types: () => types,
4749
+ escapeLiteral: () => escapeLiteral,
4750
+ escapeIdentifier: () => escapeIdentifier,
4751
+ defaults: () => defaults,
4752
+ default: () => esm_default,
4753
+ TypeOverrides: () => TypeOverrides,
4754
+ Result: () => Result,
4755
+ Query: () => Query,
4756
+ Pool: () => Pool,
4757
+ DatabaseError: () => DatabaseError,
4758
+ Connection: () => Connection,
4759
+ Client: () => Client
4760
+ });
4761
+ var import_lib = __toESM(require_lib2(), 1);
4762
+ var Client = import_lib.default.Client;
4763
+ var Pool = import_lib.default.Pool;
4764
+ var Connection = import_lib.default.Connection;
4765
+ var types = import_lib.default.types;
4766
+ var Query = import_lib.default.Query;
4767
+ var DatabaseError = import_lib.default.DatabaseError;
4768
+ var escapeIdentifier = import_lib.default.escapeIdentifier;
4769
+ var escapeLiteral = import_lib.default.escapeLiteral;
4770
+ var Result = import_lib.default.Result;
4771
+ var TypeOverrides = import_lib.default.TypeOverrides;
4772
+ var defaults = import_lib.default.defaults;
4773
+ var esm_default = import_lib.default;
4774
+
4775
+ // src/addon/pg/index.ts
4776
+ var pg_default = exports_esm;
4777
+ export {
4778
+ types,
4779
+ escapeLiteral,
4780
+ escapeIdentifier,
4781
+ defaults,
4782
+ pg_default as default,
4783
+ TypeOverrides,
4784
+ Result,
4785
+ Query,
4786
+ Pool,
4787
+ DatabaseError,
4788
+ Connection,
4789
+ Client
4790
+ };