@arcote.tech/arc-adapter-db-postgres 0.4.9 → 0.5.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 (2) hide show
  1. package/dist/index.js +505 -32
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- // ../../../../node_modules/mutative/dist/mutative.esm.mjs
1
+ // ../../../../node_modules/.bun/mutative@1.3.0/node_modules/mutative/dist/mutative.esm.mjs
2
2
  var Operation = {
3
3
  Remove: "remove",
4
4
  Replace: "replace",
@@ -2826,6 +2826,147 @@ class ArcEvent extends ArcContextElement {
2826
2826
  return ArcEvent.sharedDatabaseStoreSchema();
2827
2827
  }
2828
2828
  }
2829
+ function buildElementContext(queryElements, mutationElements, adapters) {
2830
+ const queryMap = new Map;
2831
+ const mutateMap = new Map;
2832
+ const queryProps = {};
2833
+ for (const element of queryElements) {
2834
+ if (element.queryContext) {
2835
+ const ctx = element.queryContext(adapters);
2836
+ queryProps[element.name] = ctx;
2837
+ queryMap.set(element, ctx);
2838
+ }
2839
+ }
2840
+ const mutateProps = {};
2841
+ for (const element of mutationElements) {
2842
+ if (element.mutateContext) {
2843
+ const ctx = element.mutateContext(adapters);
2844
+ mutateProps[element.name] = ctx;
2845
+ mutateMap.set(element, ctx);
2846
+ }
2847
+ }
2848
+ const queryFn = (element) => {
2849
+ const cached = queryMap.get(element);
2850
+ if (cached)
2851
+ return cached;
2852
+ if (element.queryContext) {
2853
+ const ctx = element.queryContext(adapters);
2854
+ queryMap.set(element, ctx);
2855
+ return ctx;
2856
+ }
2857
+ throw new Error(`Element "${element.name}" has no queryContext`);
2858
+ };
2859
+ Object.assign(queryFn, queryProps);
2860
+ const mutateFn = (element) => {
2861
+ const cached = mutateMap.get(element);
2862
+ if (cached)
2863
+ return cached;
2864
+ if (element.mutateContext) {
2865
+ const ctx = element.mutateContext(adapters);
2866
+ mutateMap.set(element, ctx);
2867
+ return ctx;
2868
+ }
2869
+ throw new Error(`Element "${element.name}" has no mutateContext`);
2870
+ };
2871
+ Object.assign(mutateFn, mutateProps);
2872
+ return {
2873
+ query: queryFn,
2874
+ mutate: mutateFn
2875
+ };
2876
+ }
2877
+
2878
+ class ArcFunction {
2879
+ data;
2880
+ constructor(data) {
2881
+ this.data = data;
2882
+ }
2883
+ withParams(schema) {
2884
+ return new ArcFunction({
2885
+ ...this.data,
2886
+ params: schema instanceof ArcObject ? schema : new ArcObject(schema)
2887
+ });
2888
+ }
2889
+ withResult(schema) {
2890
+ return new ArcFunction({
2891
+ ...this.data,
2892
+ result: schema instanceof ArcObject ? schema : new ArcObject(schema)
2893
+ });
2894
+ }
2895
+ query(elements) {
2896
+ return new ArcFunction({
2897
+ ...this.data,
2898
+ queryElements: elements
2899
+ });
2900
+ }
2901
+ mutate(elements) {
2902
+ return new ArcFunction({
2903
+ ...this.data,
2904
+ mutationElements: elements
2905
+ });
2906
+ }
2907
+ protectedBy(token, check) {
2908
+ const existingProtections = this.data.protections || [];
2909
+ return new ArcFunction({
2910
+ ...this.data,
2911
+ protections: [...existingProtections, { token, check }]
2912
+ });
2913
+ }
2914
+ description(desc) {
2915
+ return new ArcFunction({
2916
+ ...this.data,
2917
+ description: desc
2918
+ });
2919
+ }
2920
+ handle(handler) {
2921
+ return new ArcFunction({
2922
+ ...this.data,
2923
+ handler
2924
+ });
2925
+ }
2926
+ get isPublic() {
2927
+ return !this.hasProtections;
2928
+ }
2929
+ get hasProtections() {
2930
+ return (this.data.protections?.length ?? 0) > 0;
2931
+ }
2932
+ get protections() {
2933
+ return this.data.protections || [];
2934
+ }
2935
+ get handler() {
2936
+ return this.data.handler;
2937
+ }
2938
+ get params() {
2939
+ return this.data.params;
2940
+ }
2941
+ get result() {
2942
+ return this.data.result;
2943
+ }
2944
+ async verifyProtections(tokens) {
2945
+ if (!this.data.protections || this.data.protections.length === 0) {
2946
+ return true;
2947
+ }
2948
+ for (const protection of this.data.protections) {
2949
+ const tokenInstance = tokens.find((t) => t.getTokenDefinition() === protection.token);
2950
+ if (!tokenInstance) {
2951
+ return false;
2952
+ }
2953
+ const result = await protection.check(tokenInstance);
2954
+ if (result === false) {
2955
+ return false;
2956
+ }
2957
+ }
2958
+ return true;
2959
+ }
2960
+ buildContext(adapters) {
2961
+ return buildElementContext(this.data.queryElements || [], this.data.mutationElements || [], adapters);
2962
+ }
2963
+ toJsonSchema() {
2964
+ return {
2965
+ params: this.data.params?.toJsonSchema?.() ?? null,
2966
+ result: this.data.result?.toJsonSchema?.() ?? null
2967
+ };
2968
+ }
2969
+ }
2829
2970
  class AggregateBase {
2830
2971
  value;
2831
2972
  _id;
@@ -2863,6 +3004,315 @@ class AggregateBase {
2863
3004
  return result;
2864
3005
  }
2865
3006
  }
3007
+ class ArcCommand extends ArcContextElement {
3008
+ data;
3009
+ #fn;
3010
+ constructor(data, fn) {
3011
+ super(data.name);
3012
+ this.data = data;
3013
+ this.#fn = fn ?? new ArcFunction({
3014
+ params: data.params,
3015
+ result: null,
3016
+ queryElements: data.queryElements,
3017
+ mutationElements: data.mutationElements,
3018
+ protections: data.protections || [],
3019
+ handler: data.handler ?? null,
3020
+ description: data.description
3021
+ });
3022
+ }
3023
+ description(description) {
3024
+ const newFn = this.#fn.description(description);
3025
+ return new ArcCommand({ ...this.data, description }, newFn);
3026
+ }
3027
+ get isPublic() {
3028
+ return this.#fn.isPublic;
3029
+ }
3030
+ query(elements) {
3031
+ const newFn = this.#fn.query(elements);
3032
+ return new ArcCommand({ ...this.data, queryElements: elements }, newFn);
3033
+ }
3034
+ mutate(elements) {
3035
+ const newFn = this.#fn.mutate(elements);
3036
+ return new ArcCommand({ ...this.data, mutationElements: elements }, newFn);
3037
+ }
3038
+ withParams(schema) {
3039
+ const newFn = this.#fn.withParams(schema);
3040
+ return new ArcCommand({
3041
+ ...this.data,
3042
+ params: schema instanceof ArcObject ? schema : new ArcObject(schema)
3043
+ }, newFn);
3044
+ }
3045
+ withResult(...schemas) {
3046
+ return new ArcCommand({ ...this.data, results: schemas }, this.#fn);
3047
+ }
3048
+ handle(handler) {
3049
+ const newFn = new ArcFunction({
3050
+ ...this.#fn.data,
3051
+ handler
3052
+ });
3053
+ return new ArcCommand({ ...this.data, handler }, newFn);
3054
+ }
3055
+ protectBy(token, check) {
3056
+ const newFn = this.#fn.protectedBy(token, check);
3057
+ const existingProtections = this.data.protections || [];
3058
+ return new ArcCommand({
3059
+ ...this.data,
3060
+ protections: [...existingProtections, { token, check }]
3061
+ }, newFn);
3062
+ }
3063
+ get hasProtections() {
3064
+ return this.#fn.hasProtections;
3065
+ }
3066
+ get protections() {
3067
+ return this.#fn.protections;
3068
+ }
3069
+ async verifyProtections(tokens) {
3070
+ return this.#fn.verifyProtections(tokens);
3071
+ }
3072
+ async init(environment, adapters) {
3073
+ if (environment === "server" && this.data.handler && adapters.commandWire?.registerCommandHandler) {
3074
+ adapters.commandWire.registerCommandHandler(this.data.name, async (params) => {
3075
+ const executeFunc = this.mutateContext(adapters);
3076
+ return await executeFunc(params);
3077
+ });
3078
+ }
3079
+ }
3080
+ mutateContext(adapters) {
3081
+ const executeFunc = async (params) => {
3082
+ if (this.data.handler) {
3083
+ return await this.executeLocally(params, adapters);
3084
+ }
3085
+ if (!adapters.commandWire) {
3086
+ throw new Error(`Command "${this.data.name}" has no handler and no commandWire adapter available for remote execution`);
3087
+ }
3088
+ return await adapters.commandWire.executeCommand(this.data.name, params);
3089
+ };
3090
+ return Object.assign(executeFunc, { params: this.data.params });
3091
+ }
3092
+ async executeLocally(params, adapters) {
3093
+ if (!this.data.handler) {
3094
+ throw new Error(`Command "${this.data.name}" has no handler`);
3095
+ }
3096
+ const context2 = this.buildCommandContext(adapters);
3097
+ return await this.data.handler(context2, params);
3098
+ }
3099
+ buildCommandContext(adapters) {
3100
+ const context2 = this.#fn.buildContext(adapters);
3101
+ if (this.#fn.hasProtections && adapters.authAdapter) {
3102
+ const decoded = adapters.authAdapter.getDecoded();
3103
+ if (decoded) {
3104
+ context2.$auth = {
3105
+ params: decoded.params,
3106
+ tokenName: decoded.tokenName
3107
+ };
3108
+ } else {
3109
+ throw new Error(`Command "${this.data.name}" requires authentication but no valid token found`);
3110
+ }
3111
+ }
3112
+ return context2;
3113
+ }
3114
+ toJsonSchema() {
3115
+ const parametersSchema = this.data.params ? this.data.params.toJsonSchema?.() ?? {
3116
+ type: "object",
3117
+ properties: {}
3118
+ } : { type: "object", properties: {} };
3119
+ return {
3120
+ type: "function",
3121
+ name: this.data.name,
3122
+ description: this.data.description ?? undefined,
3123
+ parameters: parametersSchema,
3124
+ strict: true
3125
+ };
3126
+ }
3127
+ }
3128
+ class ArcListener extends ArcContextElement {
3129
+ data;
3130
+ #fn;
3131
+ unsubscribers = [];
3132
+ constructor(data, fn) {
3133
+ super(data.name);
3134
+ this.data = data;
3135
+ this.#fn = fn ?? new ArcFunction({
3136
+ params: null,
3137
+ result: null,
3138
+ queryElements: data.queryElements,
3139
+ mutationElements: data.mutationElements,
3140
+ protections: [],
3141
+ handler: null,
3142
+ description: data.description
3143
+ });
3144
+ }
3145
+ description(description) {
3146
+ const newFn = this.#fn.description(description);
3147
+ return new ArcListener({ ...this.data, description }, newFn);
3148
+ }
3149
+ listenTo(events) {
3150
+ return new ArcListener({ ...this.data, eventElements: events }, this.#fn);
3151
+ }
3152
+ query(elements) {
3153
+ const newFn = this.#fn.query(elements);
3154
+ return new ArcListener({ ...this.data, queryElements: elements }, newFn);
3155
+ }
3156
+ mutate(elements) {
3157
+ const newFn = this.#fn.mutate(elements);
3158
+ return new ArcListener({ ...this.data, mutationElements: elements }, newFn);
3159
+ }
3160
+ async() {
3161
+ return new ArcListener({ ...this.data, isAsync: true }, this.#fn);
3162
+ }
3163
+ handle(handler) {
3164
+ return new ArcListener({ ...this.data, handler }, this.#fn);
3165
+ }
3166
+ get eventElements() {
3167
+ return this.data.eventElements || [];
3168
+ }
3169
+ get isAsync() {
3170
+ return this.data.isAsync;
3171
+ }
3172
+ async init(environment, adapters) {
3173
+ if (environment !== "server") {
3174
+ return;
3175
+ }
3176
+ if (!this.data.handler) {
3177
+ console.warn(`Listener "${this.data.name}" has no handler`);
3178
+ return;
3179
+ }
3180
+ if (!adapters.eventPublisher) {
3181
+ console.warn(`Listener "${this.data.name}" cannot subscribe: no eventPublisher adapter`);
3182
+ return;
3183
+ }
3184
+ for (const eventElement of this.data.eventElements) {
3185
+ const unsubscribe = adapters.eventPublisher.subscribe(eventElement.name, async (event2) => {
3186
+ await this.handleEvent(event2, adapters);
3187
+ });
3188
+ this.unsubscribers.push(unsubscribe);
3189
+ }
3190
+ }
3191
+ async handleEvent(event2, adapters) {
3192
+ if (!this.data.handler)
3193
+ return;
3194
+ const context2 = this.#fn.buildContext(adapters);
3195
+ if (adapters.authAdapter) {
3196
+ const decoded = adapters.authAdapter.getDecoded();
3197
+ if (decoded) {
3198
+ context2.$auth = {
3199
+ params: decoded.params,
3200
+ tokenName: decoded.tokenName
3201
+ };
3202
+ }
3203
+ }
3204
+ if (this.data.isAsync) {
3205
+ Promise.resolve(this.data.handler(context2, event2)).catch((error) => {
3206
+ console.error(`Async listener "${this.data.name}" error:`, error);
3207
+ });
3208
+ } else {
3209
+ await this.data.handler(context2, event2);
3210
+ }
3211
+ }
3212
+ destroy() {
3213
+ for (const unsubscribe of this.unsubscribers) {
3214
+ unsubscribe();
3215
+ }
3216
+ this.unsubscribers = [];
3217
+ }
3218
+ }
3219
+ class ArcRoute extends ArcContextElement {
3220
+ data;
3221
+ #fn;
3222
+ constructor(data, fn) {
3223
+ super(data.name);
3224
+ this.data = data;
3225
+ this.#fn = fn ?? new ArcFunction({
3226
+ params: null,
3227
+ result: null,
3228
+ queryElements: data.queryElements,
3229
+ mutationElements: data.mutationElements,
3230
+ protections: data.protections || [],
3231
+ handler: null,
3232
+ description: data.description
3233
+ });
3234
+ }
3235
+ description(description) {
3236
+ const newFn = this.#fn.description(description);
3237
+ return new ArcRoute({ ...this.data, description }, newFn);
3238
+ }
3239
+ path(path) {
3240
+ return new ArcRoute({ ...this.data, path }, this.#fn);
3241
+ }
3242
+ public() {
3243
+ return new ArcRoute({ ...this.data, isPublic: true }, this.#fn);
3244
+ }
3245
+ query(elements) {
3246
+ const newFn = this.#fn.query(elements);
3247
+ return new ArcRoute({ ...this.data, queryElements: elements }, newFn);
3248
+ }
3249
+ mutate(elements) {
3250
+ const newFn = this.#fn.mutate(elements);
3251
+ return new ArcRoute({ ...this.data, mutationElements: elements }, newFn);
3252
+ }
3253
+ protectBy(token, check) {
3254
+ const newFn = this.#fn.protectedBy(token, check);
3255
+ const existingProtections = this.data.protections || [];
3256
+ return new ArcRoute({
3257
+ ...this.data,
3258
+ protections: [...existingProtections, { token, check }]
3259
+ }, newFn);
3260
+ }
3261
+ handle(handlers) {
3262
+ return new ArcRoute({ ...this.data, handlers }, this.#fn);
3263
+ }
3264
+ get routePath() {
3265
+ return this.data.path || `/${this.data.name}`;
3266
+ }
3267
+ get fullPath() {
3268
+ return `/route${this.routePath}`;
3269
+ }
3270
+ get isPublic() {
3271
+ return this.data.isPublic;
3272
+ }
3273
+ get hasProtections() {
3274
+ return this.#fn.hasProtections;
3275
+ }
3276
+ get protections() {
3277
+ return this.data.protections || [];
3278
+ }
3279
+ getHandler(method) {
3280
+ return this.data.handlers?.[method];
3281
+ }
3282
+ matchesPath(pathname) {
3283
+ const routePath = this.fullPath;
3284
+ const routeParts = routePath.split("/").filter(Boolean);
3285
+ const pathParts = pathname.split("/").filter(Boolean);
3286
+ if (routeParts.length !== pathParts.length) {
3287
+ return { matches: false, params: {} };
3288
+ }
3289
+ const params = {};
3290
+ for (let i = 0;i < routeParts.length; i++) {
3291
+ const routePart = routeParts[i];
3292
+ const pathPart = pathParts[i];
3293
+ if (routePart.startsWith(":")) {
3294
+ const paramName = routePart.slice(1);
3295
+ params[paramName] = pathPart;
3296
+ } else if (routePart !== pathPart) {
3297
+ return { matches: false, params: {} };
3298
+ }
3299
+ }
3300
+ return { matches: true, params };
3301
+ }
3302
+ async verifyProtections(tokens) {
3303
+ if (this.data.isPublic) {
3304
+ return true;
3305
+ }
3306
+ return this.#fn.verifyProtections(tokens);
3307
+ }
3308
+ buildContext(adapters, authParams) {
3309
+ const context2 = this.#fn.buildContext(adapters);
3310
+ if (authParams) {
3311
+ context2.$auth = authParams;
3312
+ }
3313
+ return context2;
3314
+ }
3315
+ }
2866
3316
  class DataStorage {
2867
3317
  async commitChanges(changes) {
2868
3318
  await Promise.all(changes.map(({ store, changes: changes2 }) => this.getStore(store).applyChanges(changes2)));
@@ -4162,11 +4612,11 @@ class TokenCache {
4162
4612
  }
4163
4613
  }
4164
4614
 
4165
- // ../../../../node_modules/postgres/src/index.js
4615
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/index.js
4166
4616
  import os from "os";
4167
4617
  import fs from "fs";
4168
4618
 
4169
- // ../../../../node_modules/postgres/src/query.js
4619
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/query.js
4170
4620
  var originCache = new Map;
4171
4621
  var originStackCache = new Map;
4172
4622
  var originError = Symbol("OriginError");
@@ -4304,7 +4754,7 @@ function cachedError(xs) {
4304
4754
  return originCache.get(xs);
4305
4755
  }
4306
4756
 
4307
- // ../../../../node_modules/postgres/src/errors.js
4757
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/errors.js
4308
4758
  class PostgresError extends Error {
4309
4759
  constructor(x) {
4310
4760
  super(x.message);
@@ -4347,7 +4797,7 @@ function notSupported(x) {
4347
4797
  return error;
4348
4798
  }
4349
4799
 
4350
- // ../../../../node_modules/postgres/src/types.js
4800
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/types.js
4351
4801
  var types = {
4352
4802
  string: {
4353
4803
  to: 25,
@@ -4628,14 +5078,14 @@ fromKebab.column = { to: fromKebab };
4628
5078
  var kebab = { ...toKebab };
4629
5079
  kebab.column.to = fromKebab;
4630
5080
 
4631
- // ../../../../node_modules/postgres/src/connection.js
5081
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/connection.js
4632
5082
  import net from "net";
4633
5083
  import tls from "tls";
4634
5084
  import crypto from "crypto";
4635
5085
  import Stream from "stream";
4636
5086
  import { performance } from "perf_hooks";
4637
5087
 
4638
- // ../../../../node_modules/postgres/src/result.js
5088
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/result.js
4639
5089
  class Result extends Array {
4640
5090
  constructor() {
4641
5091
  super();
@@ -4652,7 +5102,7 @@ class Result extends Array {
4652
5102
  }
4653
5103
  }
4654
5104
 
4655
- // ../../../../node_modules/postgres/src/queue.js
5105
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/queue.js
4656
5106
  var queue_default = Queue;
4657
5107
  function Queue(initial = []) {
4658
5108
  let xs = initial.slice();
@@ -4679,7 +5129,7 @@ function Queue(initial = []) {
4679
5129
  };
4680
5130
  }
4681
5131
 
4682
- // ../../../../node_modules/postgres/src/bytes.js
5132
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/bytes.js
4683
5133
  var size = 256;
4684
5134
  var buffer = Buffer.allocUnsafe(size);
4685
5135
  var messages = "BCcDdEFfHPpQSX".split("").reduce((acc, x) => {
@@ -4752,7 +5202,7 @@ function reset() {
4752
5202
  return b;
4753
5203
  }
4754
5204
 
4755
- // ../../../../node_modules/postgres/src/connection.js
5205
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/connection.js
4756
5206
  var connection_default = Connection;
4757
5207
  var uid = 1;
4758
5208
  var Sync = bytes_default().S().end();
@@ -4788,6 +5238,7 @@ var errorFields = {
4788
5238
  };
4789
5239
  function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) {
4790
5240
  const {
5241
+ sslnegotiation,
4791
5242
  ssl,
4792
5243
  max,
4793
5244
  user,
@@ -4805,7 +5256,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
4805
5256
  target_session_attrs
4806
5257
  } = options;
4807
5258
  const sent = queue_default(), id2 = uid++, backend = { pid: null, secret: null }, idleTimer = timer(end, options.idle_timeout), lifeTimer = timer(end, options.max_lifetime), connectTimer = timer(connectTimedOut, options.connect_timeout);
4808
- let socket = null, cancelMessage, result = new Result, incoming = Buffer.alloc(0), needsTypes = options.fetch_types, backendParameters = {}, statements = {}, statementId = Math.random().toString(36).slice(2), statementCount = 1, closedDate = 0, remaining = 0, hostIndex = 0, retries = 0, length = 0, delay = 0, rows = 0, serverSignature = null, nextWriteTimer = null, terminated = false, incomings = null, results = null, initial = null, ending = null, stream = null, chunk = null, ended = null, nonce = null, query = null, final = null;
5259
+ let socket = null, cancelMessage, errorResponse = null, result = new Result, incoming = Buffer.alloc(0), needsTypes = options.fetch_types, backendParameters = {}, statements = {}, statementId = Math.random().toString(36).slice(2), statementCount = 1, closedTime = 0, remaining = 0, hostIndex = 0, retries = 0, length = 0, delay = 0, rows = 0, serverSignature = null, nextWriteTimer = null, terminated = false, incomings = null, results = null, initial = null, ending = null, stream = null, chunk = null, ended = null, nonce = null, query = null, final = null;
4809
5260
  const connection2 = {
4810
5261
  queue: queues.closed,
4811
5262
  idleTimer,
@@ -4848,6 +5299,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
4848
5299
  function execute(q) {
4849
5300
  if (terminated)
4850
5301
  return queryError(q, Errors.connection("CONNECTION_DESTROYED", options));
5302
+ if (stream)
5303
+ return queryError(q, Errors.generic("COPY_IN_PROGRESS", "You cannot execute queries during copy"));
4851
5304
  if (q.cancelled)
4852
5305
  return;
4853
5306
  try {
@@ -4917,16 +5370,24 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
4917
5370
  socket.destroy();
4918
5371
  }
4919
5372
  async function secure() {
4920
- write(SSLRequest);
4921
- const canSSL = await new Promise((r) => socket.once("data", (x) => r(x[0] === 83)));
4922
- if (!canSSL && ssl === "prefer")
4923
- return connected();
4924
- socket.removeAllListeners();
4925
- socket = tls.connect({
5373
+ if (sslnegotiation !== "direct") {
5374
+ write(SSLRequest);
5375
+ const canSSL = await new Promise((r) => socket.once("data", (x) => r(x[0] === 83)));
5376
+ if (!canSSL && ssl === "prefer")
5377
+ return connected();
5378
+ }
5379
+ const options2 = {
4926
5380
  socket,
4927
- servername: net.isIP(socket.host) ? undefined : socket.host,
4928
- ...ssl === "require" || ssl === "allow" || ssl === "prefer" ? { rejectUnauthorized: false } : ssl === "verify-full" ? {} : typeof ssl === "object" ? ssl : {}
4929
- });
5381
+ servername: net.isIP(socket.host) ? undefined : socket.host
5382
+ };
5383
+ if (sslnegotiation === "direct")
5384
+ options2.ALPNProtocols = ["postgresql"];
5385
+ if (ssl === "require" || ssl === "allow" || ssl === "prefer")
5386
+ options2.rejectUnauthorized = false;
5387
+ else if (typeof ssl === "object")
5388
+ Object.assign(options2, ssl);
5389
+ socket.removeAllListeners();
5390
+ socket = tls.connect(options2);
4930
5391
  socket.on("secureConnect", connected);
4931
5392
  socket.on("error", error);
4932
5393
  socket.on("close", closed);
@@ -4980,7 +5441,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
4980
5441
  hostIndex = (hostIndex + 1) % port.length;
4981
5442
  }
4982
5443
  function reconnect() {
4983
- setTimeout(connect, closedDate ? closedDate + delay - performance.now() : 0);
5444
+ setTimeout(connect, closedTime ? Math.max(0, closedTime + delay - performance.now()) : 0);
4984
5445
  }
4985
5446
  function connected() {
4986
5447
  try {
@@ -5054,7 +5515,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
5054
5515
  if (initial)
5055
5516
  return reconnect();
5056
5517
  !hadError && (query || sent.length) && error(Errors.connection("CONNECTION_CLOSED", options, socket));
5057
- closedDate = performance.now();
5518
+ closedTime = performance.now();
5058
5519
  hadError && options.shared.retries++;
5059
5520
  delay = (typeof backoff === "function" ? backoff(options.shared.retries) : backoff) * 1000;
5060
5521
  onclose(connection2, Errors.connection("CONNECTION_CLOSED", options, socket));
@@ -5086,8 +5547,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
5086
5547
  }
5087
5548
  }
5088
5549
  function ReadyForQuery(x) {
5089
- query && query.options.simple && query.resolve(results || result);
5090
- query = results = null;
5550
+ if (query) {
5551
+ if (errorResponse) {
5552
+ query.retried ? errored(query.retried) : query.prepared && retryRoutines.has(errorResponse.routine) ? retry(query, errorResponse) : errored(errorResponse);
5553
+ } else {
5554
+ query.resolve(results || result);
5555
+ }
5556
+ } else if (errorResponse) {
5557
+ errored(errorResponse);
5558
+ }
5559
+ query = results = errorResponse = null;
5091
5560
  result = new Result;
5092
5561
  connectTimer.cancel();
5093
5562
  if (initial) {
@@ -5132,7 +5601,6 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
5132
5601
  result.count && query.cursorFn(result);
5133
5602
  write(Sync);
5134
5603
  }
5135
- query.resolve(result);
5136
5604
  }
5137
5605
  function ParseComplete() {
5138
5606
  query.parsing = false;
@@ -5263,9 +5731,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
5263
5731
  query2.execute();
5264
5732
  }
5265
5733
  function ErrorResponse(x) {
5266
- query && (query.cursorFn || query.describeFirst) && write(Sync);
5267
- const error2 = Errors.postgres(parseError(x));
5268
- query && query.retried ? errored(query.retried) : query && query.prepared && retryRoutines.has(error2.routine) ? retry(query, error2) : errored(error2);
5734
+ if (query) {
5735
+ (query.cursorFn || query.describeFirst) && write(Sync);
5736
+ errorResponse = Errors.postgres(parseError(x));
5737
+ } else {
5738
+ errored(Errors.postgres(parseError(x)));
5739
+ }
5269
5740
  }
5270
5741
  function retry(q, error2) {
5271
5742
  delete statements[q.signature];
@@ -5308,6 +5779,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
5308
5779
  final(callback) {
5309
5780
  socket.write(bytes_default().c().end());
5310
5781
  final = callback;
5782
+ stream = null;
5311
5783
  }
5312
5784
  });
5313
5785
  query.resolve(stream);
@@ -5453,7 +5925,7 @@ function timer(fn, seconds) {
5453
5925
  }
5454
5926
  }
5455
5927
 
5456
- // ../../../../node_modules/postgres/src/subscribe.js
5928
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/subscribe.js
5457
5929
  var noop2 = () => {};
5458
5930
  function Subscribe(postgres2, options) {
5459
5931
  const subscribers = new Map, slot = "postgresjs_" + Math.random().toString(36).slice(2), state = {};
@@ -5649,7 +6121,7 @@ function parseEvent(x) {
5649
6121
  return (command || "*") + (path ? ":" + (path.indexOf(".") === -1 ? "public." + path : path) : "") + (key ? "=" + key : "");
5650
6122
  }
5651
6123
 
5652
- // ../../../../node_modules/postgres/src/large.js
6124
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/large.js
5653
6125
  import Stream2 from "stream";
5654
6126
  function largeObject(sql, oid, mode = 131072 | 262144) {
5655
6127
  return new Promise(async (resolve, reject) => {
@@ -5715,7 +6187,7 @@ function largeObject(sql, oid, mode = 131072 | 262144) {
5715
6187
  });
5716
6188
  }
5717
6189
 
5718
- // ../../../../node_modules/postgres/src/index.js
6190
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/index.js
5719
6191
  Object.assign(Postgres, {
5720
6192
  PostgresError,
5721
6193
  toPascal,
@@ -6008,8 +6480,9 @@ function parseOptions(a, b2) {
6008
6480
  query.sslrootcert === "system" && (query.ssl = "verify-full");
6009
6481
  const ints = ["idle_timeout", "connect_timeout", "max_lifetime", "max_pipeline", "backoff", "keep_alive"];
6010
6482
  const defaults = {
6011
- max: 10,
6483
+ max: globalThis.Cloudflare ? 3 : 10,
6012
6484
  ssl: false,
6485
+ sslnegotiation: null,
6013
6486
  idle_timeout: null,
6014
6487
  connect_timeout: 30,
6015
6488
  max_lifetime,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arcote.tech/arc-adapter-db-postgres",
3
- "version": "0.4.9",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -23,7 +23,7 @@
23
23
  "postgres": "^3.4.4"
24
24
  },
25
25
  "peerDependencies": {
26
- "@arcote.tech/arc": "^0.4.9"
26
+ "@arcote.tech/arc": "^0.5.0"
27
27
  },
28
28
  "devDependencies": {
29
29
  "@types/pg": "^8.11.0",