@arcote.tech/arc-adapter-db-postgres 0.4.7 → 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 +518 -34
  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",
@@ -1354,14 +1354,23 @@ var TOKEN_PREFIX = "arc:token:";
1354
1354
  function hasLocalStorage() {
1355
1355
  return typeof localStorage !== "undefined";
1356
1356
  }
1357
+ function notifyTokenChange(scope) {
1358
+ if (typeof window !== "undefined") {
1359
+ queueMicrotask(() => {
1360
+ window.dispatchEvent(new CustomEvent("arc:token-change", { detail: { scope } }));
1361
+ });
1362
+ }
1363
+ }
1357
1364
 
1358
1365
  class AuthAdapter {
1359
1366
  scopes = new Map;
1360
1367
  setToken(token, scope = "default") {
1361
1368
  if (!token) {
1362
1369
  this.scopes.delete(scope);
1363
- if (hasLocalStorage())
1370
+ if (hasLocalStorage()) {
1364
1371
  localStorage.removeItem(TOKEN_PREFIX + scope);
1372
+ notifyTokenChange(scope);
1373
+ }
1365
1374
  return;
1366
1375
  }
1367
1376
  try {
@@ -1382,8 +1391,10 @@ class AuthAdapter {
1382
1391
  exp: payload.exp
1383
1392
  }
1384
1393
  });
1385
- if (hasLocalStorage())
1394
+ if (hasLocalStorage()) {
1386
1395
  localStorage.setItem(TOKEN_PREFIX + scope, token);
1396
+ notifyTokenChange(scope);
1397
+ }
1387
1398
  } catch {
1388
1399
  this.scopes.delete(scope);
1389
1400
  if (hasLocalStorage())
@@ -2815,6 +2826,147 @@ class ArcEvent extends ArcContextElement {
2815
2826
  return ArcEvent.sharedDatabaseStoreSchema();
2816
2827
  }
2817
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
+ }
2818
2970
  class AggregateBase {
2819
2971
  value;
2820
2972
  _id;
@@ -2852,6 +3004,315 @@ class AggregateBase {
2852
3004
  return result;
2853
3005
  }
2854
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
+ }
2855
3316
  class DataStorage {
2856
3317
  async commitChanges(changes) {
2857
3318
  await Promise.all(changes.map(({ store, changes: changes2 }) => this.getStore(store).applyChanges(changes2)));
@@ -4151,11 +4612,11 @@ class TokenCache {
4151
4612
  }
4152
4613
  }
4153
4614
 
4154
- // ../../../../node_modules/postgres/src/index.js
4615
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/index.js
4155
4616
  import os from "os";
4156
4617
  import fs from "fs";
4157
4618
 
4158
- // ../../../../node_modules/postgres/src/query.js
4619
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/query.js
4159
4620
  var originCache = new Map;
4160
4621
  var originStackCache = new Map;
4161
4622
  var originError = Symbol("OriginError");
@@ -4293,7 +4754,7 @@ function cachedError(xs) {
4293
4754
  return originCache.get(xs);
4294
4755
  }
4295
4756
 
4296
- // ../../../../node_modules/postgres/src/errors.js
4757
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/errors.js
4297
4758
  class PostgresError extends Error {
4298
4759
  constructor(x) {
4299
4760
  super(x.message);
@@ -4336,7 +4797,7 @@ function notSupported(x) {
4336
4797
  return error;
4337
4798
  }
4338
4799
 
4339
- // ../../../../node_modules/postgres/src/types.js
4800
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/types.js
4340
4801
  var types = {
4341
4802
  string: {
4342
4803
  to: 25,
@@ -4617,14 +5078,14 @@ fromKebab.column = { to: fromKebab };
4617
5078
  var kebab = { ...toKebab };
4618
5079
  kebab.column.to = fromKebab;
4619
5080
 
4620
- // ../../../../node_modules/postgres/src/connection.js
5081
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/connection.js
4621
5082
  import net from "net";
4622
5083
  import tls from "tls";
4623
5084
  import crypto from "crypto";
4624
5085
  import Stream from "stream";
4625
5086
  import { performance } from "perf_hooks";
4626
5087
 
4627
- // ../../../../node_modules/postgres/src/result.js
5088
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/result.js
4628
5089
  class Result extends Array {
4629
5090
  constructor() {
4630
5091
  super();
@@ -4641,7 +5102,7 @@ class Result extends Array {
4641
5102
  }
4642
5103
  }
4643
5104
 
4644
- // ../../../../node_modules/postgres/src/queue.js
5105
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/queue.js
4645
5106
  var queue_default = Queue;
4646
5107
  function Queue(initial = []) {
4647
5108
  let xs = initial.slice();
@@ -4668,7 +5129,7 @@ function Queue(initial = []) {
4668
5129
  };
4669
5130
  }
4670
5131
 
4671
- // ../../../../node_modules/postgres/src/bytes.js
5132
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/bytes.js
4672
5133
  var size = 256;
4673
5134
  var buffer = Buffer.allocUnsafe(size);
4674
5135
  var messages = "BCcDdEFfHPpQSX".split("").reduce((acc, x) => {
@@ -4741,7 +5202,7 @@ function reset() {
4741
5202
  return b;
4742
5203
  }
4743
5204
 
4744
- // ../../../../node_modules/postgres/src/connection.js
5205
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/connection.js
4745
5206
  var connection_default = Connection;
4746
5207
  var uid = 1;
4747
5208
  var Sync = bytes_default().S().end();
@@ -4777,6 +5238,7 @@ var errorFields = {
4777
5238
  };
4778
5239
  function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose = noop } = {}) {
4779
5240
  const {
5241
+ sslnegotiation,
4780
5242
  ssl,
4781
5243
  max,
4782
5244
  user,
@@ -4794,7 +5256,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
4794
5256
  target_session_attrs
4795
5257
  } = options;
4796
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);
4797
- 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;
4798
5260
  const connection2 = {
4799
5261
  queue: queues.closed,
4800
5262
  idleTimer,
@@ -4837,6 +5299,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
4837
5299
  function execute(q) {
4838
5300
  if (terminated)
4839
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"));
4840
5304
  if (q.cancelled)
4841
5305
  return;
4842
5306
  try {
@@ -4906,16 +5370,24 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
4906
5370
  socket.destroy();
4907
5371
  }
4908
5372
  async function secure() {
4909
- write(SSLRequest);
4910
- const canSSL = await new Promise((r) => socket.once("data", (x) => r(x[0] === 83)));
4911
- if (!canSSL && ssl === "prefer")
4912
- return connected();
4913
- socket.removeAllListeners();
4914
- 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 = {
4915
5380
  socket,
4916
- servername: net.isIP(socket.host) ? undefined : socket.host,
4917
- ...ssl === "require" || ssl === "allow" || ssl === "prefer" ? { rejectUnauthorized: false } : ssl === "verify-full" ? {} : typeof ssl === "object" ? ssl : {}
4918
- });
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);
4919
5391
  socket.on("secureConnect", connected);
4920
5392
  socket.on("error", error);
4921
5393
  socket.on("close", closed);
@@ -4969,7 +5441,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
4969
5441
  hostIndex = (hostIndex + 1) % port.length;
4970
5442
  }
4971
5443
  function reconnect() {
4972
- setTimeout(connect, closedDate ? closedDate + delay - performance.now() : 0);
5444
+ setTimeout(connect, closedTime ? Math.max(0, closedTime + delay - performance.now()) : 0);
4973
5445
  }
4974
5446
  function connected() {
4975
5447
  try {
@@ -5043,7 +5515,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
5043
5515
  if (initial)
5044
5516
  return reconnect();
5045
5517
  !hadError && (query || sent.length) && error(Errors.connection("CONNECTION_CLOSED", options, socket));
5046
- closedDate = performance.now();
5518
+ closedTime = performance.now();
5047
5519
  hadError && options.shared.retries++;
5048
5520
  delay = (typeof backoff === "function" ? backoff(options.shared.retries) : backoff) * 1000;
5049
5521
  onclose(connection2, Errors.connection("CONNECTION_CLOSED", options, socket));
@@ -5075,8 +5547,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
5075
5547
  }
5076
5548
  }
5077
5549
  function ReadyForQuery(x) {
5078
- query && query.options.simple && query.resolve(results || result);
5079
- 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;
5080
5560
  result = new Result;
5081
5561
  connectTimer.cancel();
5082
5562
  if (initial) {
@@ -5121,7 +5601,6 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
5121
5601
  result.count && query.cursorFn(result);
5122
5602
  write(Sync);
5123
5603
  }
5124
- query.resolve(result);
5125
5604
  }
5126
5605
  function ParseComplete() {
5127
5606
  query.parsing = false;
@@ -5252,9 +5731,12 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
5252
5731
  query2.execute();
5253
5732
  }
5254
5733
  function ErrorResponse(x) {
5255
- query && (query.cursorFn || query.describeFirst) && write(Sync);
5256
- const error2 = Errors.postgres(parseError(x));
5257
- 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
+ }
5258
5740
  }
5259
5741
  function retry(q, error2) {
5260
5742
  delete statements[q.signature];
@@ -5297,6 +5779,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
5297
5779
  final(callback) {
5298
5780
  socket.write(bytes_default().c().end());
5299
5781
  final = callback;
5782
+ stream = null;
5300
5783
  }
5301
5784
  });
5302
5785
  query.resolve(stream);
@@ -5442,7 +5925,7 @@ function timer(fn, seconds) {
5442
5925
  }
5443
5926
  }
5444
5927
 
5445
- // ../../../../node_modules/postgres/src/subscribe.js
5928
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/subscribe.js
5446
5929
  var noop2 = () => {};
5447
5930
  function Subscribe(postgres2, options) {
5448
5931
  const subscribers = new Map, slot = "postgresjs_" + Math.random().toString(36).slice(2), state = {};
@@ -5638,7 +6121,7 @@ function parseEvent(x) {
5638
6121
  return (command || "*") + (path ? ":" + (path.indexOf(".") === -1 ? "public." + path : path) : "") + (key ? "=" + key : "");
5639
6122
  }
5640
6123
 
5641
- // ../../../../node_modules/postgres/src/large.js
6124
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/large.js
5642
6125
  import Stream2 from "stream";
5643
6126
  function largeObject(sql, oid, mode = 131072 | 262144) {
5644
6127
  return new Promise(async (resolve, reject) => {
@@ -5704,7 +6187,7 @@ function largeObject(sql, oid, mode = 131072 | 262144) {
5704
6187
  });
5705
6188
  }
5706
6189
 
5707
- // ../../../../node_modules/postgres/src/index.js
6190
+ // ../../../../node_modules/.bun/postgres@3.4.8/node_modules/postgres/src/index.js
5708
6191
  Object.assign(Postgres, {
5709
6192
  PostgresError,
5710
6193
  toPascal,
@@ -5997,8 +6480,9 @@ function parseOptions(a, b2) {
5997
6480
  query.sslrootcert === "system" && (query.ssl = "verify-full");
5998
6481
  const ints = ["idle_timeout", "connect_timeout", "max_lifetime", "max_pipeline", "backoff", "keep_alive"];
5999
6482
  const defaults = {
6000
- max: 10,
6483
+ max: globalThis.Cloudflare ? 3 : 10,
6001
6484
  ssl: false,
6485
+ sslnegotiation: null,
6002
6486
  idle_timeout: null,
6003
6487
  connect_timeout: 30,
6004
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.7",
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.7"
26
+ "@arcote.tech/arc": "^0.5.0"
27
27
  },
28
28
  "devDependencies": {
29
29
  "@types/pg": "^8.11.0",