(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,54403,(e,t,r)=>{var s={675:function(e,t){"use strict";t.byteLength=function(e){var t=l(e),r=t[0],s=t[1];return(r+s)*3/4-s},t.toByteArray=function(e){var t,r,n=l(e),a=n[0],o=n[1],u=new i((a+o)*3/4-o),h=0,c=o>0?a-4:a;for(r=0;r>16&255,u[h++]=t>>8&255,u[h++]=255&t;return 2===o&&(t=s[e.charCodeAt(r)]<<2|s[e.charCodeAt(r+1)]>>4,u[h++]=255&t),1===o&&(t=s[e.charCodeAt(r)]<<10|s[e.charCodeAt(r+1)]<<4|s[e.charCodeAt(r+2)]>>2,u[h++]=t>>8&255,u[h++]=255&t),u},t.fromByteArray=function(e){for(var t,s=e.length,i=s%3,n=[],a=0,o=s-i;a>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return n.join("")}(e,a,a+16383>o?o:a+16383));return 1===i?n.push(r[(t=e[s-1])>>2]+r[t<<4&63]+"=="):2===i&&n.push(r[(t=(e[s-2]<<8)+e[s-1])>>10]+r[t>>4&63]+r[t<<2&63]+"="),n.join("")};for(var r=[],s=[],i="u">typeof Uint8Array?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,o=n.length;a0)throw Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");-1===r&&(r=t);var s=r===t?0:4-r%4;return[r,s]}s[45]=62,s[95]=63},72:function(e,t,r){"use strict";var s=r(675),i=r(783),n="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;function a(e){if(e>0x7fffffff)throw RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return Object.setPrototypeOf(t,o.prototype),t}function o(e,t,r){if("number"==typeof e){if("string"==typeof t)throw TypeError('The "string" argument must be of type string. Received type number');return h(e)}return l(e,t,r)}function l(e,t,r){if("string"==typeof e){var s=e,i=t;if(("string"!=typeof i||""===i)&&(i="utf8"),!o.isEncoding(i))throw TypeError("Unknown encoding: "+i);var n=0|f(s,i),l=a(n),u=l.write(s,i);return u!==n&&(l=l.slice(0,u)),l}if(ArrayBuffer.isView(e))return c(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(j(e,ArrayBuffer)||e&&j(e.buffer,ArrayBuffer)||"u">typeof SharedArrayBuffer&&(j(e,SharedArrayBuffer)||e&&j(e.buffer,SharedArrayBuffer)))return function(e,t,r){var s;if(t<0||e.byteLengthtypeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return o.from(e[Symbol.toPrimitive]("string"),t,r);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function u(e){if("number"!=typeof e)throw TypeError('"size" argument must be of type number');if(e<0)throw RangeError('The value "'+e+'" is invalid for option "size"')}function h(e){return u(e),a(e<0?0:0|d(e))}function c(e){for(var t=e.length<0?0:0|d(e.length),r=a(t),s=0;stypeof console&&"function"==typeof console.error&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}}),o.poolSize=8192,o.from=function(e,t,r){return l(e,t,r)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array),o.alloc=function(e,t,r){return(u(e),e<=0)?a(e):void 0!==t?"string"==typeof r?a(e).fill(t,r):a(e).fill(t):a(e)},o.allocUnsafe=function(e){return h(e)},o.allocUnsafeSlow=function(e){return h(e)};function d(e){if(e>=0x7fffffff)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x7fffffff bytes");return 0|e}function f(e,t){if(o.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||j(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var r=e.length,s=arguments.length>2&&!0===arguments[2];if(!s&&0===r)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return T(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return A(e).length;default:if(i)return s?-1:T(e).length;t=(""+t).toLowerCase(),i=!0}}function p(e,t,r){var i,n,a,o=!1;if((void 0===t||t<0)&&(t=0),t>this.length||((void 0===r||r>this.length)&&(r=this.length),r<=0||(r>>>=0)<=(t>>>=0)))return"";for(e||(e="utf8");;)switch(e){case"hex":return function(e,t,r){var s=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>s)&&(r=s);for(var i="",n=t;n0x7fffffff?r=0x7fffffff:r<-0x80000000&&(r=-0x80000000),(n=r*=1)!=n&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length)if(i)return -1;else r=e.length-1;else if(r<0)if(!i)return -1;else r=0;if("string"==typeof t&&(t=o.from(t,s)),o.isBuffer(t))return 0===t.length?-1:m(e,t,r,s,i);if("number"==typeof t){if(t&=255,"function"==typeof Uint8Array.prototype.indexOf)if(i)return Uint8Array.prototype.indexOf.call(e,t,r);else return Uint8Array.prototype.lastIndexOf.call(e,t,r);return m(e,[t],r,s,i)}throw TypeError("val must be string, number or Buffer")}function m(e,t,r,s,i){var n,a=1,o=e.length,l=t.length;if(void 0!==s&&("ucs2"===(s=String(s).toLowerCase())||"ucs-2"===s||"utf16le"===s||"utf-16le"===s)){if(e.length<2||t.length<2)return -1;a=2,o/=2,l/=2,r/=2}function u(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){var h=-1;for(n=r;no&&(r=o-l),n=r;n>=0;n--){for(var c=!0,d=0;dr&&(e+=" ... "),""},n&&(o.prototype[n]=o.prototype.inspect),o.prototype.compare=function(e,t,r,s,i){if(j(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),!o.isBuffer(e))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===s&&(s=0),void 0===i&&(i=this.length),t<0||r>e.length||s<0||i>this.length)throw RangeError("out of range index");if(s>=i&&t>=r)return 0;if(s>=i)return -1;if(t>=r)return 1;if(t>>>=0,r>>>=0,s>>>=0,i>>>=0,this===e)return 0;for(var n=i-s,a=r-t,l=Math.min(n,a),u=this.slice(s,i),h=e.slice(t,r),c=0;c239?4:u>223?3:u>191?2:1;if(i+c<=r)switch(c){case 1:u<128&&(h=u);break;case 2:(192&(n=e[i+1]))==128&&(l=(31&u)<<6|63&n)>127&&(h=l);break;case 3:n=e[i+1],a=e[i+2],(192&n)==128&&(192&a)==128&&(l=(15&u)<<12|(63&n)<<6|63&a)>2047&&(l<55296||l>57343)&&(h=l);break;case 4:n=e[i+1],a=e[i+2],o=e[i+3],(192&n)==128&&(192&a)==128&&(192&o)==128&&(l=(15&u)<<18|(63&n)<<12|(63&a)<<6|63&o)>65535&&l<1114112&&(h=l)}null===h?(h=65533,c=1):h>65535&&(h-=65536,s.push(h>>>10&1023|55296),h=56320|1023&h),s.push(h),i+=c}var d=s,f=d.length;if(f<=4096)return String.fromCharCode.apply(String,d);for(var p="",g=0;gr)throw RangeError("Trying to access beyond buffer length")}function v(e,t,r,s,i,n){if(!o.isBuffer(e))throw TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw RangeError("Index out of range")}function _(e,t,r,s,i,n){if(r+s>e.length||r<0)throw RangeError("Index out of range")}function k(e,t,r,s,n){return t*=1,r>>>=0,n||_(e,t,r,4,34028234663852886e22,-34028234663852886e22),i.write(e,t,r,s,23,4),r+4}function S(e,t,r,s,n){return t*=1,r>>>=0,n||_(e,t,r,8,17976931348623157e292,-17976931348623157e292),i.write(e,t,r,s,52,8),r+8}o.prototype.write=function(e,t,r,s){if(void 0===t)s="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)s=t,r=this.length,t=0;else if(isFinite(t))t>>>=0,isFinite(r)?(r>>>=0,void 0===s&&(s="utf8")):(s=r,r=void 0);else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var i,n,a,o,l,u,h,c,d=this.length-t;if((void 0===r||r>d)&&(r=d),e.length>0&&(r<0||t<0)||t>this.length)throw RangeError("Attempt to write outside buffer bounds");s||(s="utf8");for(var f=!1;;)switch(s){case"hex":return function(e,t,r,s){r=Number(r)||0;var i=e.length-r;s?(s=Number(s))>i&&(s=i):s=i;var n=t.length;s>n/2&&(s=n/2);for(var a=0;a>8,i.push(r%256),i.push(s);return i}(e,this.length-h),this,h,c);default:if(f)throw TypeError("Unknown encoding: "+s);s=(""+s).toLowerCase(),f=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},o.prototype.slice=function(e,t){var r=this.length;e=~~e,t=void 0===t?r:~~t,e<0?(e+=r)<0&&(e=0):e>r&&(e=r),t<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||b(e,t,this.length);for(var s=this[e],i=1,n=0;++n>>=0,t>>>=0,r||b(e,t,this.length);for(var s=this[e+--t],i=1;t>0&&(i*=256);)s+=this[e+--t]*i;return s},o.prototype.readUInt8=function(e,t){return e>>>=0,t||b(e,1,this.length),this[e]},o.prototype.readUInt16LE=function(e,t){return e>>>=0,t||b(e,2,this.length),this[e]|this[e+1]<<8},o.prototype.readUInt16BE=function(e,t){return e>>>=0,t||b(e,2,this.length),this[e]<<8|this[e+1]},o.prototype.readUInt32LE=function(e,t){return e>>>=0,t||b(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+0x1000000*this[e+3]},o.prototype.readUInt32BE=function(e,t){return e>>>=0,t||b(e,4,this.length),0x1000000*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},o.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||b(e,t,this.length);for(var s=this[e],i=1,n=0;++n=(i*=128)&&(s-=Math.pow(2,8*t)),s},o.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||b(e,t,this.length);for(var s=t,i=1,n=this[e+--s];s>0&&(i*=256);)n+=this[e+--s]*i;return n>=(i*=128)&&(n-=Math.pow(2,8*t)),n},o.prototype.readInt8=function(e,t){return(e>>>=0,t||b(e,1,this.length),128&this[e])?-((255-this[e]+1)*1):this[e]},o.prototype.readInt16LE=function(e,t){e>>>=0,t||b(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?0xffff0000|r:r},o.prototype.readInt16BE=function(e,t){e>>>=0,t||b(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?0xffff0000|r:r},o.prototype.readInt32LE=function(e,t){return e>>>=0,t||b(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},o.prototype.readInt32BE=function(e,t){return e>>>=0,t||b(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},o.prototype.readFloatLE=function(e,t){return e>>>=0,t||b(e,4,this.length),i.read(this,e,!0,23,4)},o.prototype.readFloatBE=function(e,t){return e>>>=0,t||b(e,4,this.length),i.read(this,e,!1,23,4)},o.prototype.readDoubleLE=function(e,t){return e>>>=0,t||b(e,8,this.length),i.read(this,e,!0,52,8)},o.prototype.readDoubleBE=function(e,t){return e>>>=0,t||b(e,8,this.length),i.read(this,e,!1,52,8)},o.prototype.writeUIntLE=function(e,t,r,s){if(e*=1,t>>>=0,r>>>=0,!s){var i=Math.pow(2,8*r)-1;v(this,e,t,r,i,0)}var n=1,a=0;for(this[t]=255&e;++a>>=0,r>>>=0,!s){var i=Math.pow(2,8*r)-1;v(this,e,t,r,i,0)}var n=r-1,a=1;for(this[t+n]=255&e;--n>=0&&(a*=256);)this[t+n]=e/a&255;return t+r},o.prototype.writeUInt8=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,1,255,0),this[t]=255&e,t+1},o.prototype.writeUInt16LE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeUInt16BE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeUInt32LE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,4,0xffffffff,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},o.prototype.writeUInt32BE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,4,0xffffffff,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeIntLE=function(e,t,r,s){if(e*=1,t>>>=0,!s){var i=Math.pow(2,8*r-1);v(this,e,t,r,i-1,-i)}var n=0,a=1,o=0;for(this[t]=255&e;++n>>=0,!s){var i=Math.pow(2,8*r-1);v(this,e,t,r,i-1,-i)}var n=r-1,a=1,o=0;for(this[t+n]=255&e;--n>=0&&(a*=256);)e<0&&0===o&&0!==this[t+n+1]&&(o=1),this[t+n]=(e/a|0)-o&255;return t+r},o.prototype.writeInt8=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},o.prototype.writeInt16LE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeInt16BE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeInt32LE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,4,0x7fffffff,-0x80000000),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},o.prototype.writeInt32BE=function(e,t,r){return e*=1,t>>>=0,r||v(this,e,t,4,0x7fffffff,-0x80000000),e<0&&(e=0xffffffff+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeFloatLE=function(e,t,r){return k(this,e,t,!0,r)},o.prototype.writeFloatBE=function(e,t,r){return k(this,e,t,!1,r)},o.prototype.writeDoubleLE=function(e,t,r){return S(this,e,t,!0,r)},o.prototype.writeDoubleBE=function(e,t,r){return S(this,e,t,!1,r)},o.prototype.copy=function(e,t,r,s){if(!o.isBuffer(e))throw TypeError("argument should be a Buffer");if(r||(r=0),s||0===s||(s=this.length),t>=e.length&&(t=e.length),t||(t=0),s>0&&s=this.length)throw RangeError("Index out of range");if(s<0)throw RangeError("sourceEnd out of bounds");s>this.length&&(s=this.length),e.length-t=0;--n)e[n+t]=this[n+r];else Uint8Array.prototype.set.call(e,this.subarray(r,s),t);return i},o.prototype.fill=function(e,t,r,s){if("string"==typeof e){if("string"==typeof t?(s=t,t=0,r=this.length):"string"==typeof r&&(s=r,r=this.length),void 0!==s&&"string"!=typeof s)throw TypeError("encoding must be a string");if("string"==typeof s&&!o.isEncoding(s))throw TypeError("Unknown encoding: "+s);if(1===e.length){var i,n=e.charCodeAt(0);("utf8"===s&&n<128||"latin1"===s)&&(e=n)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i55295&&r<57344){if(!i){if(r>56319||a+1===s){(t-=3)>-1&&n.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&n.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(t-=3)>-1&&n.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;n.push(r)}else if(r<2048){if((t-=2)<0)break;n.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;n.push(r>>12|224,r>>6&63|128,63&r|128)}else if(r<1114112){if((t-=4)<0)break;n.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}else throw Error("Invalid code point")}return n}function O(e){for(var t=[],r=0;r=t.length)&&!(i>=e.length);++i)t[i+r]=e[i];return i}function j(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}var I=function(){for(var e="0123456789abcdef",t=Array(256),r=0;r<16;++r)for(var s=16*r,i=0;i<16;++i)t[s+i]=e[r]+e[i];return t}()},783:function(e,t){t.read=function(e,t,r,s,i){var n,a,o=8*i-s-1,l=(1<>1,h=-7,c=r?i-1:0,d=r?-1:1,f=e[t+c];for(c+=d,n=f&(1<<-h)-1,f>>=-h,h+=o;h>0;n=256*n+e[t+c],c+=d,h-=8);for(a=n&(1<<-h)-1,n>>=-h,h+=s;h>0;a=256*a+e[t+c],c+=d,h-=8);if(0===n)n=1-u;else{if(n===l)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,s),n-=u}return(f?-1:1)*a*Math.pow(2,n-s)},t.write=function(e,t,r,s,i,n){var a,o,l,u=8*n-i-1,h=(1<>1,d=5960464477539062e-23*(23===i),f=s?0:n-1,p=s?1:-1,g=+(t<0||0===t&&1/t<0);for(isNaN(t=Math.abs(t))||t===1/0?(o=+!!isNaN(t),a=h):(a=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-a))<1&&(a--,l*=2),a+c>=1?t+=d/l:t+=d*Math.pow(2,1-c),t*l>=2&&(a++,l/=2),a+c>=h?(o=0,a=h):a+c>=1?(o=(t*l-1)*Math.pow(2,i),a+=c):(o=t*Math.pow(2,c-1)*Math.pow(2,i),a=0));i>=8;e[r+f]=255&o,f+=p,o/=256,i-=8);for(a=a<0;e[r+f]=255&a,f+=p,a/=256,u-=8);e[r+f-p]|=128*g}}},i={};function n(e){var t=i[e];if(void 0!==t)return t.exports;var r=i[e]={exports:{}},a=!0;try{s[e](r,r.exports,n),a=!1}finally{a&&delete i[e]}return r.exports}n.ab="/ROOT/Documents/GitHub/VivianMonoRepo/vivian-landing/node_modules/next/dist/compiled/buffer/",t.exports=n(72)},86782,80551,59451,45073,35823,e=>{"use strict";let t,r,s,i,n,a;e.i(48158);class o extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class l extends o{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class u extends o{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class h extends o{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}function c(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&0>t.indexOf(s)&&(r[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,s=Object.getOwnPropertySymbols(e);it.indexOf(s[i])&&Object.prototype.propertyIsEnumerable.call(e,s[i])&&(r[s[i]]=e[s[i]]);return r}(k=S||(S={})).Any="any",k.ApNortheast1="ap-northeast-1",k.ApNortheast2="ap-northeast-2",k.ApSouth1="ap-south-1",k.ApSoutheast1="ap-southeast-1",k.ApSoutheast2="ap-southeast-2",k.CaCentral1="ca-central-1",k.EuCentral1="eu-central-1",k.EuWest1="eu-west-1",k.EuWest2="eu-west-2",k.EuWest3="eu-west-3",k.SaEast1="sa-east-1",k.UsEast1="us-east-1",k.UsWest1="us-west-1",k.UsWest2="us-west-2";"function"==typeof SuppressedError&&SuppressedError;class d{constructor(e,{headers:t={},customFetch:r,region:s=S.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){var t,r,s,i;return t=this,r=arguments,s=void 0,i=function*(e,t={}){var r;let s,i;try{let n,{headers:a,method:o,body:c,signal:d,timeout:f}=t,p={},{region:g}=t;g||(g=this.region);let y=new URL(`${this.url}/${e}`);g&&"any"!==g&&(p["x-region"]=g,y.searchParams.set("forceFunctionRegion",g)),c&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?"u">typeof Blob&&c instanceof Blob||c instanceof ArrayBuffer?(p["Content-Type"]="application/octet-stream",n=c):"string"==typeof c?(p["Content-Type"]="text/plain",n=c):"u">typeof FormData&&c instanceof FormData?n=c:(p["Content-Type"]="application/json",n=JSON.stringify(c)):n=!c||"string"==typeof c||"u">typeof Blob&&c instanceof Blob||c instanceof ArrayBuffer||"u">typeof FormData&&c instanceof FormData?c:JSON.stringify(c);let m=d;f&&(i=new AbortController,s=setTimeout(()=>i.abort(),f),d?(m=i.signal,d.addEventListener("abort",()=>i.abort())):m=i.signal);let w=yield this.fetch(y.toString(),{method:o||"POST",headers:Object.assign(Object.assign(Object.assign({},p),this.headers),a),body:n,signal:m}).catch(e=>{throw new l(e)}),b=w.headers.get("x-relay-error");if(b&&"true"===b)throw new u(w);if(!w.ok)throw new h(w);let v=(null!=(r=w.headers.get("Content-Type"))?r:"text/plain").split(";")[0].trim();return{data:"application/json"===v?yield w.json():"application/octet-stream"===v||"application/pdf"===v?yield w.blob():"text/event-stream"===v?w:"multipart/form-data"===v?yield w.formData():yield w.text(),error:null,response:w}}catch(e){return{data:null,error:e,response:e instanceof h||e instanceof u?e.context:void 0}}finally{s&&clearTimeout(s)}},new(s||(s=Promise))(function(e,n){function a(e){try{l(i.next(e))}catch(e){n(e)}}function o(e){try{l(i.throw(e))}catch(e){n(e)}}function l(t){var r;t.done?e(t.value):((r=t.value)instanceof s?r:new s(function(e){e(r)})).then(a,o)}l((i=i.apply(t,r||[])).next())})}}var f,p,g,y,m,w,b,v,_,k,S,E,T,O,A,R,j,I,$,C,P,x=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}},U=class{constructor(e){var t,r;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=null!=(t=e.shouldThrowOnError)&&t,this.signal=e.signal,this.isMaybeSingle=null!=(r=e.isMaybeSingle)&&r,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){var r=this;void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json");let s=(0,this.fetch)(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{var t,s,i,n;let a=null,o=null,l=null,u=e.status,h=e.statusText;if(e.ok){if("HEAD"!==r.method){let t=await e.text();""===t||(o="text/csv"===r.headers.get("Accept")||r.headers.get("Accept")&&(null==(i=r.headers.get("Accept"))?void 0:i.includes("application/vnd.pgrst.plan+text"))?t:JSON.parse(t))}let n=null==(t=r.headers.get("Prefer"))?void 0:t.match(/count=(exact|planned|estimated)/),c=null==(s=e.headers.get("content-range"))?void 0:s.split("/");n&&c&&c.length>1&&(l=parseInt(c[1])),r.isMaybeSingle&&"GET"===r.method&&Array.isArray(o)&&(o.length>1?(a={code:"PGRST116",details:`Results contain ${o.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},o=null,l=null,u=406,h="Not Acceptable"):o=1===o.length?o[0]:null)}else{let t=await e.text();try{a=JSON.parse(t),Array.isArray(a)&&404===e.status&&(o=[],a=null,u=200,h="OK")}catch(r){404===e.status&&""===t?(u=204,h="No Content"):a={message:t}}if(a&&r.isMaybeSingle&&(null==a||null==(n=a.details)?void 0:n.includes("0 rows"))&&(a=null,u=200,h="OK"),a&&r.shouldThrowOnError)throw new x(a)}return{error:a,data:o,count:l,status:u,statusText:h}});return this.shouldThrowOnError||(s=s.catch(e=>{var t,r,s,i,n,a;let o="",l=null==e?void 0:e.cause;if(l){let t=null!=(r=null==l?void 0:l.message)?r:"",a=null!=(s=null==l?void 0:l.code)?s:"";o=`${null!=(i=null==e?void 0:e.name)?i:"FetchError"}: ${null==e?void 0:e.message} Caused by: ${null!=(n=null==l?void 0:l.name)?n:"Error"}: ${t}`,a&&(o+=` (${a})`),(null==l?void 0:l.stack)&&(o+=` ${l.stack}`)}else o=null!=(a=null==e?void 0:e.stack)?a:"";return{error:{message:`${null!=(t=null==e?void 0:e.name)?t:"FetchError"}: ${null==e?void 0:e.message}`,details:o,hint:"",code:""},data:null,count:null,status:0,statusText:""}})),s.then(e,t)}returns(){return this}overrideTypes(){return this}},N=class extends U{select(e){let t=!1,r=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:s,referencedTable:i=s}={}){let n=i?`${i}.order`:"order",a=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let s=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:s=r}={}){let i=void 0===s?"offset":`${s}.offset`,n=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(n,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return"GET"===this.method?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:s=!1,wal:i=!1,format:n="text"}={}){var a;let o=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=null!=(a=this.headers.get("Accept"))?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${l}"; options=${o};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};let B=RegExp("[,()]");var D=class extends N{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map(e=>"string"==typeof e&&B.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}notIn(e,t){let r=Array.from(new Set(t)).map(e=>"string"==typeof e&&B.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`not.in.(${r})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:s}={}){let i="";"plain"===s?i="pl":"phrase"===s?i="ph":"websearch"===s&&(i="w");let n=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${i}fts${n}.${t}`),this}match(e){return Object.entries(e).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}},L=class{constructor(e,{headers:t={},schema:r,fetch:s}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=s}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){let{head:r=!1,count:s}=null!=t?t:{},i=!1,n=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!i?"":('"'===e&&(i=!i),e)).join(""),{url:a,headers:o}=this.cloneRequestState();return a.searchParams.set("select",n),s&&o.append("Prefer",`count=${s}`),new D({method:r?"HEAD":"GET",url:a,headers:o,schema:this.schema,fetch:this.fetch})}insert(e,{count:t,defaultToNull:r=!0}={}){var s;let{url:i,headers:n}=this.cloneRequestState();if(t&&n.append("Prefer",`count=${t}`),r||n.append("Prefer","missing=default"),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);i.searchParams.set("columns",e.join(","))}}return new D({method:"POST",url:i,headers:n,schema:this.schema,body:e,fetch:null!=(s=this.fetch)?s:fetch})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:s,defaultToNull:i=!0}={}){var n;let{url:a,headers:o}=this.cloneRequestState();if(o.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==t&&a.searchParams.set("on_conflict",t),s&&o.append("Prefer",`count=${s}`),i||o.append("Prefer","missing=default"),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);a.searchParams.set("columns",e.join(","))}}return new D({method:"POST",url:a,headers:o,schema:this.schema,body:e,fetch:null!=(n=this.fetch)?n:fetch})}update(e,{count:t}={}){var r;let{url:s,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new D({method:"PATCH",url:s,headers:i,schema:this.schema,body:e,fetch:null!=(r=this.fetch)?r:fetch})}delete({count:e}={}){var t;let{url:r,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new D({method:"DELETE",url:r,headers:s,schema:this.schema,fetch:null!=(t=this.fetch)?t:fetch})}},q=class e{constructor(e,{headers:t={},schema:r,fetch:s}={}){this.url=e,this.headers=new Headers(t),this.schemaName=r,this.fetch=s}from(e){if(!e||"string"!=typeof e||""===e.trim())throw Error("Invalid relation name: relation must be a non-empty string.");return new L(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:s=!1,count:i}={}){var n;let a,o,l=new URL(`${this.url}/rpc/${e}`),u=e=>null!==e&&"object"==typeof e&&(!Array.isArray(e)||e.some(u)),h=r&&Object.values(t).some(u);h?(a="POST",o=t):r||s?(a=r?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{l.searchParams.append(e,t)})):(a="POST",o=t);let c=new Headers(this.headers);return h?c.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&c.set("Prefer",`count=${i}`),new D({method:a,url:l,headers:c,schema:this.schemaName,body:o,fetch:null!=(n=this.fetch)?n:fetch})}};let M=class{static detectEnvironment(){var t;if("u">typeof WebSocket)return{type:"native",constructor:WebSocket};if("u">typeof globalThis&&void 0!==globalThis.WebSocket)return{type:"native",constructor:globalThis.WebSocket};if(void 0!==e.g.WebSocket)return{type:"native",constructor:e.g.WebSocket};if("u">typeof globalThis&&void 0!==globalThis.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("u">typeof globalThis&&globalThis.EdgeRuntime||"u">typeof navigator&&(null==(t=navigator.userAgent)?void 0:t.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let r=globalThis.process;if(r){let e=r.versions;if(e&&e.node){let t=parseInt(e.node.replace(/^v/,"").split(".")[0]);return t>=22?void 0!==globalThis.WebSocket?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${t} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${t} detected without native WebSocket support.`,workaround:'For Node.js < 22, install "ws" package and provide it via the transport option:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){let e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=` Suggested solution: ${e.workaround}`),Error(t)}static createWebSocket(e,t){return new(this.getWebSocketConstructor())(e,t)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return"native"===e.type||"ws"===e.type}catch(e){return!1}}},W="2.0.0";(f=E||(E={}))[f.connecting=0]="connecting",f[f.open=1]="open",f[f.closing=2]="closing",f[f.closed=3]="closed",(p=T||(T={})).closed="closed",p.errored="errored",p.joined="joined",p.joining="joining",p.leaving="leaving",(g=O||(O={})).close="phx_close",g.error="phx_error",g.join="phx_join",g.reply="phx_reply",g.leave="phx_leave",g.access_token="access_token",(A||(A={})).websocket="websocket",(y=R||(R={})).Connecting="connecting",y.Open="open",y.Closing="closing",y.Closed="closed";class K{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=null!=e?e:[]}encode(e,t){return e.event!==this.BROADCAST_EVENT||e.payload instanceof ArrayBuffer||"string"!=typeof e.payload.event?t(JSON.stringify([e.join_ref,e.ref,e.topic,e.event,e.payload])):t(this._binaryEncodeUserBroadcastPush(e))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer(null==(t=e.payload)?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,r;let s=null!=(r=null==(t=e.payload)?void 0:t.payload)?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(e){var t,r;let s=null!=(r=null==(t=e.payload)?void 0:t.payload)?r:{},i=new TextEncoder().encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,i)}_encodeUserBroadcastPush(e,t,r){let s=e.topic,i=null!=(f=e.ref)?f:"",n=null!=(p=e.join_ref)?p:"",a=e.payload.event,o=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},l=0===Object.keys(o).length?"":JSON.stringify(o);if(n.length>255)throw Error(`joinRef length ${n.length} exceeds maximum of 255`);if(i.length>255)throw Error(`ref length ${i.length} exceeds maximum of 255`);if(s.length>255)throw Error(`topic length ${s.length} exceeds maximum of 255`);if(a.length>255)throw Error(`userEvent length ${a.length} exceeds maximum of 255`);if(l.length>255)throw Error(`metadata length ${l.length} exceeds maximum of 255`);let u=this.USER_BROADCAST_PUSH_META_LENGTH+n.length+i.length+s.length+a.length+l.length,h=new ArrayBuffer(this.HEADER_LENGTH+u),c=new DataView(h),d=0;c.setUint8(d++,this.KINDS.userBroadcastPush),c.setUint8(d++,n.length),c.setUint8(d++,i.length),c.setUint8(d++,s.length),c.setUint8(d++,a.length),c.setUint8(d++,l.length),c.setUint8(d++,t),Array.from(n,e=>c.setUint8(d++,e.charCodeAt(0))),Array.from(i,e=>c.setUint8(d++,e.charCodeAt(0))),Array.from(s,e=>c.setUint8(d++,e.charCodeAt(0))),Array.from(a,e=>c.setUint8(d++,e.charCodeAt(0))),Array.from(l,e=>c.setUint8(d++,e.charCodeAt(0)));var f,p,g=new Uint8Array(h.byteLength+r.byteLength);return g.set(new Uint8Array(h),0),g.set(new Uint8Array(r),h.byteLength),g.buffer}decode(e,t){if(this._isArrayBuffer(e))return t(this._binaryDecode(e));if("string"==typeof e){let[r,s,i,n,a]=JSON.parse(e);return t({join_ref:r,ref:s,topic:i,event:n,payload:a})}return t({})}_binaryDecode(e){let t=new DataView(e),r=t.getUint8(0),s=new TextDecoder;if(r===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,t,s)}_decodeUserBroadcast(e,t,r){let s=t.getUint8(1),i=t.getUint8(2),n=t.getUint8(3),a=t.getUint8(4),o=this.HEADER_LENGTH+4,l=r.decode(e.slice(o,o+s));o+=s;let u=r.decode(e.slice(o,o+i));o+=i;let h=r.decode(e.slice(o,o+n));o+=n;let c=e.slice(o,e.byteLength),d=a===this.JSON_ENCODING?JSON.parse(r.decode(c)):c,f={type:this.BROADCAST_EVENT,event:u,payload:d};return n>0&&(f.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:l,event:this.BROADCAST_EVENT,payload:f}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||(null==(t=null==e?void 0:e.constructor)?void 0:t.name)==="ArrayBuffer"}_pick(e,t){return e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e))):{}}}class F{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}(m=j||(j={})).abstime="abstime",m.bool="bool",m.date="date",m.daterange="daterange",m.float4="float4",m.float8="float8",m.int2="int2",m.int4="int4",m.int4range="int4range",m.int8="int8",m.int8range="int8range",m.json="json",m.jsonb="jsonb",m.money="money",m.numeric="numeric",m.oid="oid",m.reltime="reltime",m.text="text",m.time="time",m.timestamp="timestamp",m.timestamptz="timestamptz",m.timetz="timetz",m.tsrange="tsrange",m.tstzrange="tstzrange";let z=(e,t,r={})=>{var s;let i=null!=(s=r.skipTypes)?s:[];return t?Object.keys(t).reduce((r,s)=>(r[s]=J(s,e,t,i),r),{}):{}},J=(e,t,r,s)=>{let i=t.find(t=>t.name===e),n=null==i?void 0:i.type,a=r[e];return n&&!s.includes(n)?V(n,a):G(a)},V=(e,t)=>{if("_"===e.charAt(0))return Z(t,e.slice(1,e.length));switch(e){case j.bool:return H(t);case j.float4:case j.float8:case j.int2:case j.int4:case j.int8:case j.numeric:case j.oid:return Y(t);case j.json:case j.jsonb:return X(t);case j.timestamp:return Q(t);case j.abstime:case j.date:case j.daterange:case j.int4range:case j.int8range:case j.money:case j.reltime:case j.text:case j.time:case j.timestamptz:case j.timetz:case j.tsrange:case j.tstzrange:default:return G(t)}},G=e=>e,H=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},Y=e=>{if("string"==typeof e){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},X=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(e){}return e},Z=(e,t)=>{if("string"!=typeof e)return e;let r=e.length-1,s=e[r];if("{"===e[0]&&"}"===s){let s,i=e.slice(1,r);try{s=JSON.parse("["+i+"]")}catch(e){s=i?i.split(","):[]}return s.map(e=>V(t,e))}return e},Q=e=>"string"==typeof e?e.replace(" ","T"):e,ee=e=>{let t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===t.pathname||"/"===t.pathname?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};class et{constructor(e,t,r={},s=1e4){this.channel=e,this.event=t,this.payload=r,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t(null==(r=this.receivedResp)?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(e)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}(w=I||(I={})).SYNC="sync",w.JOIN="join",w.LEAVE="leave";class er{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(null==t?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},e=>{let{onJoin:t,onLeave:r,onSync:s}=this.caller;this.joinRef=this.channel._joinRef(),this.state=er.syncState(this.state,e,t,r),this.pendingDiffs.forEach(e=>{this.state=er.syncDiff(this.state,e,t,r)}),this.pendingDiffs=[],s()}),this.channel._on(r.diff,{},e=>{let{onJoin:t,onLeave:r,onSync:s}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=er.syncDiff(this.state,e,t,r),s())}),this.onJoin((e,t,r)=>{this.channel._trigger("presence",{event:"join",key:e,currentPresences:t,newPresences:r})}),this.onLeave((e,t,r)=>{this.channel._trigger("presence",{event:"leave",key:e,currentPresences:t,leftPresences:r})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,s){let i=this.cloneDeep(e),n=this.transformState(t),a={},o={};return this.map(i,(e,t)=>{n[e]||(o[e]=t)}),this.map(n,(e,t)=>{let r=i[e];if(r){let s=t.map(e=>e.presence_ref),i=r.map(e=>e.presence_ref),n=t.filter(e=>0>i.indexOf(e.presence_ref)),l=r.filter(e=>0>s.indexOf(e.presence_ref));n.length>0&&(a[e]=n),l.length>0&&(o[e]=l)}else a[e]=t}),this.syncDiff(i,{joins:a,leaves:o},r,s)}static syncDiff(e,t,r,s){let{joins:i,leaves:n}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),s||(s=()=>{}),this.map(i,(t,s)=>{var i;let n=null!=(i=e[t])?i:[];if(e[t]=this.cloneDeep(s),n.length>0){let r=e[t].map(e=>e.presence_ref),s=n.filter(e=>0>r.indexOf(e.presence_ref));e[t].unshift(...s)}r(t,n,s)}),this.map(n,(t,r)=>{let i=e[t];if(!i)return;let n=r.map(e=>e.presence_ref);i=i.filter(e=>0>n.indexOf(e.presence_ref)),e[t]=i,s(t,i,r),0===i.length&&delete e[t]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return Object.getOwnPropertyNames(e=this.cloneDeep(e)).reduce((t,r)=>{let s=e[r];return"metas"in s?t[r]=s.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):t[r]=s,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}(b=$||($={})).ALL="*",b.INSERT="INSERT",b.UPDATE="UPDATE",b.DELETE="DELETE",(v=C||(C={})).BROADCAST="broadcast",v.PRESENCE="presence",v.POSTGRES_CHANGES="postgres_changes",v.SYSTEM="system",(_=P||(P={})).SUBSCRIBED="SUBSCRIBED",_.TIMED_OUT="TIMED_OUT",_.CLOSED="CLOSED",_.CHANNEL_ERROR="CHANNEL_ERROR";class es{constructor(e,t={config:{}},r){var s,i;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=T.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new et(this,O.join,this.params,this.timeout),this.rejoinTimer=new F(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=T.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=T.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=T.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=T.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=T.errored,this.rejoinTimer.scheduleTimeout())}),this._on(O.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new er(this),this.broadcastEndpointURL=ee(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(null==(i=null==(s=this.params.config)?void 0:s.broadcast)?void 0:i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var r,s,i;if(this.socket.isConnected()||this.socket.connect(),this.state==T.closed){let{config:{broadcast:n,presence:a,private:o}}=this.params,l=null!=(s=null==(r=this.bindings.postgres_changes)?void 0:r.map(e=>e.filter))?s:[],u=!!this.bindings[C.PRESENCE]&&this.bindings[C.PRESENCE].length>0||(null==(i=this.params.config.presence)?void 0:i.enabled)===!0,h={},c={broadcast:n,presence:Object.assign(Object.assign({},a),{enabled:u}),postgres_changes:l,private:o};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(t=>null==e?void 0:e(P.CHANNEL_ERROR,t)),this._onClose(()=>null==e?void 0:e(P.CLOSED)),this.updateJoinPayload(Object.assign({config:c},h)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:t})=>{var r;if(this.socket._isManualToken()||this.socket.setAuth(),void 0===t){null==e||e(P.SUBSCRIBED);return}{let s=this.bindings.postgres_changes,i=null!=(r=null==s?void 0:s.length)?r:0,n=[];for(let r=0;r{this.state=T.errored,null==e||e(P.CHANNEL_ERROR,Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{null==e||e(P.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this.state===T.joined&&e===C.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,t,r)}async httpSend(e,t,r={}){var s;if(null==t)return Promise.reject("Payload is required for httpSend()");let i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);let n={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,n,null!=(s=r.timeout)?s:this.timeout);if(202===a.status)return{success:!0};let o=a.statusText;try{let e=await a.json();o=e.error||e.message||o}catch(e){}return Promise.reject(Error(o))}async send(e,t={}){var r,s;if(this._canPush()||"broadcast"!==e.type)return new Promise(r=>{var s,i,n;let a=this._push(e.type,e,t.timeout||this.timeout);"broadcast"!==e.type||(null==(n=null==(i=null==(s=this.params)?void 0:s.config)?void 0:i.broadcast)?void 0:n.ack)||r("ok"),a.receive("ok",()=>r("ok")),a.receive("error",()=>r("error")),a.receive("timeout",()=>r("timed out"))});{console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");let{event:i,payload:n}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);let o={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:n,private:this.private}]})};try{let e=await this._fetchWithTimeout(this.broadcastEndpointURL,o,null!=(r=t.timeout)?r:this.timeout);return await (null==(s=e.body)?void 0:s.cancel()),e.ok?"ok":"error"}catch(e){if("AbortError"===e.name)return"timed out";return"error"}}}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=T.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(O.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(s=>{(r=new et(this,O.leave,{},e)).receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),r.send(),this._canPush()||r.trigger("ok",{})}).finally(()=>{null==r||r.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=T.closed,this.bindings={}}async _fetchWithTimeout(e,t,r){let s=new AbortController,i=setTimeout(()=>s.abort(),r),n=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(i),n}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new et(this,e,t,r);return this._canPush()?s.send():this._addToPushBuffer(s),s}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>100){let e=this.pushBuffer.shift();e&&(e.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${e.event}`,e.payload))}}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var s,i;let n=e.toLocaleLowerCase(),{close:a,error:o,leave:l,join:u}=O;if(r&&[a,o,l,u].indexOf(n)>=0&&r!==this._joinRef())return;let h=this._onMessage(n,t,r);if(t&&!h)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(n)?null==(s=this.bindings.postgres_changes)||s.filter(e=>{var t,r,s;return(null==(t=e.filter)?void 0:t.event)==="*"||(null==(s=null==(r=e.filter)?void 0:r.event)?void 0:s.toLocaleLowerCase())===n}).map(e=>e.callback(h,r)):null==(i=this.bindings[n])||i.filter(e=>{var r,s,i,a,o,l;if(!["broadcast","presence","postgres_changes"].includes(n))return e.type.toLocaleLowerCase()===n;if("id"in e){let n=e.id,a=null==(r=e.filter)?void 0:r.event;return n&&(null==(s=t.ids)?void 0:s.includes(n))&&("*"===a||(null==a?void 0:a.toLocaleLowerCase())===(null==(i=t.data)?void 0:i.type.toLocaleLowerCase()))}{let r=null==(o=null==(a=null==e?void 0:e.filter)?void 0:a.event)?void 0:o.toLocaleLowerCase();return"*"===r||r===(null==(l=null==t?void 0:t.event)?void 0:l.toLocaleLowerCase())}}).map(e=>{if("object"==typeof h&&"ids"in h){let e=h.data,{schema:t,table:r,commit_timestamp:s,type:i,errors:n}=e;h=Object.assign(Object.assign({},{schema:t,table:r,commit_timestamp:s,eventType:i,new:{},old:{},errors:n}),this._getPayloadRecords(e))}e.callback(h,r)})}_isClosed(){return this.state===T.closed}_isJoined(){return this.state===T.joined}_isJoining(){return this.state===T.joining}_isLeaving(){return this.state===T.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){let s=e.toLocaleLowerCase(),i={type:s,filter:t,callback:r};return this.bindings[s]?this.bindings[s].push(i):this.bindings[s]=[i],this}_off(e,t){let r=e.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(e=>{var s;return!((null==(s=e.type)?void 0:s.toLocaleLowerCase())===r&&es.isEqual(e.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e)if(e[r]!==t[r])return!1;return!0}static isFilterValueEqual(e,t){return(null!=e?e:void 0)===(null!=t?t:void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(O.close,{},e)}_onError(e){this._on(O.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=T.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return("INSERT"===e.type||"UPDATE"===e.type)&&(t.new=z(e.columns,e.record)),("UPDATE"===e.type||"DELETE"===e.type)&&(t.old=z(e.columns,e.old_record)),t}}let ei=()=>{},en=[1e3,2e3,5e3,1e4],ea=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class eo{constructor(e,t){var r;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=1e4,this.transport=null,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=ei,this.ref=0,this.reconnectTimer=null,this.vsn=W,this.logger=ei,this.conn=null,this.sendBuffer=[],this.serializer=new K,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!(null==(r=null==t?void 0:t.params)?void 0:r.apikey))throw Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${A.websocket}`,this.httpEndpoint=ee(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||null!==this.conn&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=M.createWebSocket(this.endpointURL())}catch(t){this._setConnectionState("disconnected");let e=t.message;if(e.includes("Node.js"))throw Error(`${e} To use Realtime in Node.js, you need to provide a WebSocket implementation: Option 1: Use Node.js 22+ which has native WebSocket support Option 2: Install and provide the "ws" package: npm install ws import ws from "ws" const client = new RealtimeClient(url, { ...options, transport: ws })`);throw Error(`WebSocket not available: ${e}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){let r=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(r),this._setConnectionState("disconnected")},"function"==typeof this.conn.close&&(e?this.conn.close(e,null!=t?t:""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(e=>e.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case E.connecting:return R.Connecting;case E.open:return R.Open;case E.closing:return R.Closing;default:return R.Closed}}isConnected(){return this.connectionState()===R.Open}isConnecting(){return"connecting"===this._connectionState}isDisconnecting(){return"disconnecting"===this._connectionState}channel(e,t={config:{}}){let r=`realtime:${e}`,s=this.getChannels().find(e=>e.topic===r);if(s)return s;{let r=new es(`realtime:${e}`,t,this);return this.channels.push(r),r}}push(e){let{topic:t,event:r,payload:s,ref:i}=e,n=()=>{this.encode(e,e=>{var t;null==(t=this.conn)||t.send(e)})};this.log("push",`${t} ${r} (${i})`,s),this.isConnected()?n():this.sendBuffer.push(n)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}this._wasManualDisconnect=!1,null==(e=this.conn)||e.close(1e3,"heartbeat timeout"),setTimeout(()=>{var e;this.isConnected()||null==(e=this.reconnectTimer)||e.scheduleTimeout()},100);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,e=>{if("phoenix"===e.topic&&"phx_reply"===e.event&&e.ref&&e.ref===this.pendingHeartbeatRef){let t=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback("ok"===e.payload.status?"ok":"error",t)}catch(e){this.log("error","error in heartbeat callback",e)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}let{topic:t,event:r,payload:s,ref:i}=e,n=i?`(${i})`:"",a=s.status||"";this.log("receive",`${a} ${t} ${r} ${n}`.trim(),s),this.channels.filter(e=>e._isMember(t)).forEach(e=>e._trigger(r,s,i)),this._triggerStateCallbacks("message",e)})}_clearTimer(e){var t;"heartbeat"===e&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):"reconnect"===e&&(null==(t=this.reconnectTimer)||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e),this.conn.readyState===E.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===E.open||this.conn.readyState===E.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(e=>{this.log("error","error waiting for auth on connect",e),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this._terminateWorker()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||null==(t=this.reconnectTimer)||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e);try{this.heartbeatCallback("error")}catch(e){this.log("error","error in heartbeat callback",e)}}_triggerChanError(){this.channels.forEach(e=>e._trigger(O.error))}_appendParams(e,t){if(0===Object.keys(t).length)return e;let r=e.match(/\?/)?"&":"?",s=new URLSearchParams(t);return`${e}${r}${s}`}_workerObjectUrl(e){let t;if(e)t=e;else{let e=new Blob([ea],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_setConnectionState(e,t=!1){this._connectionState=e,"connecting"===e?this._wasManualDisconnect=!1:"disconnecting"===e&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t,r=!1;if(e)t=e,r=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(e){this.log("error","Error fetching access token from callback",e),t=this.accessTokenValue}else t=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{let r={access_token:t,version:"realtime-js/2.93.1"};t&&e.updateJoinPayload(r),e.joinedOnce&&e._isJoined()&&e._push(O.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(t=>{this.log("error",`Error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(r=>{try{r(t)}catch(t){this.log("error",`error in ${e} callback`,t)}})}catch(t){this.log("error",`error triggering ${e} callbacks`,t)}}_setupReconnectionTimer(){this.reconnectTimer=new F(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},10)},this.reconnectAfterMs)}_initializeOptions(e){var t,r,s,i,n,a,o,l,u,h,c,d;switch(this.transport=null!=(t=null==e?void 0:e.transport)?t:null,this.timeout=null!=(r=null==e?void 0:e.timeout)?r:1e4,this.heartbeatIntervalMs=null!=(s=null==e?void 0:e.heartbeatIntervalMs)?s:25e3,this.worker=null!=(i=null==e?void 0:e.worker)&&i,this.accessToken=null!=(n=null==e?void 0:e.accessToken)?n:null,this.heartbeatCallback=null!=(a=null==e?void 0:e.heartbeatCallback)?a:ei,this.vsn=null!=(o=null==e?void 0:e.vsn)?o:W,(null==e?void 0:e.params)&&(this.params=e.params),(null==e?void 0:e.logger)&&(this.logger=e.logger),((null==e?void 0:e.logLevel)||(null==e?void 0:e.log_level))&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=null!=(l=null==e?void 0:e.reconnectAfterMs)?l:e=>en[e-1]||1e4,this.vsn){case"1.0.0":this.encode=null!=(u=null==e?void 0:e.encode)?u:(e,t)=>t(JSON.stringify(e)),this.decode=null!=(h=null==e?void 0:e.decode)?h:(e,t)=>t(JSON.parse(e));break;case W:this.encode=null!=(c=null==e?void 0:e.encode)?c:this.serializer.encode.bind(this.serializer),this.decode=null!=(d=null==e?void 0:e.decode)?d:this.serializer.decode.bind(this.serializer);break;default:throw Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if("u">typeof window&&!window.Worker)throw Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl}}}var el=e.i(54403),eu=class extends Error{constructor(e,t){super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown="CommitStateUnknownException"===t.icebergType||[500,502,504].includes(t.status)&&t.icebergType?.includes("CommitState")===!0}isNotFound(){return 404===this.status}isConflict(){return 409===this.status}isAuthenticationTimeout(){return 419===this.status}};async function eh(e){return e&&"none"!==e.type?"bearer"===e.type?{Authorization:`Bearer ${e.token}`}:"header"===e.type?{[e.name]:e.value}:"custom"===e.type?await e.getHeaders():{}:{}}function ec(e){return e.join("\x1f")}var ed=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){let t=e?{parent:ec(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(e=>({namespace:e}))}async createNamespace(e,t){let r={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${ec(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ec(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${ec(e.namespace)}`}),!0}catch(e){if(e instanceof eu&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof eu&&409===e.status)return;throw e}}};function ef(e){return e.join("\x1f")}var ep=class{constructor(e,t="",r){this.client=e,this.prefix=t,this.accessDelegation=r}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ef(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${ef(e.namespace)}/tables`,body:t,headers:r})).data.metadata}async updateTable(e,t){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${ef(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${ef(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){let t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ef(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){let t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${ef(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof eu&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof eu&&409===r.status)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}},eg=class{constructor(e){let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);const r=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=function(e){let t=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:i,body:n,headers:a}){let o=function(e,t,r){let s=new URL(t,e);if(r)for(let[e,t]of Object.entries(r))void 0!==t&&s.searchParams.set(e,t);return s.toString()}(e.baseUrl,s,i),l=await eh(e.auth),u=await t(o,{method:r,headers:{...n?{"Content-Type":"application/json"}:{},...l,...a},body:n?JSON.stringify(n):void 0}),h=await u.text(),c=(u.headers.get("content-type")||"").includes("application/json"),d=c&&h?JSON.parse(h):h;if(!u.ok){let e=c?d:void 0,t=e?.error;throw new eu(t?.message??`Request failed with status ${u.status}`,{status:u.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:u.status,headers:u.headers,data:d}}}}({baseUrl:r,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new ed(this.client,t),this.tableOps=new ep(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}},ey=class extends Error{constructor(e,t="storage",r,s){super(e),this.__isStorageError=!0,this.namespace=t,this.name="vectors"===t?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=s}};function em(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}var ew=class extends ey{constructor(e,t,r,s="storage"){super(e,s,t,r),this.name="vectors"===s?"StorageVectorsApiError":"StorageApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},eb=class extends ey{constructor(e,t,r="storage"){super(e,r),this.name="vectors"===r?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};let ev=e=>{if(Array.isArray(e))return e.map(e=>ev(e));if("function"==typeof e||e!==Object(e))return e;let t={};return Object.entries(e).forEach(([e,r])=>{t[e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,""))]=ev(r)}),t};function e_(e){return(e_="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function ek(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,s)}return r}function eS(e){for(var t=1;t{var t;return e.msg||e.message||e.error_description||("string"==typeof e.error?e.error:null==(t=e.error)?void 0:t.message)||JSON.stringify(e)},eT=async(e,t,r,s)=>{if(e&&"object"==typeof e&&"status"in e&&"ok"in e&&"number"==typeof e.status&&!(null==r?void 0:r.noResolveJson)){let r=e.status||500;"function"==typeof e.json?e.json().then(e=>{let i=(null==e?void 0:e.statusCode)||(null==e?void 0:e.code)||r+"";t(new ew(eE(e),r,i,s))}).catch(()=>{t(new ew(e.statusText||`HTTP ${r} error`,r,r+"",s))}):t(new ew(e.statusText||`HTTP ${r} error`,r,r+"",s))}else t(new eb(eE(e),e,s))};async function eO(e,t,r,s,i,n,a){return new Promise((o,l)=>{let u;e(r,(u={method:t,headers:(null==s?void 0:s.headers)||{}},"GET"===t||"HEAD"===t||!n||((e=>{if("object"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return(null===t||t===Object.prototype||null===Object.getPrototypeOf(t))&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)})(n)?(u.headers=eS({"Content-Type":"application/json"},null==s?void 0:s.headers),u.body=JSON.stringify(n)):u.body=n,(null==s?void 0:s.duplex)&&(u.duplex=s.duplex)),eS(eS({},u),i))).then(e=>{if(!e.ok)throw e;if(null==s?void 0:s.noResolveJson)return e;if("vectors"===a){let t=e.headers.get("content-type");if(!t||!t.includes("application/json"))return{}}return e.json()}).then(e=>o(e)).catch(e=>eT(e,l,s,a))})}let{get:eA,post:eR,put:ej,head:eI,remove:e$}=function(e="storage"){return{get:async(t,r,s,i)=>eO(t,"GET",r,s,i,void 0,e),post:async(t,r,s,i,n)=>eO(t,"POST",r,i,n,s,e),put:async(t,r,s,i,n)=>eO(t,"PUT",r,i,n,s,e),head:async(t,r,s,i)=>eO(t,"HEAD",r,eS(eS({},s),{},{noResolveJson:!0}),i,void 0,e),remove:async(t,r,s,i,n)=>eO(t,"DELETE",r,i,n,s,e)}}("storage");var eC=class{constructor(e,t={},r,s="storage"){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.fetch=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}async handleOperation(e){try{return{data:await e(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(em(e))return{data:null,error:e};throw e}}},eP=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}async execute(){try{return{data:(await this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(em(e))return{data:null,error:e};throw e}}};t=Symbol.toStringTag;var ex=class{constructor(e,r){this.downloadFn=e,this.shouldThrowOnError=r,this[t]="BlobDownloadBuilder",this.promise=null}asStream(){return new eP(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){try{return{data:await (await this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(em(e))return{data:null,error:e};throw e}}};let eU={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},eN={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var eB=class extends eC{constructor(e,t={},r,s){super(e,t,s,"storage"),this.bucketId=r}async uploadOrUpdate(e,t,r,s){var i=this;return i.handleOperation(async()=>{let n,a=eS(eS({},eN),s),o=eS(eS({},i.headers),"POST"===e&&{"x-upsert":String(a.upsert)}),l=a.metadata;"u">typeof Blob&&r instanceof Blob?((n=new FormData).append("cacheControl",a.cacheControl),l&&n.append("metadata",i.encodeMetadata(l)),n.append("",r)):"u">typeof FormData&&r instanceof FormData?((n=r).has("cacheControl")||n.append("cacheControl",a.cacheControl),l&&!n.has("metadata")&&n.append("metadata",i.encodeMetadata(l))):(n=r,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,l&&(o["x-metadata"]=i.toBase64(i.encodeMetadata(l))),("u">typeof ReadableStream&&n instanceof ReadableStream||n&&"object"==typeof n&&"pipe"in n&&"function"==typeof n.pipe)&&!a.duplex&&(a.duplex="half")),(null==s?void 0:s.headers)&&(o=eS(eS({},o),s.headers));let u=i._removeEmptyFolders(t),h=i._getFinalPath(u),c=await ("PUT"==e?ej:eR)(i.fetch,`${i.url}/object/${h}`,n,eS({headers:o},(null==a?void 0:a.duplex)?{duplex:a.duplex}:{}));return{path:u,id:c.Id,fullPath:c.Key}})}async upload(e,t,r){return this.uploadOrUpdate("POST",e,t,r)}async uploadToSignedUrl(e,t,r,s){var i=this;let n=i._removeEmptyFolders(e),a=i._getFinalPath(n),o=new URL(i.url+`/object/upload/sign/${a}`);return o.searchParams.set("token",t),i.handleOperation(async()=>{let e,t=eS({upsert:eN.upsert},s),a=eS(eS({},i.headers),{"x-upsert":String(t.upsert)});return"u">typeof Blob&&r instanceof Blob?((e=new FormData).append("cacheControl",t.cacheControl),e.append("",r)):"u">typeof FormData&&r instanceof FormData?(e=r).append("cacheControl",t.cacheControl):(e=r,a["cache-control"]=`max-age=${t.cacheControl}`,a["content-type"]=t.contentType),{path:n,fullPath:(await ej(i.fetch,o.toString(),e,{headers:a})).Key}})}async createSignedUploadUrl(e,t){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(e),i=eS({},r.headers);(null==t?void 0:t.upsert)&&(i["x-upsert"]="true");let n=await eR(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:i}),a=new URL(r.url+n.url),o=a.searchParams.get("token");if(!o)throw new ey("No token returned by API");return{signedUrl:a.toString(),path:e,token:o}})}async update(e,t,r){return this.uploadOrUpdate("PUT",e,t,r)}async move(e,t,r){var s=this;return s.handleOperation(async()=>await eR(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:s.headers}))}async copy(e,t,r){var s=this;return s.handleOperation(async()=>({path:(await eR(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:s.headers})).Key}))}async createSignedUrl(e,t,r){var s=this;return s.handleOperation(async()=>{let i=s._getFinalPath(e),n=await eR(s.fetch,`${s.url}/object/sign/${i}`,eS({expiresIn:t},(null==r?void 0:r.transform)?{transform:r.transform}:{}),{headers:s.headers}),a=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return{signedUrl:encodeURI(`${s.url}${n.signedURL}${a}`)}})}async createSignedUrls(e,t,r){var s=this;return s.handleOperation(async()=>{let i=await eR(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:t,paths:e},{headers:s.headers}),n=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return i.map(e=>eS(eS({},e),{},{signedUrl:e.signedURL?encodeURI(`${s.url}${e.signedURL}${n}`):null}))})}download(e,t){let r=void 0!==(null==t?void 0:t.transform)?"render/image/authenticated":"object",s=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),i=s?`?${s}`:"",n=this._getFinalPath(e);return new ex(()=>eA(this.fetch,`${this.url}/${r}/${n}${i}`,{headers:this.headers,noResolveJson:!0}),this.shouldThrowOnError)}async info(e){var t=this;let r=t._getFinalPath(e);return t.handleOperation(async()=>ev(await eA(t.fetch,`${t.url}/object/info/${r}`,{headers:t.headers})))}async exists(e){let t=this._getFinalPath(e);try{return await eI(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(em(e)&&e instanceof eb){let t=e.originalError;if([400,404].includes(null==t?void 0:t.status))return{data:!1,error:e}}throw e}}getPublicUrl(e,t){let r=this._getFinalPath(e),s=[],i=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==i&&s.push(i);let n=void 0!==(null==t?void 0:t.transform)?"render/image":"object",a=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==a&&s.push(a);let o=s.join("&");return""!==o&&(o=`?${o}`),{data:{publicUrl:encodeURI(`${this.url}/${n}/public/${r}${o}`)}}}async remove(e){var t=this;return t.handleOperation(async()=>await e$(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}))}async list(e,t,r){var s=this;return s.handleOperation(async()=>{let i=eS(eS(eS({},eU),t),{},{prefix:e||""});return await eR(s.fetch,`${s.url}/object/list/${s.bucketId}`,i,{headers:s.headers},r)})}async listV2(e,t){var r=this;return r.handleOperation(async()=>{let s=eS({},e);return await eR(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},t)})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return void 0!==el.Buffer?el.Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};let eD={"X-Client-Info":"storage-js/2.93.1"};var eL=class extends eC{constructor(e,t={},r,s){const i=new URL(e);(null==s?void 0:s.useNewHostname)&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase.")),super(i.href.replace(/\/$/,""),eS(eS({},eD),t),r,"storage")}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let r=t.listBucketOptionsToQueryString(e);return await eA(t.fetch,`${t.url}/bucket${r}`,{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await eA(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}))}async createBucket(e,t={public:!1}){var r=this;return r.handleOperation(async()=>await eR(r.fetch,`${r.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}))}async updateBucket(e,t){var r=this;return r.handleOperation(async()=>await ej(r.fetch,`${r.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(e){var t=this;return t.handleOperation(async()=>await eR(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await e$(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}listBucketOptionsToQueryString(e){let t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},eq=class extends eC{constructor(e,t={},r){super(e.replace(/\/$/,""),eS(eS({},eD),t),r,"storage")}async createBucket(e){var t=this;return t.handleOperation(async()=>await eR(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}))}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let r=new URLSearchParams;(null==e?void 0:e.limit)!==void 0&&r.set("limit",e.limit.toString()),(null==e?void 0:e.offset)!==void 0&&r.set("offset",e.offset.toString()),(null==e?void 0:e.sortColumn)&&r.set("sortColumn",e.sortColumn),(null==e?void 0:e.sortOrder)&&r.set("sortOrder",e.sortOrder),(null==e?void 0:e.search)&&r.set("search",e.search);let s=r.toString(),i=s?`${t.url}/bucket?${s}`:`${t.url}/bucket`;return await eA(t.fetch,i,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await e$(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}from(e){var t=this;if(!(!(!e||"string"!=typeof e||0===e.length||e.length>100||e.trim()!==e||e.includes("/")||e.includes("\\"))&&/^[\w!.\*'() &$@=;:+,?-]+$/.test(e)))throw new ey("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let r=new eg({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(e,t){let r=e[t];return"function"!=typeof r?r:async(...t)=>{try{return{data:await r.apply(e,t),error:null}}catch(e){if(s)throw e;return{data:null,error:e}}}}})}},eM=class extends eC{constructor(e,t={},r){super(e.replace(/\/$/,""),eS(eS({},eD),{},{"Content-Type":"application/json"},t),r,"vectors")}async createIndex(e){var t=this;return t.handleOperation(async()=>await eR(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{})}async getIndex(e,t){var r=this;return r.handleOperation(async()=>await eR(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await eR(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}))}async deleteIndex(e,t){var r=this;return r.handleOperation(async()=>await eR(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})||{})}},eW=class extends eC{constructor(e,t={},r){super(e.replace(/\/$/,""),eS(eS({},eD),{},{"Content-Type":"application/json"},t),r,"vectors")}async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw Error("Vector batch size must be between 1 and 500 items");return t.handleOperation(async()=>await eR(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await eR(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}))}async listVectors(e){var t=this;if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw Error("segmentCount must be between 1 and 16");if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return t.handleOperation(async()=>await eR(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await eR(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw Error("Keys batch size must be between 1 and 500 items");return t.handleOperation(async()=>await eR(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{})}},eK=class extends eC{constructor(e,t={},r){super(e.replace(/\/$/,""),eS(eS({},eD),{},{"Content-Type":"application/json"},t),r,"vectors")}async createBucket(e){var t=this;return t.handleOperation(async()=>await eR(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await eR(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}))}async listBuckets(e={}){var t=this;return t.handleOperation(async()=>await eR(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await eR(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}},eF=class extends eK{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new ez(this.url,this.headers,e,this.fetch)}async createBucket(e){return super.createBucket.call(this,e)}async getBucket(e){return super.getBucket.call(this,e)}async listBuckets(e={}){return super.listBuckets.call(this,e)}async deleteBucket(e){return super.deleteBucket.call(this,e)}},ez=class extends eM{constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}async createIndex(e){return super.createIndex.call(this,eS(eS({},e),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(e={}){return super.listIndexes.call(this,eS(eS({},e),{},{vectorBucketName:this.vectorBucketName}))}async getIndex(e){return super.getIndex.call(this,this.vectorBucketName,e)}async deleteIndex(e){return super.deleteIndex.call(this,this.vectorBucketName,e)}index(e){return new eJ(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},eJ=class extends eW{constructor(e,t,r,s,i){super(e,t,i),this.vectorBucketName=r,this.indexName=s}async putVectors(e){return super.putVectors.call(this,eS(eS({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async getVectors(e){return super.getVectors.call(this,eS(eS({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async listVectors(e={}){return super.listVectors.call(this,eS(eS({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async queryVectors(e){return super.queryVectors.call(this,eS(eS({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}async deleteVectors(e){return super.deleteVectors.call(this,eS(eS({},e),{},{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))}},eV=class extends eL{constructor(e,t={},r,s){super(e,t,r,s)}from(e){return new eB(this.url,this.headers,e,this.fetch)}get vectors(){return new eF(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new eq(this.url+"/iceberg",this.headers,this.fetch)}};let eG="2.93.1",eH={"X-Client-Info":`gotrue-js/${eG}`},eY="X-Supabase-Api-Version",eX={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},eZ=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class eQ extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}}function e0(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class e1 extends eQ{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}class e2 extends eQ{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class e5 extends eQ{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}}class e8 extends e5{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function e6(e){return e0(e)&&"AuthSessionMissingError"===e.name}class e3 extends e5{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class e4 extends e5{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class e9 extends e5{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class e7 extends e5{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class te extends e5{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class tt extends e5{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function tr(e){return e0(e)&&"AuthRetryableFetchError"===e.name}class ts extends e5{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}}class ti extends e5{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}let tn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),ta=" \n\r=".split(""),to=(()=>{let e=Array(128);for(let t=0;t=6;)r(tn[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6;else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;)r(tn[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6}function tu(e,t,r){let s=to[e];if(s>-1)for(t.queue=t.queue<<6|s,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else if(-2===s)return;else throw Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}function th(e){let t=[],r=e=>{t.push(String.fromCodePoint(e))},s={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},n=e=>{!function(e,t,r){if(0===t.utf8seq){if(e<=127)return r(e);for(let r=1;r<6;r+=1)if((e>>7-r&1)==0){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else if(4===t.utf8seq)t.codepoint=7&e;else throw Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}}(e,s,r)};for(let t=0;t{t.push(e)};for(let t=0;t{t.push(e)};return e.forEach(e=>tl(e,r,s)),tl(null,r,s),t.join("")}let tf=()=>"u">typeof window&&"u">typeof document,tp={tested:!1,writable:!1},tg=()=>{if(!tf())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(tp.tested)return tp.writable;let e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),tp.tested=!0,tp.writable=!0}catch(e){tp.tested=!0,tp.writable=!1}return tp.writable},ty=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),tm=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},tw=async(e,t)=>{let r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return r}},tb=async(e,t)=>{await e.removeItem(t)};class tv{constructor(){this.promise=new tv.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function t_(e){let t=e.split(".");if(3!==t.length)throw new ti("Invalid JWT structure");for(let e=0;e{setTimeout(()=>t(null),e)})}function tS(e){return("0"+e.toString(16)).substr(-2)}async function tE(e){let t=new TextEncoder().encode(e);return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",t))).map(e=>String.fromCharCode(e)).join("")}async function tT(e){return"u">typeof crypto&&void 0!==crypto.subtle&&"u">typeof TextEncoder?btoa(await tE(e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""):(console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e)}async function tO(e,t,r=!1){let s=function(){let e=new Uint32Array(56);if("u"{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){let e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)return}throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function t$(e){return JSON.parse(JSON.stringify(e))}let tC=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),tP=[502,503,504];async function tx(e){var t;let r,s;if(!("object"==typeof e&&null!==e&&"status"in e&&"ok"in e&&"json"in e&&"function"==typeof e.json))throw new tt(tC(e),0);if(tP.includes(e.status))throw new tt(tC(e),e.status);try{r=await e.json()}catch(e){throw new e2(tC(e),e)}let i=function(e){let t=e.headers.get(eY);if(!t||!t.match(tA))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(e){return null}}(e);if(i&&i.getTime()>=eX["2024-01-01"].timestamp&&"object"==typeof r&&r&&"string"==typeof r.code?s=r.code:"object"==typeof r&&r&&"string"==typeof r.error_code&&(s=r.error_code),s){if("weak_password"===s)throw new ts(tC(r),e.status,(null==(t=r.weak_password)?void 0:t.reasons)||[]);else if("session_not_found"===s)throw new e8}else if("object"==typeof r&&r&&"object"==typeof r.weak_password&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new ts(tC(r),e.status,r.weak_password.reasons);throw new e1(tC(r),e.status||500,s)}async function tU(e,t,r,s){var i;let n=Object.assign({},null==s?void 0:s.headers);n[eY]||(n[eY]=eX["2024-01-01"].name),(null==s?void 0:s.jwt)&&(n.Authorization=`Bearer ${s.jwt}`);let a=null!=(i=null==s?void 0:s.query)?i:{};(null==s?void 0:s.redirectTo)&&(a.redirect_to=s.redirectTo);let o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",l=await tN(e,t,r+o,{headers:n,noResolveJson:null==s?void 0:s.noResolveJson},{},null==s?void 0:s.body);return(null==s?void 0:s.xform)?null==s?void 0:s.xform(l):{data:Object.assign({},l),error:null}}async function tN(e,t,r,s,i,n){let a,o,l=(o={method:t,headers:(null==s?void 0:s.headers)||{}},"GET"===t?o:(o.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==s?void 0:s.headers),o.body=JSON.stringify(n),Object.assign(Object.assign({},o),i)));try{a=await e(r,Object.assign({},l))}catch(e){throw console.error(e),new tt(tC(e),0)}if(a.ok||await tx(a),null==s?void 0:s.noResolveJson)return a;try{return await a.json()}catch(e){await tx(e)}}function tB(e){var t,r,s;let i=null;(s=e).access_token&&s.refresh_token&&s.expires_in&&(i=Object.assign({},e),e.expires_at||(i.expires_at=(r=e.expires_in,Math.round(Date.now()/1e3)+r)));return{data:{session:i,user:null!=(t=e.user)?t:e},error:null}}function tD(e){let t=tB(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function tL(e){var t;return{data:{user:null!=(t=e.user)?t:e},error:null}}function tq(e){return{data:e,error:null}}function tM(e){let{action_link:t,email_otp:r,hashed_token:s,redirect_to:i,verification_type:n}=e;return{data:{properties:{action_link:t,email_otp:r,hashed_token:s,redirect_to:i,verification_type:n},user:Object.assign({},c(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]))},error:null}}function tW(e){return e}let tK=["global","local","others"];class tF{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=ty(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)}}async signOut(e,t=tK[0]){if(0>tK.indexOf(t))throw Error(`@supabase/auth-js: Parameter scope must be one of ${tK.join(", ")}`);try{return await tU(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(e0(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await tU(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:tL})}catch(e){if(e0(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{let{options:t}=e,r=c(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=null==r?void 0:r.newEmail,delete s.newEmail),await tU(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:tM,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(e0(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await tU(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:tL})}catch(e){if(e0(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,r,s,i,n,a,o;try{let l={nextPage:null,lastPage:0,total:0},u=await tU(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!=(r=null==(t=null==e?void 0:e.page)?void 0:t.toString())?r:"",per_page:null!=(i=null==(s=null==e?void 0:e.perPage)?void 0:s.toString())?i:""},xform:tW});if(u.error)throw u.error;let h=await u.json(),c=null!=(n=u.headers.get("x-total-count"))?n:0,d=null!=(o=null==(a=u.headers.get("link"))?void 0:a.split(","))?o:[];return d.length>0&&(d.forEach(e=>{let t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(c)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(e){if(e0(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){tj(e);try{return await tU(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:tL})}catch(e){if(e0(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){tj(e);try{return await tU(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:tL})}catch(e){if(e0(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){tj(e);try{return await tU(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:tL})}catch(e){if(e0(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){tj(e.userId);try{let{data:t,error:r}=await tU(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:r}}catch(e){if(e0(e))return{data:null,error:e};throw e}}async _deleteFactor(e){tj(e.userId),tj(e.id);try{return{data:await tU(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(e0(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){var t,r,s,i,n,a,o;try{let l={nextPage:null,lastPage:0,total:0},u=await tU(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:null!=(r=null==(t=null==e?void 0:e.page)?void 0:t.toString())?r:"",per_page:null!=(i=null==(s=null==e?void 0:e.perPage)?void 0:s.toString())?i:""},xform:tW});if(u.error)throw u.error;let h=await u.json(),c=null!=(n=u.headers.get("x-total-count"))?n:0,d=null!=(o=null==(a=u.headers.get("link"))?void 0:a.split(","))?o:[];return d.length>0&&(d.forEach(e=>{let t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(c)),{data:Object.assign(Object.assign({},h),l),error:null}}catch(e){if(e0(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await tU(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(e0(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await tU(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(e0(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await tU(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(e0(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await tU(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(e0(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await tU(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(e0(e))return{data:null,error:e};throw e}}}function tz(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}let tJ={debug:!!(globalThis&&tg()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"))};class tV extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class tG extends tV{}async function tH(e,t,r){tJ.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);let s=new globalThis.AbortController;return t>0&&setTimeout(()=>{s.abort(),tJ.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async s=>{if(s){tJ.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,s.name);try{return await r()}finally{tJ.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,s.name)}}if(0===t)throw tJ.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new tG(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(tJ.debug)try{let e=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(e,null," "))}catch(e){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",e)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}))}function tY(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}class tX extends Error{constructor({message:e,code:t,cause:r,name:s}){var i;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=null!=(i=null!=s?s:r instanceof Error?r.name:void 0)?i:"Unknown Error",this.code=t}}class tZ extends tX{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}let tQ=new class{createNewAbortSignal(){if(this.controller){let e=Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};function t0(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function t1(){var e,t;return!!(tf()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null==(e=null==navigator?void 0:navigator.credentials)?void 0:e.create)&&"function"==typeof(null==(t=null==navigator?void 0:navigator.credentials)?void 0:t.get))}async function t2(e){try{let t=await navigator.credentials.create(e);if(!t)return{data:null,error:new tZ("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new tZ("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:function({error:e,options:t}){var r,s,i;let{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new tX({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if((null==(r=n.authenticatorSelection)?void 0:r.requireResidentKey)===!0)return new tX({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});else if("conditional"===t.mediation&&(null==(s=n.authenticatorSelection)?void 0:s.userVerification)==="required")return new tX({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});else if((null==(i=n.authenticatorSelection)?void 0:i.userVerification)==="required")return new tX({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else if("InvalidStateError"===e.name)return new tX({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});else if("NotAllowedError"===e.name)return new tX({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});else if("NotSupportedError"===e.name)return new tX(0===n.pubKeyCredParams.filter(e=>"public-key"===e.type).length?{message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}:{message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});else if("SecurityError"===e.name){let t=window.location.hostname;if(!t0(t))return new tX({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rp.id!==t)return new tX({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new tX({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new tX({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e});return new tX({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}({error:t,options:e})}}}async function t5(e){try{let t=await navigator.credentials.get(e);if(!t)return{data:null,error:new tZ("Empty credential response",t)};if(!(t instanceof PublicKeyCredential))return{data:null,error:new tZ("Browser returned unexpected credential type",t)};return{data:t,error:null}}catch(t){return{data:null,error:function({error:e,options:t}){let{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new tX({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("NotAllowedError"===e.name)return new tX({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});else if("SecurityError"===e.name){let t=window.location.hostname;if(!t0(t))return new tX({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rpId!==t)return new tX({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new tX({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e});return new tX({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}({error:t,options:e})}}}let t8={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},t6={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function t3(...e){let t=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),r=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),s={};for(let i of e)if(i)for(let e in i){let n=i[e];if(void 0!==n)if(Array.isArray(n))s[e]=n;else if(r(n))s[e]=n;else if(t(n)){let r=s[e];t(r)?s[e]=t3(r,n):s[e]=t3(n)}else s[e]=n}return s}class t4{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:s},i){try{var n,a,o,l;let{data:u,error:h}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!u)return{data:null,error:h};let c=null!=s?s:tQ.createNewAbortSignal();if("create"===u.webauthn.type){let{user:e}=u.webauthn.credential_options.publicKey;e.name||(e.name=`${e.id}:${r}`),e.displayName||(e.displayName=e.name)}switch(u.webauthn.type){case"create":{let t=(n=u.webauthn.credential_options.publicKey,a=null==i?void 0:i.create,t3(t8,n,a||{})),{data:r,error:s}=await t2({publicKey:t,signal:c});if(r)return{data:{factorId:e,challengeId:u.id,webauthn:{type:u.webauthn.type,credential_response:r}},error:null};return{data:null,error:s}}case"request":{let t=(o=u.webauthn.credential_options.publicKey,l=null==i?void 0:i.request,t3(t6,o,l||{})),{data:r,error:s}=await t5(Object.assign(Object.assign({},u.webauthn.credential_options),{publicKey:t,signal:c}));if(r)return{data:{factorId:e,challengeId:u.id,webauthn:{type:u.webauthn.type,credential_response:r}},error:null};return{data:null,error:s}}}}catch(e){if(e0(e))return{data:null,error:e};return{data:null,error:new e2("Unexpected error in challenge",e)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t="u">typeof window?window.location.hostname:void 0,rpOrigins:r="u">typeof window?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new eQ("rpId is required for WebAuthn authentication")};try{if(!t1())return{data:null,error:new e2("Browser does not support WebAuthn",null)};let{data:n,error:a}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:i});if(!n)return{data:null,error:a};let{webauthn:o}=n;return this._verify({factorId:e,challengeId:n.challengeId,webauthn:{type:o.type,rpId:t,rpOrigins:r,credential_response:o.credential_response}})}catch(e){if(e0(e))return{data:null,error:e};return{data:null,error:new e2("Unexpected error in authenticate",e)}}}async _register({friendlyName:e,webauthn:{rpId:t="u">typeof window?window.location.hostname:void 0,rpOrigins:r="u">typeof window?[window.location.origin]:void 0,signal:s}={}},i){if(!t)return{data:null,error:new eQ("rpId is required for WebAuthn registration")};try{if(!t1())return{data:null,error:new e2("Browser does not support WebAuthn",null)};let{data:n,error:a}=await this._enroll({friendlyName:e});if(!n)return await this.client.mfa.listFactors().then(t=>{var r;return null==(r=t.data)?void 0:r.all.find(t=>"webauthn"===t.factor_type&&t.friendly_name===e&&"unverified"!==t.status)}).then(e=>e?this.client.mfa.unenroll({factorId:null==e?void 0:e.id}):void 0),{data:null,error:a};let{data:o,error:l}=await this._challenge({factorId:n.id,friendlyName:n.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:i});if(!o)return{data:null,error:l};return this._verify({factorId:n.id,challengeId:o.challengeId,webauthn:{rpId:t,rpOrigins:r,type:o.webauthn.type,credential_response:o.webauthn.credential_response}})}catch(e){if(e0(e))return{data:null,error:e};return{data:null,error:new e2("Unexpected error in register",e)}}}}if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"u">typeof self&&(self.globalThis=self)}let t9={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:eH,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4};async function t7(e,t,r){return await r()}let re={};class rt{get jwks(){var e,t;return null!=(t=null==(e=re[this.storageKey])?void 0:e.jwks)?t:{keys:[]}}set jwks(e){re[this.storageKey]=Object.assign(Object.assign({},re[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!=(t=null==(e=re[this.storageKey])?void 0:e.cachedAt)?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){re[this.storageKey]=Object.assign(Object.assign({},re[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},t9),e);if(this.storageKey=i.storageKey,this.instanceID=null!=(t=rt.nextInstanceID[this.storageKey])?t:0,rt.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,"function"==typeof i.debug&&(this.logger=i.debug),this.instanceID>0&&tf()){const e=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new tF({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=ty(i.fetch),this.lock=i.lock||t7,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock?this.lock=i.lock:this.persistSession&&tf()&&(null==(r=null==globalThis?void 0:globalThis.navigator)?void 0:r.locks)?this.lock=tH:this.lock=t7,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new t4(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:tg()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=tz(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=tz(this.memoryStorage)),tf()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null==(s=this.broadcastChannel)||s.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e);try{await this._notifyAllSubscribers(e.data.event,e.data.session,!1)}catch(e){this._debug("#broadcastChannel","error",e)}})}this.initialize().catch(e=>{this._debug("#initialize()","error",e)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${eG}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){var e;try{let t={},r="none";if(tf()&&(t=function(e){let t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEach((e,r)=>{t[r]=e})}catch(e){}return r.searchParams.forEach((e,r)=>{t[r]=e}),t}(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),tf()&&this.detectSessionInUrl&&"none"!==r){let{data:s,error:i}=await this._getSessionFromURL(t,r);if(i){(this._debug("#_initialize()","error detecting session from URL",i),e0(i)&&"AuthImplicitGrantRedirectError"===i.name)&&(null==(e=i.details)||e.code);return{error:i}}let{session:n,redirectType:a}=s;return this._debug("#_initialize()","detected session in URL",n,"redirect type",a),await this._saveSession(n),setTimeout(async()=>{"recovery"===a?await this._notifyAllSubscribers("PASSWORD_RECOVERY",n):await this._notifyAllSubscribers("SIGNED_IN",n)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){if(e0(e))return this._returnResult({error:e});return this._returnResult({error:new e2("Unexpected error during initialization",e)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{let{data:i,error:n}=await tU(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!=(r=null==(t=null==e?void 0:e.options)?void 0:t.data)?r:{},gotrue_meta_security:{captcha_token:null==(s=null==e?void 0:e.options)?void 0:s.captchaToken}},xform:tB});if(n||!i)return this._returnResult({data:{user:null,session:null},error:n});let a=i.session,o=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",a)),this._returnResult({data:{user:o,session:a},error:null})}catch(e){if(e0(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){var t,r,s;try{let i;if("email"in e){let{email:r,password:s,options:n}=e,a=null,o=null;"pkce"===this.flowType&&([a,o]=await tO(this.storage,this.storageKey)),i=await tU(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==n?void 0:n.emailRedirectTo,body:{email:r,password:s,data:null!=(t=null==n?void 0:n.data)?t:{},gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},code_challenge:a,code_challenge_method:o},xform:tB})}else if("phone"in e){let{phone:t,password:n,options:a}=e;i=await tU(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:n,data:null!=(r=null==a?void 0:a.data)?r:{},channel:null!=(s=null==a?void 0:a.channel)?s:"sms",gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken}},xform:tB})}else throw new e4("You must provide either an email or phone number and a password");let{data:n,error:a}=i;if(a||!n)return await tb(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let o=n.session,l=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",o)),this._returnResult({data:{user:l,session:o},error:null})}catch(e){if(await tb(this.storage,`${this.storageKey}-code-verifier`),e0(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if("email"in e){let{email:r,password:s,options:i}=e;t=await tU(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:r,password:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:tD})}else if("phone"in e){let{phone:r,password:s,options:i}=e;t=await tU(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:r,password:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:tD})}else throw new e4("You must provide either an email or phone number and a password");let{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){let e=new e3;return this._returnResult({data:{user:null,session:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(e){if(e0(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){var t,r,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:null==(t=e.options)?void 0:t.redirectTo,scopes:null==(r=e.options)?void 0:r.scopes,queryParams:null==(s=e.options)?void 0:s.queryParams,skipBrowserRedirect:null==(i=e.options)?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,i,n,a,o,l,u,h,c,d;let f,p;if("message"in e)f=e.message,p=e.signature;else{let h,{chain:c,wallet:g,statement:y,options:m}=e;if(tf())if("object"==typeof g)h=g;else{let e=window;if("ethereum"in e&&"object"==typeof e.ethereum&&"request"in e.ethereum&&"function"==typeof e.ethereum.request)h=e.ethereum;else throw Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if("object"!=typeof g||!(null==m?void 0:m.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");h=g}let w=new URL(null!=(t=null==m?void 0:m.url)?t:window.location.href),b=await h.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!b||0===b.length)throw Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let v=tY(b[0]),_=null==(r=null==m?void 0:m.signInWithEthereum)?void 0:r.chainId;_||(_=parseInt(await h.request({method:"eth_chainId"}),16)),f=function(e){var t;let{chainId:r,domain:s,expirationTime:i,issuedAt:n=new Date,nonce:a,notBefore:o,requestId:l,resources:u,scheme:h,uri:c,version:d}=e;if(!Number.isInteger(r))throw Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!c)throw Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==d)throw Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(null==(t=e.statement)?void 0:t.includes("\n"))throw Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);let f=tY(e.address),p=h?`${h}://${s}`:s,g=e.statement?`${e.statement} `:"",y=`${p} wants you to sign in with your Ethereum account: ${f} ${g}`,m=`URI: ${c} Version: ${d} Chain ID: ${r}${a?` Nonce: ${a}`:""} Issued At: ${n.toISOString()}`;if(i&&(m+=` Expiration Time: ${i.toISOString()}`),o&&(m+=` Not Before: ${o.toISOString()}`),l&&(m+=` Request ID: ${l}`),u){let e="\nResources:";for(let t of u){if(!t||"string"!=typeof t)throw Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=` - ${t}`}m+=e}return`${y} ${m}`}({domain:w.host,address:v,statement:y,uri:w.href,version:"1",chainId:_,nonce:null==(s=null==m?void 0:m.signInWithEthereum)?void 0:s.nonce,issuedAt:null!=(n=null==(i=null==m?void 0:m.signInWithEthereum)?void 0:i.issuedAt)?n:new Date,expirationTime:null==(a=null==m?void 0:m.signInWithEthereum)?void 0:a.expirationTime,notBefore:null==(o=null==m?void 0:m.signInWithEthereum)?void 0:o.notBefore,requestId:null==(l=null==m?void 0:m.signInWithEthereum)?void 0:l.requestId,resources:null==(u=null==m?void 0:m.signInWithEthereum)?void 0:u.resources}),p=await h.request({method:"personal_sign",params:[(d=f,"0x"+Array.from(new TextEncoder().encode(d),e=>e.toString(16).padStart(2,"0")).join("")),v]})}try{let{data:t,error:r}=await tU(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:p},(null==(h=e.options)?void 0:h.captchaToken)?{gotrue_meta_security:{captcha_token:null==(c=e.options)?void 0:c.captchaToken}}:null),xform:tB});if(r)throw r;if(!t||!t.session||!t.user){let e=new e3;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(e0(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){var t,r,s,i,n,a,o,l,u,h,c,d;let f,p;if("message"in e)f=e.message,p=e.signature;else{let c,{chain:d,wallet:g,statement:y,options:m}=e;if(tf())if("object"==typeof g)c=g;else{let e=window;if("solana"in e&&"object"==typeof e.solana&&("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))c=e.solana;else throw Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if("object"!=typeof g||!(null==m?void 0:m.url))throw Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");c=g}let w=new URL(null!=(t=null==m?void 0:m.url)?t:window.location.href);if("signIn"in c&&c.signIn){let e,t=await c.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},null==m?void 0:m.signInWithSolana),{version:"1",domain:w.host,uri:w.href}),y?{statement:y}:null));if(Array.isArray(t)&&t[0]&&"object"==typeof t[0])e=t[0];else if(t&&"object"==typeof t&&"signedMessage"in t&&"signature"in t)e=t;else throw Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in e&&"signature"in e&&("string"==typeof e.signedMessage||e.signedMessage instanceof Uint8Array)&&e.signature instanceof Uint8Array)f="string"==typeof e.signedMessage?e.signedMessage:new TextDecoder().decode(e.signedMessage),p=e.signature;else throw Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in c)||"function"!=typeof c.signMessage||!("publicKey"in c)||"object"!=typeof c||!c.publicKey||!("toBase58"in c.publicKey)||"function"!=typeof c.publicKey.toBase58)throw Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");f=[`${w.host} wants you to sign in with your Solana account:`,c.publicKey.toBase58(),...y?["",y,""]:[""],"Version: 1",`URI: ${w.href}`,`Issued At: ${null!=(s=null==(r=null==m?void 0:m.signInWithSolana)?void 0:r.issuedAt)?s:new Date().toISOString()}`,...(null==(i=null==m?void 0:m.signInWithSolana)?void 0:i.notBefore)?[`Not Before: ${m.signInWithSolana.notBefore}`]:[],...(null==(n=null==m?void 0:m.signInWithSolana)?void 0:n.expirationTime)?[`Expiration Time: ${m.signInWithSolana.expirationTime}`]:[],...(null==(a=null==m?void 0:m.signInWithSolana)?void 0:a.chainId)?[`Chain ID: ${m.signInWithSolana.chainId}`]:[],...(null==(o=null==m?void 0:m.signInWithSolana)?void 0:o.nonce)?[`Nonce: ${m.signInWithSolana.nonce}`]:[],...(null==(l=null==m?void 0:m.signInWithSolana)?void 0:l.requestId)?[`Request ID: ${m.signInWithSolana.requestId}`]:[],...(null==(h=null==(u=null==m?void 0:m.signInWithSolana)?void 0:u.resources)?void 0:h.length)?["Resources",...m.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");let e=await c.signMessage(new TextEncoder().encode(f),"utf8");if(!e||!(e instanceof Uint8Array))throw Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");p=e}}try{let{data:t,error:r}=await tU(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:f,signature:td(p)},(null==(c=e.options)?void 0:c.captchaToken)?{gotrue_meta_security:{captcha_token:null==(d=e.options)?void 0:d.captchaToken}}:null),xform:tB});if(r)throw r;if(!t||!t.session||!t.user){let e=new e3;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(e0(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){let t=await tw(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(null!=t?t:"").split("/");try{if(!r&&"pkce"===this.flowType)throw new te;let{data:t,error:i}=await tU(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:tB});if(await tb(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!t||!t.session||!t.user){let e=new e3;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign(Object.assign({},t),{redirectType:null!=s?s:null}),error:i})}catch(e){if(await tb(this.storage,`${this.storageKey}-code-verifier`),e0(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{let{options:t,provider:r,token:s,access_token:i,nonce:n}=e,{data:a,error:o}=await tU(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:n,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:tB});if(o)return this._returnResult({data:{user:null,session:null},error:o});if(!a||!a.session||!a.user){let e=new e3;return this._returnResult({data:{user:null,session:null},error:e})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),this._returnResult({data:a,error:o})}catch(e){if(e0(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){var t,r,s,i,n;try{if("email"in e){let{email:s,options:i}=e,n=null,a=null;"pkce"===this.flowType&&([n,a]=await tO(this.storage,this.storageKey));let{error:o}=await tU(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:s,data:null!=(t=null==i?void 0:i.data)?t:{},create_user:null==(r=null==i?void 0:i.shouldCreateUser)||r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:n,code_challenge_method:a},redirectTo:null==i?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}if("phone"in e){let{phone:t,options:r}=e,{data:a,error:o}=await tU(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!=(s=null==r?void 0:r.data)?s:{},create_user:null==(i=null==r?void 0:r.shouldCreateUser)||i,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken},channel:null!=(n=null==r?void 0:r.channel)?n:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:null==a?void 0:a.message_id},error:o})}throw new e4("You must provide either an email or phone number.")}catch(e){if(await tb(this.storage,`${this.storageKey}-code-verifier`),e0(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){var t,r;try{let s,i;"options"in e&&(s=null==(t=e.options)?void 0:t.redirectTo,i=null==(r=e.options)?void 0:r.captchaToken);let{data:n,error:a}=await tU(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:tB});if(a)throw a;if(!n)throw Error("An error occurred on token verification.");let o=n.session,l=n.user;return(null==o?void 0:o.access_token)&&(await this._saveSession(o),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",o)),this._returnResult({data:{user:l,session:o},error:null})}catch(e){if(e0(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){var t,r,s,i,n;try{let a=null,o=null;"pkce"===this.flowType&&([a,o]=await tO(this.storage,this.storageKey));let l=await tU(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:null!=(r=null==(t=e.options)?void 0:t.redirectTo)?r:void 0}),(null==(s=null==e?void 0:e.options)?void 0:s.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:o}),headers:this.headers,xform:tq});return(null==(i=l.data)?void 0:i.url)&&tf()&&!(null==(n=e.options)?void 0:n.skipBrowserRedirect)&&window.location.assign(l.data.url),this._returnResult(l)}catch(e){if(await tb(this.storage,`${this.storageKey}-code-verifier`),e0(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new e8;let{error:s}=await tU(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(e0(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:r,type:s,options:i}=e,{error:n}=await tU(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},redirectTo:null==i?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:n})}if("phone"in e){let{phone:r,type:s,options:i}=e,{data:n,error:a}=await tU(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:null==n?void 0:n.message_id},error:a})}throw new e4("You must provide either an email or phone number and a type")}catch(e){if(e0(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch(e){}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){let e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",Error().stack);try{let t=null,r=await tw(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),null!==r&&(this._isValidSession(r)?t=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};let s=!!t.expires_at&&1e3*t.expires_at-Date.now()<9e4;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",t.expires_at),!s){if(this.userStorage){let e=await tw(this.userStorage,this.storageKey+"-user");(null==e?void 0:e.user)?t.user=e.user:t.user=tI()}if(this.storage.isServer&&t.user&&!t.user.__isUserNotAvailableProxy){var e;let r={value:this.suppressGetSessionWarning};t.user=(e=t.user,new Proxy(e,{get:(e,t,s)=>{if("__isInsecureUserWarningProxy"===t)return!0;if("symbol"==typeof t){let r=t.toString();if("Symbol(Symbol.toPrimitive)"===r||"Symbol(Symbol.toStringTag)"===r||"Symbol(util.inspect.custom)"===r||"Symbol(nodejs.util.inspect.custom)"===r)return Reflect.get(e,t,s)}return r.value||"string"!=typeof t||(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),r.value=!0),Reflect.get(e,t,s)}})),r.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:t},error:null}}let{data:i,error:n}=await this._callRefreshToken(t.refresh_token);if(n)return this._returnResult({data:{session:null},error:n});return this._returnResult({data:{session:i},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{if(e)return await tU(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:tL});return await this._useSession(async e=>{var t,r,s;let{data:i,error:n}=e;if(n)throw n;return(null==(t=i.session)?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await tU(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!=(s=null==(r=i.session)?void 0:r.access_token)?s:void 0,xform:tL}):{data:{user:null},error:new e8}})}catch(e){if(e0(e))return e6(e)&&(await this._removeSession(),await tb(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{let{data:s,error:i}=r;if(i)throw i;if(!s.session)throw new e8;let n=s.session,a=null,o=null;"pkce"===this.flowType&&null!=e.email&&([a,o]=await tO(this.storage,this.storageKey));let{data:l,error:u}=await tU(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:o}),jwt:n.access_token,xform:tL});if(u)throw u;return n.user=l.user,await this._saveSession(n),await this._notifyAllSubscribers("USER_UPDATED",n),this._returnResult({data:{user:n.user},error:null})})}catch(e){if(await tb(this.storage,`${this.storageKey}-code-verifier`),e0(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new e8;let t=Date.now()/1e3,r=t,s=!0,i=null,{payload:n}=t_(e.access_token);if(n.exp&&(s=(r=n.exp)<=t),s){let{data:t,error:r}=await this._callRefreshToken(e.refresh_token);if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!t)return{data:{user:null,session:null},error:null};i=t}else{let{data:s,error:n}=await this._getUser(e.access_token);if(n)return this._returnResult({data:{user:null,session:null},error:n});i={access_token:e.access_token,refresh_token:e.refresh_token,user:s.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(e){if(e0(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:s,error:i}=t;if(i)throw i;e=null!=(r=s.session)?r:void 0}if(!(null==e?void 0:e.refresh_token))throw new e8;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(e){if(e0(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!tf())throw new e9("No browser detected.");if(e.error||e.error_description||e.error_code)throw new e9(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if("pkce"===this.flowType)throw new e7("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new e9("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new e7("No code detected.");let{data:t,error:r}=await this._exchangeCodeForSession(e.code);if(r)throw r;let s=new URL(window.location.href);return s.searchParams.delete("code"),window.history.replaceState(window.history.state,"",s.toString()),{data:{session:t.session,redirectType:null},error:null}}let{provider_token:r,provider_refresh_token:s,access_token:i,refresh_token:n,expires_in:a,expires_at:o,token_type:l}=e;if(!i||!a||!n||!l)throw new e9("No session defined in URL");let u=Math.round(Date.now()/1e3),h=parseInt(a),c=u+h;o&&(c=parseInt(o));let d=c-u;1e3*d<=3e4&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${d}s, should have been closer to ${h}s`);let f=c-h;u-f>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",f,c,u):u-f<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",f,c,u);let{data:p,error:g}=await this._getUser(i);if(g)throw g;let y={provider_token:r,provider_refresh_token:s,access_token:i,expires_in:h,expires_at:c,refresh_token:n,token_type:l,user:p.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:y,redirectType:e.type},error:null})}catch(e){if(e0(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return"function"==typeof this.detectSessionInUrl?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await tw(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i&&!e6(i))return this._returnResult({error:i});let n=null==(r=s.session)?void 0:r.access_token;if(n){let{error:t}=await this.admin.signOut(n,e);if(t&&!(e0(t)&&"AuthApiError"===t.name&&(404===t.status||401===t.status||403===t.status)||e6(t)))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await tb(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let t=Symbol("auth-callback"),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>{await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{let{data:{session:s},error:i}=t;if(i)throw i;await (null==(r=this.stateChangeEmitters.get(e))?void 0:r.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(t){await (null==(s=this.stateChangeEmitters.get(e))?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),console.error(t)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null;"pkce"===this.flowType&&([r,s]=await tO(this.storage,this.storageKey,!0));try{return await tU(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(await tb(this.storage,`${this.storageKey}-code-verifier`),e0(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:null!=(e=t.user.identities)?e:[]},error:null})}catch(e){if(e0(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{let{data:r,error:s}=await this._useSession(async t=>{var r,s,i,n,a;let{data:o,error:l}=t;if(l)throw l;let u=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null==(r=e.options)?void 0:r.redirectTo,scopes:null==(s=e.options)?void 0:s.scopes,queryParams:null==(i=e.options)?void 0:i.queryParams,skipBrowserRedirect:!0});return await tU(this.fetch,"GET",u,{headers:this.headers,jwt:null!=(a=null==(n=o.session)?void 0:n.access_token)?a:void 0})});if(s)throw s;return!tf()||(null==(t=e.options)?void 0:t.skipBrowserRedirect)||window.location.assign(null==r?void 0:r.url),this._returnResult({data:{provider:e.provider,url:null==r?void 0:r.url},error:null})}catch(t){if(e0(t))return this._returnResult({data:{provider:e.provider,url:null},error:t});throw t}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{let{error:s,data:{session:i}}=t;if(s)throw s;let{options:n,provider:a,token:o,access_token:l,nonce:u}=e,{data:h,error:c}=await tU(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:null!=(r=null==i?void 0:i.access_token)?r:void 0,body:{provider:a,id_token:o,access_token:l,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},xform:tB});if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!h||!h.session||!h.user)return this._returnResult({data:{user:null,session:null},error:new e3});return h.session&&(await this._saveSession(h.session),await this._notifyAllSubscribers("USER_UPDATED",h.session)),this._returnResult({data:h,error:c})}catch(e){if(await tb(this.storage,`${this.storageKey}-code-verifier`),e0(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:n}=t;if(n)throw n;return await tU(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!=(s=null==(r=i.session)?void 0:r.access_token)?s:void 0})})}catch(e){if(e0(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{var r,s;let i=Date.now();return await (r=async r=>(r>0&&await tk(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await tU(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:tB})),s=(e,t)=>{let r=200*Math.pow(2,e);return t&&tr(t)&&Date.now()+r-i<3e4},new Promise((e,t)=>{(async()=>{for(let i=0;i<1/0;i++)try{let t=await r(i);if(!s(i,null,t))return void e(t)}catch(e){if(!s(i,e))return void t(e)}})()}))}catch(e){if(this._debug(t,"error",e),e0(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}finally{this._debug(t,"end")}}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),tf()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;let r="#_recoverAndRefresh()";this._debug(r,"begin");try{let s=await tw(this.storage,this.storageKey);if(s&&this.userStorage){let t=await tw(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!t&&(t={user:s.user},await tm(this.userStorage,this.storageKey+"-user",t)),s.user=null!=(e=null==t?void 0:t.user)?e:tI()}else if(s&&!s.user&&!s.user){let e=await tw(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(s.user=e.user,await tb(this.storage,this.storageKey+"-user"),await tm(this.storage,this.storageKey,s)):s.user=tI()}if(this._debug(r,"session from storage",s),!this._isValidSession(s)){this._debug(r,"session is not valid"),null!==s&&await this._removeSession();return}let i=(null!=(t=s.expires_at)?t:1/0)*1e3-Date.now()<9e4;if(this._debug(r,`session has${i?"":" not"} expired with margin of 90000s`),i){if(this.autoRefreshToken&&s.refresh_token){let{error:e}=await this._callRefreshToken(s.refresh_token);e&&(console.error(e),tr(e)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else if(s.user&&!0===s.user.__isUserNotAvailableProxy)try{let{data:e,error:t}=await this._getUser(s.access_token);!t&&(null==e?void 0:e.user)?(s.user=e.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(e){console.error("Error getting user data:",e),this._debug(r,"error getting user data, skipping SIGNED_IN notification",e)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(e){this._debug(r,"error",e),console.error(e);return}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new e8;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new tv;let{data:t,error:r}=await this._refreshAccessToken(e);if(r)throw r;if(!t.session)throw new e8;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);let s={data:t.session,error:null};return this.refreshingDeferred.resolve(s),s}catch(e){if(this._debug(s,"error",e),e0(e)){let r={data:null,error:e};return tr(e)||await this._removeSession(),null==(t=this.refreshingDeferred)||t.resolve(r),r}throw null==(r=this.refreshingDeferred)||r.reject(e),e}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let s=[],i=Array.from(this.stateChangeEmitters.values()).map(async r=>{try{await r.callback(e,t)}catch(e){s.push(e)}});if(await Promise.all(i),s.length>0){for(let e=0;ethis._autoRefreshTokenTick(),3e4);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"u">typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&"object"==typeof t&&"function"==typeof t.unref?t.unref():"u">typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");let s=Math.floor((1e3*r.expires_at-e)/3e4);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),s<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof tV)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!tf()||!(null==window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},null==window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{"visible"!==document.visibilityState?this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting"):await this._recoverAndRefresh()}))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let s=[`provider=${encodeURIComponent(t)}`];if((null==r?void 0:r.redirectTo)&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),(null==r?void 0:r.scopes)&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),"pkce"===this.flowType){let[e,t]=await tO(this.storage,this.storageKey),r=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});s.push(r.toString())}if(null==r?void 0:r.queryParams){let e=new URLSearchParams(r.queryParams);s.push(e.toString())}return(null==r?void 0:r.skipBrowserRedirect)&&s.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;return i?this._returnResult({data:null,error:i}):await tU(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null==(r=null==s?void 0:s.session)?void 0:r.access_token})})}catch(e){if(e0(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:n}=t;if(n)return this._returnResult({data:null,error:n});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:o,error:l}=await tU(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:null==(r=null==i?void 0:i.session)?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):("totp"===e.factorType&&"totp"===o.type&&(null==(s=null==o?void 0:o.totp)?void 0:s.qr_code)&&(o.totp.qr_code=`data:image/svg+xml;utf-8,${o.totp.qr_code}`),this._returnResult({data:o,error:null}))})}catch(e){if(e0(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r,s,i;let{data:n,error:a}=t;if(a)return this._returnResult({data:null,error:a});let o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?(s=e.webauthn.credential_response,"toJSON"in s&&"function"==typeof s.toJSON?s.toJSON():{id:s.id,rawId:s.id,response:{attestationObject:td(new Uint8Array(s.response.attestationObject)),clientDataJSON:td(new Uint8Array(s.response.clientDataJSON))},type:"public-key",clientExtensionResults:s.getClientExtensionResults(),authenticatorAttachment:null!=(i=s.authenticatorAttachment)?i:void 0}):function(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();let r=e.getClientExtensionResults(),s=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:td(new Uint8Array(s.authenticatorData)),clientDataJSON:td(new Uint8Array(s.clientDataJSON)),signature:td(new Uint8Array(s.signature)),userHandle:s.userHandle?td(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:null!=(t=e.authenticatorAttachment)?t:void 0}}(e.webauthn.credential_response)})}:{code:e.code}),{data:l,error:u}=await tU(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:null==(r=null==n?void 0:n.session)?void 0:r.access_token});return u?this._returnResult({data:null,error:u}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),this._returnResult({data:l,error:u}))})}catch(e){if(e0(e))return this._returnResult({data:null,error:e});throw e}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return this._returnResult({data:null,error:i});let n=await tU(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:null==(r=null==s?void 0:s.session)?void 0:r.access_token});if(n.error)return n;let{data:a}=n;if("webauthn"!==a.type)return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:function(e){if(!e)throw Error("Credential creation options are required");if("u">typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);let{challenge:t,user:r,excludeCredentials:s}=e,i=c(e,["challenge","user","excludeCredentials"]),n=tc(t).buffer,a=Object.assign(Object.assign({},r),{id:tc(r.id).buffer}),o=Object.assign(Object.assign({},i),{challenge:n,user:a});if(s&&s.length>0){o.excludeCredentials=Array(s.length);for(let e=0;etypeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);let{challenge:t,allowCredentials:r}=e,s=c(e,["challenge","allowCredentials"]),i=tc(t).buffer,n=Object.assign(Object.assign({},s),{challenge:i});if(r&&r.length>0){n.allowCredentials=Array(r.length);for(let e=0;e"verified"===e.status))?r:[]).length>0&&(n="aal2");let l=s.amr||[];return{data:{currentLevel:i,nextLevel:n,currentAuthenticationMethods:l},error:null}}catch(e){if(e0(e))return this._returnResult({data:null,error:e});throw e}let{data:{session:n},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!n)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:o}=t_(n.access_token),l=null;o.aal&&(l=o.aal);let u=l;return(null!=(i=null==(s=n.user.factors)?void 0:s.filter(e=>"verified"===e.status))?i:[]).length>0&&(u="aal2"),{data:{currentLevel:l,nextLevel:u,currentAuthenticationMethods:o.amr||[]},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await tU(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new e8})})}catch(e){if(e0(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new e8});let n=await tU(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:e=>({data:e,error:null})});return n.data&&n.data.redirect_url&&tf()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(n.data.redirect_url),n})}catch(e){if(e0(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{let{data:{session:s},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new e8});let n=await tU(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:e=>({data:e,error:null})});return n.data&&n.data.redirect_url&&tf()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(n.data.redirect_url),n})}catch(e){if(e0(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await tU(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new e8})})}catch(e){if(e0(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await tU(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new e8})})}catch(e){if(e0(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(t=>t.kid===e);if(r)return r;let s=Date.now();if((r=this.jwks.keys.find(t=>t.kid===e))&&this.jwks_cached_at+6e5>s)return r;let{data:i,error:n}=await tU(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(n)throw n;return i.keys&&0!==i.keys.length&&(this.jwks=i,this.jwks_cached_at=s,r=i.keys.find(t=>t.kid===e))?r:null}async getClaims(e,t={}){try{var r;let s,i=e;if(!i){let{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});i=e.session.access_token}let{header:n,payload:a,signature:o,raw:{header:l,payload:u}}=t_(i);(null==t?void 0:t.allowExpired)||function(e){if(!e)throw Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw Error("JWT has expired")}(a.exp);let h=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks);if(!h){let{error:e}=await this.getUser(i);if(e)throw e;return{data:{claims:a,header:n,signature:o},error:null}}let c=function(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw Error("Invalid alg claim")}}(n.alg),d=await crypto.subtle.importKey("jwk",h,c,!0,["verify"]);if(!await crypto.subtle.verify(c,d,o,(r=`${l}.${u}`,s=[],!function(e,t){for(let r=0;r55295&&s<=56319){let t=(s-55296)*1024&65535;s=(e.charCodeAt(r+1)-56320&65535|t)+65536,r+=1}!function(e,t){if(e<=127)return t(e);if(e<=2047){t(192|e>>6),t(128|63&e);return}if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|63&e);return}if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|63&e);return}throw Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}(s,t)}}(r,e=>s.push(e)),new Uint8Array(s))))throw new ti("Invalid JWT signature");return{data:{claims:a,header:n,signature:o},error:null}}catch(e){if(e0(e))return this._returnResult({data:null,error:e});throw e}}}rt.nextInstanceID={};let rr=rt,rs="";rs="u">typeof Deno?"deno":"u">typeof document?"web":"u">typeof navigator&&"ReactNative"===navigator.product?"react-native":"node";let ri={headers:(r={"X-Client-Info":`supabase-js-${rs}/2.93.1`},(s=function(){let e=globalThis.process;if(e&&e.platform){let t=e.platform;if("darwin"===t)return"macOS";if("win32"===t)return"Windows";if("linux"===t)return"Linux";if("android"===t)return"Android"}if("u">typeof navigator&&navigator.userAgentData&&navigator.userAgentData.platform){let e=navigator.userAgentData.platform;if("macOS"===e)return"macOS";if("Windows"===e)return"Windows";if("Linux"===e)return"Linux";if("Android"===e)return"Android";if("iOS"===e)return"iOS"}return null}())&&(r["X-Supabase-Client-Platform"]=s),(i=function(){let e=globalThis.process;if(e){let t=e.versions;if(t&&t.node&&"u"typeof Deno&&Deno.osRelease)try{return Deno.osRelease()}catch(e){return null}return"u">typeof navigator&&navigator.userAgentData&&navigator.userAgentData.platformVersion?navigator.userAgentData.platformVersion:null}())&&(r["X-Supabase-Client-Platform-Version"]=i),(n=function(){if("u">typeof Deno)return"deno";if("u">typeof Bun)return"bun";let e=globalThis.process;if(e){let t=e.versions;if(t&&t.node)return"node"}return null}())&&(r["X-Supabase-Client-Runtime"]=n),(a=function(){if("u">typeof Deno&&Deno.version)return Deno.version.deno;if("u">typeof Bun&&Bun.version)return Bun.version;let e=globalThis.process;if(e){let t=e.versions;if(t&&t.node)return t.node}return null}())&&(r["X-Supabase-Client-Runtime-Version"]=a),r)},rn={schema:"public"},ra={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},ro={};function rl(e){return(rl="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function ru(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,s)}return r}function rh(e){for(var t=1;t""};return e.accessToken?d.accessToken=e.accessToken:delete d.accessToken,d}(null!=r?r:{},{db:rn,realtime:ro,auth:rh(rh({},ra),{},{storageKey:o}),global:ri});this.storageKey=null!=(s=l.auth.storageKey)?s:"",this.headers=null!=(i=l.global.headers)?i:{},l.accessToken?(this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!=(n=l.auth)?n:{},this.headers,l.global.fetch),this.fetch=((e,t,r)=>{let s=r?(...e)=>r(...e):(...e)=>fetch(...e),i=Headers;return async(r,n)=>{var a;let o=null!=(a=await t())?a:e,l=new i(null==n?void 0:n.headers);return l.has("apikey")||l.set("apikey",e),l.has("Authorization")||l.set("Authorization",`Bearer ${o}`),s(r,rh(rh({},n),{},{headers:l}))}})(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(rh({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(e=>this.realtime.setAuth(e)).catch(e=>console.warn("Failed to set initial Realtime auth token:",e)),this.rest=new q(new URL("rest/v1",a).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this.storage=new eV(this.storageUrl.href,this.headers,this.fetch,null==r?void 0:r.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new d(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e,t;if(this.accessToken)return await this.accessToken();let{data:r}=await this.auth.getSession();return null!=(e=null==(t=r.session)?void 0:t.access_token)?e:this.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:i,storageKey:n,flowType:a,lock:o,debug:l,throwOnError:u},h,c){let d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new rc({url:this.authUrl.href,headers:rh(rh({},d),h),storageKey:n,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:i,flowType:a,lock:o,debug:l,throwOnError:u,fetch:c,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>"authorization"===e.toLowerCase())})}_initRealtimeClient(e){return new eo(this.realtimeUrl.href,rh(rh({},e),{},{params:rh(rh({},{apikey:this.supabaseKey}),null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,r){("TOKEN_REFRESHED"===e||"SIGNED_IN"===e)&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0)}};(function(){if("u">typeof window)return!1;let e=globalThis.process;if(!e)return!1;let t=e.version;if(null==t)return!1;let r=t.match(/^v(\d+)\./);return!!r&&18>=parseInt(r[1],10)})()&&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");let rf=new rd("https://xjtycbqriiisxsdnkaqq.supabase.co","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhqdHljYnFyaWlpc3hzZG5rYXFxIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Njk1MDAwNzksImV4cCI6MjA4NTA3NjA3OX0.gLTVx7mxW2cMirK1Y3qz_YtAx3Fd_nwXRiRlj6FTpqE",void 0);e.s(["supabase",0,rf],86782);var rp=e.i(36130);let rg=(...e)=>e.filter((e,t,r)=>!!e&&""!==e.trim()&&r.indexOf(e)===t).join(" ").trim(),ry=e=>{let t=e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,r)=>r?r.toUpperCase():t.toLowerCase());return t.charAt(0).toUpperCase()+t.slice(1)};var rm={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};let rw=(0,rp.forwardRef)(({color:e="currentColor",size:t=24,strokeWidth:r=2,absoluteStrokeWidth:s,className:i="",children:n,iconNode:a,...o},l)=>(0,rp.createElement)("svg",{ref:l,...rm,width:t,height:t,stroke:e,strokeWidth:s?24*Number(r)/Number(t):r,className:rg("lucide",i),...!n&&!(e=>{for(let t in e)if(t.startsWith("aria-")||"role"===t||"title"===t)return!0;return!1})(o)&&{"aria-hidden":"true"},...o},[...a.map(([e,t])=>(0,rp.createElement)(e,t)),...Array.isArray(n)?n:[n]])),rb=(e,t)=>{let r=(0,rp.forwardRef)(({className:r,...s},i)=>(0,rp.createElement)(rw,{ref:i,iconNode:t,className:rg(`lucide-${ry(e).replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,`lucide-${e}`,r),...s}));return r.displayName=ry(e),r};e.s(["default",()=>rb],80551);let rv=rb("mail",[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]]);e.s(["Mail",()=>rv],59451);let r_=rb("map-pin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);e.s(["MapPin",()=>r_],45073);let rk=rb("message-circle",[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]]);e.s(["MessageCircle",()=>rk],35823)}]);