@biltme/backend 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -757,7 +757,8 @@ var require_FunctionsClient = __commonJS((exports) => {
757
757
  url.searchParams.set("forceFunctionRegion", region);
758
758
  }
759
759
  let body;
760
- if (functionArgs && (headers && !Object.prototype.hasOwnProperty.call(headers, "Content-Type") || !headers)) {
760
+ const hasContentTypeHeader = !!headers && Object.keys(headers).some((key) => key.toLowerCase() === "content-type");
761
+ if (functionArgs && !hasContentTypeHeader) {
761
762
  if (typeof Blob !== "undefined" && functionArgs instanceof Blob || functionArgs instanceof ArrayBuffer) {
762
763
  _headers["Content-Type"] = "application/octet-stream";
763
764
  body = functionArgs;
@@ -870,22 +871,24 @@ var require_websocket_factory = __commonJS((exports) => {
870
871
  static detectEnvironment() {
871
872
  var _a;
872
873
  if (typeof WebSocket !== "undefined") {
873
- return { type: "native", constructor: WebSocket };
874
+ return { type: "native", wsConstructor: WebSocket };
874
875
  }
875
- if (typeof globalThis !== "undefined" && typeof globalThis.WebSocket !== "undefined") {
876
- return { type: "native", constructor: globalThis.WebSocket };
876
+ const gt = globalThis;
877
+ if (typeof globalThis !== "undefined" && typeof gt.WebSocket !== "undefined") {
878
+ return { type: "native", wsConstructor: gt.WebSocket };
877
879
  }
878
- if (typeof global !== "undefined" && typeof global.WebSocket !== "undefined") {
879
- return { type: "native", constructor: global.WebSocket };
880
+ const gl = typeof global !== "undefined" ? global : undefined;
881
+ if (gl && typeof gl.WebSocket !== "undefined") {
882
+ return { type: "native", wsConstructor: gl.WebSocket };
880
883
  }
881
- if (typeof globalThis !== "undefined" && typeof globalThis.WebSocketPair !== "undefined" && typeof globalThis.WebSocket === "undefined") {
884
+ if (typeof globalThis !== "undefined" && typeof gt.WebSocketPair !== "undefined" && typeof globalThis.WebSocket === "undefined") {
882
885
  return {
883
886
  type: "cloudflare",
884
887
  error: "Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",
885
888
  workaround: "Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."
886
889
  };
887
890
  }
888
- if (typeof globalThis !== "undefined" && globalThis.EdgeRuntime || typeof navigator !== "undefined" && ((_a = navigator.userAgent) === null || _a === undefined ? undefined : _a.includes("Vercel-Edge"))) {
891
+ if (typeof globalThis !== "undefined" && gt.EdgeRuntime || typeof navigator !== "undefined" && ((_a = navigator.userAgent) === null || _a === undefined ? undefined : _a.includes("Vercel-Edge"))) {
889
892
  return {
890
893
  type: "unsupported",
891
894
  error: "Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",
@@ -896,24 +899,10 @@ var require_websocket_factory = __commonJS((exports) => {
896
899
  if (_process) {
897
900
  const processVersions = _process["versions"];
898
901
  if (processVersions && processVersions["node"]) {
899
- const versionString = processVersions["node"];
900
- const nodeVersion = parseInt(versionString.replace(/^v/, "").split(".")[0]);
901
- if (nodeVersion >= 22) {
902
- if (typeof globalThis.WebSocket !== "undefined") {
903
- return { type: "native", constructor: globalThis.WebSocket };
904
- }
905
- return {
906
- type: "unsupported",
907
- error: `Node.js ${nodeVersion} detected but native WebSocket not found.`,
908
- workaround: "Provide a WebSocket implementation via the transport option."
909
- };
910
- }
911
902
  return {
912
903
  type: "unsupported",
913
- error: `Node.js ${nodeVersion} detected without native WebSocket support.`,
914
- workaround: `For Node.js < 22, install "ws" package and provide it via the transport option:
915
- ` + `import ws from "ws"
916
- ` + "new RealtimeClient(url, { transport: ws })"
904
+ error: "Node.js detected but native WebSocket not found.",
905
+ workaround: "Ensure you are running Node.js 22+ or provide a WebSocket implementation via the transport option."
917
906
  };
918
907
  }
919
908
  }
@@ -925,8 +914,8 @@ var require_websocket_factory = __commonJS((exports) => {
925
914
  }
926
915
  static getWebSocketConstructor() {
927
916
  const env = this.detectEnvironment();
928
- if (env.constructor) {
929
- return env.constructor;
917
+ if (env.wsConstructor) {
918
+ return env.wsConstructor;
930
919
  }
931
920
  let errorMessage = env.error || "WebSocket not supported in this environment.";
932
921
  if (env.workaround) {
@@ -939,7 +928,7 @@ Suggested solution: ${env.workaround}`;
939
928
  static isWebSocketSupported() {
940
929
  try {
941
930
  const env = this.detectEnvironment();
942
- return env.type === "native" || env.type === "ws";
931
+ return env.type === "native";
943
932
  } catch (_a) {
944
933
  return false;
945
934
  }
@@ -953,7 +942,7 @@ Suggested solution: ${env.workaround}`;
953
942
  var require_version = __commonJS((exports) => {
954
943
  Object.defineProperty(exports, "__esModule", { value: true });
955
944
  exports.version = undefined;
956
- exports.version = "2.105.1";
945
+ exports.version = "2.110.7";
957
946
  });
958
947
 
959
948
  // node_modules/@supabase/realtime-js/dist/main/lib/constants.js
@@ -1045,12 +1034,13 @@ var require_serializer = __commonJS((exports) => {
1045
1034
  }
1046
1035
  _encodeUserBroadcastPush(message, encodingType, encodedPayload) {
1047
1036
  var _a, _b;
1048
- const topic = message.topic;
1049
- const ref = (_a = message.ref) !== null && _a !== undefined ? _a : "";
1050
- const joinRef = (_b = message.join_ref) !== null && _b !== undefined ? _b : "";
1051
- const userEvent = message.payload.event;
1037
+ const encoder = new TextEncoder;
1038
+ const topic = encoder.encode(message.topic);
1039
+ const ref = encoder.encode((_a = message.ref) !== null && _a !== undefined ? _a : "");
1040
+ const joinRef = encoder.encode((_b = message.join_ref) !== null && _b !== undefined ? _b : "");
1041
+ const userEvent = encoder.encode(message.payload.event);
1052
1042
  const rest = this.allowedMetadataKeys ? this._pick(message.payload, this.allowedMetadataKeys) : {};
1053
- const metadata = Object.keys(rest).length === 0 ? "" : JSON.stringify(rest);
1043
+ const metadata = encoder.encode(Object.keys(rest).length === 0 ? "" : JSON.stringify(rest));
1054
1044
  if (joinRef.length > 255) {
1055
1045
  throw new Error(`joinRef length ${joinRef.length} exceeds maximum of 255`);
1056
1046
  }
@@ -1068,7 +1058,8 @@ var require_serializer = __commonJS((exports) => {
1068
1058
  }
1069
1059
  const metaLength = this.USER_BROADCAST_PUSH_META_LENGTH + joinRef.length + ref.length + topic.length + userEvent.length + metadata.length;
1070
1060
  const header = new ArrayBuffer(this.HEADER_LENGTH + metaLength);
1071
- let view = new DataView(header);
1061
+ const view = new DataView(header);
1062
+ const bytes = new Uint8Array(header);
1072
1063
  let offset = 0;
1073
1064
  view.setUint8(offset++, this.KINDS.userBroadcastPush);
1074
1065
  view.setUint8(offset++, joinRef.length);
@@ -1077,11 +1068,16 @@ var require_serializer = __commonJS((exports) => {
1077
1068
  view.setUint8(offset++, userEvent.length);
1078
1069
  view.setUint8(offset++, metadata.length);
1079
1070
  view.setUint8(offset++, encodingType);
1080
- Array.from(joinRef, (char) => view.setUint8(offset++, char.charCodeAt(0)));
1081
- Array.from(ref, (char) => view.setUint8(offset++, char.charCodeAt(0)));
1082
- Array.from(topic, (char) => view.setUint8(offset++, char.charCodeAt(0)));
1083
- Array.from(userEvent, (char) => view.setUint8(offset++, char.charCodeAt(0)));
1084
- Array.from(metadata, (char) => view.setUint8(offset++, char.charCodeAt(0)));
1071
+ bytes.set(joinRef, offset);
1072
+ offset += joinRef.length;
1073
+ bytes.set(ref, offset);
1074
+ offset += ref.length;
1075
+ bytes.set(topic, offset);
1076
+ offset += topic.length;
1077
+ bytes.set(userEvent, offset);
1078
+ offset += userEvent.length;
1079
+ bytes.set(metadata, offset);
1080
+ offset += metadata.length;
1085
1081
  var combined = new Uint8Array(header.byteLength + encodedPayload.byteLength);
1086
1082
  combined.set(new Uint8Array(header), 0);
1087
1083
  combined.set(new Uint8Array(encodedPayload), header.byteLength);
@@ -1361,6 +1357,7 @@ var require_phoenix_cjs = __commonJS((exports, module) => {
1361
1357
  var DEFAULT_VSN = "2.0.0";
1362
1358
  var DEFAULT_TIMEOUT = 1e4;
1363
1359
  var WS_CLOSE_NORMAL = 1000;
1360
+ var MAX_LONGPOLL_BATCH_SIZE = 100;
1364
1361
  var SOCKET_STATES = { connecting: 0, open: 1, closing: 2, closed: 3 };
1365
1362
  var CHANNEL_STATES = {
1366
1363
  closed: "closed",
@@ -1903,17 +1900,23 @@ var require_phoenix_cjs = __commonJS((exports, module) => {
1903
1900
  }, 0);
1904
1901
  }
1905
1902
  }
1906
- batchSend(messages) {
1903
+ batchSend(messages, offset = 0) {
1907
1904
  this.awaitingBatchAck = true;
1908
- this.ajax("POST", { "Content-Type": "application/x-ndjson" }, messages.join(`
1905
+ const next = offset + MAX_LONGPOLL_BATCH_SIZE;
1906
+ const batch = messages.slice(offset, next);
1907
+ this.ajax("POST", { "Content-Type": "application/x-ndjson" }, batch.join(`
1909
1908
  `), () => this.onerror("timeout"), (resp) => {
1910
- this.awaitingBatchAck = false;
1911
1909
  if (!resp || resp.status !== 200) {
1910
+ this.awaitingBatchAck = false;
1912
1911
  this.onerror(resp && resp.status);
1913
1912
  this.closeAndRetry(1011, "internal server error", false);
1913
+ } else if (next < messages.length) {
1914
+ this.batchSend(messages, next);
1914
1915
  } else if (this.batchBuffer.length > 0) {
1915
1916
  this.batchSend(this.batchBuffer);
1916
1917
  this.batchBuffer = [];
1918
+ } else {
1919
+ this.awaitingBatchAck = false;
1917
1920
  }
1918
1921
  });
1919
1922
  }
@@ -1950,7 +1953,7 @@ var require_phoenix_cjs = __commonJS((exports, module) => {
1950
1953
  var Presence = class _Presence {
1951
1954
  constructor(channel, opts = {}) {
1952
1955
  let events = opts.events || { state: "presence_state", diff: "presence_diff" };
1953
- this.state = {};
1956
+ this.state = /* @__PURE__ */ Object.create(null);
1954
1957
  this.pendingDiffs = [];
1955
1958
  this.channel = channel;
1956
1959
  this.joinRef = null;
@@ -1995,9 +1998,10 @@ var require_phoenix_cjs = __commonJS((exports, module) => {
1995
1998
  return !this.joinRef || this.joinRef !== this.channel.joinRef();
1996
1999
  }
1997
2000
  static syncState(currentState, newState, onJoin, onLeave) {
1998
- let state = this.clone(currentState);
1999
- let joins = {};
2000
- let leaves = {};
2001
+ let state = this.toNullProtoObj(this.clone(currentState));
2002
+ newState = this.toNullProtoObj(newState);
2003
+ let joins = /* @__PURE__ */ Object.create(null);
2004
+ let leaves = /* @__PURE__ */ Object.create(null);
2001
2005
  this.map(state, (key, presence) => {
2002
2006
  if (!newState[key]) {
2003
2007
  leaves[key] = presence;
@@ -2025,6 +2029,7 @@ var require_phoenix_cjs = __commonJS((exports, module) => {
2025
2029
  return this.syncDiff(state, { joins, leaves }, onJoin, onLeave);
2026
2030
  }
2027
2031
  static syncDiff(state, diff, onJoin, onLeave) {
2032
+ state = this.toNullProtoObj(state);
2028
2033
  let { joins, leaves } = this.clone(diff);
2029
2034
  if (!onJoin) {
2030
2035
  onJoin = function() {};
@@ -2071,6 +2076,16 @@ var require_phoenix_cjs = __commonJS((exports, module) => {
2071
2076
  static map(obj, func) {
2072
2077
  return Object.getOwnPropertyNames(obj).map((key) => func(key, obj[key]));
2073
2078
  }
2079
+ static toNullProtoObj(obj) {
2080
+ if (Object.getPrototypeOf(obj) === null) {
2081
+ return obj;
2082
+ }
2083
+ let cleaned = /* @__PURE__ */ Object.create(null);
2084
+ Object.getOwnPropertyNames(obj).forEach((key) => {
2085
+ cleaned[key] = obj[key];
2086
+ });
2087
+ return cleaned;
2088
+ }
2074
2089
  static clone(obj) {
2075
2090
  return JSON.parse(JSON.stringify(obj));
2076
2091
  }
@@ -2097,24 +2112,43 @@ var require_phoenix_cjs = __commonJS((exports, module) => {
2097
2112
  },
2098
2113
  binaryEncode(message) {
2099
2114
  let { join_ref, ref, event, topic, payload } = message;
2100
- let metaLength = this.META_LENGTH + join_ref.length + ref.length + topic.length + event.length;
2115
+ let encoder = new TextEncoder;
2116
+ let joinRefBytes = encoder.encode(join_ref);
2117
+ let refBytes = encoder.encode(ref);
2118
+ let topicBytes = encoder.encode(topic);
2119
+ let eventBytes = encoder.encode(event);
2120
+ this.assertFieldSize(joinRefBytes.byteLength, "join_ref");
2121
+ this.assertFieldSize(refBytes.byteLength, "ref");
2122
+ this.assertFieldSize(topicBytes.byteLength, "topic");
2123
+ this.assertFieldSize(eventBytes.byteLength, "event");
2124
+ let metaLength = this.META_LENGTH + joinRefBytes.byteLength + refBytes.byteLength + topicBytes.byteLength + eventBytes.byteLength;
2101
2125
  let header = new ArrayBuffer(this.HEADER_LENGTH + metaLength);
2126
+ let headerBytes = new Uint8Array(header);
2102
2127
  let view = new DataView(header);
2103
2128
  let offset = 0;
2104
2129
  view.setUint8(offset++, this.KINDS.push);
2105
- view.setUint8(offset++, join_ref.length);
2106
- view.setUint8(offset++, ref.length);
2107
- view.setUint8(offset++, topic.length);
2108
- view.setUint8(offset++, event.length);
2109
- Array.from(join_ref, (char) => view.setUint8(offset++, char.charCodeAt(0)));
2110
- Array.from(ref, (char) => view.setUint8(offset++, char.charCodeAt(0)));
2111
- Array.from(topic, (char) => view.setUint8(offset++, char.charCodeAt(0)));
2112
- Array.from(event, (char) => view.setUint8(offset++, char.charCodeAt(0)));
2130
+ view.setUint8(offset++, joinRefBytes.byteLength);
2131
+ view.setUint8(offset++, refBytes.byteLength);
2132
+ view.setUint8(offset++, topicBytes.byteLength);
2133
+ view.setUint8(offset++, eventBytes.byteLength);
2134
+ headerBytes.set(joinRefBytes, offset);
2135
+ offset += joinRefBytes.byteLength;
2136
+ headerBytes.set(refBytes, offset);
2137
+ offset += refBytes.byteLength;
2138
+ headerBytes.set(topicBytes, offset);
2139
+ offset += topicBytes.byteLength;
2140
+ headerBytes.set(eventBytes, offset);
2141
+ offset += eventBytes.byteLength;
2113
2142
  var combined = new Uint8Array(header.byteLength + payload.byteLength);
2114
- combined.set(new Uint8Array(header), 0);
2143
+ combined.set(headerBytes, 0);
2115
2144
  combined.set(new Uint8Array(payload), header.byteLength);
2116
2145
  return combined.buffer;
2117
2146
  },
2147
+ assertFieldSize(size, name) {
2148
+ if (size > 255) {
2149
+ throw new Error(`unable to convert ${name} to binary: must be less than or equal to 255 bytes, but is ${size} bytes`);
2150
+ }
2151
+ },
2118
2152
  binaryDecode(buffer) {
2119
2153
  let view = new DataView(buffer);
2120
2154
  let kind = view.getUint8(0);
@@ -2185,7 +2219,11 @@ var require_phoenix_cjs = __commonJS((exports, module) => {
2185
2219
  this.primaryPassedHealthCheck = false;
2186
2220
  this.longPollFallbackMs = opts.longPollFallbackMs;
2187
2221
  this.fallbackTimer = null;
2188
- this.sessionStore = opts.sessionStorage || global2 && global2.sessionStorage;
2222
+ let envSessionStorage = null;
2223
+ try {
2224
+ envSessionStorage = global2 && global2.sessionStorage;
2225
+ } catch {}
2226
+ this.sessionStore = opts.sessionStorage || envSessionStorage;
2189
2227
  this.establishedConnections = 0;
2190
2228
  this.defaultEncoder = serializer_default.encode.bind(serializer_default);
2191
2229
  this.defaultDecoder = serializer_default.decode.bind(serializer_default);
@@ -2271,7 +2309,7 @@ var require_phoenix_cjs = __commonJS((exports, module) => {
2271
2309
  this.connect();
2272
2310
  });
2273
2311
  }, this.reconnectAfterMs);
2274
- this.authToken = opts.authToken;
2312
+ this.authToken = opts.authToken && closure(opts.authToken);
2275
2313
  }
2276
2314
  getLongPollTransport() {
2277
2315
  return LongPoll;
@@ -2382,7 +2420,7 @@ var require_phoenix_cjs = __commonJS((exports, module) => {
2382
2420
  this.closeWasClean = false;
2383
2421
  let protocols = undefined;
2384
2422
  if (this.authToken) {
2385
- protocols = ["phoenix", `${AUTH_TOKEN_PREFIX}${btoa(this.authToken).replace(/=/g, "")}`];
2423
+ protocols = ["phoenix", `${AUTH_TOKEN_PREFIX}${btoa(this.authToken()).replace(/=/g, "")}`];
2386
2424
  }
2387
2425
  this.conn = new this.transport(this.endPointURL(), protocols);
2388
2426
  this.conn.binaryType = this.binaryType;
@@ -2912,10 +2950,100 @@ var require_channelAdapter = __commonJS((exports) => {
2912
2950
  }
2913
2951
  });
2914
2952
 
2953
+ // node_modules/@supabase/realtime-js/dist/main/RealtimePostgresFilterBuilder.js
2954
+ var require_RealtimePostgresFilterBuilder = __commonJS((exports) => {
2955
+ Object.defineProperty(exports, "__esModule", { value: true });
2956
+ exports.postgresChangesFilter = exports.RealtimePostgresFilterBuilder = undefined;
2957
+ var PostgrestReservedCharsRegexp2 = /[,()"\\]/;
2958
+ var needsQuoting = (value) => PostgrestReservedCharsRegexp2.test(value) || value !== value.trim();
2959
+ var quote = (value) => `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
2960
+ var serializeScalar = (value) => {
2961
+ const serialized = value === null ? "null" : String(value);
2962
+ return needsQuoting(serialized) ? quote(serialized) : serialized;
2963
+ };
2964
+ var serializeIsValue = (value) => value === null ? "null" : String(value);
2965
+ var serialize = (operator, value) => {
2966
+ if (operator === "in") {
2967
+ const values = Array.isArray(value) ? value : [value];
2968
+ if (values.length === 0) {
2969
+ throw new Error("Realtime `in` filter requires at least one value.");
2970
+ }
2971
+ const items = Array.from(new Set(values)).map((v) => serializeScalar(v)).join(",");
2972
+ return `in.(${items})`;
2973
+ }
2974
+ if (operator === "is") {
2975
+ return `is.${serializeIsValue(value)}`;
2976
+ }
2977
+ return `${operator}.${serializeScalar(value)}`;
2978
+ };
2979
+
2980
+ class RealtimePostgresFilterBuilder {
2981
+ constructor() {
2982
+ this.filters = [];
2983
+ }
2984
+ add(column, operator, value, negate = false) {
2985
+ const prefix = negate ? "not." : "";
2986
+ this.filters.push(`${column}=${prefix}${serialize(operator, value)}`);
2987
+ return this;
2988
+ }
2989
+ eq(column, value) {
2990
+ return this.add(column, "eq", value);
2991
+ }
2992
+ neq(column, value) {
2993
+ return this.add(column, "neq", value);
2994
+ }
2995
+ gt(column, value) {
2996
+ return this.add(column, "gt", value);
2997
+ }
2998
+ gte(column, value) {
2999
+ return this.add(column, "gte", value);
3000
+ }
3001
+ lt(column, value) {
3002
+ return this.add(column, "lt", value);
3003
+ }
3004
+ lte(column, value) {
3005
+ return this.add(column, "lte", value);
3006
+ }
3007
+ in(column, values) {
3008
+ return this.add(column, "in", values);
3009
+ }
3010
+ like(column, pattern) {
3011
+ return this.add(column, "like", pattern);
3012
+ }
3013
+ ilike(column, pattern) {
3014
+ return this.add(column, "ilike", pattern);
3015
+ }
3016
+ match(column, pattern) {
3017
+ return this.add(column, "match", pattern);
3018
+ }
3019
+ imatch(column, pattern) {
3020
+ return this.add(column, "imatch", pattern);
3021
+ }
3022
+ is(column, value) {
3023
+ return this.add(column, "is", value);
3024
+ }
3025
+ isDistinct(column, value) {
3026
+ return this.add(column, "isdistinct", value);
3027
+ }
3028
+ not(column, operator, value) {
3029
+ return this.add(column, operator, value, true);
3030
+ }
3031
+ build() {
3032
+ return this.filters.join(",");
3033
+ }
3034
+ toString() {
3035
+ return this.build();
3036
+ }
3037
+ }
3038
+ exports.RealtimePostgresFilterBuilder = RealtimePostgresFilterBuilder;
3039
+ var postgresChangesFilter = () => new RealtimePostgresFilterBuilder;
3040
+ exports.postgresChangesFilter = postgresChangesFilter;
3041
+ });
3042
+
2915
3043
  // node_modules/@supabase/realtime-js/dist/main/RealtimeChannel.js
2916
3044
  var require_RealtimeChannel = __commonJS((exports) => {
2917
3045
  Object.defineProperty(exports, "__esModule", { value: true });
2918
- exports.REALTIME_CHANNEL_STATES = exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_LISTEN_TYPES = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = undefined;
3046
+ exports.REALTIME_CHANNEL_STATES = exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_LISTEN_TYPES = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = exports.postgresChangesFilter = exports.RealtimePostgresFilterBuilder = undefined;
2919
3047
  var tslib_1 = require_tslib();
2920
3048
  var constants_1 = require_constants();
2921
3049
  var RealtimePresence_1 = tslib_1.__importDefault(require_RealtimePresence());
@@ -2923,6 +3051,14 @@ var require_RealtimeChannel = __commonJS((exports) => {
2923
3051
  var transformers_1 = require_transformers();
2924
3052
  var normalizeChannelError_1 = require_normalizeChannelError();
2925
3053
  var channelAdapter_1 = tslib_1.__importDefault(require_channelAdapter());
3054
+ var RealtimePostgresFilterBuilder_1 = require_RealtimePostgresFilterBuilder();
3055
+ var RealtimePostgresFilterBuilder_2 = require_RealtimePostgresFilterBuilder();
3056
+ Object.defineProperty(exports, "RealtimePostgresFilterBuilder", { enumerable: true, get: function() {
3057
+ return RealtimePostgresFilterBuilder_2.RealtimePostgresFilterBuilder;
3058
+ } });
3059
+ Object.defineProperty(exports, "postgresChangesFilter", { enumerable: true, get: function() {
3060
+ return RealtimePostgresFilterBuilder_2.postgresChangesFilter;
3061
+ } });
2926
3062
  var REALTIME_POSTGRES_CHANGES_LISTEN_EVENT;
2927
3063
  (function(REALTIME_POSTGRES_CHANGES_LISTEN_EVENT2) {
2928
3064
  REALTIME_POSTGRES_CHANGES_LISTEN_EVENT2["ALL"] = "*";
@@ -3064,7 +3200,7 @@ var require_RealtimeChannel = __commonJS((exports) => {
3064
3200
  type: "presence",
3065
3201
  event: "track",
3066
3202
  payload
3067
- }, opts.timeout || this.timeout);
3203
+ }, opts);
3068
3204
  }
3069
3205
  async untrack(opts = {}) {
3070
3206
  return await this.send({
@@ -3086,31 +3222,31 @@ var require_RealtimeChannel = __commonJS((exports) => {
3086
3222
  if (payload === undefined || payload === null) {
3087
3223
  return Promise.reject(new Error("Payload is required for httpSend()"));
3088
3224
  }
3225
+ const isBinary = payload instanceof ArrayBuffer || ArrayBuffer.isView(payload);
3089
3226
  const headers = {
3090
3227
  apikey: this.socket.apiKey ? this.socket.apiKey : "",
3091
- "Content-Type": "application/json"
3228
+ "Content-Type": isBinary ? "application/octet-stream" : "application/json"
3092
3229
  };
3093
3230
  if (this.socket.accessTokenValue) {
3094
3231
  headers["Authorization"] = `Bearer ${this.socket.accessTokenValue}`;
3095
3232
  }
3233
+ const url = new URL(this.broadcastEndpointURL);
3234
+ url.pathname += `/${encodeURIComponent(this.subTopic)}/events/${encodeURIComponent(event)}`;
3235
+ if (this.private) {
3236
+ url.searchParams.set("private", "true");
3237
+ }
3096
3238
  const options = {
3097
3239
  method: "POST",
3098
3240
  headers,
3099
- body: JSON.stringify({
3100
- messages: [
3101
- {
3102
- topic: this.subTopic,
3103
- event,
3104
- payload,
3105
- private: this.private
3106
- }
3107
- ]
3108
- })
3241
+ body: isBinary ? payload : JSON.stringify(payload)
3109
3242
  };
3110
- const response = await this._fetchWithTimeout(this.broadcastEndpointURL, options, (_a = opts.timeout) !== null && _a !== undefined ? _a : this.timeout);
3243
+ const response = await this._fetchWithTimeout(url.toString(), options, (_a = opts.timeout) !== null && _a !== undefined ? _a : this.timeout);
3111
3244
  if (response.status === 202) {
3112
3245
  return { success: true };
3113
3246
  }
3247
+ if (response.status === 404) {
3248
+ return Promise.reject(new Error("httpSend() requires Realtime server v2.97.0 or newer; the endpoint returned 404. " + "Update your Supabase CLI to a recent version, or upgrade the Realtime server in your self-hosted setup. " + "See https://github.com/supabase/supabase-js/blob/master/packages/core/realtime-js/migrations/httpsend-server-version.md"));
3249
+ }
3114
3250
  let errorMessage = response.statusText;
3115
3251
  try {
3116
3252
  const errorBody = await response.json();
@@ -3149,7 +3285,7 @@ var require_RealtimeChannel = __commonJS((exports) => {
3149
3285
  await ((_b = response.body) === null || _b === undefined ? undefined : _b.cancel());
3150
3286
  return response.ok ? "ok" : "error";
3151
3287
  } catch (error) {
3152
- if (error.name === "AbortError") {
3288
+ if (error instanceof Error && error.name === "AbortError") {
3153
3289
  return "timed out";
3154
3290
  } else {
3155
3291
  return "error";
@@ -3188,6 +3324,10 @@ var require_RealtimeChannel = __commonJS((exports) => {
3188
3324
  }
3189
3325
  _on(type, filter, callback) {
3190
3326
  const typeLower = type.toLocaleLowerCase();
3327
+ const filterValue = filter === null || filter === undefined ? undefined : filter.filter;
3328
+ if (filterValue instanceof RealtimePostgresFilterBuilder_1.RealtimePostgresFilterBuilder || typeof filterValue === "object" && filterValue !== null && typeof filterValue.build === "function") {
3329
+ filter = Object.assign(Object.assign({}, filter), { filter: filterValue.build() });
3330
+ }
3191
3331
  const ref = this.channelAdapter.on(type, callback);
3192
3332
  const binding = {
3193
3333
  type: typeLower,
@@ -3420,6 +3560,38 @@ var require_RealtimeClient = __commonJS((exports) => {
3420
3560
  };
3421
3561
  var RECONNECT_INTERVALS = [1000, 2000, 5000, 1e4];
3422
3562
  var DEFAULT_RECONNECT_FALLBACK = 1e4;
3563
+ function createMemorySessionStorage() {
3564
+ const store = new Map;
3565
+ return {
3566
+ get length() {
3567
+ return store.size;
3568
+ },
3569
+ clear() {
3570
+ store.clear();
3571
+ },
3572
+ getItem(key) {
3573
+ return store.has(key) ? store.get(key) : null;
3574
+ },
3575
+ key(index) {
3576
+ var _a;
3577
+ return (_a = Array.from(store.keys())[index]) !== null && _a !== undefined ? _a : null;
3578
+ },
3579
+ removeItem(key) {
3580
+ store.delete(key);
3581
+ },
3582
+ setItem(key, value) {
3583
+ store.set(key, String(value));
3584
+ }
3585
+ };
3586
+ }
3587
+ function resolveSessionStorage() {
3588
+ try {
3589
+ if (typeof globalThis !== "undefined" && globalThis.sessionStorage) {
3590
+ return globalThis.sessionStorage;
3591
+ }
3592
+ } catch (_a) {}
3593
+ return createMemorySessionStorage();
3594
+ }
3423
3595
  var WORKER_SCRIPT = `
3424
3596
  addEventListener("message", (e) => {
3425
3597
  if (e.data.event === "start") {
@@ -3520,22 +3692,6 @@ var require_RealtimeClient = __commonJS((exports) => {
3520
3692
  this.socketAdapter.connect();
3521
3693
  } catch (error) {
3522
3694
  const errorMessage = error.message;
3523
- if (errorMessage.includes("Node.js")) {
3524
- throw new Error(`${errorMessage}
3525
-
3526
- ` + `To use Realtime in Node.js, you need to provide a WebSocket implementation:
3527
-
3528
- ` + `Option 1: Use Node.js 22+ which has native WebSocket support
3529
- ` + `Option 2: Install and provide the "ws" package:
3530
-
3531
- ` + ` npm install ws
3532
-
3533
- ` + ` import ws from "ws"
3534
- ` + ` const client = new RealtimeClient(url, {
3535
- ` + ` ...options,
3536
- ` + ` transport: ws
3537
- ` + " })");
3538
- }
3539
3695
  throw new Error(`WebSocket not available: ${errorMessage}`);
3540
3696
  }
3541
3697
  this._handleNodeJsRaceCondition();
@@ -3730,6 +3886,8 @@ var require_RealtimeClient = __commonJS((exports) => {
3730
3886
  }
3731
3887
  _wrapHeartbeatCallback(heartbeatCallback) {
3732
3888
  return (status, latency) => {
3889
+ if (status === "disconnected")
3890
+ return;
3733
3891
  if (status == "sent")
3734
3892
  this._setAuthSafely();
3735
3893
  if (heartbeatCallback)
@@ -3777,7 +3935,7 @@ var require_RealtimeClient = __commonJS((exports) => {
3777
3935
  return result_url;
3778
3936
  }
3779
3937
  _initializeOptions(options) {
3780
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
3938
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
3781
3939
  this.worker = (_a = options === null || options === undefined ? undefined : options.worker) !== null && _a !== undefined ? _a : false;
3782
3940
  this.accessToken = (_b = options === null || options === undefined ? undefined : options.accessToken) !== null && _b !== undefined ? _b : null;
3783
3941
  const result = {};
@@ -3788,12 +3946,13 @@ var require_RealtimeClient = __commonJS((exports) => {
3788
3946
  result.params = options === null || options === undefined ? undefined : options.params;
3789
3947
  result.logger = options === null || options === undefined ? undefined : options.logger;
3790
3948
  result.heartbeatCallback = this._wrapHeartbeatCallback(options === null || options === undefined ? undefined : options.heartbeatCallback);
3791
- result.reconnectAfterMs = (_h = options === null || options === undefined ? undefined : options.reconnectAfterMs) !== null && _h !== undefined ? _h : (tries) => {
3949
+ result.sessionStorage = (_h = options === null || options === undefined ? undefined : options.sessionStorage) !== null && _h !== undefined ? _h : resolveSessionStorage();
3950
+ result.reconnectAfterMs = (_j = options === null || options === undefined ? undefined : options.reconnectAfterMs) !== null && _j !== undefined ? _j : (tries) => {
3792
3951
  return RECONNECT_INTERVALS[tries - 1] || DEFAULT_RECONNECT_FALLBACK;
3793
3952
  };
3794
3953
  let defaultEncode;
3795
3954
  let defaultDecode;
3796
- const vsn = (_j = options === null || options === undefined ? undefined : options.vsn) !== null && _j !== undefined ? _j : constants_1.DEFAULT_VSN;
3955
+ const vsn = (_k = options === null || options === undefined ? undefined : options.vsn) !== null && _k !== undefined ? _k : constants_1.DEFAULT_VSN;
3797
3956
  switch (vsn) {
3798
3957
  case constants_1.VSN_1_0_0:
3799
3958
  defaultEncode = (payload, callback) => {
@@ -3811,8 +3970,8 @@ var require_RealtimeClient = __commonJS((exports) => {
3811
3970
  throw new Error(`Unsupported serializer version: ${result.vsn}`);
3812
3971
  }
3813
3972
  result.vsn = vsn;
3814
- result.encode = (_k = options === null || options === undefined ? undefined : options.encode) !== null && _k !== undefined ? _k : defaultEncode;
3815
- result.decode = (_l = options === null || options === undefined ? undefined : options.decode) !== null && _l !== undefined ? _l : defaultDecode;
3973
+ result.encode = (_l = options === null || options === undefined ? undefined : options.encode) !== null && _l !== undefined ? _l : defaultEncode;
3974
+ result.decode = (_m = options === null || options === undefined ? undefined : options.decode) !== null && _m !== undefined ? _m : defaultDecode;
3816
3975
  result.beforeReconnect = this._reconnectAuth.bind(this);
3817
3976
  if ((options === null || options === undefined ? undefined : options.logLevel) || (options === null || options === undefined ? undefined : options.log_level)) {
3818
3977
  this.logLevel = options.logLevel || options.log_level;
@@ -3840,12 +3999,18 @@ var require_RealtimeClient = __commonJS((exports) => {
3840
3999
  // node_modules/@supabase/realtime-js/dist/main/index.js
3841
4000
  var require_main2 = __commonJS((exports) => {
3842
4001
  Object.defineProperty(exports, "__esModule", { value: true });
3843
- exports.WebSocketFactory = exports.REALTIME_CHANNEL_STATES = exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_PRESENCE_LISTEN_EVENTS = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = exports.REALTIME_LISTEN_TYPES = exports.RealtimeClient = exports.RealtimeChannel = exports.RealtimePresence = undefined;
4002
+ exports.WebSocketFactory = exports.REALTIME_CHANNEL_STATES = exports.REALTIME_SUBSCRIBE_STATES = exports.REALTIME_PRESENCE_LISTEN_EVENTS = exports.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT = exports.REALTIME_LISTEN_TYPES = exports.postgresChangesFilter = exports.RealtimePostgresFilterBuilder = exports.RealtimeClient = exports.RealtimeChannel = exports.RealtimePresence = undefined;
3844
4003
  var tslib_1 = require_tslib();
3845
4004
  var RealtimeClient_1 = tslib_1.__importDefault(require_RealtimeClient());
3846
4005
  exports.RealtimeClient = RealtimeClient_1.default;
3847
4006
  var RealtimeChannel_1 = tslib_1.__importStar(require_RealtimeChannel());
3848
4007
  exports.RealtimeChannel = RealtimeChannel_1.default;
4008
+ Object.defineProperty(exports, "RealtimePostgresFilterBuilder", { enumerable: true, get: function() {
4009
+ return RealtimeChannel_1.RealtimePostgresFilterBuilder;
4010
+ } });
4011
+ Object.defineProperty(exports, "postgresChangesFilter", { enumerable: true, get: function() {
4012
+ return RealtimeChannel_1.postgresChangesFilter;
4013
+ } });
3849
4014
  Object.defineProperty(exports, "REALTIME_LISTEN_TYPES", { enumerable: true, get: function() {
3850
4015
  return RealtimeChannel_1.REALTIME_LISTEN_TYPES;
3851
4016
  } });
@@ -3871,17 +4036,18 @@ var require_main2 = __commonJS((exports) => {
3871
4036
  var require_version2 = __commonJS((exports) => {
3872
4037
  Object.defineProperty(exports, "__esModule", { value: true });
3873
4038
  exports.version = undefined;
3874
- exports.version = "2.105.1";
4039
+ exports.version = "2.110.7";
3875
4040
  });
3876
4041
 
3877
4042
  // node_modules/@supabase/auth-js/dist/main/lib/constants.js
3878
4043
  var require_constants2 = __commonJS((exports) => {
3879
4044
  Object.defineProperty(exports, "__esModule", { value: true });
3880
- exports.JWKS_TTL = exports.BASE64URL_REGEX = exports.API_VERSIONS = exports.API_VERSION_HEADER_NAME = exports.NETWORK_FAILURE = exports.DEFAULT_HEADERS = exports.AUDIENCE = exports.STORAGE_KEY = exports.GOTRUE_URL = exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD = exports.AUTO_REFRESH_TICK_DURATION_MS = undefined;
4045
+ exports.JWKS_TTL = exports.BASE64URL_REGEX = exports.API_VERSIONS = exports.API_VERSION_HEADER_NAME = exports.NETWORK_FAILURE = exports.DEFAULT_HEADERS = exports.AUDIENCE = exports.STORAGE_KEY = exports.GOTRUE_URL = exports.REFRESH_FAILURE_COOLDOWN_MS = exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD = exports.AUTO_REFRESH_TICK_DURATION_MS = undefined;
3881
4046
  var version_1 = require_version2();
3882
4047
  exports.AUTO_REFRESH_TICK_DURATION_MS = 30 * 1000;
3883
4048
  exports.AUTO_REFRESH_TICK_THRESHOLD = 3;
3884
4049
  exports.EXPIRY_MARGIN_MS = exports.AUTO_REFRESH_TICK_THRESHOLD * exports.AUTO_REFRESH_TICK_DURATION_MS;
4050
+ exports.REFRESH_FAILURE_COOLDOWN_MS = 2 * exports.AUTO_REFRESH_TICK_DURATION_MS;
3885
4051
  exports.GOTRUE_URL = "http://localhost:9999";
3886
4052
  exports.STORAGE_KEY = "supabase.auth.token";
3887
4053
  exports.AUDIENCE = "";
@@ -3904,13 +4070,14 @@ var require_constants2 = __commonJS((exports) => {
3904
4070
  // node_modules/@supabase/auth-js/dist/main/lib/errors.js
3905
4071
  var require_errors = __commonJS((exports) => {
3906
4072
  Object.defineProperty(exports, "__esModule", { value: true });
3907
- exports.AuthInvalidJwtError = exports.AuthWeakPasswordError = exports.AuthRetryableFetchError = exports.AuthPKCECodeVerifierMissingError = exports.AuthPKCEGrantCodeExchangeError = exports.AuthImplicitGrantRedirectError = exports.AuthInvalidCredentialsError = exports.AuthInvalidTokenResponseError = exports.AuthSessionMissingError = exports.CustomAuthError = exports.AuthUnknownError = exports.AuthApiError = exports.AuthError = undefined;
4073
+ exports.AuthInvalidJwtError = exports.AuthWeakPasswordError = exports.AuthRefreshDiscardedError = exports.AuthRetryableFetchError = exports.AuthPKCECodeVerifierMissingError = exports.AuthPKCEGrantCodeExchangeError = exports.AuthImplicitGrantRedirectError = exports.AuthInvalidCredentialsError = exports.AuthInvalidTokenResponseError = exports.AuthSessionMissingError = exports.CustomAuthError = exports.AuthUnknownError = exports.AuthApiError = exports.AuthError = undefined;
3908
4074
  exports.isAuthError = isAuthError;
3909
4075
  exports.isAuthApiError = isAuthApiError;
3910
4076
  exports.isAuthSessionMissingError = isAuthSessionMissingError;
3911
4077
  exports.isAuthImplicitGrantRedirectError = isAuthImplicitGrantRedirectError;
3912
4078
  exports.isAuthPKCECodeVerifierMissingError = isAuthPKCECodeVerifierMissingError;
3913
4079
  exports.isAuthRetryableFetchError = isAuthRetryableFetchError;
4080
+ exports.isAuthRefreshDiscardedError = isAuthRefreshDiscardedError;
3914
4081
  exports.isAuthWeakPasswordError = isAuthWeakPasswordError;
3915
4082
 
3916
4083
  class AuthError extends Error {
@@ -4037,6 +4204,16 @@ var require_errors = __commonJS((exports) => {
4037
4204
  return isAuthError(error) && error.name === "AuthRetryableFetchError";
4038
4205
  }
4039
4206
 
4207
+ class AuthRefreshDiscardedError extends CustomAuthError {
4208
+ constructor(message = "Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)") {
4209
+ super(message, "AuthRefreshDiscardedError", 409, undefined);
4210
+ }
4211
+ }
4212
+ exports.AuthRefreshDiscardedError = AuthRefreshDiscardedError;
4213
+ function isAuthRefreshDiscardedError(error) {
4214
+ return isAuthError(error) && error.name === "AuthRefreshDiscardedError";
4215
+ }
4216
+
4040
4217
  class AuthWeakPasswordError extends CustomAuthError {
4041
4218
  constructor(message, status, reasons) {
4042
4219
  super(message, "AuthWeakPasswordError", status, "weak_password");
@@ -4320,7 +4497,7 @@ var require_helpers = __commonJS((exports) => {
4320
4497
  hashSearchParams.forEach((value, key) => {
4321
4498
  result[key] = value;
4322
4499
  });
4323
- } catch (e) {}
4500
+ } catch (_e) {}
4324
4501
  }
4325
4502
  url.searchParams.forEach((value, key) => {
4326
4503
  result[key] = value;
@@ -4350,7 +4527,7 @@ var require_helpers = __commonJS((exports) => {
4350
4527
  try {
4351
4528
  return JSON.parse(value);
4352
4529
  } catch (_a) {
4353
- return value;
4530
+ return null;
4354
4531
  }
4355
4532
  };
4356
4533
  exports.getItemAsync = getItemAsync;
@@ -4473,7 +4650,7 @@ var require_helpers = __commonJS((exports) => {
4473
4650
  try {
4474
4651
  const date = new Date(`${apiVersion}T00:00:00.0Z`);
4475
4652
  return date;
4476
- } catch (e) {
4653
+ } catch (_e) {
4477
4654
  return null;
4478
4655
  }
4479
4656
  }
@@ -4577,8 +4754,38 @@ var require_fetch = __commonJS((exports) => {
4577
4754
  var constants_1 = require_constants2();
4578
4755
  var helpers_1 = require_helpers();
4579
4756
  var errors_1 = require_errors();
4580
- var _getErrorMessage2 = (err) => err.msg || err.message || err.error_description || err.error || JSON.stringify(err);
4581
- var NETWORK_ERROR_CODES = [502, 503, 504, 520, 521, 522, 523, 524, 530];
4757
+ var _getErrorMessage2 = (err) => {
4758
+ if (typeof err === "object" && err !== null) {
4759
+ const e = err;
4760
+ if (typeof e.msg === "string")
4761
+ return e.msg;
4762
+ if (typeof e.message === "string")
4763
+ return e.message;
4764
+ if (typeof e.error_description === "string")
4765
+ return e.error_description;
4766
+ if (typeof e.error === "string")
4767
+ return e.error;
4768
+ }
4769
+ return JSON.stringify(err);
4770
+ };
4771
+ var NETWORK_ERROR_CODES = [
4772
+ 500,
4773
+ 501,
4774
+ 502,
4775
+ 503,
4776
+ 504,
4777
+ 520,
4778
+ 521,
4779
+ 522,
4780
+ 523,
4781
+ 524,
4782
+ 525,
4783
+ 526,
4784
+ 527,
4785
+ 528,
4786
+ 529,
4787
+ 530
4788
+ ];
4582
4789
  async function handleError2(error) {
4583
4790
  var _a;
4584
4791
  if (!(0, helpers_1.looksLikeFetchResponse)(error)) {
@@ -4670,7 +4877,7 @@ var require_fetch = __commonJS((exports) => {
4670
4877
  session.expires_at = (0, helpers_1.expiresAt)(data.expires_in);
4671
4878
  }
4672
4879
  }
4673
- const user = (_a = data.user) !== null && _a !== undefined ? _a : data;
4880
+ const user = (_a = data.user) !== null && _a !== undefined ? _a : typeof (data === null || data === undefined ? undefined : data.id) === "string" ? data : null;
4674
4881
  return { data: { session, user }, error: null };
4675
4882
  }
4676
4883
  function _sessionResponsePassword(data) {
@@ -4710,7 +4917,7 @@ var require_fetch = __commonJS((exports) => {
4710
4917
  return data;
4711
4918
  }
4712
4919
  function hasSession(data) {
4713
- return data.access_token && data.refresh_token && data.expires_in;
4920
+ return !!data.access_token && !!data.refresh_token && !!data.expires_in;
4714
4921
  }
4715
4922
  });
4716
4923
 
@@ -5273,7 +5480,7 @@ var require_locks = __commonJS((exports) => {
5273
5480
  if (acquireTimeout > 0) {
5274
5481
  clearTimeout(acquireTimeoutTimer);
5275
5482
  }
5276
- if ((e === null || e === undefined ? undefined : e.name) === "AbortError" && acquireTimeout > 0) {
5483
+ if (e !== null && typeof e === "object" && "name" in e && e.name === "AbortError" && acquireTimeout > 0) {
5277
5484
  if (abortController.signal.aborted) {
5278
5485
  if (exports.internals.debug) {
5279
5486
  console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock", name);
@@ -5338,7 +5545,7 @@ var require_locks = __commonJS((exports) => {
5338
5545
  if (timeoutId !== null) {
5339
5546
  clearTimeout(timeoutId);
5340
5547
  }
5341
- if (e && e.isAcquireTimeout) {
5548
+ if (e instanceof LockAcquireTimeoutError) {
5342
5549
  throw e;
5343
5550
  }
5344
5551
  }
@@ -5348,7 +5555,7 @@ var require_locks = __commonJS((exports) => {
5348
5555
  try {
5349
5556
  return await currentOperation;
5350
5557
  } catch (e) {
5351
- if (e && e.isAcquireTimeout) {
5558
+ if (e instanceof LockAcquireTimeoutError) {
5352
5559
  try {
5353
5560
  await previousOperation;
5354
5561
  } catch (prevError) {}
@@ -5479,6 +5686,13 @@ var require_webauthn_errors = __commonJS((exports) => {
5479
5686
  this.name = (_a = name !== null && name !== undefined ? name : cause instanceof Error ? cause.name : undefined) !== null && _a !== undefined ? _a : "Unknown Error";
5480
5687
  this.code = code;
5481
5688
  }
5689
+ toJSON() {
5690
+ return {
5691
+ name: this.name,
5692
+ message: this.message,
5693
+ code: this.code
5694
+ };
5695
+ }
5482
5696
  }
5483
5697
  exports.WebAuthnError = WebAuthnError;
5484
5698
 
@@ -6128,9 +6342,6 @@ var require_GoTrueClient = __commonJS((exports) => {
6128
6342
  skipAutoInitialize: false,
6129
6343
  experimental: {}
6130
6344
  };
6131
- async function lockNoOp(name, acquireTimeout, fn) {
6132
- return await fn();
6133
- }
6134
6345
  var GLOBAL_JWKS = {};
6135
6346
 
6136
6347
  class GoTrueClient {
@@ -6149,7 +6360,7 @@ var require_GoTrueClient = __commonJS((exports) => {
6149
6360
  GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { cachedAt: value });
6150
6361
  }
6151
6362
  constructor(options) {
6152
- var _a, _b, _c, _d;
6363
+ var _a, _b, _c;
6153
6364
  this.userStorage = null;
6154
6365
  this.memoryStorage = null;
6155
6366
  this.stateChangeEmitters = new Map;
@@ -6157,10 +6368,14 @@ var require_GoTrueClient = __commonJS((exports) => {
6157
6368
  this.autoRefreshTickTimeout = null;
6158
6369
  this.visibilityChangedCallback = null;
6159
6370
  this.refreshingDeferred = null;
6371
+ this.lastRefreshFailure = null;
6372
+ this._sessionRemovalEpoch = 0;
6160
6373
  this.initializePromise = null;
6374
+ this._pendingInitNotifications = null;
6161
6375
  this.detectSessionInUrl = true;
6162
6376
  this.hasCustomAuthorizationHeader = false;
6163
6377
  this.suppressGetSessionWarning = false;
6378
+ this.lock = null;
6164
6379
  this.lockAcquired = false;
6165
6380
  this.pendingInLock = [];
6166
6381
  this.broadcastChannel = null;
@@ -6192,18 +6407,13 @@ var require_GoTrueClient = __commonJS((exports) => {
6192
6407
  this.url = settings.url;
6193
6408
  this.headers = settings.headers;
6194
6409
  this.fetch = (0, helpers_1.resolveFetch)(settings.fetch);
6195
- this.lock = settings.lock || lockNoOp;
6196
6410
  this.detectSessionInUrl = settings.detectSessionInUrl;
6197
6411
  this.flowType = settings.flowType;
6198
6412
  this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader;
6199
6413
  this.throwOnError = settings.throwOnError;
6200
6414
  this.lockAcquireTimeout = settings.lockAcquireTimeout;
6201
- if (settings.lock) {
6415
+ if (settings.lock != null) {
6202
6416
  this.lock = settings.lock;
6203
- } else if (this.persistSession && (0, helpers_1.isBrowser)() && ((_c = globalThis === null || globalThis === undefined ? undefined : globalThis.navigator) === null || _c === undefined ? undefined : _c.locks)) {
6204
- this.lock = locks_1.navigatorLock;
6205
- } else {
6206
- this.lock = lockNoOp;
6207
6417
  }
6208
6418
  if (!this.jwks) {
6209
6419
  this.jwks = { keys: [] };
@@ -6259,8 +6469,11 @@ var require_GoTrueClient = __commonJS((exports) => {
6259
6469
  } catch (e) {
6260
6470
  console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available", e);
6261
6471
  }
6262
- (_d = this.broadcastChannel) === null || _d === undefined || _d.addEventListener("message", async (event) => {
6472
+ (_c = this.broadcastChannel) === null || _c === undefined || _c.addEventListener("message", async (event) => {
6263
6473
  this._debug("received broadcast notification from other tab or client", event);
6474
+ if (event.data.event === "TOKEN_REFRESHED" || event.data.event === "SIGNED_IN") {
6475
+ this.lastRefreshFailure = null;
6476
+ }
6264
6477
  try {
6265
6478
  await this._notifyAllSubscribers(event.data.event, event.data.session, false);
6266
6479
  } catch (error) {
@@ -6293,15 +6506,26 @@ var require_GoTrueClient = __commonJS((exports) => {
6293
6506
  return this;
6294
6507
  }
6295
6508
  async initialize() {
6509
+ var _a;
6296
6510
  if (this.initializePromise) {
6297
6511
  return await this.initializePromise;
6298
6512
  }
6513
+ this._pendingInitNotifications = [];
6299
6514
  this.initializePromise = (async () => {
6300
- return await this._acquireLock(this.lockAcquireTimeout, async () => {
6301
- return await this._initialize();
6302
- });
6515
+ if (this.lock != null) {
6516
+ return await this._acquireLock(this.lockAcquireTimeout, async () => {
6517
+ return await this._initialize();
6518
+ });
6519
+ }
6520
+ return await this._initialize();
6303
6521
  })();
6304
- return await this.initializePromise;
6522
+ const result = await this.initializePromise;
6523
+ const queue = (_a = this._pendingInitNotifications) !== null && _a !== undefined ? _a : [];
6524
+ this._pendingInitNotifications = null;
6525
+ for (const n of queue) {
6526
+ await this._notifyAllSubscribers(n.event, n.session, n.broadcast);
6527
+ }
6528
+ return result;
6305
6529
  }
6306
6530
  async _initialize() {
6307
6531
  var _a;
@@ -6504,9 +6728,12 @@ var require_GoTrueClient = __commonJS((exports) => {
6504
6728
  }
6505
6729
  async exchangeCodeForSession(authCode) {
6506
6730
  await this.initializePromise;
6507
- return this._acquireLock(this.lockAcquireTimeout, async () => {
6508
- return this._exchangeCodeForSession(authCode);
6509
- });
6731
+ if (this.lock != null) {
6732
+ return this._acquireLock(this.lockAcquireTimeout, async () => {
6733
+ return this._exchangeCodeForSession(authCode);
6734
+ });
6735
+ }
6736
+ return this._exchangeCodeForSession(authCode);
6510
6737
  }
6511
6738
  async signInWithWeb3(credentials) {
6512
6739
  const { chain } = credentials;
@@ -6520,7 +6747,7 @@ var require_GoTrueClient = __commonJS((exports) => {
6520
6747
  }
6521
6748
  }
6522
6749
  async signInWithEthereum(credentials) {
6523
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
6750
+ var _a, _b, _c, _d, _f, _g, _h, _j, _k, _l, _m;
6524
6751
  let message;
6525
6752
  let signature;
6526
6753
  if ("message" in credentials) {
@@ -6569,11 +6796,11 @@ var require_GoTrueClient = __commonJS((exports) => {
6569
6796
  version: "1",
6570
6797
  chainId,
6571
6798
  nonce: (_c = options === null || options === undefined ? undefined : options.signInWithEthereum) === null || _c === undefined ? undefined : _c.nonce,
6572
- issuedAt: (_e = (_d = options === null || options === undefined ? undefined : options.signInWithEthereum) === null || _d === undefined ? undefined : _d.issuedAt) !== null && _e !== undefined ? _e : new Date,
6573
- expirationTime: (_f = options === null || options === undefined ? undefined : options.signInWithEthereum) === null || _f === undefined ? undefined : _f.expirationTime,
6574
- notBefore: (_g = options === null || options === undefined ? undefined : options.signInWithEthereum) === null || _g === undefined ? undefined : _g.notBefore,
6575
- requestId: (_h = options === null || options === undefined ? undefined : options.signInWithEthereum) === null || _h === undefined ? undefined : _h.requestId,
6576
- resources: (_j = options === null || options === undefined ? undefined : options.signInWithEthereum) === null || _j === undefined ? undefined : _j.resources
6799
+ issuedAt: (_f = (_d = options === null || options === undefined ? undefined : options.signInWithEthereum) === null || _d === undefined ? undefined : _d.issuedAt) !== null && _f !== undefined ? _f : new Date,
6800
+ expirationTime: (_g = options === null || options === undefined ? undefined : options.signInWithEthereum) === null || _g === undefined ? undefined : _g.expirationTime,
6801
+ notBefore: (_h = options === null || options === undefined ? undefined : options.signInWithEthereum) === null || _h === undefined ? undefined : _h.notBefore,
6802
+ requestId: (_j = options === null || options === undefined ? undefined : options.signInWithEthereum) === null || _j === undefined ? undefined : _j.requestId,
6803
+ resources: (_k = options === null || options === undefined ? undefined : options.signInWithEthereum) === null || _k === undefined ? undefined : _k.resources
6577
6804
  };
6578
6805
  message = (0, ethereum_1.createSiweMessage)(siweMessage);
6579
6806
  signature = await resolvedWallet.request({
@@ -6588,7 +6815,7 @@ var require_GoTrueClient = __commonJS((exports) => {
6588
6815
  chain: "ethereum",
6589
6816
  message,
6590
6817
  signature
6591
- }, ((_k = credentials.options) === null || _k === undefined ? undefined : _k.captchaToken) ? { gotrue_meta_security: { captcha_token: (_l = credentials.options) === null || _l === undefined ? undefined : _l.captchaToken } } : null),
6818
+ }, ((_l = credentials.options) === null || _l === undefined ? undefined : _l.captchaToken) ? { gotrue_meta_security: { captcha_token: (_m = credentials.options) === null || _m === undefined ? undefined : _m.captchaToken } } : null),
6592
6819
  xform: fetch_1._sessionResponse
6593
6820
  });
6594
6821
  if (error) {
@@ -6611,7 +6838,7 @@ var require_GoTrueClient = __commonJS((exports) => {
6611
6838
  }
6612
6839
  }
6613
6840
  async signInWithSolana(credentials) {
6614
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
6841
+ var _a, _b, _c, _d, _f, _g, _h, _j, _k, _l, _m, _o;
6615
6842
  let message;
6616
6843
  let signature;
6617
6844
  if ("message" in credentials) {
@@ -6668,11 +6895,11 @@ var require_GoTrueClient = __commonJS((exports) => {
6668
6895
  `URI: ${url.href}`,
6669
6896
  `Issued At: ${(_c = (_b = options === null || options === undefined ? undefined : options.signInWithSolana) === null || _b === undefined ? undefined : _b.issuedAt) !== null && _c !== undefined ? _c : new Date().toISOString()}`,
6670
6897
  ...((_d = options === null || options === undefined ? undefined : options.signInWithSolana) === null || _d === undefined ? undefined : _d.notBefore) ? [`Not Before: ${options.signInWithSolana.notBefore}`] : [],
6671
- ...((_e = options === null || options === undefined ? undefined : options.signInWithSolana) === null || _e === undefined ? undefined : _e.expirationTime) ? [`Expiration Time: ${options.signInWithSolana.expirationTime}`] : [],
6672
- ...((_f = options === null || options === undefined ? undefined : options.signInWithSolana) === null || _f === undefined ? undefined : _f.chainId) ? [`Chain ID: ${options.signInWithSolana.chainId}`] : [],
6673
- ...((_g = options === null || options === undefined ? undefined : options.signInWithSolana) === null || _g === undefined ? undefined : _g.nonce) ? [`Nonce: ${options.signInWithSolana.nonce}`] : [],
6674
- ...((_h = options === null || options === undefined ? undefined : options.signInWithSolana) === null || _h === undefined ? undefined : _h.requestId) ? [`Request ID: ${options.signInWithSolana.requestId}`] : [],
6675
- ...((_k = (_j = options === null || options === undefined ? undefined : options.signInWithSolana) === null || _j === undefined ? undefined : _j.resources) === null || _k === undefined ? undefined : _k.length) ? [
6898
+ ...((_f = options === null || options === undefined ? undefined : options.signInWithSolana) === null || _f === undefined ? undefined : _f.expirationTime) ? [`Expiration Time: ${options.signInWithSolana.expirationTime}`] : [],
6899
+ ...((_g = options === null || options === undefined ? undefined : options.signInWithSolana) === null || _g === undefined ? undefined : _g.chainId) ? [`Chain ID: ${options.signInWithSolana.chainId}`] : [],
6900
+ ...((_h = options === null || options === undefined ? undefined : options.signInWithSolana) === null || _h === undefined ? undefined : _h.nonce) ? [`Nonce: ${options.signInWithSolana.nonce}`] : [],
6901
+ ...((_j = options === null || options === undefined ? undefined : options.signInWithSolana) === null || _j === undefined ? undefined : _j.requestId) ? [`Request ID: ${options.signInWithSolana.requestId}`] : [],
6902
+ ...((_l = (_k = options === null || options === undefined ? undefined : options.signInWithSolana) === null || _k === undefined ? undefined : _k.resources) === null || _l === undefined ? undefined : _l.length) ? [
6676
6903
  "Resources",
6677
6904
  ...options.signInWithSolana.resources.map((resource) => `- ${resource}`)
6678
6905
  ] : []
@@ -6688,7 +6915,7 @@ var require_GoTrueClient = __commonJS((exports) => {
6688
6915
  try {
6689
6916
  const { data, error } = await (0, fetch_1._request)(this.fetch, "POST", `${this.url}/token?grant_type=web3`, {
6690
6917
  headers: this.headers,
6691
- body: Object.assign({ chain: "solana", message, signature: (0, base64url_1.bytesToBase64URL)(signature) }, ((_l = credentials.options) === null || _l === undefined ? undefined : _l.captchaToken) ? { gotrue_meta_security: { captcha_token: (_m = credentials.options) === null || _m === undefined ? undefined : _m.captchaToken } } : null),
6918
+ body: Object.assign({ chain: "solana", message, signature: (0, base64url_1.bytesToBase64URL)(signature) }, ((_m = credentials.options) === null || _m === undefined ? undefined : _m.captchaToken) ? { gotrue_meta_security: { captcha_token: (_o = credentials.options) === null || _o === undefined ? undefined : _o.captchaToken } } : null),
6692
6919
  xform: fetch_1._sessionResponse
6693
6920
  });
6694
6921
  if (error) {
@@ -6786,7 +7013,7 @@ var require_GoTrueClient = __commonJS((exports) => {
6786
7013
  }
6787
7014
  }
6788
7015
  async signInWithOtp(credentials) {
6789
- var _a, _b, _c, _d, _e;
7016
+ var _a, _b, _c, _d, _f;
6790
7017
  try {
6791
7018
  if ("email" in credentials) {
6792
7019
  const { email, options } = credentials;
@@ -6818,7 +7045,7 @@ var require_GoTrueClient = __commonJS((exports) => {
6818
7045
  data: (_c = options === null || options === undefined ? undefined : options.data) !== null && _c !== undefined ? _c : {},
6819
7046
  create_user: (_d = options === null || options === undefined ? undefined : options.shouldCreateUser) !== null && _d !== undefined ? _d : true,
6820
7047
  gotrue_meta_security: { captcha_token: options === null || options === undefined ? undefined : options.captchaToken },
6821
- channel: (_e = options === null || options === undefined ? undefined : options.channel) !== null && _e !== undefined ? _e : "sms"
7048
+ channel: (_f = options === null || options === undefined ? undefined : options.channel) !== null && _f !== undefined ? _f : "sms"
6822
7049
  }
6823
7050
  });
6824
7051
  return this._returnResult({
@@ -6872,7 +7099,7 @@ var require_GoTrueClient = __commonJS((exports) => {
6872
7099
  }
6873
7100
  }
6874
7101
  async signInWithSSO(params) {
6875
- var _a, _b, _c, _d, _e;
7102
+ var _a, _b, _c, _d, _f;
6876
7103
  try {
6877
7104
  let codeChallenge = null;
6878
7105
  let codeChallengeMethod = null;
@@ -6884,7 +7111,7 @@ var require_GoTrueClient = __commonJS((exports) => {
6884
7111
  headers: this.headers,
6885
7112
  xform: fetch_1._ssoResponse
6886
7113
  });
6887
- if (((_d = result.data) === null || _d === undefined ? undefined : _d.url) && (0, helpers_1.isBrowser)() && !((_e = params.options) === null || _e === undefined ? undefined : _e.skipBrowserRedirect)) {
7114
+ if (((_d = result.data) === null || _d === undefined ? undefined : _d.url) && (0, helpers_1.isBrowser)() && !((_f = params.options) === null || _f === undefined ? undefined : _f.skipBrowserRedirect)) {
6888
7115
  window.location.assign(result.data.url);
6889
7116
  }
6890
7117
  return this._returnResult(result);
@@ -6898,9 +7125,12 @@ var require_GoTrueClient = __commonJS((exports) => {
6898
7125
  }
6899
7126
  async reauthenticate() {
6900
7127
  await this.initializePromise;
6901
- return await this._acquireLock(this.lockAcquireTimeout, async () => {
6902
- return await this._reauthenticate();
6903
- });
7128
+ if (this.lock != null) {
7129
+ return await this._acquireLock(this.lockAcquireTimeout, async () => {
7130
+ return await this._reauthenticate();
7131
+ });
7132
+ }
7133
+ return await this._reauthenticate();
6904
7134
  }
6905
7135
  async _reauthenticate() {
6906
7136
  try {
@@ -6928,15 +7158,25 @@ var require_GoTrueClient = __commonJS((exports) => {
6928
7158
  const endpoint = `${this.url}/resend`;
6929
7159
  if ("email" in credentials) {
6930
7160
  const { email, type, options } = credentials;
7161
+ let codeChallenge = null;
7162
+ let codeChallengeMethod = null;
7163
+ if (this.flowType === "pkce") {
7164
+ [codeChallenge, codeChallengeMethod] = await (0, helpers_1.getCodeChallengeAndMethod)(this.storage, this.storageKey);
7165
+ }
6931
7166
  const { error } = await (0, fetch_1._request)(this.fetch, "POST", endpoint, {
6932
7167
  headers: this.headers,
6933
7168
  body: {
6934
7169
  email,
6935
7170
  type,
6936
- gotrue_meta_security: { captcha_token: options === null || options === undefined ? undefined : options.captchaToken }
7171
+ gotrue_meta_security: { captcha_token: options === null || options === undefined ? undefined : options.captchaToken },
7172
+ code_challenge: codeChallenge,
7173
+ code_challenge_method: codeChallengeMethod
6937
7174
  },
6938
7175
  redirectTo: options === null || options === undefined ? undefined : options.emailRedirectTo
6939
7176
  });
7177
+ if (error) {
7178
+ await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`);
7179
+ }
6940
7180
  return this._returnResult({ data: { user: null, session: null }, error });
6941
7181
  } else if ("phone" in credentials) {
6942
7182
  const { phone, type, options } = credentials;
@@ -6955,6 +7195,7 @@ var require_GoTrueClient = __commonJS((exports) => {
6955
7195
  }
6956
7196
  throw new errors_1.AuthInvalidCredentialsError("You must provide either an email or phone number and a type");
6957
7197
  } catch (error) {
7198
+ await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`);
6958
7199
  if ((0, errors_1.isAuthError)(error)) {
6959
7200
  return this._returnResult({ data: { user: null, session: null }, error });
6960
7201
  }
@@ -6963,12 +7204,16 @@ var require_GoTrueClient = __commonJS((exports) => {
6963
7204
  }
6964
7205
  async getSession() {
6965
7206
  await this.initializePromise;
6966
- const result = await this._acquireLock(this.lockAcquireTimeout, async () => {
6967
- return this._useSession(async (result2) => {
6968
- return result2;
7207
+ if (this.lock != null) {
7208
+ return await this._acquireLock(this.lockAcquireTimeout, async () => {
7209
+ return this._useSession(async (result) => {
7210
+ return result;
7211
+ });
6969
7212
  });
7213
+ }
7214
+ return await this._useSession(async (result) => {
7215
+ return result;
6970
7216
  });
6971
- return result;
6972
7217
  }
6973
7218
  async _acquireLock(acquireTimeout, fn) {
6974
7219
  this._debug("#_acquireLock", "begin", acquireTimeout);
@@ -6982,7 +7227,7 @@ var require_GoTrueClient = __commonJS((exports) => {
6982
7227
  this.pendingInLock.push((async () => {
6983
7228
  try {
6984
7229
  await result;
6985
- } catch (e) {}
7230
+ } catch (_e) {}
6986
7231
  })());
6987
7232
  return result;
6988
7233
  }
@@ -7023,7 +7268,7 @@ var require_GoTrueClient = __commonJS((exports) => {
7023
7268
  }
7024
7269
  async __loadSession() {
7025
7270
  this._debug("#__loadSession()", "begin");
7026
- if (!this.lockAcquired) {
7271
+ if (this.lock != null && !this.lockAcquired) {
7027
7272
  this._debug("#__loadSession()", "used outside of an acquired lock!", new Error().stack);
7028
7273
  }
7029
7274
  try {
@@ -7063,6 +7308,13 @@ var require_GoTrueClient = __commonJS((exports) => {
7063
7308
  }
7064
7309
  const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token);
7065
7310
  if (error) {
7311
+ const accessTokenStillValid = !!(currentSession.expires_at && currentSession.expires_at * 1000 > Date.now());
7312
+ if (accessTokenStillValid) {
7313
+ const stillStored = await (0, helpers_1.getItemAsync)(this.storage, this.storageKey);
7314
+ if (stillStored && stillStored.refresh_token === currentSession.refresh_token) {
7315
+ return this._returnResult({ data: { session: currentSession }, error: null });
7316
+ }
7317
+ }
7066
7318
  return this._returnResult({ data: { session: null }, error });
7067
7319
  }
7068
7320
  return this._returnResult({ data: { session }, error: null });
@@ -7075,9 +7327,14 @@ var require_GoTrueClient = __commonJS((exports) => {
7075
7327
  return await this._getUser(jwt);
7076
7328
  }
7077
7329
  await this.initializePromise;
7078
- const result = await this._acquireLock(this.lockAcquireTimeout, async () => {
7079
- return await this._getUser();
7080
- });
7330
+ let result;
7331
+ if (this.lock != null) {
7332
+ result = await this._acquireLock(this.lockAcquireTimeout, async () => {
7333
+ return await this._getUser();
7334
+ });
7335
+ } else {
7336
+ result = await this._getUser();
7337
+ }
7081
7338
  if (result.data.user) {
7082
7339
  this.suppressGetSessionWarning = true;
7083
7340
  }
@@ -7120,9 +7377,12 @@ var require_GoTrueClient = __commonJS((exports) => {
7120
7377
  }
7121
7378
  async updateUser(attributes, options = {}) {
7122
7379
  await this.initializePromise;
7123
- return await this._acquireLock(this.lockAcquireTimeout, async () => {
7124
- return await this._updateUser(attributes, options);
7125
- });
7380
+ if (this.lock != null) {
7381
+ return await this._acquireLock(this.lockAcquireTimeout, async () => {
7382
+ return await this._updateUser(attributes, options);
7383
+ });
7384
+ }
7385
+ return await this._updateUser(attributes, options);
7126
7386
  }
7127
7387
  async _updateUser(attributes, options = {}) {
7128
7388
  try {
@@ -7165,9 +7425,12 @@ var require_GoTrueClient = __commonJS((exports) => {
7165
7425
  }
7166
7426
  async setSession(currentSession) {
7167
7427
  await this.initializePromise;
7168
- return await this._acquireLock(this.lockAcquireTimeout, async () => {
7169
- return await this._setSession(currentSession);
7170
- });
7428
+ if (this.lock != null) {
7429
+ return await this._acquireLock(this.lockAcquireTimeout, async () => {
7430
+ return await this._setSession(currentSession);
7431
+ });
7432
+ }
7433
+ return await this._setSession(currentSession);
7171
7434
  }
7172
7435
  async _setSession(currentSession) {
7173
7436
  try {
@@ -7218,9 +7481,12 @@ var require_GoTrueClient = __commonJS((exports) => {
7218
7481
  }
7219
7482
  async refreshSession(currentSession) {
7220
7483
  await this.initializePromise;
7221
- return await this._acquireLock(this.lockAcquireTimeout, async () => {
7222
- return await this._refreshSession(currentSession);
7223
- });
7484
+ if (this.lock != null) {
7485
+ return await this._acquireLock(this.lockAcquireTimeout, async () => {
7486
+ return await this._refreshSession(currentSession);
7487
+ });
7488
+ }
7489
+ return await this._refreshSession(currentSession);
7224
7490
  }
7225
7491
  async _refreshSession(currentSession) {
7226
7492
  try {
@@ -7338,7 +7604,7 @@ var require_GoTrueClient = __commonJS((exports) => {
7338
7604
  if (typeof this.detectSessionInUrl === "function") {
7339
7605
  return this.detectSessionInUrl(new URL(window.location.href), params);
7340
7606
  }
7341
- return Boolean(params.access_token || params.error_description);
7607
+ return Boolean(params.access_token || params.error || params.error_description || params.error_code);
7342
7608
  }
7343
7609
  async _isPKCECallback(params) {
7344
7610
  const currentStorageContent = await (0, helpers_1.getItemAsync)(this.storage, `${this.storageKey}-code-verifier`);
@@ -7346,13 +7612,20 @@ var require_GoTrueClient = __commonJS((exports) => {
7346
7612
  }
7347
7613
  async signOut(options = { scope: "global" }) {
7348
7614
  await this.initializePromise;
7349
- return await this._acquireLock(this.lockAcquireTimeout, async () => {
7350
- return await this._signOut(options);
7351
- });
7615
+ if (this.lock != null) {
7616
+ return await this._acquireLock(this.lockAcquireTimeout, async () => {
7617
+ return await this._signOut(options);
7618
+ });
7619
+ }
7620
+ return await this._signOut(options);
7352
7621
  }
7353
7622
  async _signOut({ scope } = { scope: "global" }) {
7354
7623
  return await this._useSession(async (result) => {
7355
7624
  var _a;
7625
+ const removeCurrentSession = async () => {
7626
+ await this._removeSession();
7627
+ await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`);
7628
+ };
7356
7629
  const { data, error: sessionError } = result;
7357
7630
  if (sessionError && !(0, errors_1.isAuthSessionMissingError)(sessionError)) {
7358
7631
  return this._returnResult({ error: sessionError });
@@ -7362,13 +7635,15 @@ var require_GoTrueClient = __commonJS((exports) => {
7362
7635
  const { error } = await this.admin.signOut(accessToken, scope);
7363
7636
  if (error) {
7364
7637
  if (!((0, errors_1.isAuthApiError)(error) && (error.status === 404 || error.status === 401 || error.status === 403) || (0, errors_1.isAuthSessionMissingError)(error))) {
7638
+ if (scope !== "others") {
7639
+ await removeCurrentSession();
7640
+ }
7365
7641
  return this._returnResult({ error });
7366
7642
  }
7367
7643
  }
7368
7644
  }
7369
7645
  if (scope !== "others") {
7370
- await this._removeSession();
7371
- await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`);
7646
+ await removeCurrentSession();
7372
7647
  }
7373
7648
  return this._returnResult({ error: null });
7374
7649
  });
@@ -7387,9 +7662,13 @@ var require_GoTrueClient = __commonJS((exports) => {
7387
7662
  this.stateChangeEmitters.set(id, subscription);
7388
7663
  (async () => {
7389
7664
  await this.initializePromise;
7390
- await this._acquireLock(this.lockAcquireTimeout, async () => {
7391
- this._emitInitialSession(id);
7392
- });
7665
+ if (this.lock != null) {
7666
+ await this._acquireLock(this.lockAcquireTimeout, async () => {
7667
+ this._emitInitialSession(id);
7668
+ });
7669
+ } else {
7670
+ await this._emitInitialSession(id);
7671
+ }
7393
7672
  })();
7394
7673
  return { data: { subscription } };
7395
7674
  }
@@ -7462,7 +7741,7 @@ var require_GoTrueClient = __commonJS((exports) => {
7462
7741
  var _a;
7463
7742
  try {
7464
7743
  const { data, error } = await this._useSession(async (result) => {
7465
- var _a2, _b, _c, _d, _e;
7744
+ var _a2, _b, _c, _d, _f;
7466
7745
  const { data: data2, error: error2 } = result;
7467
7746
  if (error2)
7468
7747
  throw error2;
@@ -7474,7 +7753,7 @@ var require_GoTrueClient = __commonJS((exports) => {
7474
7753
  });
7475
7754
  return await (0, fetch_1._request)(this.fetch, "GET", url, {
7476
7755
  headers: this.headers,
7477
- jwt: (_e = (_d = data2.session) === null || _d === undefined ? undefined : _d.access_token) !== null && _e !== undefined ? _e : undefined
7756
+ jwt: (_f = (_d = data2.session) === null || _d === undefined ? undefined : _d.access_token) !== null && _f !== undefined ? _f : undefined
7478
7757
  });
7479
7758
  });
7480
7759
  if (error)
@@ -7558,7 +7837,7 @@ var require_GoTrueClient = __commonJS((exports) => {
7558
7837
  }
7559
7838
  }
7560
7839
  async _refreshAccessToken(refreshToken) {
7561
- const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)`;
7840
+ const debugName = `#_refreshAccessToken()`;
7562
7841
  this._debug(debugName, "begin");
7563
7842
  try {
7564
7843
  const startedAt = Date.now();
@@ -7641,10 +7920,10 @@ var require_GoTrueClient = __commonJS((exports) => {
7641
7920
  if (this.autoRefreshToken && currentSession.refresh_token) {
7642
7921
  const { error } = await this._callRefreshToken(currentSession.refresh_token);
7643
7922
  if (error) {
7644
- console.error(error);
7645
- if (!(0, errors_1.isAuthRetryableFetchError)(error)) {
7646
- this._debug(debugName, "refresh failed with a non-retryable error, removing the session", error);
7647
- await this._removeSession();
7923
+ if ((0, errors_1.isAuthRefreshDiscardedError)(error)) {
7924
+ this._debug(debugName, "refresh discarded by commit guard", error);
7925
+ } else {
7926
+ this._debug(debugName, "refresh failed", error);
7648
7927
  }
7649
7928
  }
7650
7929
  }
@@ -7681,18 +7960,52 @@ var require_GoTrueClient = __commonJS((exports) => {
7681
7960
  if (this.refreshingDeferred) {
7682
7961
  return this.refreshingDeferred.promise;
7683
7962
  }
7684
- const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)`;
7963
+ if (this.lastRefreshFailure && this.lastRefreshFailure.refreshToken === refreshToken && Date.now() < this.lastRefreshFailure.expiresAt) {
7964
+ this._debug("#_callRefreshToken()", "returning cached failure (cooldown active)");
7965
+ return this.lastRefreshFailure.result;
7966
+ }
7967
+ const debugName = `#_callRefreshToken()`;
7685
7968
  this._debug(debugName, "begin");
7686
7969
  try {
7687
7970
  this.refreshingDeferred = new helpers_1.Deferred;
7971
+ const storedAtStart = await (0, helpers_1.getItemAsync)(this.storage, this.storageKey);
7688
7972
  const { data, error } = await this._refreshAccessToken(refreshToken);
7689
7973
  if (error)
7690
7974
  throw error;
7691
7975
  if (!data.session)
7692
7976
  throw new errors_1.AuthSessionMissingError;
7977
+ const storedAfter = await (0, helpers_1.getItemAsync)(this.storage, this.storageKey);
7978
+ const storageChangedUnderUs = storedAtStart !== null && (storedAfter === null || storedAfter.refresh_token !== storedAtStart.refresh_token);
7979
+ if (storageChangedUnderUs) {
7980
+ this._debug(debugName, "commit guard: storage changed since refresh started, discarding rotated tokens", {
7981
+ startedWith: "present",
7982
+ nowHolds: storedAfter ? "replaced" : "cleared"
7983
+ });
7984
+ const discarded = {
7985
+ data: null,
7986
+ error: new errors_1.AuthRefreshDiscardedError
7987
+ };
7988
+ this.refreshingDeferred.resolve(discarded);
7989
+ return discarded;
7990
+ }
7991
+ const epochBeforeSave = this._sessionRemovalEpoch;
7693
7992
  await this._saveSession(data.session);
7993
+ if (this._sessionRemovalEpoch !== epochBeforeSave) {
7994
+ this._debug(debugName, "commit guard (post-save): _removeSession ran during _saveSession, undoing write");
7995
+ await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey);
7996
+ if (this.userStorage) {
7997
+ await (0, helpers_1.removeItemAsync)(this.userStorage, this.storageKey + "-user");
7998
+ }
7999
+ const discarded = {
8000
+ data: null,
8001
+ error: new errors_1.AuthRefreshDiscardedError
8002
+ };
8003
+ this.refreshingDeferred.resolve(discarded);
8004
+ return discarded;
8005
+ }
7694
8006
  await this._notifyAllSubscribers("TOKEN_REFRESHED", data.session);
7695
8007
  const result = { data: data.session, error: null };
8008
+ this.lastRefreshFailure = null;
7696
8009
  this.refreshingDeferred.resolve(result);
7697
8010
  return result;
7698
8011
  } catch (error) {
@@ -7700,8 +8013,19 @@ var require_GoTrueClient = __commonJS((exports) => {
7700
8013
  if ((0, errors_1.isAuthError)(error)) {
7701
8014
  const result = { data: null, error };
7702
8015
  if (!(0, errors_1.isAuthRetryableFetchError)(error)) {
7703
- await this._removeSession();
8016
+ const storedNow = await (0, helpers_1.getItemAsync)(this.storage, this.storageKey);
8017
+ const accessTokenStillValid = !!((storedNow === null || storedNow === undefined ? undefined : storedNow.expires_at) && storedNow.expires_at * 1000 > Date.now());
8018
+ if (accessTokenStillValid) {
8019
+ this._debug(debugName, "proactive refresh failed, access token still valid — preserving session");
8020
+ } else {
8021
+ await this._removeSession();
8022
+ }
7704
8023
  }
8024
+ this.lastRefreshFailure = {
8025
+ refreshToken,
8026
+ result,
8027
+ expiresAt: Date.now() + constants_1.REFRESH_FAILURE_COOLDOWN_MS
8028
+ };
7705
8029
  (_a = this.refreshingDeferred) === null || _a === undefined || _a.resolve(result);
7706
8030
  return result;
7707
8031
  }
@@ -7713,6 +8037,10 @@ var require_GoTrueClient = __commonJS((exports) => {
7713
8037
  }
7714
8038
  }
7715
8039
  async _notifyAllSubscribers(event, session, broadcast = true) {
8040
+ if (this._pendingInitNotifications !== null && broadcast) {
8041
+ this._pendingInitNotifications.push({ event, session, broadcast });
8042
+ return;
8043
+ }
7716
8044
  const debugName = `#_notifyAllSubscribers(${event})`;
7717
8045
  this._debug(debugName, "begin", session, `broadcast = ${broadcast}`);
7718
8046
  try {
@@ -7741,7 +8069,6 @@ var require_GoTrueClient = __commonJS((exports) => {
7741
8069
  async _saveSession(session) {
7742
8070
  this._debug("#_saveSession()", session);
7743
8071
  this.suppressGetSessionWarning = true;
7744
- await (0, helpers_1.removeItemAsync)(this.storage, `${this.storageKey}-code-verifier`);
7745
8072
  const sessionToProcess = Object.assign({}, session);
7746
8073
  const userIsProxy = sessionToProcess.user && sessionToProcess.user.__isUserNotAvailableProxy === true;
7747
8074
  if (this.userStorage) {
@@ -7760,7 +8087,9 @@ var require_GoTrueClient = __commonJS((exports) => {
7760
8087
  }
7761
8088
  }
7762
8089
  async _removeSession() {
8090
+ this._sessionRemovalEpoch += 1;
7763
8091
  this._debug("#_removeSession()");
8092
+ this.lastRefreshFailure = null;
7764
8093
  this.suppressGetSessionWarning = false;
7765
8094
  await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey);
7766
8095
  await (0, helpers_1.removeItemAsync)(this.storage, this.storageKey + "-code-verifier");
@@ -7824,38 +8153,74 @@ var require_GoTrueClient = __commonJS((exports) => {
7824
8153
  this._removeVisibilityChangedCallback();
7825
8154
  await this._stopAutoRefresh();
7826
8155
  }
8156
+ async dispose() {
8157
+ var _a;
8158
+ this._removeVisibilityChangedCallback();
8159
+ await this._stopAutoRefresh();
8160
+ (_a = this.broadcastChannel) === null || _a === undefined || _a.close();
8161
+ this.broadcastChannel = null;
8162
+ this.stateChangeEmitters.clear();
8163
+ }
7827
8164
  async _autoRefreshTokenTick() {
7828
8165
  this._debug("#_autoRefreshTokenTick()", "begin");
7829
- try {
7830
- await this._acquireLock(0, async () => {
7831
- try {
7832
- const now = Date.now();
8166
+ if (this.lock != null) {
8167
+ try {
8168
+ await this._acquireLock(0, async () => {
7833
8169
  try {
7834
- return await this._useSession(async (result) => {
7835
- const { data: { session } } = result;
7836
- if (!session || !session.refresh_token || !session.expires_at) {
7837
- this._debug("#_autoRefreshTokenTick()", "no session");
7838
- return;
7839
- }
7840
- const expiresInTicks = Math.floor((session.expires_at * 1000 - now) / constants_1.AUTO_REFRESH_TICK_DURATION_MS);
7841
- this._debug("#_autoRefreshTokenTick()", `access token expires in ${expiresInTicks} ticks, a tick lasts ${constants_1.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${constants_1.AUTO_REFRESH_TICK_THRESHOLD} ticks`);
7842
- if (expiresInTicks <= constants_1.AUTO_REFRESH_TICK_THRESHOLD) {
7843
- await this._callRefreshToken(session.refresh_token);
7844
- }
7845
- });
7846
- } catch (e) {
7847
- console.error("Auto refresh tick failed with error. This is likely a transient error.", e);
8170
+ const now = Date.now();
8171
+ try {
8172
+ return await this._useSession(async (result) => {
8173
+ const { data: { session } } = result;
8174
+ if (!session || !session.refresh_token || !session.expires_at) {
8175
+ this._debug("#_autoRefreshTokenTick()", "no session");
8176
+ return;
8177
+ }
8178
+ const expiresInTicks = Math.floor((session.expires_at * 1000 - now) / constants_1.AUTO_REFRESH_TICK_DURATION_MS);
8179
+ this._debug("#_autoRefreshTokenTick()", `access token expires in ${expiresInTicks} ticks, a tick lasts ${constants_1.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${constants_1.AUTO_REFRESH_TICK_THRESHOLD} ticks`);
8180
+ if (expiresInTicks <= constants_1.AUTO_REFRESH_TICK_THRESHOLD) {
8181
+ await this._callRefreshToken(session.refresh_token);
8182
+ }
8183
+ });
8184
+ } catch (e) {
8185
+ console.error("Auto refresh tick failed with error. This is likely a transient error.", e);
8186
+ }
8187
+ } finally {
8188
+ this._debug("#_autoRefreshTokenTick()", "end");
7848
8189
  }
7849
- } finally {
7850
- this._debug("#_autoRefreshTokenTick()", "end");
8190
+ });
8191
+ } catch (e) {
8192
+ if (e instanceof locks_1.LockAcquireTimeoutError) {
8193
+ this._debug("auto refresh token tick lock not available");
8194
+ } else {
8195
+ throw e;
7851
8196
  }
7852
- });
7853
- } catch (e) {
7854
- if (e.isAcquireTimeout || e instanceof locks_1.LockAcquireTimeoutError) {
7855
- this._debug("auto refresh token tick lock not available");
7856
- } else {
7857
- throw e;
7858
8197
  }
8198
+ return;
8199
+ }
8200
+ if (this.refreshingDeferred !== null) {
8201
+ this._debug("#_autoRefreshTokenTick()", "refresh already in flight, skipping");
8202
+ return;
8203
+ }
8204
+ try {
8205
+ const now = Date.now();
8206
+ try {
8207
+ await this._useSession(async (result) => {
8208
+ const { data: { session } } = result;
8209
+ if (!session || !session.refresh_token || !session.expires_at) {
8210
+ this._debug("#_autoRefreshTokenTick()", "no session");
8211
+ return;
8212
+ }
8213
+ const expiresInTicks = Math.floor((session.expires_at * 1000 - now) / constants_1.AUTO_REFRESH_TICK_DURATION_MS);
8214
+ this._debug("#_autoRefreshTokenTick()", `access token expires in ${expiresInTicks} ticks, a tick lasts ${constants_1.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${constants_1.AUTO_REFRESH_TICK_THRESHOLD} ticks`);
8215
+ if (expiresInTicks <= constants_1.AUTO_REFRESH_TICK_THRESHOLD) {
8216
+ await this._callRefreshToken(session.refresh_token);
8217
+ }
8218
+ });
8219
+ } catch (e) {
8220
+ console.error("Auto refresh tick failed with error. This is likely a transient error.", e);
8221
+ }
8222
+ } finally {
8223
+ this._debug("#_autoRefreshTokenTick()", "end");
7859
8224
  }
7860
8225
  }
7861
8226
  async _handleVisibilityChange() {
@@ -7889,13 +8254,21 @@ var require_GoTrueClient = __commonJS((exports) => {
7889
8254
  }
7890
8255
  if (!calledFromInitialize) {
7891
8256
  await this.initializePromise;
7892
- await this._acquireLock(this.lockAcquireTimeout, async () => {
8257
+ if (this.lock != null) {
8258
+ await this._acquireLock(this.lockAcquireTimeout, async () => {
8259
+ if (document.visibilityState !== "visible") {
8260
+ this._debug(methodName, "acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");
8261
+ return;
8262
+ }
8263
+ await this._recoverAndRefresh();
8264
+ });
8265
+ } else {
7893
8266
  if (document.visibilityState !== "visible") {
7894
- this._debug(methodName, "acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");
8267
+ this._debug(methodName, "visibilityState is no longer visible, skipping recovery");
7895
8268
  return;
7896
8269
  }
7897
8270
  await this._recoverAndRefresh();
7898
- });
8271
+ }
7899
8272
  }
7900
8273
  } else if (document.visibilityState === "hidden") {
7901
8274
  if (this.autoRefreshToken) {
@@ -7978,7 +8351,7 @@ var require_GoTrueClient = __commonJS((exports) => {
7978
8351
  }
7979
8352
  }
7980
8353
  async _verify(params) {
7981
- return this._acquireLock(this.lockAcquireTimeout, async () => {
8354
+ const run = async () => {
7982
8355
  try {
7983
8356
  return await this._useSession(async (result) => {
7984
8357
  var _a;
@@ -8007,10 +8380,14 @@ var require_GoTrueClient = __commonJS((exports) => {
8007
8380
  }
8008
8381
  throw error;
8009
8382
  }
8010
- });
8383
+ };
8384
+ if (this.lock != null) {
8385
+ return this._acquireLock(this.lockAcquireTimeout, run);
8386
+ }
8387
+ return run();
8011
8388
  }
8012
8389
  async _challenge(params) {
8013
- return this._acquireLock(this.lockAcquireTimeout, async () => {
8390
+ const run = async () => {
8014
8391
  try {
8015
8392
  return await this._useSession(async (result) => {
8016
8393
  var _a;
@@ -8049,7 +8426,11 @@ var require_GoTrueClient = __commonJS((exports) => {
8049
8426
  }
8050
8427
  throw error;
8051
8428
  }
8052
- });
8429
+ };
8430
+ if (this.lock != null) {
8431
+ return this._acquireLock(this.lockAcquireTimeout, run);
8432
+ }
8433
+ return run();
8053
8434
  }
8054
8435
  async _challengeAndVerify(params) {
8055
8436
  const { data: challengeData, error: challengeError } = await this._challenge({
@@ -8307,7 +8688,11 @@ var require_GoTrueClient = __commonJS((exports) => {
8307
8688
  }
8308
8689
  const { header, payload, signature, raw: { header: rawHeader, payload: rawPayload } } = (0, helpers_1.decodeJWT)(token);
8309
8690
  if (!(options === null || options === undefined ? undefined : options.allowExpired)) {
8310
- (0, helpers_1.validateExp)(payload.exp);
8691
+ try {
8692
+ (0, helpers_1.validateExp)(payload.exp);
8693
+ } catch (e) {
8694
+ throw new errors_1.AuthInvalidJwtError(e instanceof Error ? e.message : "JWT validation failed");
8695
+ }
8311
8696
  }
8312
8697
  const signingKey = !header.alg || header.alg.startsWith("HS") || !header.kid || !(("crypto" in globalThis) && ("subtle" in globalThis.crypto)) ? null : await this.fetchJwk(header.kid, (options === null || options === undefined ? undefined : options.keys) ? { keys: options.keys } : options === null || options === undefined ? undefined : options.jwks);
8313
8698
  if (!signingKey) {
@@ -8805,14 +9190,17 @@ var PostgrestBuilder = class {
8805
9190
  const executeWithRetry = async () => {
8806
9191
  let attemptCount = 0;
8807
9192
  while (true) {
8808
- const requestHeaders = new Headers(_this.headers);
9193
+ const headers = {};
9194
+ _this.headers.forEach((value, key) => {
9195
+ headers[key] = value;
9196
+ });
8809
9197
  if (attemptCount > 0)
8810
- requestHeaders.set("X-Retry-Count", String(attemptCount));
9198
+ headers["X-Retry-Count"] = String(attemptCount);
8811
9199
  let res$1;
8812
9200
  try {
8813
9201
  res$1 = await _fetch(_this.url.toString(), {
8814
9202
  method: _this.method,
8815
- headers: requestHeaders,
9203
+ headers,
8816
9204
  body: JSON.stringify(_this.body, (_, value) => typeof value === "bigint" ? value.toString() : value),
8817
9205
  signal: _this.signal
8818
9206
  });
@@ -8911,7 +9299,19 @@ ${cause.stack}`;
8911
9299
  else if (_this2.headers.get("Accept") && ((_this$headers$get = _this2.headers.get("Accept")) === null || _this$headers$get === undefined ? undefined : _this$headers$get.includes("application/vnd.pgrst.plan+text")))
8912
9300
  data = body;
8913
9301
  else
8914
- data = JSON.parse(body);
9302
+ try {
9303
+ data = JSON.parse(body);
9304
+ } catch (_unused) {
9305
+ error = { message: body };
9306
+ data = null;
9307
+ if (_this2.shouldThrowOnError)
9308
+ throw new PostgrestError({
9309
+ message: body,
9310
+ details: "",
9311
+ hint: "",
9312
+ code: ""
9313
+ });
9314
+ }
8915
9315
  }
8916
9316
  const countHeader = (_this$headers$get2 = _this2.headers.get("Prefer")) === null || _this$headers$get2 === undefined ? undefined : _this$headers$get2.match(/count=(exact|planned|estimated)/);
8917
9317
  const contentRange = (_res$headers$get2 = res.headers.get("content-range")) === null || _res$headers$get2 === undefined ? undefined : _res$headers$get2.split("/");
@@ -8943,7 +9343,7 @@ ${cause.stack}`;
8943
9343
  status = 200;
8944
9344
  statusText = "OK";
8945
9345
  }
8946
- } catch (_unused) {
9346
+ } catch (_unused2) {
8947
9347
  if (res.status === 404 && body === "") {
8948
9348
  status = 204;
8949
9349
  statusText = "No Content";
@@ -8970,6 +9370,9 @@ ${cause.stack}`;
8970
9370
  }
8971
9371
  };
8972
9372
  var PostgrestTransformBuilder = class extends PostgrestBuilder {
9373
+ throwOnError() {
9374
+ return super.throwOnError();
9375
+ }
8973
9376
  select(columns) {
8974
9377
  let quoted = false;
8975
9378
  const cleanedColumns = (columns !== null && columns !== undefined ? columns : "*").split("").map((c) => {
@@ -8989,9 +9392,9 @@ var PostgrestTransformBuilder = class extends PostgrestBuilder {
8989
9392
  this.url.searchParams.set(key, `${existingOrder ? `${existingOrder},` : ""}${column}.${ascending ? "asc" : "desc"}${nullsFirst === undefined ? "" : nullsFirst ? ".nullsfirst" : ".nullslast"}`);
8990
9393
  return this;
8991
9394
  }
8992
- limit(count, { foreignTable, referencedTable = foreignTable } = {}) {
9395
+ limit(rows, { foreignTable, referencedTable = foreignTable } = {}) {
8993
9396
  const key = typeof referencedTable === "undefined" ? "limit" : `${referencedTable}.limit`;
8994
- this.url.searchParams.set(key, `${count}`);
9397
+ this.url.searchParams.set(key, `${rows}`);
8995
9398
  return this;
8996
9399
  }
8997
9400
  range(from, to, { foreignTable, referencedTable = foreignTable } = {}) {
@@ -9044,14 +9447,17 @@ var PostgrestTransformBuilder = class extends PostgrestBuilder {
9044
9447
  returns() {
9045
9448
  return this;
9046
9449
  }
9047
- maxAffected(value) {
9450
+ maxAffected(rows) {
9048
9451
  this.headers.append("Prefer", "handling=strict");
9049
- this.headers.append("Prefer", `max-affected=${value}`);
9452
+ this.headers.append("Prefer", `max-affected=${rows}`);
9050
9453
  return this;
9051
9454
  }
9052
9455
  };
9053
9456
  var PostgrestReservedCharsRegexp = /* @__PURE__ */ new RegExp("[,()]");
9054
9457
  var PostgrestFilterBuilder = class extends PostgrestTransformBuilder {
9458
+ throwOnError() {
9459
+ return super.throwOnError();
9460
+ }
9055
9461
  eq(column, value) {
9056
9462
  this.url.searchParams.append(column, `eq.${value}`);
9057
9463
  return this;
@@ -9988,13 +10394,28 @@ var isValidBucketName = (bucketName) => {
9988
10394
  return /^[\w!.\*'() &$@=;:+,?-]+$/.test(bucketName);
9989
10395
  };
9990
10396
  var _getErrorMessage = (err) => {
9991
- var _err$error;
9992
- return err.msg || err.message || err.error_description || (typeof err.error === "string" ? err.error : (_err$error = err.error) === null || _err$error === undefined ? undefined : _err$error.message) || JSON.stringify(err);
10397
+ if (typeof err === "object" && err !== null) {
10398
+ const e = err;
10399
+ if (typeof e.msg === "string")
10400
+ return e.msg;
10401
+ if (typeof e.message === "string")
10402
+ return e.message;
10403
+ if (typeof e.error_description === "string")
10404
+ return e.error_description;
10405
+ if (typeof e.error === "string")
10406
+ return e.error;
10407
+ if (typeof e.error === "object" && e.error !== null) {
10408
+ const nested = e.error;
10409
+ if (typeof nested.message === "string")
10410
+ return nested.message;
10411
+ }
10412
+ }
10413
+ return JSON.stringify(err);
9993
10414
  };
9994
10415
  var handleError = async (error, reject, options, namespace) => {
9995
- if (error !== null && typeof error === "object" && typeof error.json === "function") {
10416
+ if (error !== null && typeof error === "object" && "json" in error && typeof error.json === "function") {
9996
10417
  const responseError = error;
9997
- let status = parseInt(responseError.status, 10);
10418
+ let status = parseInt(String(responseError.status), 10);
9998
10419
  if (!Number.isFinite(status))
9999
10420
  status = 500;
10000
10421
  responseError.json().then((err) => {
@@ -10104,13 +10525,28 @@ var BaseApiClient = class {
10104
10525
  }
10105
10526
  }
10106
10527
  };
10528
+ var _Symbol$toStringTag$1;
10529
+ _Symbol$toStringTag$1 = Symbol.toStringTag;
10107
10530
  var StreamDownloadBuilder = class {
10108
10531
  constructor(downloadFn, shouldThrowOnError) {
10109
10532
  this.downloadFn = downloadFn;
10110
10533
  this.shouldThrowOnError = shouldThrowOnError;
10534
+ this[_Symbol$toStringTag$1] = "StreamDownloadBuilder";
10535
+ this.promise = null;
10111
10536
  }
10112
10537
  then(onfulfilled, onrejected) {
10113
- return this.execute().then(onfulfilled, onrejected);
10538
+ return this.getPromise().then(onfulfilled, onrejected);
10539
+ }
10540
+ catch(onrejected) {
10541
+ return this.getPromise().catch(onrejected);
10542
+ }
10543
+ finally(onfinally) {
10544
+ return this.getPromise().finally(onfinally);
10545
+ }
10546
+ getPromise() {
10547
+ if (!this.promise)
10548
+ this.promise = this.execute();
10549
+ return this.promise;
10114
10550
  }
10115
10551
  async execute() {
10116
10552
  var _this = this;
@@ -10419,18 +10855,33 @@ var StorageFileApi = class extends BaseApiClient {
10419
10855
  return await remove(_this12.fetch, `${_this12.url}/object/${_this12.bucketId}`, { prefixes: paths }, { headers: _this12.headers });
10420
10856
  });
10421
10857
  }
10422
- async list(path, options, parameters) {
10858
+ async purgeCache(path, options, parameters) {
10423
10859
  var _this13 = this;
10424
10860
  return _this13.handleOperation(async () => {
10425
- const body = _objectSpread22(_objectSpread22(_objectSpread22({}, DEFAULT_SEARCH_OPTIONS), options), {}, { prefix: path || "" });
10426
- return await post(_this13.fetch, `${_this13.url}/object/list/${_this13.bucketId}`, body, { headers: _this13.headers }, parameters);
10861
+ const _path = _this13._getFinalPath(path);
10862
+ const query = new URLSearchParams;
10863
+ if (options === null || options === undefined ? undefined : options.transformations)
10864
+ query.set("transformations", "true");
10865
+ const queryString = query.toString();
10866
+ return await remove(_this13.fetch, `${_this13.url}/cdn/${_path}${queryString ? `?${queryString}` : ""}`, {}, { headers: _this13.headers }, parameters);
10427
10867
  });
10428
10868
  }
10429
- async listV2(options, parameters) {
10869
+ async list(path, options, parameters) {
10430
10870
  var _this14 = this;
10431
10871
  return _this14.handleOperation(async () => {
10872
+ const sortBy = (options === null || options === undefined ? undefined : options.sortBy) ? _objectSpread22(_objectSpread22({}, DEFAULT_SEARCH_OPTIONS.sortBy), options.sortBy) : DEFAULT_SEARCH_OPTIONS.sortBy;
10873
+ const body = _objectSpread22(_objectSpread22(_objectSpread22({}, DEFAULT_SEARCH_OPTIONS), options), {}, {
10874
+ sortBy,
10875
+ prefix: path || ""
10876
+ });
10877
+ return await post(_this14.fetch, `${_this14.url}/object/list/${_this14.bucketId}`, body, { headers: _this14.headers }, parameters);
10878
+ });
10879
+ }
10880
+ async listV2(options, parameters) {
10881
+ var _this15 = this;
10882
+ return _this15.handleOperation(async () => {
10432
10883
  const body = _objectSpread22({}, options);
10433
- return await post(_this14.fetch, `${_this14.url}/object/list-v2/${_this14.bucketId}`, body, { headers: _this14.headers }, parameters);
10884
+ return await post(_this15.fetch, `${_this15.url}/object/list-v2/${_this15.bucketId}`, body, { headers: _this15.headers }, parameters);
10434
10885
  });
10435
10886
  }
10436
10887
  encodeMetadata(metadata) {
@@ -10461,7 +10912,7 @@ var StorageFileApi = class extends BaseApiClient {
10461
10912
  return query;
10462
10913
  }
10463
10914
  };
10464
- var version = "2.105.1";
10915
+ var version = "2.110.7";
10465
10916
  var DEFAULT_HEADERS = { "X-Client-Info": `storage-js/${version}` };
10466
10917
  var StorageBucketApi = class extends BaseApiClient {
10467
10918
  constructor(url, headers = {}, fetch$1, opts) {
@@ -10524,6 +10975,16 @@ var StorageBucketApi = class extends BaseApiClient {
10524
10975
  return await remove(_this6.fetch, `${_this6.url}/bucket/${id}`, {}, { headers: _this6.headers });
10525
10976
  });
10526
10977
  }
10978
+ async purgeBucketCache(id, options, parameters) {
10979
+ var _this7 = this;
10980
+ return _this7.handleOperation(async () => {
10981
+ const query = new URLSearchParams;
10982
+ if (options === null || options === undefined ? undefined : options.transformations)
10983
+ query.set("transformations", "true");
10984
+ const queryString = query.toString();
10985
+ return await remove(_this7.fetch, `${_this7.url}/cdn/${id}${queryString ? `?${queryString}` : ""}`, {}, { headers: _this7.headers }, parameters);
10986
+ });
10987
+ }
10527
10988
  listBucketOptionsToQueryString(options) {
10528
10989
  const params = {};
10529
10990
  if (options) {
@@ -10844,17 +11305,27 @@ var StorageClient = class extends StorageBucketApi {
10844
11305
  var import_auth_js = __toESM(require_main3(), 1);
10845
11306
  __reExport(exports_dist3, __toESM(require_main2(), 1));
10846
11307
  __reExport(exports_dist3, __toESM(require_main3(), 1));
10847
- var version2 = "2.105.1";
11308
+ var version2 = "2.110.7";
10848
11309
  var JS_ENV = "";
10849
- if (typeof Deno !== "undefined")
11310
+ var JS_RUNTIME_VERSION;
11311
+ if (typeof Deno !== "undefined") {
10850
11312
  JS_ENV = "deno";
10851
- else if (typeof document !== "undefined")
11313
+ JS_RUNTIME_VERSION = (_Deno$version = Deno.version) === null || _Deno$version === undefined ? undefined : _Deno$version.deno;
11314
+ } else if (typeof document !== "undefined")
10852
11315
  JS_ENV = "web";
10853
11316
  else if (typeof navigator !== "undefined" && navigator.product === "ReactNative")
10854
11317
  JS_ENV = "react-native";
10855
- else
11318
+ else {
10856
11319
  JS_ENV = "node";
10857
- var DEFAULT_HEADERS2 = { "X-Client-Info": `supabase-js-${JS_ENV}/${version2}` };
11320
+ const _process = globalThis["process"];
11321
+ JS_RUNTIME_VERSION = _process === null || _process === undefined || (_process$version = _process["version"]) === null || _process$version === undefined ? undefined : _process$version.replace(/^v/, "");
11322
+ }
11323
+ var _Deno$version;
11324
+ var _process$version;
11325
+ var _runtimeMeta = [`runtime=${JS_ENV}`];
11326
+ if (JS_RUNTIME_VERSION)
11327
+ _runtimeMeta.push(`runtime-version=${JS_RUNTIME_VERSION}`);
11328
+ var DEFAULT_HEADERS2 = { "X-Client-Info": `supabase-js/${version2}; ${_runtimeMeta.join("; ")}` };
10858
11329
  var DEFAULT_GLOBAL_OPTIONS = { headers: DEFAULT_HEADERS2 };
10859
11330
  var DEFAULT_DB_OPTIONS = { schema: "public" };
10860
11331
  var DEFAULT_AUTH_OPTIONS = {
@@ -10864,6 +11335,138 @@ var DEFAULT_AUTH_OPTIONS = {
10864
11335
  flowType: "implicit"
10865
11336
  };
10866
11337
  var DEFAULT_REALTIME_OPTIONS = {};
11338
+ var DEFAULT_TRACE_PROPAGATION_OPTIONS = {
11339
+ enabled: false,
11340
+ respectSamplingDecision: true
11341
+ };
11342
+ function __awaiter(thisArg, _arguments, P, generator) {
11343
+ function adopt(value) {
11344
+ return value instanceof P ? value : new P(function(resolve) {
11345
+ resolve(value);
11346
+ });
11347
+ }
11348
+ return new (P || (P = Promise))(function(resolve, reject) {
11349
+ function fulfilled(value) {
11350
+ try {
11351
+ step(generator.next(value));
11352
+ } catch (e) {
11353
+ reject(e);
11354
+ }
11355
+ }
11356
+ function rejected(value) {
11357
+ try {
11358
+ step(generator["throw"](value));
11359
+ } catch (e) {
11360
+ reject(e);
11361
+ }
11362
+ }
11363
+ function step(result) {
11364
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
11365
+ }
11366
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
11367
+ });
11368
+ }
11369
+ var otelModulePromise = null;
11370
+ var OTEL_PKG = "@opentelemetry/api";
11371
+ function loadOtel() {
11372
+ if (otelModulePromise === null)
11373
+ otelModulePromise = import(OTEL_PKG).catch(() => null);
11374
+ return otelModulePromise;
11375
+ }
11376
+ function extractTraceContext() {
11377
+ return __awaiter(this, undefined, undefined, function* () {
11378
+ try {
11379
+ const otel = yield loadOtel();
11380
+ if (!otel || !otel.propagation || !otel.context)
11381
+ return null;
11382
+ const carrier = {};
11383
+ otel.propagation.inject(otel.context.active(), carrier);
11384
+ const traceparent = carrier["traceparent"];
11385
+ if (!traceparent)
11386
+ return null;
11387
+ return {
11388
+ traceparent,
11389
+ tracestate: carrier["tracestate"],
11390
+ baggage: carrier["baggage"]
11391
+ };
11392
+ } catch (_a) {
11393
+ return null;
11394
+ }
11395
+ });
11396
+ }
11397
+ function parseTraceParent(traceparent) {
11398
+ if (!traceparent || typeof traceparent !== "string")
11399
+ return null;
11400
+ const parts = traceparent.split("-");
11401
+ if (parts.length !== 4)
11402
+ return null;
11403
+ const [version$1, traceId, parentId, traceFlags] = parts;
11404
+ if (version$1.length !== 2 || traceId.length !== 32 || parentId.length !== 16 || traceFlags.length !== 2)
11405
+ return null;
11406
+ const hexRegex = /^[0-9a-f]+$/i;
11407
+ if (!hexRegex.test(version$1) || !hexRegex.test(traceId) || !hexRegex.test(parentId) || !hexRegex.test(traceFlags))
11408
+ return null;
11409
+ if (traceId === "00000000000000000000000000000000" || parentId === "0000000000000000")
11410
+ return null;
11411
+ return {
11412
+ version: version$1,
11413
+ traceId,
11414
+ parentId,
11415
+ traceFlags,
11416
+ isSampled: (parseInt(traceFlags, 16) & 1) === 1
11417
+ };
11418
+ }
11419
+ function shouldPropagateToTarget(targetUrl, targets) {
11420
+ if (!targetUrl || !targets || targets.length === 0)
11421
+ return false;
11422
+ let url;
11423
+ if (targetUrl instanceof URL)
11424
+ url = targetUrl;
11425
+ else
11426
+ try {
11427
+ url = new URL(targetUrl);
11428
+ } catch (error) {
11429
+ return false;
11430
+ }
11431
+ for (const target of targets)
11432
+ try {
11433
+ if (typeof target === "string") {
11434
+ if (matchStringTarget(url.hostname, target))
11435
+ return true;
11436
+ } else if (target instanceof RegExp) {
11437
+ if (target.test(url.hostname))
11438
+ return true;
11439
+ } else if (typeof target === "function") {
11440
+ if (target(url))
11441
+ return true;
11442
+ }
11443
+ } catch (error) {
11444
+ continue;
11445
+ }
11446
+ return false;
11447
+ }
11448
+ function matchStringTarget(hostname, target) {
11449
+ if (target === hostname)
11450
+ return true;
11451
+ if (target.startsWith("*.")) {
11452
+ const domain = target.slice(2);
11453
+ if (hostname.endsWith(domain)) {
11454
+ if (hostname === domain || hostname.endsWith("." + domain))
11455
+ return true;
11456
+ }
11457
+ }
11458
+ return false;
11459
+ }
11460
+ function getDefaultPropagationTargets(supabaseUrl) {
11461
+ const targets = [];
11462
+ try {
11463
+ const url = new URL(supabaseUrl);
11464
+ targets.push(url.hostname);
11465
+ } catch (error) {}
11466
+ targets.push("*.supabase.co", "*.supabase.in");
11467
+ targets.push("localhost", "127.0.0.1", "[::1]");
11468
+ return targets;
11469
+ }
10867
11470
  function _typeof3(o) {
10868
11471
  "@babel/helpers - typeof";
10869
11472
  return _typeof3 = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(o$1) {
@@ -10925,33 +11528,85 @@ var resolveFetch2 = (customFetch) => {
10925
11528
  var resolveHeadersConstructor = () => {
10926
11529
  return Headers;
10927
11530
  };
10928
- var fetchWithAuth = (supabaseKey, getAccessToken, customFetch) => {
11531
+ var isNewApiKey = (key) => key.startsWith("sb_publishable_") || key.startsWith("sb_secret_");
11532
+ var TEMP_KEY_PREFIX = "sb_temp_";
11533
+ var warnedKeySubtypes = /* @__PURE__ */ new Set;
11534
+ var checkApiKeyFormat = (key) => {
11535
+ var _key$match$, _key$match;
11536
+ if (!key.startsWith("sb_") || isNewApiKey(key) || key.startsWith(TEMP_KEY_PREFIX))
11537
+ return;
11538
+ const subtype = (_key$match$ = (_key$match = key.match(/^sb_[a-zA-Z0-9]+_/)) === null || _key$match === undefined ? undefined : _key$match[0]) !== null && _key$match$ !== undefined ? _key$match$ : "unknown";
11539
+ if (warnedKeySubtypes.has(subtype))
11540
+ return;
11541
+ warnedKeySubtypes.add(subtype);
11542
+ console.warn("@supabase/supabase-js: Unrecognized Supabase API key format. The client will proceed and send this key as-is; if you see authentication errors you may need to upgrade @supabase/supabase-js to a version that recognizes this key type.");
11543
+ };
11544
+ var fetchWithAuth = (supabaseKey, supabaseUrl, getAccessToken, customFetch, tracePropagationOptions, options) => {
10929
11545
  const fetch$1 = resolveFetch2(customFetch);
10930
11546
  const HeadersConstructor = resolveHeadersConstructor();
11547
+ const traceEnabled = (tracePropagationOptions === null || tracePropagationOptions === undefined ? undefined : tracePropagationOptions.enabled) === true;
11548
+ const respectSampling = (tracePropagationOptions === null || tracePropagationOptions === undefined ? undefined : tracePropagationOptions.respectSamplingDecision) !== false;
11549
+ const traceTargets = traceEnabled ? getDefaultPropagationTargets(supabaseUrl) : null;
11550
+ const allowKeyAsBearer = !((options === null || options === undefined ? undefined : options.omitApiKeyAsBearer) && isNewApiKey(supabaseKey));
10931
11551
  return async (input, init) => {
10932
- var _await$getAccessToken;
10933
- const accessToken = (_await$getAccessToken = await getAccessToken()) !== null && _await$getAccessToken !== undefined ? _await$getAccessToken : supabaseKey;
11552
+ const realToken = await getAccessToken();
10934
11553
  let headers = new HeadersConstructor(init === null || init === undefined ? undefined : init.headers);
10935
11554
  if (!headers.has("apikey"))
10936
11555
  headers.set("apikey", supabaseKey);
10937
- if (!headers.has("Authorization"))
10938
- headers.set("Authorization", `Bearer ${accessToken}`);
11556
+ if (!headers.has("Authorization")) {
11557
+ const bearer = realToken !== null && realToken !== undefined ? realToken : allowKeyAsBearer ? supabaseKey : null;
11558
+ if (bearer)
11559
+ headers.set("Authorization", `Bearer ${bearer}`);
11560
+ }
11561
+ if (traceTargets) {
11562
+ const traceHeaders = await getTraceHeaders(input, traceTargets, respectSampling);
11563
+ if (traceHeaders) {
11564
+ if (traceHeaders.traceparent && !headers.has("traceparent"))
11565
+ headers.set("traceparent", traceHeaders.traceparent);
11566
+ if (traceHeaders.tracestate && !headers.has("tracestate"))
11567
+ headers.set("tracestate", traceHeaders.tracestate);
11568
+ if (traceHeaders.baggage && !headers.has("baggage"))
11569
+ headers.set("baggage", traceHeaders.baggage);
11570
+ }
11571
+ }
10939
11572
  return fetch$1(input, _objectSpread23(_objectSpread23({}, init), {}, { headers }));
10940
11573
  };
10941
11574
  };
11575
+ async function getTraceHeaders(input, targets, respectSampling) {
11576
+ if (!shouldPropagateToTarget(typeof input === "string" ? input : input instanceof URL ? input : input.url, targets))
11577
+ return null;
11578
+ const traceContext = await extractTraceContext();
11579
+ if (!traceContext || !traceContext.traceparent)
11580
+ return null;
11581
+ if (respectSampling) {
11582
+ const parsed = parseTraceParent(traceContext.traceparent);
11583
+ if (parsed && !parsed.isSampled)
11584
+ return null;
11585
+ }
11586
+ return traceContext;
11587
+ }
11588
+ function normalizeTracePropagation(value) {
11589
+ return typeof value === "boolean" ? { enabled: value } : value;
11590
+ }
10942
11591
  function ensureTrailingSlash(url) {
10943
11592
  return url.endsWith("/") ? url : url + "/";
10944
11593
  }
10945
11594
  function applySettingDefaults(options, defaults) {
10946
- var _DEFAULT_GLOBAL_OPTIO, _globalOptions$header;
11595
+ var _DEFAULT_GLOBAL_OPTIO, _globalOptions$header, _ref, _tracePropagationOpti, _ref2, _tracePropagationOpti2;
10947
11596
  const { db: dbOptions, auth: authOptions, realtime: realtimeOptions, global: globalOptions } = options;
10948
11597
  const { db: DEFAULT_DB_OPTIONS$1, auth: DEFAULT_AUTH_OPTIONS$1, realtime: DEFAULT_REALTIME_OPTIONS$1, global: DEFAULT_GLOBAL_OPTIONS$1 } = defaults;
11598
+ const tracePropagationOptions = normalizeTracePropagation(options.tracePropagation);
11599
+ const DEFAULT_TRACE_PROPAGATION_OPTIONS$1 = normalizeTracePropagation(defaults.tracePropagation);
10949
11600
  const result = {
10950
11601
  db: _objectSpread23(_objectSpread23({}, DEFAULT_DB_OPTIONS$1), dbOptions),
10951
11602
  auth: _objectSpread23(_objectSpread23({}, DEFAULT_AUTH_OPTIONS$1), authOptions),
10952
11603
  realtime: _objectSpread23(_objectSpread23({}, DEFAULT_REALTIME_OPTIONS$1), realtimeOptions),
10953
11604
  storage: {},
10954
11605
  global: _objectSpread23(_objectSpread23(_objectSpread23({}, DEFAULT_GLOBAL_OPTIONS$1), globalOptions), {}, { headers: _objectSpread23(_objectSpread23({}, (_DEFAULT_GLOBAL_OPTIO = DEFAULT_GLOBAL_OPTIONS$1 === null || DEFAULT_GLOBAL_OPTIONS$1 === undefined ? undefined : DEFAULT_GLOBAL_OPTIONS$1.headers) !== null && _DEFAULT_GLOBAL_OPTIO !== undefined ? _DEFAULT_GLOBAL_OPTIO : {}), (_globalOptions$header = globalOptions === null || globalOptions === undefined ? undefined : globalOptions.headers) !== null && _globalOptions$header !== undefined ? _globalOptions$header : {}) }),
11606
+ tracePropagation: {
11607
+ enabled: (_ref = (_tracePropagationOpti = tracePropagationOptions === null || tracePropagationOptions === undefined ? undefined : tracePropagationOptions.enabled) !== null && _tracePropagationOpti !== undefined ? _tracePropagationOpti : DEFAULT_TRACE_PROPAGATION_OPTIONS$1 === null || DEFAULT_TRACE_PROPAGATION_OPTIONS$1 === undefined ? undefined : DEFAULT_TRACE_PROPAGATION_OPTIONS$1.enabled) !== null && _ref !== undefined ? _ref : false,
11608
+ respectSamplingDecision: (_ref2 = (_tracePropagationOpti2 = tracePropagationOptions === null || tracePropagationOptions === undefined ? undefined : tracePropagationOptions.respectSamplingDecision) !== null && _tracePropagationOpti2 !== undefined ? _tracePropagationOpti2 : DEFAULT_TRACE_PROPAGATION_OPTIONS$1 === null || DEFAULT_TRACE_PROPAGATION_OPTIONS$1 === undefined ? undefined : DEFAULT_TRACE_PROPAGATION_OPTIONS$1.respectSamplingDecision) !== null && _ref2 !== undefined ? _ref2 : true
11609
+ },
10955
11610
  accessToken: async () => ""
10956
11611
  };
10957
11612
  if (options.accessToken)
@@ -10985,6 +11640,7 @@ var SupabaseClient = class {
10985
11640
  const baseUrl = validateSupabaseUrl(supabaseUrl);
10986
11641
  if (!supabaseKey)
10987
11642
  throw new Error("supabaseKey is required.");
11643
+ checkApiKeyFormat(supabaseKey);
10988
11644
  this.realtimeUrl = new URL("realtime/v1", baseUrl);
10989
11645
  this.realtimeUrl.protocol = this.realtimeUrl.protocol.replace("http", "ws");
10990
11646
  this.authUrl = new URL("auth/v1", baseUrl);
@@ -10995,9 +11651,11 @@ var SupabaseClient = class {
10995
11651
  db: DEFAULT_DB_OPTIONS,
10996
11652
  realtime: DEFAULT_REALTIME_OPTIONS,
10997
11653
  auth: _objectSpread23(_objectSpread23({}, DEFAULT_AUTH_OPTIONS), {}, { storageKey: defaultStorageKey }),
10998
- global: DEFAULT_GLOBAL_OPTIONS
11654
+ global: DEFAULT_GLOBAL_OPTIONS,
11655
+ tracePropagation: DEFAULT_TRACE_PROPAGATION_OPTIONS
10999
11656
  };
11000
11657
  const settings = applySettingDefaults(options !== null && options !== undefined ? options : {}, DEFAULTS);
11658
+ this.settings = settings;
11001
11659
  this.storageKey = (_settings$auth$storag = settings.auth.storageKey) !== null && _settings$auth$storag !== undefined ? _settings$auth$storag : "";
11002
11660
  this.headers = (_settings$global$head = settings.global.headers) !== null && _settings$global$head !== undefined ? _settings$global$head : {};
11003
11661
  if (!settings.accessToken) {
@@ -11009,7 +11667,8 @@ var SupabaseClient = class {
11009
11667
  throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(prop)} is not possible`);
11010
11668
  } });
11011
11669
  }
11012
- this.fetch = fetchWithAuth(supabaseKey, this._getAccessToken.bind(this), settings.global.fetch);
11670
+ this.fetch = fetchWithAuth(supabaseKey, supabaseUrl, this._getSessionToken.bind(this), settings.global.fetch, settings.tracePropagation);
11671
+ this.functionsFetch = fetchWithAuth(supabaseKey, supabaseUrl, this._getSessionToken.bind(this), settings.global.fetch, settings.tracePropagation, { omitApiKeyAsBearer: true });
11013
11672
  this.realtime = this._initRealtimeClient(_objectSpread23({
11014
11673
  headers: this.headers,
11015
11674
  accessToken: this._getAccessToken.bind(this),
@@ -11031,7 +11690,7 @@ var SupabaseClient = class {
11031
11690
  get functions() {
11032
11691
  return new import_functions_js.FunctionsClient(this.functionsUrl.href, {
11033
11692
  headers: this.headers,
11034
- customFetch: this.fetch
11693
+ customFetch: this.functionsFetch
11035
11694
  });
11036
11695
  }
11037
11696
  from(relation) {
@@ -11059,15 +11718,20 @@ var SupabaseClient = class {
11059
11718
  removeAllChannels() {
11060
11719
  return this.realtime.removeAllChannels();
11061
11720
  }
11062
- async _getAccessToken() {
11721
+ async _getSessionToken() {
11063
11722
  var _this = this;
11064
11723
  var _data$session$access_, _data$session;
11065
11724
  if (_this.accessToken)
11066
11725
  return await _this.accessToken();
11067
11726
  const { data } = await _this.auth.getSession();
11068
- return (_data$session$access_ = (_data$session = data.session) === null || _data$session === undefined ? undefined : _data$session.access_token) !== null && _data$session$access_ !== undefined ? _data$session$access_ : _this.supabaseKey;
11727
+ return (_data$session$access_ = (_data$session = data.session) === null || _data$session === undefined ? undefined : _data$session.access_token) !== null && _data$session$access_ !== undefined ? _data$session$access_ : null;
11728
+ }
11729
+ async _getAccessToken() {
11730
+ var _this2 = this;
11731
+ var _await$this$_getSessi;
11732
+ return (_await$this$_getSessi = await _this2._getSessionToken()) !== null && _await$this$_getSessi !== undefined ? _await$this$_getSessi : _this2.supabaseKey;
11069
11733
  }
11070
- _initSupabaseAuthClient({ autoRefreshToken, persistSession, detectSessionInUrl, storage, userStorage, storageKey, flowType, lock, debug, throwOnError, experimental }, headers, fetch$1) {
11734
+ _initSupabaseAuthClient({ autoRefreshToken, persistSession, detectSessionInUrl, storage, userStorage, storageKey, flowType, lock, debug, throwOnError, experimental, lockAcquireTimeout, skipAutoInitialize }, headers, fetch$1) {
11071
11735
  const authHeaders = {
11072
11736
  Authorization: `Bearer ${this.supabaseKey}`,
11073
11737
  apikey: `${this.supabaseKey}`
@@ -11087,6 +11751,8 @@ var SupabaseClient = class {
11087
11751
  throwOnError,
11088
11752
  experimental,
11089
11753
  fetch: fetch$1,
11754
+ lockAcquireTimeout,
11755
+ skipAutoInitialize,
11090
11756
  hasCustomAuthorizationHeader: Object.keys(this.headers).some((key) => key.toLowerCase() === "authorization")
11091
11757
  });
11092
11758
  }
@@ -11099,7 +11765,7 @@ var SupabaseClient = class {
11099
11765
  });
11100
11766
  }
11101
11767
  _handleTokenChanged(event, source, token) {
11102
- if ((event === "TOKEN_REFRESHED" || event === "SIGNED_IN") && this.changedAccessToken !== token) {
11768
+ if ((event === "TOKEN_REFRESHED" || event === "SIGNED_IN" || event === "INITIAL_SESSION") && this.changedAccessToken !== token) {
11103
11769
  this.changedAccessToken = token;
11104
11770
  this.realtime.setAuth(token);
11105
11771
  } else if (event === "SIGNED_OUT") {
@@ -11125,10 +11791,10 @@ function shouldShowDeprecationWarning() {
11125
11791
  const versionMatch = processVersion.match(/^v(\d+)\./);
11126
11792
  if (!versionMatch)
11127
11793
  return false;
11128
- return parseInt(versionMatch[1], 10) <= 18;
11794
+ return parseInt(versionMatch[1], 10) <= 20;
11129
11795
  }
11130
11796
  if (shouldShowDeprecationWarning())
11131
- console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");
11797
+ console.warn("⚠️ Node.js 20 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 22 or later. For more information, visit: https://github.com/orgs/supabase/discussions/45715");
11132
11798
  // src/storage/memory.ts
11133
11799
  function memoryStorage() {
11134
11800
  const store = new Map;