@supabase/supabase-js 2.33.0 → 2.33.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,6 @@
1
1
  declare type Fetch = typeof fetch;
2
2
  export declare const resolveFetch: (customFetch?: Fetch) => Fetch;
3
- export declare const resolveHeadersConstructor: () => {
4
- new (init?: HeadersInit | undefined): Headers;
5
- prototype: Headers;
6
- };
3
+ export declare const resolveHeadersConstructor: () => any;
7
4
  export declare const fetchWithAuth: (supabaseKey: string, getAccessToken: () => Promise<string | null>, customFetch?: Fetch) => Fetch;
8
5
  export {};
9
6
  //# sourceMappingURL=fetch.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":"AAEA,aAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,eAAO,MAAM,YAAY,iBAAkB,KAAK,KAAG,KAUlD,CAAA;AAED,eAAO,MAAM,yBAAyB;;;CAMrC,CAAA;AAED,eAAO,MAAM,aAAa,gBACX,MAAM,kBACH,MAAM,QAAQ,MAAM,GAAG,IAAI,CAAC,gBAC9B,KAAK,KAClB,KAkBF,CAAA"}
1
+ {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":"AAGA,aAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,eAAO,MAAM,YAAY,iBAAkB,KAAK,KAAG,KAUlD,CAAA;AAED,eAAO,MAAM,yBAAyB,WAMrC,CAAA;AAED,eAAO,MAAM,aAAa,gBACX,MAAM,kBACH,MAAM,QAAQ,MAAM,GAAG,IAAI,CAAC,gBAC9B,KAAK,KAClB,KAkBF,CAAA"}
@@ -33,14 +33,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
33
33
  };
34
34
  Object.defineProperty(exports, "__esModule", { value: true });
35
35
  exports.fetchWithAuth = exports.resolveHeadersConstructor = exports.resolveFetch = void 0;
36
- const cross_fetch_1 = __importStar(require("cross-fetch"));
36
+ // @ts-ignore
37
+ const node_fetch_1 = __importStar(require("@supabase/node-fetch"));
37
38
  const resolveFetch = (customFetch) => {
38
39
  let _fetch;
39
40
  if (customFetch) {
40
41
  _fetch = customFetch;
41
42
  }
42
43
  else if (typeof fetch === 'undefined') {
43
- _fetch = cross_fetch_1.default;
44
+ _fetch = node_fetch_1.default;
44
45
  }
45
46
  else {
46
47
  _fetch = fetch;
@@ -50,7 +51,7 @@ const resolveFetch = (customFetch) => {
50
51
  exports.resolveFetch = resolveFetch;
51
52
  const resolveHeadersConstructor = () => {
52
53
  if (typeof Headers === 'undefined') {
53
- return cross_fetch_1.Headers;
54
+ return node_fetch_1.Headers;
54
55
  }
55
56
  return Headers;
56
57
  };
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2DAAsE;AAI/D,MAAM,YAAY,GAAG,CAAC,WAAmB,EAAS,EAAE;IACzD,IAAI,MAAa,CAAA;IACjB,IAAI,WAAW,EAAE;QACf,MAAM,GAAG,WAAW,CAAA;KACrB;SAAM,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;QACvC,MAAM,GAAG,qBAA8B,CAAA;KACxC;SAAM;QACL,MAAM,GAAG,KAAK,CAAA;KACf;IACD,OAAO,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAA;AACrC,CAAC,CAAA;AAVY,QAAA,YAAY,gBAUxB;AAEM,MAAM,yBAAyB,GAAG,GAAG,EAAE;IAC5C,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;QAClC,OAAO,qBAAiB,CAAA;KACzB;IAED,OAAO,OAAO,CAAA;AAChB,CAAC,CAAA;AANY,QAAA,yBAAyB,6BAMrC;AAEM,MAAM,aAAa,GAAG,CAC3B,WAAmB,EACnB,cAA4C,EAC5C,WAAmB,EACZ,EAAE;IACT,MAAM,KAAK,GAAG,IAAA,oBAAY,EAAC,WAAW,CAAC,CAAA;IACvC,MAAM,kBAAkB,GAAG,IAAA,iCAAyB,GAAE,CAAA;IAEtD,OAAO,CAAO,KAAK,EAAE,IAAI,EAAE,EAAE;;QAC3B,MAAM,WAAW,GAAG,MAAA,CAAC,MAAM,cAAc,EAAE,CAAC,mCAAI,WAAW,CAAA;QAC3D,IAAI,OAAO,GAAG,IAAI,kBAAkB,CAAC,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,CAAC,CAAA;QAEnD,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE;YAC1B,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAA;SACnC;QAED,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE;YACjC,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,UAAU,WAAW,EAAE,CAAC,CAAA;SACtD;QAED,OAAO,KAAK,CAAC,KAAK,kCAAO,IAAI,KAAE,OAAO,IAAG,CAAA;IAC3C,CAAC,CAAA,CAAA;AACH,CAAC,CAAA;AAtBY,QAAA,aAAa,iBAsBzB"}
1
+ {"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,aAAa;AACb,mEAA6E;AAItE,MAAM,YAAY,GAAG,CAAC,WAAmB,EAAS,EAAE;IACzD,IAAI,MAAa,CAAA;IACjB,IAAI,WAAW,EAAE;QACf,MAAM,GAAG,WAAW,CAAA;KACrB;SAAM,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;QACvC,MAAM,GAAG,oBAA6B,CAAA;KACvC;SAAM;QACL,MAAM,GAAG,KAAK,CAAA;KACf;IACD,OAAO,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAA;AACrC,CAAC,CAAA;AAVY,QAAA,YAAY,gBAUxB;AAEM,MAAM,yBAAyB,GAAG,GAAG,EAAE;IAC5C,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;QAClC,OAAO,oBAAgB,CAAA;KACxB;IAED,OAAO,OAAO,CAAA;AAChB,CAAC,CAAA;AANY,QAAA,yBAAyB,6BAMrC;AAEM,MAAM,aAAa,GAAG,CAC3B,WAAmB,EACnB,cAA4C,EAC5C,WAAmB,EACZ,EAAE;IACT,MAAM,KAAK,GAAG,IAAA,oBAAY,EAAC,WAAW,CAAC,CAAA;IACvC,MAAM,kBAAkB,GAAG,IAAA,iCAAyB,GAAE,CAAA;IAEtD,OAAO,CAAO,KAAK,EAAE,IAAI,EAAE,EAAE;;QAC3B,MAAM,WAAW,GAAG,MAAA,CAAC,MAAM,cAAc,EAAE,CAAC,mCAAI,WAAW,CAAA;QAC3D,IAAI,OAAO,GAAG,IAAI,kBAAkB,CAAC,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,CAAC,CAAA;QAEnD,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE;YAC1B,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAA;SACnC;QAED,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE;YACjC,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,UAAU,WAAW,EAAE,CAAC,CAAA;SACtD;QAED,OAAO,KAAK,CAAC,KAAK,kCAAO,IAAI,KAAE,OAAO,IAAG,CAAA;IAC3C,CAAC,CAAA,CAAA;AACH,CAAC,CAAA;AAtBY,QAAA,aAAa,iBAsBzB"}
@@ -1,2 +1,2 @@
1
- export declare const version = "2.33.0";
1
+ export declare const version = "2.33.2";
2
2
  //# sourceMappingURL=version.d.ts.map
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.version = void 0;
4
- exports.version = '2.33.0';
4
+ exports.version = '2.33.2';
5
5
  //# sourceMappingURL=version.js.map
@@ -1,9 +1,6 @@
1
1
  declare type Fetch = typeof fetch;
2
2
  export declare const resolveFetch: (customFetch?: Fetch) => Fetch;
3
- export declare const resolveHeadersConstructor: () => {
4
- new (init?: HeadersInit | undefined): Headers;
5
- prototype: Headers;
6
- };
3
+ export declare const resolveHeadersConstructor: () => any;
7
4
  export declare const fetchWithAuth: (supabaseKey: string, getAccessToken: () => Promise<string | null>, customFetch?: Fetch) => Fetch;
8
5
  export {};
9
6
  //# sourceMappingURL=fetch.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":"AAEA,aAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,eAAO,MAAM,YAAY,iBAAkB,KAAK,KAAG,KAUlD,CAAA;AAED,eAAO,MAAM,yBAAyB;;;CAMrC,CAAA;AAED,eAAO,MAAM,aAAa,gBACX,MAAM,kBACH,MAAM,QAAQ,MAAM,GAAG,IAAI,CAAC,gBAC9B,KAAK,KAClB,KAkBF,CAAA"}
1
+ {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":"AAGA,aAAK,KAAK,GAAG,OAAO,KAAK,CAAA;AAEzB,eAAO,MAAM,YAAY,iBAAkB,KAAK,KAAG,KAUlD,CAAA;AAED,eAAO,MAAM,yBAAyB,WAMrC,CAAA;AAED,eAAO,MAAM,aAAa,gBACX,MAAM,kBACH,MAAM,QAAQ,MAAM,GAAG,IAAI,CAAC,gBAC9B,KAAK,KAClB,KAkBF,CAAA"}
@@ -7,14 +7,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
- import crossFetch, { Headers as CrossFetchHeaders } from 'cross-fetch';
10
+ // @ts-ignore
11
+ import nodeFetch, { Headers as NodeFetchHeaders } from '@supabase/node-fetch';
11
12
  export const resolveFetch = (customFetch) => {
12
13
  let _fetch;
13
14
  if (customFetch) {
14
15
  _fetch = customFetch;
15
16
  }
16
17
  else if (typeof fetch === 'undefined') {
17
- _fetch = crossFetch;
18
+ _fetch = nodeFetch;
18
19
  }
19
20
  else {
20
21
  _fetch = fetch;
@@ -23,7 +24,7 @@ export const resolveFetch = (customFetch) => {
23
24
  };
24
25
  export const resolveHeadersConstructor = () => {
25
26
  if (typeof Headers === 'undefined') {
26
- return CrossFetchHeaders;
27
+ return NodeFetchHeaders;
27
28
  }
28
29
  return Headers;
29
30
  };
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,UAAU,EAAE,EAAE,OAAO,IAAI,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAItE,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,WAAmB,EAAS,EAAE;IACzD,IAAI,MAAa,CAAA;IACjB,IAAI,WAAW,EAAE;QACf,MAAM,GAAG,WAAW,CAAA;KACrB;SAAM,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;QACvC,MAAM,GAAG,UAA8B,CAAA;KACxC;SAAM;QACL,MAAM,GAAG,KAAK,CAAA;KACf;IACD,OAAO,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAA;AACrC,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,yBAAyB,GAAG,GAAG,EAAE;IAC5C,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;QAClC,OAAO,iBAAiB,CAAA;KACzB;IAED,OAAO,OAAO,CAAA;AAChB,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,aAAa,GAAG,CAC3B,WAAmB,EACnB,cAA4C,EAC5C,WAAmB,EACZ,EAAE;IACT,MAAM,KAAK,GAAG,YAAY,CAAC,WAAW,CAAC,CAAA;IACvC,MAAM,kBAAkB,GAAG,yBAAyB,EAAE,CAAA;IAEtD,OAAO,CAAO,KAAK,EAAE,IAAI,EAAE,EAAE;;QAC3B,MAAM,WAAW,GAAG,MAAA,CAAC,MAAM,cAAc,EAAE,CAAC,mCAAI,WAAW,CAAA;QAC3D,IAAI,OAAO,GAAG,IAAI,kBAAkB,CAAC,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,CAAC,CAAA;QAEnD,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE;YAC1B,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAA;SACnC;QAED,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE;YACjC,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,UAAU,WAAW,EAAE,CAAC,CAAA;SACtD;QAED,OAAO,KAAK,CAAC,KAAK,kCAAO,IAAI,KAAE,OAAO,IAAG,CAAA;IAC3C,CAAC,CAAA,CAAA;AACH,CAAC,CAAA"}
1
+ {"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../../src/lib/fetch.ts"],"names":[],"mappings":";;;;;;;;;AAAA,aAAa;AACb,OAAO,SAAS,EAAE,EAAE,OAAO,IAAI,gBAAgB,EAAE,MAAM,sBAAsB,CAAA;AAI7E,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,WAAmB,EAAS,EAAE;IACzD,IAAI,MAAa,CAAA;IACjB,IAAI,WAAW,EAAE;QACf,MAAM,GAAG,WAAW,CAAA;KACrB;SAAM,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;QACvC,MAAM,GAAG,SAA6B,CAAA;KACvC;SAAM;QACL,MAAM,GAAG,KAAK,CAAA;KACf;IACD,OAAO,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,CAAA;AACrC,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,yBAAyB,GAAG,GAAG,EAAE;IAC5C,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;QAClC,OAAO,gBAAgB,CAAA;KACxB;IAED,OAAO,OAAO,CAAA;AAChB,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,aAAa,GAAG,CAC3B,WAAmB,EACnB,cAA4C,EAC5C,WAAmB,EACZ,EAAE;IACT,MAAM,KAAK,GAAG,YAAY,CAAC,WAAW,CAAC,CAAA;IACvC,MAAM,kBAAkB,GAAG,yBAAyB,EAAE,CAAA;IAEtD,OAAO,CAAO,KAAK,EAAE,IAAI,EAAE,EAAE;;QAC3B,MAAM,WAAW,GAAG,MAAA,CAAC,MAAM,cAAc,EAAE,CAAC,mCAAI,WAAW,CAAA;QAC3D,IAAI,OAAO,GAAG,IAAI,kBAAkB,CAAC,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,CAAC,CAAA;QAEnD,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE;YAC1B,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAA;SACnC;QAED,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE;YACjC,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,UAAU,WAAW,EAAE,CAAC,CAAA;SACtD;QAED,OAAO,KAAK,CAAC,KAAK,kCAAO,IAAI,KAAE,OAAO,IAAG,CAAA;IAC3C,CAAC,CAAA,CAAA;AACH,CAAC,CAAA"}
@@ -1,2 +1,2 @@
1
- export declare const version = "2.33.0";
1
+ export declare const version = "2.33.2";
2
2
  //# sourceMappingURL=version.d.ts.map
@@ -1,2 +1,2 @@
1
- export const version = '2.33.0';
1
+ export const version = '2.33.2';
2
2
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.supabase=t():e.supabase=t()}(self,(()=>(()=>{var e,t,r={982:(e,t,r)=>{"use strict";r.r(t),r.d(t,{FunctionsClient:()=>a,FunctionsError:()=>s,FunctionsFetchError:()=>i,FunctionsHttpError:()=>o,FunctionsRelayError:()=>n});class s extends Error{constructor(e,t="FunctionsError",r){super(e),super.name=t,this.context=r}}class i extends s{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class n extends s{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class o extends s{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}class a{constructor(e,{headers:t={},customFetch:s}={}){this.url=e,this.headers=t,this.fetch=(e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>{return t=void 0,s=void 0,n=function*(){return yield(yield Promise.resolve().then(r.t.bind(r,98,23))).fetch(...e)},new((i=void 0)||(i=Promise))((function(e,r){function o(e){try{c(n.next(e))}catch(e){r(e)}}function a(e){try{c(n.throw(e))}catch(e){r(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof i?r:new i((function(e){e(r)}))).then(o,a)}c((n=n.apply(t,s||[])).next())}));var t,s,i,n}:fetch),(...e)=>t(...e)})(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r,s,a,c,h;return s=this,a=void 0,h=function*(){try{const{headers:s,method:a,body:c}=t;let h,l={};c&&(s&&!Object.prototype.hasOwnProperty.call(s,"Content-Type")||!s)&&("undefined"!=typeof Blob&&c instanceof Blob||c instanceof ArrayBuffer?(l["Content-Type"]="application/octet-stream",h=c):"string"==typeof c?(l["Content-Type"]="text/plain",h=c):"undefined"!=typeof FormData&&c instanceof FormData?h=c:(l["Content-Type"]="application/json",h=JSON.stringify(c)));const u=yield this.fetch(`${this.url}/${e}`,{method:a||"POST",headers:Object.assign(Object.assign(Object.assign({},l),this.headers),s),body:h}).catch((e=>{throw new i(e)})),d=u.headers.get("x-relay-error");if(d&&"true"===d)throw new n(u);if(!u.ok)throw new o(u);let f,p=(null!==(r=u.headers.get("Content-Type"))&&void 0!==r?r:"text/plain").split(";")[0].trim();return f="application/json"===p?yield u.json():"application/octet-stream"===p?yield u.blob():"multipart/form-data"===p?yield u.formData():yield u.text(),{data:f,error:null}}catch(e){return{data:null,error:e}}},new((c=void 0)||(c=Promise))((function(e,t){function r(e){try{n(h.next(e))}catch(e){t(e)}}function i(e){try{n(h.throw(e))}catch(e){t(e)}}function n(t){var s;t.done?e(t.value):(s=t.value,s instanceof c?s:new c((function(e){e(s)}))).then(r,i)}n((h=h.apply(s,a||[])).next())}))}}},765:(e,t,r)=>{"use strict";r.r(t),r.d(t,{AuthApiError:()=>P,AuthError:()=>O,AuthImplicitGrantRedirectError:()=>L,AuthInvalidCredentialsError:()=>I,AuthInvalidTokenResponseError:()=>R,AuthPKCEGrantCodeExchangeError:()=>U,AuthRetryableFetchError:()=>D,AuthSessionMissingError:()=>C,AuthUnknownError:()=>A,CustomAuthError:()=>$,GoTrueAdminApi:()=>V,GoTrueClient:()=>te,NavigatorLockAcquireTimeoutError:()=>se,isAuthApiError:()=>x,isAuthError:()=>j,isAuthRetryableFetchError:()=>N,lockInternals:()=>re,navigatorLock:()=>ie});const s=()=>"undefined"!=typeof document,i={tested:!1,writable:!1},n=()=>{if(!s())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(i.tested)return i.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),i.tested=!0,i.writable=!0}catch(e){i.tested=!0,i.writable=!1}return i.writable};function o(e){const 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}const a=e=>{let t;return t=e||("undefined"==typeof fetch?async(...e)=>await(await Promise.resolve().then(r.t.bind(r,98,23))).fetch(...e):fetch),(...e)=>t(...e)},c=e=>"object"==typeof e&&null!==e&&"status"in e&&"ok"in e&&"json"in e&&"function"==typeof e.json,h=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},l=async(e,t)=>{const r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return r}},u=async(e,t)=>{await e.removeItem(t)};class d{constructor(){this.promise=new d.promiseConstructor(((e,t)=>{this.resolve=e,this.reject=t}))}}function f(e){const t=e.split(".");if(3!==t.length)throw new Error("JWT is not valid: not a JWT structure");if(!/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");const r=t[1];return JSON.parse(function(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let r,s,i,n,o,a,c,h="",l=0;for(e=e.replace("-","+").replace("_","/");l<e.length;)n=t.indexOf(e.charAt(l++)),o=t.indexOf(e.charAt(l++)),a=t.indexOf(e.charAt(l++)),c=t.indexOf(e.charAt(l++)),r=n<<2|o>>4,s=(15&o)<<4|a>>2,i=(3&a)<<6|c,h+=String.fromCharCode(r),64!=a&&0!=s&&(h+=String.fromCharCode(s)),64!=c&&0!=i&&(h+=String.fromCharCode(i));return h}(r))}async function p(e){return await new Promise((t=>{setTimeout((()=>t(null)),e)}))}function g(e){return("0"+e.toString(16)).substr(-2)}function y(){const e=new Uint32Array(56);if("undefined"==typeof crypto){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length;let r="";for(let s=0;s<56;s++)r+=e.charAt(Math.floor(Math.random()*t));return r}return crypto.getRandomValues(e),Array.from(e,g).join("")}async function m(e){if("undefined"==typeof crypto)return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e;const t=await async function(e){const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(r);return Array.from(s).map((e=>String.fromCharCode(e))).join("")}(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}d.promiseConstructor=Promise;const v=/__stack_guard__([a-zA-Z0-9_-]+)__/;let _,b=!1,w=!1;function S(e){var t,r;let s;_();try{throw new Error}catch(e){s=e}const i=null!==(r=null===(t=s.stack)||void 0===t?void 0:t.split("\n"))&&void 0!==r?r:[];for(let t=0;t<i.length;t+=1){const r=i[t].match(v);if(r&&r[1]===e)return!0}return!1}async function T(e,t){await _();const r=`__stack_guard__${e}__`,s={[r]:async()=>await t()};return Object.assign(s[r],{displayName:r}),await s[r]()}async function E(){return b||await _(),w}let k=!1;_=async()=>{b||(b=!0,await T("ENV_CHECK",(async()=>{await p(0);const e=S("ENV_CHECK");return w=e,e||k||(k=!0,console.warn("@supabase/gotrue-js: Stack guards not supported in this environment. Generally not an issue but may point to a very conservative transpilation environment (use ES2017 or above) that implements async/await with generators, or this is a JavaScript engine that does not support async/await stack traces. Safari is known to not support stack guards.")),e})))};class O extends Error{constructor(e,t){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t}}function j(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class P extends O{constructor(e,t){super(e,t),this.name="AuthApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}function x(e){return j(e)&&"AuthApiError"===e.name}class A extends O{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class $ extends O{constructor(e,t,r){super(e),this.name=t,this.status=r}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class C extends ${constructor(){super("Auth session missing!","AuthSessionMissingError",400)}}class R extends ${constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500)}}class I extends ${constructor(e){super(e,"AuthInvalidCredentialsError",400)}}class L extends ${constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class U extends ${constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class D extends ${constructor(e,t){super(e,"AuthRetryableFetchError",t)}}function N(e){return j(e)&&"AuthRetryableFetchError"===e.name}const F=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),B=[502,503,504];async function M(e){if(!c(e))throw new D(F(e),0);if(B.includes(e.status))throw new D(F(e),e.status);let t;try{t=await e.json()}catch(e){throw new A(F(e),e)}throw new P(F(t),e.status||500)}async function J(e,t,r,s){var i;const n=Object.assign({},null==s?void 0:s.headers);(null==s?void 0:s.jwt)&&(n.Authorization=`Bearer ${s.jwt}`);const o=null!==(i=null==s?void 0:s.query)&&void 0!==i?i:{};(null==s?void 0:s.redirectTo)&&(o.redirect_to=s.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await async function(e,t,r,s,i,n){const o=((e,t,r,s)=>{const i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==t?void 0:t.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),r))})(t,s,{},n);let a;try{a=await e(r,o)}catch(e){throw console.error(e),new D(F(e),0)}if(a.ok||await M(a),null==s?void 0:s.noResolveJson)return a;try{return await a.json()}catch(e){await M(e)}}(e,t,r+a,{headers:n,noResolveJson:null==s?void 0:s.noResolveJson},0,null==s?void 0:s.body);return(null==s?void 0:s.xform)?null==s?void 0:s.xform(c):{data:Object.assign({},c),error:null}}function q(e){var t;let r=null;var s;return function(e){return e.access_token&&e.refresh_token&&e.expires_in}(e)&&(r=Object.assign({},e),r.expires_at=(s=e.expires_in,Math.round(Date.now()/1e3)+s)),{data:{session:r,user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function H(e){var t;return{data:{user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function z(e){return{data:e,error:null}}function G(e){const{action_link:t,email_otp:r,hashed_token:s,redirect_to:i,verification_type:n}=e,o=function(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(r[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(s=Object.getOwnPropertySymbols(e);i<s.length;i++)t.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(e,s[i])&&(r[s[i]]=e[s[i]])}return r}(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]);return{data:{properties:{action_link:t,email_otp:r,hashed_token:s,redirect_to:i,verification_type:n},user:Object.assign({},o)},error:null}}function K(e){return e}class V{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=a(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await J(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(j(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await J(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:H})}catch(e){if(j(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{const{options:t}=e,r=function(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(r[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(s=Object.getOwnPropertySymbols(e);i<s.length;i++)t.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(e,s[i])&&(r[s[i]]=e[s[i]])}return r}(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 J(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:G,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(j(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await J(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:H})}catch(e){if(j(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,r,s,i,n,o,a;try{const c={nextPage:null,lastPage:0,total:0},h=await J(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?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(i=null===(s=null==e?void 0:e.perPage)||void 0===s?void 0:s.toString())&&void 0!==i?i:""},xform:K});if(h.error)throw h.error;const l=await h.json(),u=null!==(n=h.headers.get("x-total-count"))&&void 0!==n?n:0,d=null!==(a=null===(o=h.headers.get("link"))||void 0===o?void 0:o.split(","))&&void 0!==a?a:[];return d.length>0&&(d.forEach((e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);c[`${r}Page`]=t})),c.total=parseInt(u)),{data:Object.assign(Object.assign({},l),c),error:null}}catch(e){if(j(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){try{return await J(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:H})}catch(e){if(j(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){try{return await J(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:H})}catch(e){if(j(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){try{return await J(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:H})}catch(e){if(j(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){try{const{data:t,error:r}=await J(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(j(e))return{data:null,error:e};throw e}}async _deleteFactor(e){try{return{data:await J(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(j(e))return{data:null,error:e};throw e}}}const W="2.46.1",X={"X-Client-Info":`gotrue-js/${W}`},Y={getItem:e=>n()?globalThis.localStorage.getItem(e):null,setItem:(e,t)=>{n()&&globalThis.localStorage.setItem(e,t)},removeItem:e=>{n()&&globalThis.localStorage.removeItem(e)}};!function(){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){"undefined"!=typeof self&&(self.globalThis=self)}}();const Q={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:X,flowType:"implicit",debug:!1},Z=3e4;async function ee(e,t,r){return await r()}class te{constructor(e){var t;this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.broadcastChannel=null,this.instanceID=te.nextInstanceID,te.nextInstanceID+=1,this.instanceID>0&&s()&&console.warn("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.");const r=Object.assign(Object.assign({},Q),e);if(this.logDebugMessages=r.debug,this.inMemorySession=null,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.persistSession=r.persistSession,this.storage=r.storage||Y,this.admin=new V({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=a(r.fetch),this.lock=r.lock||ee,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,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)},this.persistSession&&this.storage===Y&&!n()&&console.warn("No storage option exists to persist the session, which may result in unexpected behavior when using auth.\n If you want to set persistSession to true, please provide a storage option or you may set persistSession to false to disable this warning."),s()&&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===(t=this.broadcastChannel)||void 0===t||t.addEventListener("message",(async e=>{this._debug("received broadcast notification from other tab or client",e),await this._notifyAllSubscribers(e.data.event,e.data.session,!1)}))}this.initialize()}_debug(...e){return this.logDebugMessages&&console.log(`GoTrueClient@${this.instanceID} (${W}) ${(new Date).toISOString()}`,...e),this}initialize(){return this.initializePromise?this.initializePromise:this._initialize()}async _initialize(){if(this.initializePromise)throw new Error("Double call of #_initialize()");return this.initializePromise=this._acquireLock(-1,(async()=>await T("_initialize",(async()=>{try{const e=!!s()&&await this._isPKCEFlow();if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){const{data:t,error:r}=await this._getSessionFromURL(e);if(r)return this._debug("#_initialize()","error detecting session from URL",r),await this._removeSession(),{error:r};const{session:s,redirectType:i}=t;return this._debug("#_initialize()","detected session in URL",s,"redirect type",i),await this._saveSession(s),setTimeout((async()=>{"recovery"===i?await this._notifyAllSubscribers("PASSWORD_RECOVERY",s):await this._notifyAllSubscribers("SIGNED_IN",s)}),0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return j(e)?{error:e}:{error:new A("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}})))),await this.initializePromise}async signUp(e){var t,r,s;try{let i;if(await this._removeSession(),"email"in e){const{email:r,password:s,options:n}=e;let o=null,a=null;if("pkce"===this.flowType){const e=y();await h(this.storage,`${this.storageKey}-code-verifier`,e),o=await m(e),a=e===o?"plain":"s256"}i=await J(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)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},code_challenge:o,code_challenge_method:a},xform:q})}else{if(!("phone"in e))throw new I("You must provide either an email or phone number and a password");{const{phone:t,password:n,options:o}=e;i=await J(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:n,data:null!==(r=null==o?void 0:o.data)&&void 0!==r?r:{},channel:null!==(s=null==o?void 0:o.channel)&&void 0!==s?s:"sms",gotrue_meta_security:{captcha_token:null==o?void 0:o.captchaToken}},xform:q})}}const{data:n,error:o}=i;if(o||!n)return{data:{user:null,session:null},error:o};const a=n.session,c=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:c,session:a},error:null}}catch(e){if(j(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithPassword(e){try{let t;if(await this._removeSession(),"email"in e){const{email:r,password:s,options:i}=e;t=await J(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:q})}else{if(!("phone"in e))throw new I("You must provide either an email or phone number and a password");{const{phone:r,password:s,options:i}=e;t=await J(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:q})}}const{data:r,error:s}=t;return s?{data:{user:null,session:null},error:s}:r&&r.session&&r.user?(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:{user:r.user,session:r.session},error:s}):{data:{user:null,session:null},error:new R}}catch(e){if(j(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithOAuth(e){var t,r,s,i;return await this._removeSession(),await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(r=e.options)||void 0===r?void 0:r.scopes,queryParams:null===(s=e.options)||void 0===s?void 0:s.queryParams,skipBrowserRedirect:null===(i=e.options)||void 0===i?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){const t=await l(this.storage,`${this.storageKey}-code-verifier`),{data:r,error:s}=await J(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:t},xform:q});return await u(this.storage,`${this.storageKey}-code-verifier`),s?{data:{user:null,session:null},error:s}:r&&r.session&&r.user?(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:r,error:s}):{data:{user:null,session:null},error:new R}}async signInWithIdToken(e){await this._removeSession();try{const{options:t,provider:r,token:s,access_token:i,nonce:n}=e,o=await J(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:q}),{data:a,error:c}=o;return c?{data:{user:null,session:null},error:c}:a&&a.session&&a.user?(a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),{data:a,error:c}):{data:{user:null,session:null},error:new R}}catch(e){if(j(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithOtp(e){var t,r,s,i,n;try{if(await this._removeSession(),"email"in e){const{email:s,options:i}=e;let n=null,o=null;if("pkce"===this.flowType){const e=y();await h(this.storage,`${this.storageKey}-code-verifier`,e),n=await m(e),o=e===n?"plain":"s256"}const{error:a}=await J(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:s,data:null!==(t=null==i?void 0:i.data)&&void 0!==t?t:{},create_user:null===(r=null==i?void 0:i.shouldCreateUser)||void 0===r||r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:n,code_challenge_method:o},redirectTo:null==i?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:a}}if("phone"in e){const{phone:t,options:r}=e,{data:o,error:a}=await J(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(s=null==r?void 0:r.data)&&void 0!==s?s:{},create_user:null===(i=null==r?void 0:r.shouldCreateUser)||void 0===i||i,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken},channel:null!==(n=null==r?void 0:r.channel)&&void 0!==n?n:"sms"}});return{data:{user:null,session:null,messageId:null==o?void 0:o.message_id},error:a}}throw new I("You must provide either an email or phone number.")}catch(e){if(j(e))return{data:{user:null,session:null},error:e};throw e}}async verifyOtp(e){var t,r;try{let s,i;"email_change"!==e.type&&"phone_change"!==e.type&&await this._removeSession(),"options"in e&&(s=null===(t=e.options)||void 0===t?void 0:t.redirectTo,i=null===(r=e.options)||void 0===r?void 0:r.captchaToken);const{data:n,error:o}=await J(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:q});if(o)throw o;if(!n)throw new Error("An error occurred on token verification.");const a=n.session,c=n.user;return(null==a?void 0:a.access_token)&&(await this._saveSession(a),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:c,session:a},error:null}}catch(e){if(j(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithSSO(e){var t,r,s;try{return await this._removeSession(),await J(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?void 0:t.redirectTo)&&void 0!==r?r:void 0}),(null===(s=null==e?void 0:e.options)||void 0===s?void 0:s.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0}),headers:this.headers,xform:z})}catch(e){if(j(e))return{data:null,error:e};throw e}}async reauthenticate(){try{return await this._useSession((async e=>{const{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new C;const{error:s}=await J(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:s}}))}catch(e){if(j(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{"email_change"!=e.type&&"phone_change"!=e.type&&await this._removeSession();const t=`${this.url}/resend`;if("email"in e){const{email:r,type:s,options:i}=e,{error:n}=await J(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{data:{user:null,session:null},error:n}}if("phone"in e){const{phone:r,type:s,options:i}=e,{data:n,error:o}=await J(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:null==n?void 0:n.message_id},error:o}}throw new I("You must provide either an email or phone number and a type")}catch(e){if(j(e))return{data:{user:null,session:null},error:e};throw e}}async getSession(){return this._useSession((async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{return await E()?S("_acquireLock")?(this._debug("#_acquireLock","recursive call"),await t()):await this.lock(`lock:${this.storageKey}`,e,(async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{return await T("_acquireLock",(async()=>await t()))}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey)}})):(this._debug("#_acquireLock","Stack guards not supported, so exclusive locking is not performed as it can lead to deadlocks if the lock is attempted to be recursively acquired (as the recursion cannot be detected)."),await t())}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{if(S("_useSession")){this._debug("#_useSession","recursive call");const t=await this.__loadSession();return await e(t)}return await this._acquireLock(-1,(async()=>await T("_useSession",(async()=>{const t=await this.__loadSession();return await e(t)}))))}finally{this._debug("#_useSession","end")}}async __loadSession(){if(this._debug("#__loadSession()","begin"),this.logDebugMessages&&!S("_useSession")&&await E())throw new Error("Please use #_useSession()");S("_initialize")&&this._debug("#__loadSession","#_initialize recursion detected",(new Error).stack),await this.initializePromise;try{let e=null;if(this.persistSession){const t=await l(this.storage,this.storageKey);this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession()))}else e=this.inMemorySession,this._debug("#getSession()","session from memory",e);if(!e)return{data:{session:null},error:null};const t=!!e.expires_at&&e.expires_at<=Date.now()/1e3;if(this._debug("#__loadSession()",`session has${t?"":" not"} expired`,"expires_at",e.expires_at),!t)return{data:{session:e},error:null};const{session:r,error:s}=await this._callRefreshToken(e.refresh_token);return s?{data:{session:null},error:s}:{data:{session:r},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){try{return e?await J(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:H}):await this._useSession((async e=>{var t,r;const{data:s,error:i}=e;if(i)throw i;return await J(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(r=null===(t=s.session)||void 0===t?void 0:t.access_token)&&void 0!==r?r:void 0,xform:H})}))}catch(e){if(j(e))return{data:{user:null},error:e};throw e}}async updateUser(e,t={}){try{return await this._useSession((async r=>{const{data:s,error:i}=r;if(i)throw i;if(!s.session)throw new C;const n=s.session,{data:o,error:a}=await J(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:e,jwt:n.access_token,xform:H});if(a)throw a;return n.user=o.user,await this._saveSession(n),await this._notifyAllSubscribers("USER_UPDATED",n),{data:{user:n.user},error:null}}))}catch(e){if(j(e))return{data:{user:null},error:e};throw e}}_decodeJWT(e){return f(e)}async setSession(e){try{if(!e.access_token||!e.refresh_token)throw new C;const t=Date.now()/1e3;let r=t,s=!0,i=null;const n=f(e.access_token);if(n.exp&&(r=n.exp,s=r<=t),s){const{session:t,error:r}=await this._callRefreshToken(e.refresh_token);if(r)return{data:{user:null,session:null},error:r};if(!t)return{data:{user:null,session:null},error:null};i=t}else{const{data:s,error:n}=await this.getUser(e.access_token);if(n)throw 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{data:{user:i.user,session:i},error:null}}catch(e){if(j(e))return{data:{session:null,user:null},error:e};throw e}}async refreshSession(e){try{return await this._useSession((async t=>{var r;if(!e){const{data:s,error:i}=t;if(i)throw i;e=null!==(r=s.session)&&void 0!==r?r:void 0}if(!(null==e?void 0:e.refresh_token))throw new C;const{session:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}:s?{data:{user:s.user,session:s},error:null}:{data:{user:null,session:null},error:null}}))}catch(e){if(j(e))return{data:{user:null,session:null},error:e};throw e}}async _getSessionFromURL(e){try{if(!s())throw new L("No browser detected.");if("implicit"===this.flowType&&!this._isImplicitGrantFlow())throw new L("Not a valid implicit grant flow url.");if("pkce"==this.flowType&&!e)throw new U("Not a valid PKCE flow url.");const t=o(window.location.href);if(e){if(!t.code)throw new U("No code detected.");const{data:e,error:r}=await this.exchangeCodeForSession(t.code);if(r)throw r;const s=new URL(window.location.href);return s.searchParams.delete("code"),window.history.replaceState(window.history.state,"",s.toString()),{data:{session:e.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new L(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});const{provider_token:r,provider_refresh_token:i,access_token:n,refresh_token:a,expires_in:c,token_type:h}=t;if(!(n&&c&&a&&h))throw new L("No session defined in URL");const l=Math.round(Date.now()/1e3),u=parseInt(c),d=l+u,{data:f,error:p}=await this.getUser(n);if(p)throw p;const g={provider_token:r,provider_refresh_token:i,access_token:n,expires_in:u,expires_at:d,refresh_token:a,token_type:h,user:f.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:g,redirectType:t.type},error:null}}catch(e){if(j(e))return{data:{session:null,redirectType:null},error:e};throw e}}_isImplicitGrantFlow(){const e=o(window.location.href);return!(!s()||!e.access_token&&!e.error_description)}async _isPKCEFlow(){const e=o(window.location.href),t=await l(this.storage,`${this.storageKey}-code-verifier`);return!(!e.code||!t)}async signOut({scope:e}={scope:"global"}){return await this._useSession((async t=>{var r;const{data:s,error:i}=t;if(i)return{error:i};const n=null===(r=s.session)||void 0===r?void 0:r.access_token;if(n){const{error:t}=await this.admin.signOut(n,e);if(t&&(!x(t)||404!==t.status&&401!==t.status))return{error:t}}return"others"!==e&&(await this._removeSession(),await u(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}}))}onAuthStateChange(e){const t="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)})),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),this._emitInitialSession(t),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession((async t=>{var r,s;try{const{data:{session:s},error:i}=t;if(i)throw i;await(null===(r=this.stateChangeEmitters.get(e))||void 0===r?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?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;if("pkce"===this.flowType){const e=y();await h(this.storage,`${this.storageKey}-code-verifier`,e),r=await m(e),s=e===r?"plain":"s256"}try{return await J(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(j(e))return{data:null,error:e};throw e}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const i=Date.now();return await(r=async r=>(await p(200*r),this._debug(t,"refreshing attempt",r),await J(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:q})),s=(e,t,r)=>r&&r.error&&N(r.error)&&Date.now()+200*(e+1)-i<Z,new Promise(((e,t)=>{(async()=>{for(let i=0;i<1/0;i++)try{const t=await r(i);if(!s(i,0,t))return void e(t)}catch(e){if(!s(i))return void t(e)}})()})))}catch(e){if(this._debug(t,"error",e),j(e))return{data:{session:null,user:null},error:e};throw e}finally{this._debug(t,"end")}var r,s}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const r=await this._getUrlForProvider(e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),s()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e;const t="#_recoverAndRefresh()";this._debug(t,"begin");try{const r=await l(this.storage,this.storageKey);if(this._debug(t,"session from storage",r),!this._isValidSession(r))return this._debug(t,"session is not valid"),void(null!==r&&await this._removeSession());const s=Math.round(Date.now()/1e3),i=(null!==(e=r.expires_at)&&void 0!==e?e:1/0)<s+10;if(this._debug(t,`session has${i?"":" not"} expired with margin of 10s`),i){if(this.autoRefreshToken&&r.refresh_token){const{error:e}=await this._callRefreshToken(r.refresh_token);e&&(console.error(e),N(e)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(e){return this._debug(t,"error",e),void console.error(e)}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new C;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new d;const{data:t,error:r}=await this._refreshAccessToken(e);if(r)throw r;if(!t.session)throw new C;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);const s={session:t.session,error:null};return this.refreshingDeferred.resolve(s),s}catch(e){if(this._debug(s,"error",e),j(e)){const r={session:null,error:e};return null===(t=this.refreshingDeferred)||void 0===t||t.resolve(r),r}throw null===(r=this.refreshingDeferred)||void 0===r||r.reject(e),e}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){const s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});const 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;e<s.length;e+=1)console.error(s[e]);throw s[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.persistSession||(this.inMemorySession=e),this.persistSession&&e.expires_at&&await this._persistSession(e)}_persistSession(e){return this._debug("#_persistSession()",e),h(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),this.persistSession?await u(this.storage,this.storageKey):this.inMemorySession=null}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&s()&&(null===window||void 0===window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval((()=>this._autoRefreshTokenTick()),Z);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e),setTimeout((async()=>{await this.initializePromise,await this._autoRefreshTokenTick()}),0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{const e=Date.now();try{return await this._useSession((async t=>{const{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");const s=Math.floor((1e3*r.expires_at-e)/Z);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")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!s()||!(null===window||void 0===window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),null===window||void 0===window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){this._debug(`#_onVisibilityChanged(${e})`,"visibilityState",document.visibilityState),"visible"===document.visibilityState?setTimeout((async()=>{e||(await this.initializePromise,await this._recoverAndRefresh(),this._debug("#_onVisibilityChanged()","finished waiting for initialize, _recoverAndRefresh")),this.autoRefreshToken&&this._startAutoRefresh()}),0):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t){const r=[`provider=${encodeURIComponent(e)}`];if((null==t?void 0:t.redirectTo)&&r.push(`redirect_to=${encodeURIComponent(t.redirectTo)}`),(null==t?void 0:t.scopes)&&r.push(`scopes=${encodeURIComponent(t.scopes)}`),"pkce"===this.flowType){const e=y();await h(this.storage,`${this.storageKey}-code-verifier`,e);const t=await m(e),s=e===t?"plain":"s256";this._debug("PKCE","code verifier",`${e.substring(0,5)}...`,"code challenge",t,"method",s);const i=new URLSearchParams({code_challenge:`${encodeURIComponent(t)}`,code_challenge_method:`${encodeURIComponent(s)}`});r.push(i.toString())}if(null==t?void 0:t.queryParams){const e=new URLSearchParams(t.queryParams);r.push(e.toString())}return`${this.url}/authorize?${r.join("&")}`}async _unenroll(e){try{return await this._useSession((async t=>{var r;const{data:s,error:i}=t;return i?{data:null,error:i}:await J(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token})}))}catch(e){if(j(e))return{data:null,error:e};throw e}}async _enroll(e){try{return await this._useSession((async t=>{var r,s;const{data:i,error:n}=t;if(n)return{data:null,error:n};const{data:o,error:a}=await J(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:null===(r=null==i?void 0:i.session)||void 0===r?void 0:r.access_token});return a?{data:null,error:a}:((null===(s=null==o?void 0:o.totp)||void 0===s?void 0:s.qr_code)&&(o.totp.qr_code=`data:image/svg+xml;utf-8,${o.totp.qr_code}`),{data:o,error:null})}))}catch(e){if(j(e))return{data:null,error:e};throw e}}async _verify(e){try{return await this._useSession((async t=>{var r;const{data:s,error:i}=t;if(i)return{data:null,error:i};const{data:n,error:o}=await J(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token});return o?{data:null,error:o}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+n.expires_in},n)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",n),{data:n,error:o})}))}catch(e){if(j(e))return{data:null,error:e};throw e}}async _challenge(e){try{return await this._useSession((async t=>{var r;const{data:s,error:i}=t;return i?{data:null,error:i}:await J(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token})}))}catch(e){if(j(e))return{data:null,error:e};throw e}}async _challengeAndVerify(e){const{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){const{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};const r=(null==e?void 0:e.factors)||[],s=r.filter((e=>"totp"===e.factor_type&&"verified"===e.status));return{data:{all:r,totp:s},error:null}}async _getAuthenticatorAssuranceLevel(){return await this._useSession((async e=>{var t,r;const{data:{session:s},error:i}=e;if(i)return{data:null,error:i};if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const n=this._decodeJWT(s.access_token);let o=null;n.aal&&(o=n.aal);let a=o;return(null!==(r=null===(t=s.user.factors)||void 0===t?void 0:t.filter((e=>"verified"===e.status)))&&void 0!==r?r:[]).length>0&&(a="aal2"),{data:{currentLevel:o,nextLevel:a,currentAuthenticationMethods:n.amr||[]},error:null}}))}}te.nextInstanceID=0;const re={debug:!(!globalThis||!globalThis.localStorage||"true"!==globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"))};class se extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}async function ie(e,t,r){re.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);let s=null,i=null;const n=new Promise(((e,t)=>{s=e,i=t})),o=(async()=>{await n,re.debug&&console.log("@supabase/gotrue-js: navigatorLock: operation start");try{return await r()}finally{re.debug&&console.log("@supabase/gotrue-js: navigatorLock: operation end")}})(),a=new globalThis.AbortController;return t>0&&setTimeout((()=>{s=null,a.abort(),i&&(re.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e),i&&i(new se(`Acquiring an exclusive Navigator LockManager lock "${e}" timed out after ${t}ms`)),s=null,i=null)}),t),await globalThis.navigator.locks.request(e,{mode:"exclusive",ifAvailable:0===t,signal:a.signal},(async t=>{if(t){re.debug&&console.log("@supabase/gotrue-js: navigatorLock acquired",e);try{s&&(s(),s=null,i=null,await o)}catch(e){}finally{re.debug&&console.log("@supabase/gotrue-js: navigatorLock released",e)}}else re.debug&&console.log("@supabase/gotrue-js: navigatorLock not immediately available",e),new Error(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`).isAcquireTimeout=!0,i&&i(new se(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`)),s=null,i=null})),await o}},189:(e,t,r)=>{"use strict";r.r(t),r.d(t,{PostgrestBuilder:()=>n,PostgrestClient:()=>l,PostgrestFilterBuilder:()=>a,PostgrestQueryBuilder:()=>c,PostgrestTransformBuilder:()=>o});var s=r(98),i=r.n(s);class n{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:"undefined"==typeof fetch?this.fetch=i():this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),"GET"!==this.method&&"HEAD"!==this.method&&(this.headers["Content-Type"]="application/json");let r=(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,r,s;let i=null,n=null,o=null,a=e.status,c=e.statusText;if(e.ok){if("HEAD"!==this.method){const t=await e.text();""===t||(n="text/csv"===this.headers.Accept||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?t:JSON.parse(t))}const s=null===(t=this.headers.Prefer)||void 0===t?void 0:t.match(/count=(exact|planned|estimated)/),h=null===(r=e.headers.get("content-range"))||void 0===r?void 0:r.split("/");s&&h&&h.length>1&&(o=parseInt(h[1])),this.isMaybeSingle&&"GET"===this.method&&Array.isArray(n)&&(n.length>1?(i={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,o=null,a=406,c="Not Acceptable"):n=1===n.length?n[0]:null)}else{const t=await e.text();try{i=JSON.parse(t),Array.isArray(i)&&404===e.status&&(n=[],i=null,a=200,c="OK")}catch(r){404===e.status&&""===t?(a=204,c="No Content"):i={message:t}}if(i&&this.isMaybeSingle&&(null===(s=null==i?void 0:i.details)||void 0===s?void 0:s.includes("Results contain 0 rows"))&&(i=null,a=200,c="OK"),i&&this.shouldThrowOnError)throw i}return{error:i,data:n,count:o,status:a,statusText:c}}));return this.shouldThrowOnError||(r=r.catch((e=>{var t,r,s;return{error:{message:`${null!==(t=null==e?void 0:e.name)&&void 0!==t?t:"FetchError"}: ${null==e?void 0:e.message}`,details:`${null!==(r=null==e?void 0:e.stack)&&void 0!==r?r:""}`,hint:"",code:`${null!==(s=null==e?void 0:e.code)&&void 0!==s?s:""}`},data:null,count:null,status:0,statusText:""}}))),r.then(e,t)}}class o extends n{select(e){let t=!1;const 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.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:s}={}){const i=s?`${s}.order`:"order",n=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${n?`${n},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t}={}){const r=void 0===t?"limit":`${t}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:r}={}){const s=void 0===r?"offset":`${r}.offset`,i=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this.url.searchParams.set(i,""+(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return"GET"===this.method?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:s=!1,wal:i=!1,format:n="text"}={}){const o=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),a=this.headers.Accept;return this.headers.Accept=`application/vnd.pgrst.plan+${n}; for="${a}"; options=${o};`,this}rollback(){var e;return(null!==(e=this.headers.Prefer)&&void 0!==e?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}}class a extends o{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}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){const r=t.map((e=>"string"==typeof e&&new RegExp("[,()]").test(e)?`"${e}"`:`${e}`)).join(",");return this.url.searchParams.append(e,`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");const 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}={}){const r=t?`${t}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}}class c{constructor(e,{headers:t={},schema:r,fetch:s}){this.url=e,this.headers=t,this.schema=r,this.fetch=s}select(e,{head:t=!1,count:r}={}){const s=t?"HEAD":"GET";let i=!1;const n=(null!=e?e:"*").split("").map((e=>/\s/.test(e)&&!i?"":('"'===e&&(i=!i),e))).join("");return this.url.searchParams.set("select",n),r&&(this.headers.Prefer=`count=${r}`),new a({method:s,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:r=!0}={}){const s=[];if(this.headers.Prefer&&s.push(this.headers.Prefer),t&&s.push(`count=${t}`),r||s.push("missing=default"),this.headers.Prefer=s.join(","),Array.isArray(e)){const t=e.reduce(((e,t)=>e.concat(Object.keys(t))),[]);if(t.length>0){const e=[...new Set(t)].map((e=>`"${e}"`));this.url.searchParams.set("columns",e.join(","))}}return new a({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:s,defaultToNull:i=!0}={}){const n=[`resolution=${r?"ignore":"merge"}-duplicates`];if(void 0!==t&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&n.push(this.headers.Prefer),s&&n.push(`count=${s}`),i||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){const t=e.reduce(((e,t)=>e.concat(Object.keys(t))),[]);if(t.length>0){const e=[...new Set(t)].map((e=>`"${e}"`));this.url.searchParams.set("columns",e.join(","))}}return new a({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){const r=[];return this.headers.Prefer&&r.push(this.headers.Prefer),t&&r.push(`count=${t}`),this.headers.Prefer=r.join(","),new a({method:"PATCH",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){const t=[];return e&&t.push(`count=${e}`),this.headers.Prefer&&t.unshift(this.headers.Prefer),this.headers.Prefer=t.join(","),new a({method:"DELETE",url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}}const h={"X-Client-Info":"postgrest-js/1.8.0"};class l{constructor(e,{headers:t={},schema:r,fetch:s}={}){this.url=e,this.headers=Object.assign(Object.assign({},h),t),this.schemaName=r,this.fetch=s}from(e){const t=new URL(`${this.url}/${e}`);return new c(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new l(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,count:s}={}){let i;const n=new URL(`${this.url}/rpc/${e}`);let o;r?(i="HEAD",Object.entries(t).forEach((([e,t])=>{n.searchParams.append(e,`${t}`)}))):(i="POST",o=t);const c=Object.assign({},this.headers);return s&&(c.Prefer=`count=${s}`),new a({method:i,url:n,headers:c,schema:this.schemaName,body:o,fetch:this.fetch,allowEmpty:!1})}}},73:(e,t,r)=>{"use strict";r.r(t),r.d(t,{REALTIME_LISTEN_TYPES:()=>O,REALTIME_POSTGRES_CHANGES_LISTEN_EVENT:()=>k,REALTIME_PRESENCE_LISTEN_EVENTS:()=>l,REALTIME_SUBSCRIBE_STATES:()=>j,RealtimeChannel:()=>x,RealtimeClient:()=>C,RealtimePresence:()=>g});var s=r(840);const i={"X-Client-Info":"realtime-js/2.7.3"};var n,o,a,c,h,l,u;!function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"}(n||(n={})),function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"}(o||(o={})),function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave",e.access_token="access_token"}(a||(a={})),function(e){e.websocket="websocket"}(c||(c={})),function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"}(h||(h={}));class d{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)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout((()=>{this.tries=this.tries+1,this.callback()}),this.timerCalc(this.tries+1))}}class f{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t("string"==typeof e?JSON.parse(e):{})}_binaryDecode(e){const t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){const s=t.getUint8(1),i=t.getUint8(2);let n=this.HEADER_LENGTH+2;const o=r.decode(e.slice(n,n+s));n+=s;const a=r.decode(e.slice(n,n+i));return n+=i,{ref:null,topic:o,event:a,payload:JSON.parse(r.decode(e.slice(n,e.byteLength)))}}}class p{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,this.rateLimited=!1}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,"rate limited"===this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()})&&(this.rateLimited=!0))}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?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){this.timeoutTimer||(this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref),this.channel._on(this.refEvent,{},(e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(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}}!function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"}(l||(l={}));class g{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,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=>{const{onJoin:t,onLeave:r,onSync:s}=this.caller;this.joinRef=this.channel._joinRef(),this.state=g.syncState(this.state,e,t,r),this.pendingDiffs.forEach((e=>{this.state=g.syncDiff(this.state,e,t,r)})),this.pendingDiffs=[],s()})),this.channel._on(r.diff,{},(e=>{const{onJoin:t,onLeave:r,onSync:s}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=g.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){const i=this.cloneDeep(e),n=this.transformState(t),o={},a={};return this.map(i,((e,t)=>{n[e]||(a[e]=t)})),this.map(n,((e,t)=>{const r=i[e];if(r){const s=t.map((e=>e.presence_ref)),i=r.map((e=>e.presence_ref)),n=t.filter((e=>i.indexOf(e.presence_ref)<0)),c=r.filter((e=>s.indexOf(e.presence_ref)<0));n.length>0&&(o[e]=n),c.length>0&&(a[e]=c)}else o[e]=t})),this.syncDiff(i,{joins:o,leaves:a},r,s)}static syncDiff(e,t,r,s){const{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;const n=null!==(i=e[t])&&void 0!==i?i:[];if(e[t]=this.cloneDeep(s),n.length>0){const r=e[t].map((e=>e.presence_ref)),s=n.filter((e=>r.indexOf(e.presence_ref)<0));e[t].unshift(...s)}r(t,n,s)})),this.map(n,((t,r)=>{let i=e[t];if(!i)return;const n=r.map((e=>e.presence_ref));i=i.filter((e=>n.indexOf(e.presence_ref)<0)),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 e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce(((t,r)=>{const s=e[r];return t[r]="metas"in s?s.metas.map((e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))):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()}}!function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"}(u||(u={}));const y=(e,t,r={})=>{var s;const i=null!==(s=r.skipTypes)&&void 0!==s?s:[];return Object.keys(t).reduce(((r,s)=>(r[s]=m(s,e,t,i),r)),{})},m=(e,t,r,s)=>{const i=t.find((t=>t.name===e)),n=null==i?void 0:i.type,o=r[e];return n&&!s.includes(n)?v(n,o):_(o)},v=(e,t)=>{if("_"===e.charAt(0)){const r=e.slice(1,e.length);return T(t,r)}switch(e){case u.bool:return b(t);case u.float4:case u.float8:case u.int2:case u.int4:case u.int8:case u.numeric:case u.oid:return w(t);case u.json:case u.jsonb:return S(t);case u.timestamp:return E(t);case u.abstime:case u.date:case u.daterange:case u.int4range:case u.int8range:case u.money:case u.reltime:case u.text:case u.time:case u.timestamptz:case u.timetz:case u.tsrange:case u.tstzrange:default:return _(t)}},_=e=>e,b=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},w=e=>{if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},S=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(t){return console.log(`JSON parse error: ${t}`),e}return e},T=(e,t)=>{if("string"!=typeof e)return e;const r=e.length-1,s=e[r];if("{"===e[0]&&"}"===s){let s;const 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},E=e=>"string"==typeof e?e.replace(" ","T"):e;var k,O,j,P=function(e,t,r,s){return new(r||(r=Promise))((function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((s=s.apply(e,t||[])).next())}))};!function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"}(k||(k={})),function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes"}(O||(O={})),function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"}(j||(j={}));class x{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=o.closed,this.joinedOnce=!1,this.pushBuffer=[],this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""}},t.config),this.timeout=this.socket.timeout,this.joinPush=new p(this,a.join,this.params,this.timeout),this.rejoinTimer=new d((()=>this._rejoinUntilConnected()),this.socket.reconnectAfterMs),this.joinPush.receive("ok",(()=>{this.state=o.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=o.closed,this.socket._remove(this)})),this._onError((e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=o.errored,this.rejoinTimer.scheduleTimeout())})),this.joinPush.receive("timeout",(()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=o.errored,this.rejoinTimer.scheduleTimeout())})),this._on(a.reply,{},((e,t)=>{this._trigger(this._replyEventName(t),e)})),this.presence=new g(this)}subscribe(e,t=this.timeout){var r,s;if(this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{const{config:{broadcast:i,presence:n}}=this.params;this._onError((t=>e&&e("CHANNEL_ERROR",t))),this._onClose((()=>e&&e("CLOSED")));const o={},a={broadcast:i,presence:n,postgres_changes:null!==(s=null===(r=this.bindings.postgres_changes)||void 0===r?void 0:r.map((e=>e.filter)))&&void 0!==s?s:[]};this.socket.accessToken&&(o.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:a},o)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",(({postgres_changes:t})=>{var r;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),void 0!==t){const s=this.bindings.postgres_changes,i=null!==(r=null==s?void 0:s.length)&&void 0!==r?r:0,n=[];for(let r=0;r<i;r++){const i=s[r],{filter:{event:o,schema:a,table:c,filter:h}}=i,l=t&&t[r];if(!l||l.event!==o||l.schema!==a||l.table!==c||l.filter!==h)return this.unsubscribe(),void(e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes")));n.push(Object.assign(Object.assign({},i),{id:l.id}))}return this.bindings.postgres_changes=n,void(e&&e("SUBSCRIBED"))}e&&e("SUBSCRIBED")})).receive("error",(t=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(t).join(", ")||"error")))})).receive("timeout",(()=>{e&&e("TIMED_OUT")}))}return this}presenceState(){return this.presence.state}track(e,t={}){return P(this,void 0,void 0,(function*(){return yield this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}))}untrack(e={}){return P(this,void 0,void 0,(function*(){return yield this.send({type:"presence",event:"untrack"},e)}))}on(e,t,r){return this._on(e,t,r)}send(e,t={}){return new Promise((r=>{var s,i,n;const o=this._push(e.type,e,t.timeout||this.timeout);o.rateLimited&&r("rate limited"),"broadcast"!==e.type||(null===(n=null===(i=null===(s=this.params)||void 0===s?void 0:s.config)||void 0===i?void 0:i.broadcast)||void 0===n?void 0:n.ack)||r("ok"),o.receive("ok",(()=>r("ok"))),o.receive("timeout",(()=>r("timed out")))}))}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=o.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(a.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise((r=>{const s=new p(this,a.leave,{},e);s.receive("ok",(()=>{t(),r("ok")})).receive("timeout",(()=>{t(),r("timed out")})).receive("error",(()=>{r("error")})),s.send(),this._canPush()||s.trigger("ok",{})}))}_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 p(this,e,t,r);return this._canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var s,i;const n=e.toLocaleLowerCase(),{close:o,error:c,leave:h,join:l}=a;if(r&&[o,c,h,l].indexOf(n)>=0&&r!==this._joinRef())return;let u=this._onMessage(n,t,r);if(t&&!u)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(n)?null===(s=this.bindings.postgres_changes)||void 0===s||s.filter((e=>{var t,r,s;return"*"===(null===(t=e.filter)||void 0===t?void 0:t.event)||(null===(s=null===(r=e.filter)||void 0===r?void 0:r.event)||void 0===s?void 0:s.toLocaleLowerCase())===n})).map((e=>e.callback(u,r))):null===(i=this.bindings[n])||void 0===i||i.filter((e=>{var r,s,i,o,a,c;if(["broadcast","presence","postgres_changes"].includes(n)){if("id"in e){const n=e.id,o=null===(r=e.filter)||void 0===r?void 0:r.event;return n&&(null===(s=t.ids)||void 0===s?void 0:s.includes(n))&&("*"===o||(null==o?void 0:o.toLocaleLowerCase())===(null===(i=t.data)||void 0===i?void 0:i.type.toLocaleLowerCase()))}{const r=null===(a=null===(o=null==e?void 0:e.filter)||void 0===o?void 0:o.event)||void 0===a?void 0:a.toLocaleLowerCase();return"*"===r||r===(null===(c=null==t?void 0:t.event)||void 0===c?void 0:c.toLocaleLowerCase())}}return e.type.toLocaleLowerCase()===n})).map((e=>{if("object"==typeof u&&"ids"in u){const e=u.data,{schema:t,table:r,commit_timestamp:s,type:i,errors:n}=e,o={schema:t,table:r,commit_timestamp:s,eventType:i,new:{},old:{},errors:n};u=Object.assign(Object.assign({},o),this._getPayloadRecords(e))}e.callback(u,r)}))}_isClosed(){return this.state===o.closed}_isJoined(){return this.state===o.joined}_isJoining(){return this.state===o.joining}_isLeaving(){return this.state===o.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){const 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){const r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter((e=>{var s;return!((null===(s=e.type)||void 0===s?void 0:s.toLocaleLowerCase())===r&&x.isEqual(e.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(a.close,{},e)}_onError(e){this._on(a.error,{},(t=>e(t)))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=o.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return"INSERT"!==e.type&&"UPDATE"!==e.type||(t.new=y(e.columns,e.record)),"UPDATE"!==e.type&&"DELETE"!==e.type||(t.old=y(e.columns,e.old_record)),t}}var A=function(e,t,r,s){return new(r||(r=Promise))((function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((s=s.apply(e,t||[])).next())}))};const $=()=>{};class C{constructor(e,t){var r;this.accessToken=null,this.channels=[],this.endPoint="",this.headers=i,this.params={},this.timeout=1e4,this.transport=s.w3cwebsocket,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=$,this.conn=null,this.sendBuffer=[],this.serializer=new f,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.eventsPerSecondLimitMs=100,this.inThrottle=!1,this.endPoint=`${e}/${c.websocket}`,(null==t?void 0:t.params)&&(this.params=t.params),(null==t?void 0:t.headers)&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),(null==t?void 0:t.timeout)&&(this.timeout=t.timeout),(null==t?void 0:t.logger)&&(this.logger=t.logger),(null==t?void 0:t.transport)&&(this.transport=t.transport),(null==t?void 0:t.heartbeatIntervalMs)&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);const n=null===(r=null==t?void 0:t.params)||void 0===r?void 0:r.eventsPerSecond;n&&(this.eventsPerSecondLimitMs=Math.floor(1e3/n)),this.reconnectAfterMs=(null==t?void 0:t.reconnectAfterMs)?t.reconnectAfterMs:e=>[1e3,2e3,5e3,1e4][e-1]||1e4,this.encode=(null==t?void 0:t.encode)?t.encode:(e,t)=>t(JSON.stringify(e)),this.decode=(null==t?void 0:t.decode)?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new d((()=>A(this,void 0,void 0,(function*(){this.disconnect(),this.connect()}))),this.reconnectAfterMs)}connect(){this.conn||(this.conn=new this.transport(this._endPointURL(),[],null,this.headers),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)))}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,null!=t?t:""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}removeChannel(e){return A(this,void 0,void 0,(function*(){const t=yield e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}))}removeAllChannels(){return A(this,void 0,void 0,(function*(){const e=yield Promise.all(this.channels.map((e=>e.unsubscribe())));return this.disconnect(),e}))}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case n.connecting:return h.Connecting;case n.open:return h.Open;case n.closing:return h.Closing;default:return h.Closed}}isConnected(){return this.connectionState()===h.Open}channel(e,t={config:{}}){this.isConnected()||this.connect();const r=new x(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){const{topic:t,event:r,payload:s,ref:i}=e;let n=()=>{this.encode(e,(e=>{var t;null===(t=this.conn)||void 0===t||t.send(e)}))};if(this.log("push",`${t} ${r} (${i})`,s),this.isConnected())if(["broadcast","presence","postgres_changes"].includes(r)){if(this._throttle(n)())return"rate limited"}else n();else this.sendBuffer.push(n)}setAuth(e){this.accessToken=e,this.channels.forEach((t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(a.access_token,{access_token:e})}))}_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._joinRef()!==e._joinRef()))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:"1.0.0"}))}_onConnMessage(e){this.decode(e.data,(e=>{let{topic:t,event:r,payload:s,ref:i}=e;(i&&i===this.pendingHeartbeatRef||r===(null==s?void 0:s.type))&&(this.pendingHeartbeatRef=null),this.log("receive",`${s.status||""} ${t} ${r} ${i&&"("+i+")"||""}`,s),this.channels.filter((e=>e._isMember(t))).forEach((e=>e._trigger(r,s,i))),this.stateChangeCallbacks.message.forEach((t=>t(e)))}))}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval((()=>this._sendHeartbeat()),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach((e=>e()))}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach((t=>t(e)))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach((t=>t(e)))}_triggerChanError(){this.channels.forEach((e=>e._trigger(a.error)))}_appendParams(e,t){if(0===Object.keys(t).length)return e;const r=e.match(/\?/)?"&":"?";return`${e}${r}${new URLSearchParams(t)}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach((e=>e())),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef)return this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),void(null===(e=this.conn)||void 0===e||e.close(1e3,"hearbeat timeout"));this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}_throttle(e,t=this.eventsPerSecondLimitMs){return()=>!!this.inThrottle||(e(),t>0&&(this.inThrottle=!0,setTimeout((()=>{this.inThrottle=!1}),t)),!1)}}},752:(e,t,r)=>{"use strict";r.r(t),r.d(t,{StorageApiError:()=>n,StorageClient:()=>E,StorageError:()=>s,StorageUnknownError:()=>o,isStorageError:()=>i});class s extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function i(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}class n extends s{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class o extends s{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}var a=function(e,t,r,s){return new(r||(r=Promise))((function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((s=s.apply(e,t||[])).next())}))};const c=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>a(void 0,void 0,void 0,(function*(){return yield(yield Promise.resolve().then(r.t.bind(r,98,23))).fetch(...e)})):fetch),(...e)=>t(...e)};var h=function(e,t,r,s){return new(r||(r=Promise))((function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((s=s.apply(e,t||[])).next())}))};const l=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),u=(e,t)=>h(void 0,void 0,void 0,(function*(){const s=yield a(void 0,void 0,void 0,(function*(){return"undefined"==typeof Response?(yield Promise.resolve().then(r.t.bind(r,98,23))).Response:Response}));e instanceof s?e.json().then((r=>{t(new n(l(r),e.status||500))})).catch((e=>{t(new o(l(e),e))})):t(new o(l(e),e))})),d=(e,t,r,s)=>{const i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?i:(i.headers=Object.assign({"Content-Type":"application/json"},null==t?void 0:t.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),r))};function f(e,t,r,s,i,n){return h(this,void 0,void 0,(function*(){return new Promise(((o,a)=>{e(r,d(t,s,i,n)).then((e=>{if(!e.ok)throw e;return(null==s?void 0:s.noResolveJson)?e:e.json()})).then((e=>o(e))).catch((e=>u(e,a)))}))}))}function p(e,t,r,s){return h(this,void 0,void 0,(function*(){return f(e,"GET",t,r,s)}))}function g(e,t,r,s,i){return h(this,void 0,void 0,(function*(){return f(e,"POST",t,s,i,r)}))}function y(e,t,r,s,i){return h(this,void 0,void 0,(function*(){return f(e,"DELETE",t,s,i,r)}))}var m=function(e,t,r,s){return new(r||(r=Promise))((function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((s=s.apply(e,t||[])).next())}))};const v={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},_={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class b{constructor(e,t={},r,s){this.url=e,this.headers=t,this.bucketId=r,this.fetch=c(s)}uploadOrUpdate(e,t,r,s){return m(this,void 0,void 0,(function*(){try{let i;const n=Object.assign(Object.assign({},_),s),o=Object.assign(Object.assign({},this.headers),"POST"===e&&{"x-upsert":String(n.upsert)});"undefined"!=typeof Blob&&r instanceof Blob?(i=new FormData,i.append("cacheControl",n.cacheControl),i.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(i=r,i.append("cacheControl",n.cacheControl)):(i=r,o["cache-control"]=`max-age=${n.cacheControl}`,o["content-type"]=n.contentType);const a=this._removeEmptyFolders(t),c=this._getFinalPath(a),h=yield this.fetch(`${this.url}/object/${c}`,Object.assign({method:e,body:i,headers:o},(null==n?void 0:n.duplex)?{duplex:n.duplex}:{}));return h.ok?{data:{path:a},error:null}:{data:null,error:yield h.json()}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}upload(e,t,r){return m(this,void 0,void 0,(function*(){return this.uploadOrUpdate("POST",e,t,r)}))}uploadToSignedUrl(e,t,r,s){return m(this,void 0,void 0,(function*(){const n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let e;const t=Object.assign({upsert:_.upsert},s),i=Object.assign(Object.assign({},this.headers),{"x-upsert":String(t.upsert)});"undefined"!=typeof Blob&&r instanceof Blob?(e=new FormData,e.append("cacheControl",t.cacheControl),e.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(e=r,e.append("cacheControl",t.cacheControl)):(e=r,i["cache-control"]=`max-age=${t.cacheControl}`,i["content-type"]=t.contentType);const o=yield this.fetch(a.toString(),{method:"PUT",body:e,headers:i});return o.ok?{data:{path:n},error:null}:{data:null,error:yield o.json()}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}createSignedUploadUrl(e){return m(this,void 0,void 0,(function*(){try{let t=this._getFinalPath(e);const r=yield g(this.fetch,`${this.url}/object/upload/sign/${t}`,{},{headers:this.headers}),i=new URL(this.url+r.url),n=i.searchParams.get("token");if(!n)throw new s("No token returned by API");return{data:{signedUrl:i.toString(),path:e,token:n},error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}update(e,t,r){return m(this,void 0,void 0,(function*(){return this.uploadOrUpdate("PUT",e,t,r)}))}move(e,t){return m(this,void 0,void 0,(function*(){try{return{data:yield g(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t},{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}copy(e,t){return m(this,void 0,void 0,(function*(){try{return{data:{path:(yield g(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t},{headers:this.headers})).Key},error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}createSignedUrl(e,t,r){return m(this,void 0,void 0,(function*(){try{let s=this._getFinalPath(e),i=yield g(this.fetch,`${this.url}/object/sign/${s}`,Object.assign({expiresIn:t},(null==r?void 0:r.transform)?{transform:r.transform}:{}),{headers:this.headers});const n=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${n}`)},{data:i,error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}createSignedUrls(e,t,r){return m(this,void 0,void 0,(function*(){try{const s=yield g(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return{data:s.map((e=>Object.assign(Object.assign({},e),{signedUrl:e.signedURL?encodeURI(`${this.url}${e.signedURL}${i}`):null}))),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}download(e,t){return m(this,void 0,void 0,(function*(){const r=void 0!==(null==t?void 0:t.transform)?"render/image/authenticated":"object",s=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),n=s?`?${s}`:"";try{const t=this._getFinalPath(e),s=yield p(this.fetch,`${this.url}/${r}/${t}${n}`,{headers:this.headers,noResolveJson:!0});return{data:yield s.blob(),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}getPublicUrl(e,t){const r=this._getFinalPath(e),s=[],i=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==i&&s.push(i);const n=void 0!==(null==t?void 0:t.transform)?"render/image":"object",o=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==o&&s.push(o);let a=s.join("&");return""!==a&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${n}/public/${r}${a}`)}}}remove(e){return m(this,void 0,void 0,(function*(){try{return{data:yield y(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}list(e,t,r){return m(this,void 0,void 0,(function*(){try{const s=Object.assign(Object.assign(Object.assign({},v),t),{prefix:e||""});return{data:yield g(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},r),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const 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("&")}}const w={"X-Client-Info":"storage-js/2.5.1"};var S=function(e,t,r,s){return new(r||(r=Promise))((function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((s=s.apply(e,t||[])).next())}))};class T{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},w),t),this.fetch=c(r)}listBuckets(){return S(this,void 0,void 0,(function*(){try{return{data:yield p(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}getBucket(e){return S(this,void 0,void 0,(function*(){try{return{data:yield p(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}createBucket(e,t={public:!1}){return S(this,void 0,void 0,(function*(){try{return{data:yield g(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}updateBucket(e,t){return S(this,void 0,void 0,(function*(){try{const r=yield function(e,t,r,s,i){return h(this,void 0,void 0,(function*(){return f(e,"PUT",t,s,undefined,r)}))}(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers});return{data:r,error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}emptyBucket(e){return S(this,void 0,void 0,(function*(){try{return{data:yield g(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}deleteBucket(e){return S(this,void 0,void 0,(function*(){try{return{data:yield y(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}}class E extends T{constructor(e,t={},r){super(e,t,r)}from(e){return new b(this.url,this.headers,e,this.fetch)}}},98:function(e,t){var r="undefined"!=typeof self?self:this,s=function(){function e(){this.fetch=!1,this.DOMException=r.DOMException}return e.prototype=r,new e}();!function(e){!function(t){var r="URLSearchParams"in e,s="Symbol"in e&&"iterator"in Symbol,i="FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),n="FormData"in e,o="ArrayBuffer"in e;if(o)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],c=ArrayBuffer.isView||function(e){return e&&a.indexOf(Object.prototype.toString.call(e))>-1};function h(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function l(e){return"string"!=typeof e&&(e=String(e)),e}function u(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return s&&(t[Symbol.iterator]=function(){return t}),t}function d(e){this.map={},e instanceof d?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function f(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function p(e){return new Promise((function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}}))}function g(e){var t=new FileReader,r=p(t);return t.readAsArrayBuffer(e),r}function y(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function m(){return this.bodyUsed=!1,this._initBody=function(e){var t;this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:i&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:n&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:r&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():o&&i&&(t=e)&&DataView.prototype.isPrototypeOf(t)?(this._bodyArrayBuffer=y(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):o&&(ArrayBuffer.prototype.isPrototypeOf(e)||c(e))?this._bodyArrayBuffer=y(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},i&&(this.blob=function(){var e=f(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?f(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(g)}),this.text=function(){var e,t,r,s=f(this);if(s)return s;if(this._bodyBlob)return e=this._bodyBlob,r=p(t=new FileReader),t.readAsText(e),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),s=0;s<t.length;s++)r[s]=String.fromCharCode(t[s]);return r.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},n&&(this.formData=function(){return this.text().then(b)}),this.json=function(){return this.text().then(JSON.parse)},this}d.prototype.append=function(e,t){e=h(e),t=l(t);var r=this.map[e];this.map[e]=r?r+", "+t:t},d.prototype.delete=function(e){delete this.map[h(e)]},d.prototype.get=function(e){return e=h(e),this.has(e)?this.map[e]:null},d.prototype.has=function(e){return this.map.hasOwnProperty(h(e))},d.prototype.set=function(e,t){this.map[h(e)]=l(t)},d.prototype.forEach=function(e,t){for(var r in this.map)this.map.hasOwnProperty(r)&&e.call(t,this.map[r],r,this)},d.prototype.keys=function(){var e=[];return this.forEach((function(t,r){e.push(r)})),u(e)},d.prototype.values=function(){var e=[];return this.forEach((function(t){e.push(t)})),u(e)},d.prototype.entries=function(){var e=[];return this.forEach((function(t,r){e.push([r,t])})),u(e)},s&&(d.prototype[Symbol.iterator]=d.prototype.entries);var v=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function _(e,t){var r,s,i=(t=t||{}).body;if(e instanceof _){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new d(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,i||null==e._bodyInit||(i=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"same-origin",!t.headers&&this.headers||(this.headers=new d(t.headers)),this.method=(s=(r=t.method||this.method||"GET").toUpperCase(),v.indexOf(s)>-1?s:r),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&i)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(i)}function b(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var r=e.split("="),s=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(s),decodeURIComponent(i))}})),t}function w(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new d(t.headers),this.url=t.url||"",this._initBody(e)}_.prototype.clone=function(){return new _(this,{body:this._bodyInit})},m.call(_.prototype),m.call(w.prototype),w.prototype.clone=function(){return new w(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new d(this.headers),url:this.url})},w.error=function(){var e=new w(null,{status:0,statusText:""});return e.type="error",e};var S=[301,302,303,307,308];w.redirect=function(e,t){if(-1===S.indexOf(t))throw new RangeError("Invalid status code");return new w(null,{status:t,headers:{location:e}})},t.DOMException=e.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function T(e,r){return new Promise((function(s,n){var o=new _(e,r);if(o.signal&&o.signal.aborted)return n(new t.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function c(){a.abort()}a.onload=function(){var e,t,r={status:a.status,statusText:a.statusText,headers:(e=a.getAllResponseHeaders()||"",t=new d,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(e){var r=e.split(":"),s=r.shift().trim();if(s){var i=r.join(":").trim();t.append(s,i)}})),t)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var i="response"in a?a.response:a.responseText;s(new w(i,r))},a.onerror=function(){n(new TypeError("Network request failed"))},a.ontimeout=function(){n(new TypeError("Network request failed"))},a.onabort=function(){n(new t.DOMException("Aborted","AbortError"))},a.open(o.method,o.url,!0),"include"===o.credentials?a.withCredentials=!0:"omit"===o.credentials&&(a.withCredentials=!1),"responseType"in a&&i&&(a.responseType="blob"),o.headers.forEach((function(e,t){a.setRequestHeader(t,e)})),o.signal&&(o.signal.addEventListener("abort",c),a.onreadystatechange=function(){4===a.readyState&&o.signal.removeEventListener("abort",c)}),a.send(void 0===o._bodyInit?null:o._bodyInit)}))}T.polyfill=!0,e.fetch||(e.fetch=T,e.Headers=d,e.Request=_,e.Response=w),t.Headers=d,t.Request=_,t.Response=w,t.fetch=T,Object.defineProperty(t,"__esModule",{value:!0})}({})}(s),s.fetch.ponyfill=!0,delete s.fetch.polyfill;var i=s;(t=i.fetch).default=i.fetch,t.fetch=i.fetch,t.Headers=i.Headers,t.Request=i.Request,t.Response=i.Response,e.exports=t},284:e=>{var t=function(){if("object"==typeof self&&self)return self;if("object"==typeof window&&window)return window;throw new Error("Unable to resolve global `this`")};e.exports=function(){if(this)return this;if("object"==typeof globalThis&&globalThis)return globalThis;try{Object.defineProperty(Object.prototype,"__global__",{get:function(){return this},configurable:!0})}catch(e){return t()}try{return __global__||t()}finally{delete Object.prototype.__global__}}()},296:function(e,t,r){"use strict";var s=this&&this.__awaiter||function(e,t,r,s){return new(r||(r=Promise))((function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((s=s.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0});const i=r(982),n=r(189),o=r(73),a=r(752),c=r(678),h=r(716),l=r(610),u=r(283),d={headers:c.DEFAULT_HEADERS},f={schema:"public"},p={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},g={};t.default=class{constructor(e,t,r){var s,i,o,a,c,u,y,m;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");const v=(0,l.stripTrailingSlash)(e);this.realtimeUrl=`${v}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${v}/auth/v1`,this.storageUrl=`${v}/storage/v1`,this.functionsUrl=`${v}/functions/v1`;const _=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,b={db:f,realtime:g,auth:Object.assign(Object.assign({},p),{storageKey:_}),global:d},w=(0,l.applySettingDefaults)(null!=r?r:{},b);this.storageKey=null!==(i=null===(s=w.auth)||void 0===s?void 0:s.storageKey)&&void 0!==i?i:"",this.headers=null!==(a=null===(o=w.global)||void 0===o?void 0:o.headers)&&void 0!==a?a:{},this.auth=this._initSupabaseAuthClient(null!==(c=w.auth)&&void 0!==c?c:{},this.headers,null===(u=w.global)||void 0===u?void 0:u.fetch),this.fetch=(0,h.fetchWithAuth)(t,this._getAccessToken.bind(this),null===(y=w.global)||void 0===y?void 0:y.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},w.realtime)),this.rest=new n.PostgrestClient(`${v}/rest/v1`,{headers:this.headers,schema:null===(m=w.db)||void 0===m?void 0:m.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new i.FunctionsClient(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new a.StorageClient(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r){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()}_getAccessToken(){var e,t;return s(this,void 0,void 0,(function*(){const{data:r}=yield this.auth.getSession();return null!==(t=null===(e=r.session)||void 0===e?void 0:e.access_token)&&void 0!==t?t:null}))}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,storageKey:i,flowType:n,debug:o},a,c){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new u.SupabaseAuthClient({url:this.authUrl,headers:Object.assign(Object.assign({},h),a),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,flowType:n,debug:o,fetch:c})}_initRealtimeClient(e){return new o.RealtimeClient(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({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?"SIGNED_OUT"===e&&(this.realtime.setAuth(this.supabaseKey),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0):(this.realtime.setAuth(null!=r?r:null),this.changedAccessToken=r)}}},341:function(e,t,r){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,s,i)}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||s(t,e,r)},n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.createClient=t.SupabaseClient=t.FunctionsError=t.FunctionsRelayError=t.FunctionsFetchError=t.FunctionsHttpError=void 0;const o=n(r(296));i(r(765),t);var a=r(982);Object.defineProperty(t,"FunctionsHttpError",{enumerable:!0,get:function(){return a.FunctionsHttpError}}),Object.defineProperty(t,"FunctionsFetchError",{enumerable:!0,get:function(){return a.FunctionsFetchError}}),Object.defineProperty(t,"FunctionsRelayError",{enumerable:!0,get:function(){return a.FunctionsRelayError}}),Object.defineProperty(t,"FunctionsError",{enumerable:!0,get:function(){return a.FunctionsError}}),i(r(73),t);var c=r(296);Object.defineProperty(t,"SupabaseClient",{enumerable:!0,get:function(){return n(c).default}}),t.createClient=(e,t,r)=>new o.default(e,t,r)},283:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SupabaseAuthClient=void 0;const s=r(765);class i extends s.GoTrueClient{constructor(e){super(e)}}t.SupabaseAuthClient=i},678:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_HEADERS=void 0;const s=r(506);t.DEFAULT_HEADERS={"X-Client-Info":`supabase-js/${s.version}`}},716:function(e,t,r){"use strict";var s=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,s,i)}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&s(t,e,r);return i(t,e),t},o=this&&this.__awaiter||function(e,t,r,s){return new(r||(r=Promise))((function(i,n){function o(e){try{c(s.next(e))}catch(e){n(e)}}function a(e){try{c(s.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(o,a)}c((s=s.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.fetchWithAuth=t.resolveHeadersConstructor=t.resolveFetch=void 0;const a=n(r(98));t.resolveFetch=e=>{let t;return t=e||("undefined"==typeof fetch?a.default:fetch),(...e)=>t(...e)},t.resolveHeadersConstructor=()=>"undefined"==typeof Headers?a.Headers:Headers,t.fetchWithAuth=(e,r,s)=>{const i=(0,t.resolveFetch)(s),n=(0,t.resolveHeadersConstructor)();return(t,s)=>o(void 0,void 0,void 0,(function*(){var o;const a=null!==(o=yield r())&&void 0!==o?o:e;let c=new n(null==s?void 0:s.headers);return c.has("apikey")||c.set("apikey",e),c.has("Authorization")||c.set("Authorization",`Bearer ${a}`),i(t,Object.assign(Object.assign({},s),{headers:c}))}))}},610:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.applySettingDefaults=t.isBrowser=t.stripTrailingSlash=t.uuid=void 0,t.uuid=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},t.stripTrailingSlash=function(e){return e.replace(/\/$/,"")},t.isBrowser=()=>"undefined"!=typeof window,t.applySettingDefaults=function(e,t){const{db:r,auth:s,realtime:i,global:n}=e,{db:o,auth:a,realtime:c,global:h}=t;return{db:Object.assign(Object.assign({},o),r),auth:Object.assign(Object.assign({},a),s),realtime:Object.assign(Object.assign({},c),i),global:Object.assign(Object.assign({},h),n)}}},506:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.version=void 0,t.version="2.33.0"},840:(e,t,r)=>{var s;if("object"==typeof globalThis)s=globalThis;else try{s=r(284)}catch(e){}finally{if(s||"undefined"==typeof window||(s=window),!s)throw new Error("Could not determine global this")}var i=s.WebSocket||s.MozWebSocket,n=r(387);function o(e,t){return t?new i(e,t):new i(e)}i&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach((function(e){Object.defineProperty(o,e,{get:function(){return i[e]}})})),e.exports={w3cwebsocket:i?o:null,version:n}},387:(e,t,r)=>{e.exports=r(794).version},794:e=>{"use strict";e.exports={version:"1.0.34"}}},s={};function i(e){var t=s[e];if(void 0!==t)return t.exports;var n=s[e]={exports:{}};return r[e].call(n.exports,n,n.exports,i),n.exports}return i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,i.t=function(r,s){if(1&s&&(r=this(r)),8&s)return r;if("object"==typeof r&&r){if(4&s&&r.__esModule)return r;if(16&s&&"function"==typeof r.then)return r}var n=Object.create(null);i.r(n);var o={};e=e||[null,t({}),t([]),t(t)];for(var a=2&s&&r;"object"==typeof a&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach((e=>o[e]=()=>r[e]));return o.default=()=>r,i.d(n,o),n},i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i(341)})()));
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.supabase=t():e.supabase=t()}(self,(()=>(()=>{var e,t,s={982:(e,t,s)=>{"use strict";s.r(t),s.d(t,{FunctionsClient:()=>a,FunctionsError:()=>r,FunctionsFetchError:()=>i,FunctionsHttpError:()=>o,FunctionsRelayError:()=>n});class r extends Error{constructor(e,t="FunctionsError",s){super(e),this.name=t,this.context=s}}class i extends r{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class n extends r{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class o extends r{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}class a{constructor(e,{headers:t={},customFetch:r}={}){this.url=e,this.headers=t,this.fetch=(e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>Promise.resolve().then(s.t.bind(s,743,23)).then((({default:t})=>t(...e))):fetch),(...e)=>t(...e)})(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s,r,a,c,h;return r=this,a=void 0,h=function*(){try{const{headers:r,method:a,body:c}=t;let h,l={};c&&(r&&!Object.prototype.hasOwnProperty.call(r,"Content-Type")||!r)&&("undefined"!=typeof Blob&&c instanceof Blob||c instanceof ArrayBuffer?(l["Content-Type"]="application/octet-stream",h=c):"string"==typeof c?(l["Content-Type"]="text/plain",h=c):"undefined"!=typeof FormData&&c instanceof FormData?h=c:(l["Content-Type"]="application/json",h=JSON.stringify(c)));const u=yield this.fetch(`${this.url}/${e}`,{method:a||"POST",headers:Object.assign(Object.assign(Object.assign({},l),this.headers),r),body:h}).catch((e=>{throw new i(e)})),d=u.headers.get("x-relay-error");if(d&&"true"===d)throw new n(u);if(!u.ok)throw new o(u);let f,p=(null!==(s=u.headers.get("Content-Type"))&&void 0!==s?s:"text/plain").split(";")[0].trim();return f="application/json"===p?yield u.json():"application/octet-stream"===p?yield u.blob():"multipart/form-data"===p?yield u.formData():yield u.text(),{data:f,error:null}}catch(e){return{data:null,error:e}}},new((c=void 0)||(c=Promise))((function(e,t){function s(e){try{n(h.next(e))}catch(e){t(e)}}function i(e){try{n(h.throw(e))}catch(e){t(e)}}function n(t){var r;t.done?e(t.value):(r=t.value,r instanceof c?r:new c((function(e){e(r)}))).then(s,i)}n((h=h.apply(r,a||[])).next())}))}}},765:(e,t,s)=>{"use strict";s.r(t),s.d(t,{AuthApiError:()=>_,AuthError:()=>v,AuthImplicitGrantRedirectError:()=>j,AuthInvalidCredentialsError:()=>E,AuthInvalidTokenResponseError:()=>T,AuthPKCEGrantCodeExchangeError:()=>O,AuthRetryableFetchError:()=>P,AuthSessionMissingError:()=>S,AuthUnknownError:()=>w,CustomAuthError:()=>k,GoTrueAdminApi:()=>F,GoTrueClient:()=>Y,NavigatorLockAcquireTimeoutError:()=>G,isAuthApiError:()=>b,isAuthError:()=>m,isAuthRetryableFetchError:()=>x,lockInternals:()=>J,navigatorLock:()=>H});const r=()=>"undefined"!=typeof document,i={tested:!1,writable:!1},n=()=>{if(!r())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(i.tested)return i.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),i.tested=!0,i.writable=!0}catch(e){i.tested=!0,i.writable=!1}return i.writable};function o(e){const t={},s=new URL(e);if(s.hash&&"#"===s.hash[0])try{new URLSearchParams(s.hash.substring(1)).forEach(((e,s)=>{t[s]=e}))}catch(e){}return s.searchParams.forEach(((e,s)=>{t[s]=e})),t}const a=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>Promise.resolve().then(s.t.bind(s,743,23)).then((({default:t})=>t(...e))):fetch),(...e)=>t(...e)},c=e=>"object"==typeof e&&null!==e&&"status"in e&&"ok"in e&&"json"in e&&"function"==typeof e.json,h=async(e,t,s)=>{await e.setItem(t,JSON.stringify(s))},l=async(e,t)=>{const s=await e.getItem(t);if(!s)return null;try{return JSON.parse(s)}catch(e){return s}},u=async(e,t)=>{await e.removeItem(t)};class d{constructor(){this.promise=new d.promiseConstructor(((e,t)=>{this.resolve=e,this.reject=t}))}}function f(e){const t=e.split(".");if(3!==t.length)throw new Error("JWT is not valid: not a JWT structure");if(!/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");const s=t[1];return JSON.parse(function(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let s,r,i,n,o,a,c,h="",l=0;for(e=e.replace("-","+").replace("_","/");l<e.length;)n=t.indexOf(e.charAt(l++)),o=t.indexOf(e.charAt(l++)),a=t.indexOf(e.charAt(l++)),c=t.indexOf(e.charAt(l++)),s=n<<2|o>>4,r=(15&o)<<4|a>>2,i=(3&a)<<6|c,h+=String.fromCharCode(s),64!=a&&0!=r&&(h+=String.fromCharCode(r)),64!=c&&0!=i&&(h+=String.fromCharCode(i));return h}(s))}function p(e){return("0"+e.toString(16)).substr(-2)}function g(){const e=new Uint32Array(56);if("undefined"==typeof crypto){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length;let s="";for(let r=0;r<56;r++)s+=e.charAt(Math.floor(Math.random()*t));return s}return crypto.getRandomValues(e),Array.from(e,p).join("")}async function y(e){if("undefined"==typeof crypto)return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e;const t=await async function(e){const t=(new TextEncoder).encode(e),s=await crypto.subtle.digest("SHA-256",t),r=new Uint8Array(s);return Array.from(r).map((e=>String.fromCharCode(e))).join("")}(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}d.promiseConstructor=Promise;class v extends Error{constructor(e,t){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t}}function m(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class _ extends v{constructor(e,t){super(e,t),this.name="AuthApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}function b(e){return m(e)&&"AuthApiError"===e.name}class w extends v{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class k extends v{constructor(e,t,s){super(e),this.name=t,this.status=s}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class S extends k{constructor(){super("Auth session missing!","AuthSessionMissingError",400)}}class T extends k{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500)}}class E extends k{constructor(e){super(e,"AuthInvalidCredentialsError",400)}}class j extends k{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class O extends k{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class P extends k{constructor(e,t){super(e,"AuthRetryableFetchError",t)}}function x(e){return m(e)&&"AuthRetryableFetchError"===e.name}const $=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),C=[502,503,504];async function A(e){if(!c(e))throw new P($(e),0);if(C.includes(e.status))throw new P($(e),e.status);let t;try{t=await e.json()}catch(e){throw new w($(e),e)}throw new _($(t),e.status||500)}async function R(e,t,s,r){var i;const n=Object.assign({},null==r?void 0:r.headers);(null==r?void 0:r.jwt)&&(n.Authorization=`Bearer ${r.jwt}`);const o=null!==(i=null==r?void 0:r.query)&&void 0!==i?i:{};(null==r?void 0:r.redirectTo)&&(o.redirect_to=r.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await async function(e,t,s,r,i,n){const o=((e,t,s,r)=>{const i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==t?void 0:t.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),s))})(t,r,{},n);let a;try{a=await e(s,o)}catch(e){throw console.error(e),new P($(e),0)}if(a.ok||await A(a),null==r?void 0:r.noResolveJson)return a;try{return await a.json()}catch(e){await A(e)}}(e,t,s+a,{headers:n,noResolveJson:null==r?void 0:r.noResolveJson},0,null==r?void 0:r.body);return(null==r?void 0:r.xform)?null==r?void 0:r.xform(c):{data:Object.assign({},c),error:null}}function I(e){var t;let s=null;var r;return function(e){return e.access_token&&e.refresh_token&&e.expires_in}(e)&&(s=Object.assign({},e),e.expires_at||(s.expires_at=(r=e.expires_in,Math.round(Date.now()/1e3)+r))),{data:{session:s,user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function L(e){var t;return{data:{user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function U(e){return{data:e,error:null}}function N(e){const{action_link:t,email_otp:s,hashed_token:r,redirect_to:i,verification_type:n}=e,o=function(e,t){var s={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(s[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(s[r[i]]=e[r[i]])}return s}(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]);return{data:{properties:{action_link:t,email_otp:s,hashed_token:r,redirect_to:i,verification_type:n},user:Object.assign({},o)},error:null}}function D(e){return e}class F{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=a(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await R(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(m(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await R(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:L})}catch(e){if(m(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{const{options:t}=e,s=function(e,t){var s={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(s[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(s[r[i]]=e[r[i]])}return s}(e,["options"]),r=Object.assign(Object.assign({},s),t);return"newEmail"in s&&(r.new_email=null==s?void 0:s.newEmail,delete r.newEmail),await R(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:N,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(m(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await R(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:L})}catch(e){if(m(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,s,r,i,n,o,a;try{const c={nextPage:null,lastPage:0,total:0},h=await R(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(s=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==s?s:"",per_page:null!==(i=null===(r=null==e?void 0:e.perPage)||void 0===r?void 0:r.toString())&&void 0!==i?i:""},xform:D});if(h.error)throw h.error;const l=await h.json(),u=null!==(n=h.headers.get("x-total-count"))&&void 0!==n?n:0,d=null!==(a=null===(o=h.headers.get("link"))||void 0===o?void 0:o.split(","))&&void 0!==a?a:[];return d.length>0&&(d.forEach((e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),s=JSON.parse(e.split(";")[1].split("=")[1]);c[`${s}Page`]=t})),c.total=parseInt(u)),{data:Object.assign(Object.assign({},l),c),error:null}}catch(e){if(m(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){try{return await R(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:L})}catch(e){if(m(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){try{return await R(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:L})}catch(e){if(m(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){try{return await R(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:L})}catch(e){if(m(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){try{const{data:t,error:s}=await R(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:s}}catch(e){if(m(e))return{data:null,error:e};throw e}}async _deleteFactor(e){try{return{data:await R(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(m(e))return{data:null,error:e};throw e}}}const M="2.51.0",q={"X-Client-Info":`gotrue-js/${M}`},B={getItem:e=>n()?globalThis.localStorage.getItem(e):null,setItem:(e,t)=>{n()&&globalThis.localStorage.setItem(e,t)},removeItem:e=>{n()&&globalThis.localStorage.removeItem(e)}},J={debug:!!(globalThis&&n()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"))};class z extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class G extends z{}async function H(e,t,s){J.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);const r=new globalThis.AbortController;return t>0&&setTimeout((()=>{r.abort(),J.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)}),t),await globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},(async r=>{if(!r){if(0===t)throw J.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new G(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(J.debug)try{const 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 s()}J.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,r.name);try{return await s()}finally{J.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,r.name)}}))}!function(){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){"undefined"!=typeof self&&(self.globalThis=self)}}();const K={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:q,flowType:"implicit",debug:!1},V=3e4;async function W(e,t,s){return await s()}class Y{constructor(e){var t;this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.instanceID=Y.nextInstanceID,Y.nextInstanceID+=1,this.instanceID>0&&r()&&console.warn("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.");const s=Object.assign(Object.assign({},K),e);if(this.logDebugMessages=s.debug,this.inMemorySession=null,this.storageKey=s.storageKey,this.autoRefreshToken=s.autoRefreshToken,this.persistSession=s.persistSession,this.storage=s.storage||B,this.admin=new F({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=a(s.fetch),this.lock=s.lock||W,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,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)},this.persistSession&&this.storage===B&&!n()&&console.warn("No storage option exists to persist the session, which may result in unexpected behavior when using auth.\n If you want to set persistSession to true, please provide a storage option or you may set persistSession to false to disable this warning."),r()&&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===(t=this.broadcastChannel)||void 0===t||t.addEventListener("message",(async e=>{this._debug("received broadcast notification from other tab or client",e),await this._notifyAllSubscribers(e.data.event,e.data.session,!1)}))}this.initialize()}_debug(...e){return this.logDebugMessages&&console.log(`GoTrueClient@${this.instanceID} (${M}) ${(new Date).toISOString()}`,...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(-1,(async()=>await this._initialize())))()),await this.initializePromise}async _initialize(){try{const e=!!r()&&await this._isPKCEFlow();if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){const{data:t,error:s}=await this._getSessionFromURL(e);if(s)return this._debug("#_initialize()","error detecting session from URL",s),await this._removeSession(),{error:s};const{session:r,redirectType:i}=t;return this._debug("#_initialize()","detected session in URL",r,"redirect type",i),await this._saveSession(r),setTimeout((async()=>{"recovery"===i?await this._notifyAllSubscribers("PASSWORD_RECOVERY",r):await this._notifyAllSubscribers("SIGNED_IN",r)}),0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return m(e)?{error:e}:{error:new w("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signUp(e){var t,s,r;try{let i;if(await this._removeSession(),"email"in e){const{email:s,password:r,options:n}=e;let o=null,a=null;if("pkce"===this.flowType){const e=g();await h(this.storage,`${this.storageKey}-code-verifier`,e),o=await y(e),a=e===o?"plain":"s256"}i=await R(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==n?void 0:n.emailRedirectTo,body:{email:s,password:r,data:null!==(t=null==n?void 0:n.data)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},code_challenge:o,code_challenge_method:a},xform:I})}else{if(!("phone"in e))throw new E("You must provide either an email or phone number and a password");{const{phone:t,password:n,options:o}=e;i=await R(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:n,data:null!==(s=null==o?void 0:o.data)&&void 0!==s?s:{},channel:null!==(r=null==o?void 0:o.channel)&&void 0!==r?r:"sms",gotrue_meta_security:{captcha_token:null==o?void 0:o.captchaToken}},xform:I})}}const{data:n,error:o}=i;if(o||!n)return{data:{user:null,session:null},error:o};const a=n.session,c=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:c,session:a},error:null}}catch(e){if(m(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithPassword(e){try{let t;if(await this._removeSession(),"email"in e){const{email:s,password:r,options:i}=e;t=await R(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:I})}else{if(!("phone"in e))throw new E("You must provide either an email or phone number and a password");{const{phone:s,password:r,options:i}=e;t=await R(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:I})}}const{data:s,error:r}=t;return r?{data:{user:null,session:null},error:r}:s&&s.session&&s.user?(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:{user:s.user,session:s.session},error:r}):{data:{user:null,session:null},error:new T}}catch(e){if(m(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithOAuth(e){var t,s,r,i;return await this._removeSession(),await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(s=e.options)||void 0===s?void 0:s.scopes,queryParams:null===(r=e.options)||void 0===r?void 0:r.queryParams,skipBrowserRedirect:null===(i=e.options)||void 0===i?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,(async()=>this._exchangeCodeForSession(e)))}async _exchangeCodeForSession(e){const t=await l(this.storage,`${this.storageKey}-code-verifier`),{data:s,error:r}=await R(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:t},xform:I});return await u(this.storage,`${this.storageKey}-code-verifier`),r?{data:{user:null,session:null},error:r}:s&&s.session&&s.user?(s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:s,error:r}):{data:{user:null,session:null},error:new T}}async signInWithIdToken(e){await this._removeSession();try{const{options:t,provider:s,token:r,access_token:i,nonce:n}=e,o=await R(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:r,access_token:i,nonce:n,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:I}),{data:a,error:c}=o;return c?{data:{user:null,session:null},error:c}:a&&a.session&&a.user?(a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),{data:a,error:c}):{data:{user:null,session:null},error:new T}}catch(e){if(m(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithOtp(e){var t,s,r,i,n;try{if(await this._removeSession(),"email"in e){const{email:r,options:i}=e;let n=null,o=null;if("pkce"===this.flowType){const e=g();await h(this.storage,`${this.storageKey}-code-verifier`,e),n=await y(e),o=e===n?"plain":"s256"}const{error:a}=await R(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:r,data:null!==(t=null==i?void 0:i.data)&&void 0!==t?t:{},create_user:null===(s=null==i?void 0:i.shouldCreateUser)||void 0===s||s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:n,code_challenge_method:o},redirectTo:null==i?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:a}}if("phone"in e){const{phone:t,options:s}=e,{data:o,error:a}=await R(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(r=null==s?void 0:s.data)&&void 0!==r?r:{},create_user:null===(i=null==s?void 0:s.shouldCreateUser)||void 0===i||i,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken},channel:null!==(n=null==s?void 0:s.channel)&&void 0!==n?n:"sms"}});return{data:{user:null,session:null,messageId:null==o?void 0:o.message_id},error:a}}throw new E("You must provide either an email or phone number.")}catch(e){if(m(e))return{data:{user:null,session:null},error:e};throw e}}async verifyOtp(e){var t,s;try{let r,i;"email_change"!==e.type&&"phone_change"!==e.type&&await this._removeSession(),"options"in e&&(r=null===(t=e.options)||void 0===t?void 0:t.redirectTo,i=null===(s=e.options)||void 0===s?void 0:s.captchaToken);const{data:n,error:o}=await R(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:r,xform:I});if(o)throw o;if(!n)throw new Error("An error occurred on token verification.");const a=n.session,c=n.user;return(null==a?void 0:a.access_token)&&(await this._saveSession(a),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:c,session:a},error:null}}catch(e){if(m(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithSSO(e){var t,s,r;try{return await this._removeSession(),await R(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!==(s=null===(t=e.options)||void 0===t?void 0:t.redirectTo)&&void 0!==s?s:void 0}),(null===(r=null==e?void 0:e.options)||void 0===r?void 0:r.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0}),headers:this.headers,xform:U})}catch(e){if(m(e))return{data:null,error:e};throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,(async()=>await this._reauthenticate()))}async _reauthenticate(){try{return await this._useSession((async e=>{const{data:{session:t},error:s}=e;if(s)throw s;if(!t)throw new S;const{error:r}=await R(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:r}}))}catch(e){if(m(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{"email_change"!=e.type&&"phone_change"!=e.type&&await this._removeSession();const t=`${this.url}/resend`;if("email"in e){const{email:s,type:r,options:i}=e,{error:n}=await R(this.fetch,"POST",t,{headers:this.headers,body:{email:s,type:r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},redirectTo:null==i?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:n}}if("phone"in e){const{phone:s,type:r,options:i}=e,{data:n,error:o}=await R(this.fetch,"POST",t,{headers:this.headers,body:{phone:s,type:r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:null==n?void 0:n.message_id},error:o}}throw new E("You must provide either an email or phone number and a type")}catch(e){if(m(e))return{data:{user:null,session:null},error:e};throw e}}async getSession(){return await this.initializePromise,this._acquireLock(-1,(async()=>this._useSession((async e=>e))))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch(e){}})()),s}return await this.lock(`lock:${this.storageKey}`,e,(async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){const 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{const 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!",(new Error).stack);try{let e=null;if(this.persistSession){const t=await l(this.storage,this.storageKey);this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession()))}else e=this.inMemorySession,this._debug("#getSession()","session from memory",e);if(!e)return{data:{session:null},error:null};const t=!!e.expires_at&&e.expires_at<=Date.now()/1e3;if(this._debug("#__loadSession()",`session has${t?"":" not"} expired`,"expires_at",e.expires_at),!t)return{data:{session:e},error:null};const{session:s,error:r}=await this._callRefreshToken(e.refresh_token);return r?{data:{session:null},error:r}:{data:{session:s},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,this._acquireLock(-1,(async()=>await this._getUser())))}async _getUser(e){try{return e?await R(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:L}):await this._useSession((async e=>{var t,s;const{data:r,error:i}=e;if(i)throw i;return await R(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(s=null===(t=r.session)||void 0===t?void 0:t.access_token)&&void 0!==s?s:void 0,xform:L})}))}catch(e){if(m(e))return{data:{user:null},error:e};throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,(async()=>await this._updateUser(e,t)))}async _updateUser(e,t={}){try{return await this._useSession((async s=>{const{data:r,error:i}=s;if(i)throw i;if(!r.session)throw new S;const n=r.session;let o=null,a=null;if("pkce"===this.flowType&&null!=e.email){const e=g();await h(this.storage,`${this.storageKey}-code-verifier`,e),o=await y(e),a=e===o?"plain":"s256"}const{data:c,error:l}=await R(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:a}),jwt:n.access_token,xform:L});if(l)throw l;return n.user=c.user,await this._saveSession(n),await this._notifyAllSubscribers("USER_UPDATED",n),{data:{user:n.user},error:null}}))}catch(e){if(m(e))return{data:{user:null},error:e};throw e}}_decodeJWT(e){return f(e)}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,(async()=>await this._setSession(e)))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new S;const t=Date.now()/1e3;let s=t,r=!0,i=null;const n=f(e.access_token);if(n.exp&&(s=n.exp,r=s<=t),r){const{session:t,error:s}=await this._callRefreshToken(e.refresh_token);if(s)return{data:{user:null,session:null},error:s};if(!t)return{data:{user:null,session:null},error:null};i=t}else{const{data:r,error:n}=await this._getUser(e.access_token);if(n)throw n;i={access_token:e.access_token,refresh_token:e.refresh_token,user:r.user,token_type:"bearer",expires_in:s-t,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(e){if(m(e))return{data:{session:null,user:null},error:e};throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,(async()=>await this._refreshSession(e)))}async _refreshSession(e){try{return await this._useSession((async t=>{var s;if(!e){const{data:r,error:i}=t;if(i)throw i;e=null!==(s=r.session)&&void 0!==s?s:void 0}if(!(null==e?void 0:e.refresh_token))throw new S;const{session:r,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}:r?{data:{user:r.user,session:r},error:null}:{data:{user:null,session:null},error:null}}))}catch(e){if(m(e))return{data:{user:null,session:null},error:e};throw e}}async _getSessionFromURL(e){try{if(!r())throw new j("No browser detected.");if("implicit"===this.flowType&&!this._isImplicitGrantFlow())throw new j("Not a valid implicit grant flow url.");if("pkce"==this.flowType&&!e)throw new O("Not a valid PKCE flow url.");const t=o(window.location.href);if(e){if(!t.code)throw new O("No code detected.");const{data:e,error:s}=await this._exchangeCodeForSession(t.code);if(s)throw s;const r=new URL(window.location.href);return r.searchParams.delete("code"),window.history.replaceState(window.history.state,"",r.toString()),{data:{session:e.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new j(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});const{provider_token:s,provider_refresh_token:i,access_token:n,refresh_token:a,expires_in:c,expires_at:h,token_type:l}=t;if(!(n&&c&&a&&l))throw new j("No session defined in URL");const u=Math.round(Date.now()/1e3),d=parseInt(c);let f=u+d;h&&(f=parseInt(h));const p=f-u;1e3*p<=V&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${d}s`);const g=f-d;u-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,f,u):u-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",g,f,u);const{data:y,error:v}=await this._getUser(n);if(v)throw v;const m={provider_token:s,provider_refresh_token:i,access_token:n,expires_in:d,expires_at:f,refresh_token:a,token_type:l,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:m,redirectType:t.type},error:null}}catch(e){if(m(e))return{data:{session:null,redirectType:null},error:e};throw e}}_isImplicitGrantFlow(){const e=o(window.location.href);return!(!r()||!e.access_token&&!e.error_description)}async _isPKCEFlow(){const e=o(window.location.href),t=await l(this.storage,`${this.storageKey}-code-verifier`);return!(!e.code||!t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,(async()=>await this._signOut(e)))}async _signOut({scope:e}={scope:"global"}){return await this._useSession((async t=>{var s;const{data:r,error:i}=t;if(i)return{error:i};const n=null===(s=r.session)||void 0===s?void 0:s.access_token;if(n){const{error:t}=await this.admin.signOut(n,e);if(t&&(!b(t)||404!==t.status&&401!==t.status))return{error:t}}return"others"!==e&&(await this._removeSession(),await u(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}}))}onAuthStateChange(e){const t="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)})),s={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,s),(async()=>{await this.initializePromise,await this._acquireLock(-1,(async()=>{this._emitInitialSession(t)}))})(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession((async t=>{var s,r;try{const{data:{session:r},error:i}=t;if(i)throw i;await(null===(s=this.stateChangeEmitters.get(e))||void 0===s?void 0:s.callback("INITIAL_SESSION",r)),this._debug("INITIAL_SESSION","callback id",e,"session",r)}catch(t){await(null===(r=this.stateChangeEmitters.get(e))||void 0===r?void 0:r.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),console.error(t)}}))}async resetPasswordForEmail(e,t={}){let s=null,r=null;if("pkce"===this.flowType){const e=g();await h(this.storage,`${this.storageKey}-code-verifier`,e),s=await y(e),r=e===s?"plain":"s256"}try{return await R(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:r,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(m(e))return{data:null,error:e};throw e}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const i=Date.now();return await(s=async s=>(await async function(e){return await new Promise((t=>{setTimeout((()=>t(null)),e)}))}(200*s),this._debug(t,"refreshing attempt",s),await R(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:I})),r=(e,t,s)=>s&&s.error&&x(s.error)&&Date.now()+200*(e+1)-i<V,new Promise(((e,t)=>{(async()=>{for(let i=0;i<1/0;i++)try{const t=await s(i);if(!r(i,0,t))return void e(t)}catch(e){if(!r(i))return void t(e)}})()})))}catch(e){if(this._debug(t,"error",e),m(e))return{data:{session:null,user:null},error:e};throw e}finally{this._debug(t,"end")}var s,r}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const s=await this._getUrlForProvider(e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),r()&&!t.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e;const t="#_recoverAndRefresh()";this._debug(t,"begin");try{const s=await l(this.storage,this.storageKey);if(this._debug(t,"session from storage",s),!this._isValidSession(s))return this._debug(t,"session is not valid"),void(null!==s&&await this._removeSession());const r=Math.round(Date.now()/1e3),i=(null!==(e=s.expires_at)&&void 0!==e?e:1/0)<r+10;if(this._debug(t,`session has${i?"":" not"} expired with margin of 10s`),i){if(this.autoRefreshToken&&s.refresh_token){const{error:e}=await this._callRefreshToken(s.refresh_token);e&&(console.error(e),x(e)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(e){return this._debug(t,"error",e),void console.error(e)}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,s;if(!e)throw new S;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new d;const{data:t,error:s}=await this._refreshAccessToken(e);if(s)throw s;if(!t.session)throw new S;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);const r={session:t.session,error:null};return this.refreshingDeferred.resolve(r),r}catch(e){if(this._debug(r,"error",e),m(e)){const s={session:null,error:e};return null===(t=this.refreshingDeferred)||void 0===t||t.resolve(s),s}throw null===(s=this.refreshingDeferred)||void 0===s||s.reject(e),e}finally{this.refreshingDeferred=null,this._debug(r,"end")}}async _notifyAllSubscribers(e,t,s=!0){const r=`#_notifyAllSubscribers(${e})`;this._debug(r,"begin",t,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:t});const r=[],i=Array.from(this.stateChangeEmitters.values()).map((async s=>{try{await s.callback(e,t)}catch(e){r.push(e)}}));if(await Promise.all(i),r.length>0){for(let e=0;e<r.length;e+=1)console.error(r[e]);throw r[0]}}finally{this._debug(r,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.persistSession||(this.inMemorySession=e),this.persistSession&&e.expires_at&&await this._persistSession(e)}_persistSession(e){return this._debug("#_persistSession()",e),h(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),this.persistSession?await u(this.storage,this.storageKey):this.inMemorySession=null}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&r()&&(null===window||void 0===window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval((()=>this._autoRefreshTokenTick()),V);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e),setTimeout((async()=>{await this.initializePromise,await this._autoRefreshTokenTick()}),0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}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{const e=Date.now();try{return await this._useSession((async t=>{const{data:{session:s}}=t;if(!s||!s.refresh_token||!s.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");const r=Math.floor((1e3*s.expires_at-e)/V);this._debug("#_autoRefreshTokenTick()",`access token expires in ${r} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),r<=3&&await this._callRefreshToken(s.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 z))throw e;this._debug("auto refresh token tick lock not available")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!r()||!(null===window||void 0===window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),null===window||void 0===window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,(async()=>{"visible"===document.visibilityState?await this._recoverAndRefresh():this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting")})))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t){const s=[`provider=${encodeURIComponent(e)}`];if((null==t?void 0:t.redirectTo)&&s.push(`redirect_to=${encodeURIComponent(t.redirectTo)}`),(null==t?void 0:t.scopes)&&s.push(`scopes=${encodeURIComponent(t.scopes)}`),"pkce"===this.flowType){const e=g();await h(this.storage,`${this.storageKey}-code-verifier`,e);const t=await y(e),r=e===t?"plain":"s256";this._debug("PKCE","code verifier",`${e.substring(0,5)}...`,"code challenge",t,"method",r);const i=new URLSearchParams({code_challenge:`${encodeURIComponent(t)}`,code_challenge_method:`${encodeURIComponent(r)}`});s.push(i.toString())}if(null==t?void 0:t.queryParams){const e=new URLSearchParams(t.queryParams);s.push(e.toString())}return`${this.url}/authorize?${s.join("&")}`}async _unenroll(e){try{return await this._useSession((async t=>{var s;const{data:r,error:i}=t;return i?{data:null,error:i}:await R(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null===(s=null==r?void 0:r.session)||void 0===s?void 0:s.access_token})}))}catch(e){if(m(e))return{data:null,error:e};throw e}}async _enroll(e){try{return await this._useSession((async t=>{var s,r;const{data:i,error:n}=t;if(n)return{data:null,error:n};const{data:o,error:a}=await R(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:null===(s=null==i?void 0:i.session)||void 0===s?void 0:s.access_token});return a?{data:null,error:a}:((null===(r=null==o?void 0:o.totp)||void 0===r?void 0:r.qr_code)&&(o.totp.qr_code=`data:image/svg+xml;utf-8,${o.totp.qr_code}`),{data:o,error:null})}))}catch(e){if(m(e))return{data:null,error:e};throw e}}async _verify(e){try{return await this._useSession((async t=>{var s;const{data:r,error:i}=t;if(i)return{data:null,error:i};const{data:n,error:o}=await R(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:null===(s=null==r?void 0:r.session)||void 0===s?void 0:s.access_token});return o?{data:null,error:o}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+n.expires_in},n)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",n),{data:n,error:o})}))}catch(e){if(m(e))return{data:null,error:e};throw e}}async _challenge(e){try{return await this._useSession((async t=>{var s;const{data:r,error:i}=t;return i?{data:null,error:i}:await R(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:null===(s=null==r?void 0:r.session)||void 0===s?void 0:s.access_token})}))}catch(e){if(m(e))return{data:null,error:e};throw e}}async _challengeAndVerify(e){const{data:t,error:s}=await this._challenge({factorId:e.factorId});return s?{data:null,error:s}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){const{data:{user:e},error:t}=await this._getUser();if(t)return{data:null,error:t};const s=(null==e?void 0:e.factors)||[],r=s.filter((e=>"totp"===e.factor_type&&"verified"===e.status));return{data:{all:s,totp:r},error:null}}async _getAuthenticatorAssuranceLevel(){return await this._useSession((async e=>{var t,s;const{data:{session:r},error:i}=e;if(i)return{data:null,error:i};if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const n=this._decodeJWT(r.access_token);let o=null;n.aal&&(o=n.aal);let a=o;return(null!==(s=null===(t=r.user.factors)||void 0===t?void 0:t.filter((e=>"verified"===e.status)))&&void 0!==s?s:[]).length>0&&(a="aal2"),{data:{currentLevel:o,nextLevel:a,currentAuthenticationMethods:n.amr||[]},error:null}}))}}Y.nextInstanceID=0},743:(e,t,s)=>{"use strict";var r=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==s.g)return s.g;throw new Error("unable to locate global object")}();e.exports=t=r.fetch,r.fetch&&(t.default=r.fetch.bind(r)),t.Headers=r.Headers,t.Request=r.Request,t.Response=r.Response},189:(e,t,s)=>{"use strict";s.r(t),s.d(t,{PostgrestBuilder:()=>n,PostgrestClient:()=>l,PostgrestFilterBuilder:()=>a,PostgrestQueryBuilder:()=>c,PostgrestTransformBuilder:()=>o});var r=s(743),i=s.n(r);class n{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:"undefined"==typeof fetch?this.fetch=i():this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),"GET"!==this.method&&"HEAD"!==this.method&&(this.headers["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,r;let i=null,n=null,o=null,a=e.status,c=e.statusText;if(e.ok){if("HEAD"!==this.method){const t=await e.text();""===t||(n="text/csv"===this.headers.Accept||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?t:JSON.parse(t))}const r=null===(t=this.headers.Prefer)||void 0===t?void 0:t.match(/count=(exact|planned|estimated)/),h=null===(s=e.headers.get("content-range"))||void 0===s?void 0:s.split("/");r&&h&&h.length>1&&(o=parseInt(h[1])),this.isMaybeSingle&&"GET"===this.method&&Array.isArray(n)&&(n.length>1?(i={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,o=null,a=406,c="Not Acceptable"):n=1===n.length?n[0]:null)}else{const t=await e.text();try{i=JSON.parse(t),Array.isArray(i)&&404===e.status&&(n=[],i=null,a=200,c="OK")}catch(s){404===e.status&&""===t?(a=204,c="No Content"):i={message:t}}if(i&&this.isMaybeSingle&&(null===(r=null==i?void 0:i.details)||void 0===r?void 0:r.includes("Results contain 0 rows"))&&(i=null,a=200,c="OK"),i&&this.shouldThrowOnError)throw i}return{error:i,data:n,count:o,status:a,statusText:c}}));return this.shouldThrowOnError||(s=s.catch((e=>{var t,s,r;return{error:{message:`${null!==(t=null==e?void 0:e.name)&&void 0!==t?t:"FetchError"}: ${null==e?void 0:e.message}`,details:`${null!==(s=null==e?void 0:e.stack)&&void 0!==s?s:""}`,hint:"",code:`${null!==(r=null==e?void 0:e.code)&&void 0!==r?r:""}`},data:null,count:null,status:0,statusText:""}}))),s.then(e,t)}}class o extends n{select(e){let t=!1;const s=(null!=e?e:"*").split("").map((e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e))).join("");return this.url.searchParams.set("select",s),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:s,foreignTable:r}={}){const i=r?`${r}.order`:"order",n=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${n?`${n},`:""}${e}.${t?"asc":"desc"}${void 0===s?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t}={}){const s=void 0===t?"limit":`${t}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,t,{foreignTable:s}={}){const r=void 0===s?"offset":`${s}.offset`,i=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(r,`${e}`),this.url.searchParams.set(i,""+(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return"GET"===this.method?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:s=!1,buffers:r=!1,wal:i=!1,format:n="text"}={}){const o=[e?"analyze":null,t?"verbose":null,s?"settings":null,r?"buffers":null,i?"wal":null].filter(Boolean).join("|"),a=this.headers.Accept;return this.headers.Accept=`application/vnd.pgrst.plan+${n}; for="${a}"; options=${o};`,this}rollback(){var e;return(null!==(e=this.headers.Prefer)&&void 0!==e?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}}class a extends o{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}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){const s=t.map((e=>"string"==typeof e&&new RegExp("[,()]").test(e)?`"${e}"`:`${e}`)).join(",");return this.url.searchParams.append(e,`in.(${s})`),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:s,type:r}={}){let i="";"plain"===r?i="pl":"phrase"===r?i="ph":"websearch"===r&&(i="w");const n=void 0===s?"":`(${s})`;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,s){return this.url.searchParams.append(e,`not.${t}.${s}`),this}or(e,{foreignTable:t}={}){const s=t?`${t}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}}class c{constructor(e,{headers:t={},schema:s,fetch:r}){this.url=e,this.headers=t,this.schema=s,this.fetch=r}select(e,{head:t=!1,count:s}={}){const r=t?"HEAD":"GET";let i=!1;const n=(null!=e?e:"*").split("").map((e=>/\s/.test(e)&&!i?"":('"'===e&&(i=!i),e))).join("");return this.url.searchParams.set("select",n),s&&(this.headers.Prefer=`count=${s}`),new a({method:r,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:s=!0}={}){const r=[];if(this.headers.Prefer&&r.push(this.headers.Prefer),t&&r.push(`count=${t}`),s||r.push("missing=default"),this.headers.Prefer=r.join(","),Array.isArray(e)){const t=e.reduce(((e,t)=>e.concat(Object.keys(t))),[]);if(t.length>0){const e=[...new Set(t)].map((e=>`"${e}"`));this.url.searchParams.set("columns",e.join(","))}}return new a({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:r,defaultToNull:i=!0}={}){const n=[`resolution=${s?"ignore":"merge"}-duplicates`];if(void 0!==t&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&n.push(this.headers.Prefer),r&&n.push(`count=${r}`),i||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){const t=e.reduce(((e,t)=>e.concat(Object.keys(t))),[]);if(t.length>0){const e=[...new Set(t)].map((e=>`"${e}"`));this.url.searchParams.set("columns",e.join(","))}}return new a({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){const s=[];return this.headers.Prefer&&s.push(this.headers.Prefer),t&&s.push(`count=${t}`),this.headers.Prefer=s.join(","),new a({method:"PATCH",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){const t=[];return e&&t.push(`count=${e}`),this.headers.Prefer&&t.unshift(this.headers.Prefer),this.headers.Prefer=t.join(","),new a({method:"DELETE",url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}}const h={"X-Client-Info":"postgrest-js/1.8.4"};class l{constructor(e,{headers:t={},schema:s,fetch:r}={}){this.url=e,this.headers=Object.assign(Object.assign({},h),t),this.schemaName=s,this.fetch=r}from(e){const t=new URL(`${this.url}/${e}`);return new c(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new l(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,count:r}={}){let i;const n=new URL(`${this.url}/rpc/${e}`);let o;s?(i="HEAD",Object.entries(t).forEach((([e,t])=>{n.searchParams.append(e,`${t}`)}))):(i="POST",o=t);const c=Object.assign({},this.headers);return r&&(c.Prefer=`count=${r}`),new a({method:i,url:n,headers:c,schema:this.schemaName,body:o,fetch:this.fetch,allowEmpty:!1})}}},73:(e,t,s)=>{"use strict";s.r(t),s.d(t,{REALTIME_LISTEN_TYPES:()=>j,REALTIME_POSTGRES_CHANGES_LISTEN_EVENT:()=>E,REALTIME_PRESENCE_LISTEN_EVENTS:()=>l,REALTIME_SUBSCRIBE_STATES:()=>O,RealtimeChannel:()=>x,RealtimeClient:()=>A,RealtimePresence:()=>g});var r=s(840);const i={"X-Client-Info":"realtime-js/2.7.4"};var n,o,a,c,h,l,u;!function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"}(n||(n={})),function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"}(o||(o={})),function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave",e.access_token="access_token"}(a||(a={})),function(e){e.websocket="websocket"}(c||(c={})),function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"}(h||(h={}));class d{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)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout((()=>{this.tries=this.tries+1,this.callback()}),this.timerCalc(this.tries+1))}}class f{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t("string"==typeof e?JSON.parse(e):{})}_binaryDecode(e){const t=new DataView(e),s=new TextDecoder;return this._decodeBroadcast(e,t,s)}_decodeBroadcast(e,t,s){const r=t.getUint8(1),i=t.getUint8(2);let n=this.HEADER_LENGTH+2;const o=s.decode(e.slice(n,n+r));n+=r;const a=s.decode(e.slice(n,n+i));return n+=i,{ref:null,topic:o,event:a,payload:JSON.parse(s.decode(e.slice(n,e.byteLength)))}}}class p{constructor(e,t,s={},r=1e4){this.channel=e,this.event=t,this.payload=s,this.timeout=r,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null,this.rateLimited=!1}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,"rate limited"===this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()})&&(this.rateLimited=!0))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var s;return this._hasReceived(e)&&t(null===(s=this.receivedResp)||void 0===s?void 0:s.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){this.timeoutTimer||(this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref),this.channel._on(this.refEvent,{},(e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(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}}!function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"}(l||(l={}));class g{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const s=(null==t?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},(e=>{const{onJoin:t,onLeave:s,onSync:r}=this.caller;this.joinRef=this.channel._joinRef(),this.state=g.syncState(this.state,e,t,s),this.pendingDiffs.forEach((e=>{this.state=g.syncDiff(this.state,e,t,s)})),this.pendingDiffs=[],r()})),this.channel._on(s.diff,{},(e=>{const{onJoin:t,onLeave:s,onSync:r}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=g.syncDiff(this.state,e,t,s),r())})),this.onJoin(((e,t,s)=>{this.channel._trigger("presence",{event:"join",key:e,currentPresences:t,newPresences:s})})),this.onLeave(((e,t,s)=>{this.channel._trigger("presence",{event:"leave",key:e,currentPresences:t,leftPresences:s})})),this.onSync((()=>{this.channel._trigger("presence",{event:"sync"})}))}static syncState(e,t,s,r){const i=this.cloneDeep(e),n=this.transformState(t),o={},a={};return this.map(i,((e,t)=>{n[e]||(a[e]=t)})),this.map(n,((e,t)=>{const s=i[e];if(s){const r=t.map((e=>e.presence_ref)),i=s.map((e=>e.presence_ref)),n=t.filter((e=>i.indexOf(e.presence_ref)<0)),c=s.filter((e=>r.indexOf(e.presence_ref)<0));n.length>0&&(o[e]=n),c.length>0&&(a[e]=c)}else o[e]=t})),this.syncDiff(i,{joins:o,leaves:a},s,r)}static syncDiff(e,t,s,r){const{joins:i,leaves:n}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return s||(s=()=>{}),r||(r=()=>{}),this.map(i,((t,r)=>{var i;const n=null!==(i=e[t])&&void 0!==i?i:[];if(e[t]=this.cloneDeep(r),n.length>0){const s=e[t].map((e=>e.presence_ref)),r=n.filter((e=>s.indexOf(e.presence_ref)<0));e[t].unshift(...r)}s(t,n,r)})),this.map(n,((t,s)=>{let i=e[t];if(!i)return;const n=s.map((e=>e.presence_ref));i=i.filter((e=>n.indexOf(e.presence_ref)<0)),e[t]=i,r(t,i,s),0===i.length&&delete e[t]})),e}static map(e,t){return Object.getOwnPropertyNames(e).map((s=>t(s,e[s])))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce(((t,s)=>{const r=e[s];return t[s]="metas"in r?r.metas.map((e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))):r,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()}}!function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"}(u||(u={}));const y=(e,t,s={})=>{var r;const i=null!==(r=s.skipTypes)&&void 0!==r?r:[];return Object.keys(t).reduce(((s,r)=>(s[r]=v(r,e,t,i),s)),{})},v=(e,t,s,r)=>{const i=t.find((t=>t.name===e)),n=null==i?void 0:i.type,o=s[e];return n&&!r.includes(n)?m(n,o):_(o)},m=(e,t)=>{if("_"===e.charAt(0)){const s=e.slice(1,e.length);return S(t,s)}switch(e){case u.bool:return b(t);case u.float4:case u.float8:case u.int2:case u.int4:case u.int8:case u.numeric:case u.oid:return w(t);case u.json:case u.jsonb:return k(t);case u.timestamp:return T(t);case u.abstime:case u.date:case u.daterange:case u.int4range:case u.int8range:case u.money:case u.reltime:case u.text:case u.time:case u.timestamptz:case u.timetz:case u.tsrange:case u.tstzrange:default:return _(t)}},_=e=>e,b=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},w=e=>{if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},k=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(t){return console.log(`JSON parse error: ${t}`),e}return e},S=(e,t)=>{if("string"!=typeof e)return e;const s=e.length-1,r=e[s];if("{"===e[0]&&"}"===r){let r;const i=e.slice(1,s);try{r=JSON.parse("["+i+"]")}catch(e){r=i?i.split(","):[]}return r.map((e=>m(t,e)))}return e},T=e=>"string"==typeof e?e.replace(" ","T"):e;var E,j,O,P=function(e,t,s,r){return new(s||(s=Promise))((function(i,n){function o(e){try{c(r.next(e))}catch(e){n(e)}}function a(e){try{c(r.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};!function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"}(E||(E={})),function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes"}(j||(j={})),function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"}(O||(O={}));class x{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=o.closed,this.joinedOnce=!1,this.pushBuffer=[],this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""}},t.config),this.timeout=this.socket.timeout,this.joinPush=new p(this,a.join,this.params,this.timeout),this.rejoinTimer=new d((()=>this._rejoinUntilConnected()),this.socket.reconnectAfterMs),this.joinPush.receive("ok",(()=>{this.state=o.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=o.closed,this.socket._remove(this)})),this._onError((e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=o.errored,this.rejoinTimer.scheduleTimeout())})),this.joinPush.receive("timeout",(()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=o.errored,this.rejoinTimer.scheduleTimeout())})),this._on(a.reply,{},((e,t)=>{this._trigger(this._replyEventName(t),e)})),this.presence=new g(this)}subscribe(e,t=this.timeout){var s,r;if(this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{const{config:{broadcast:i,presence:n}}=this.params;this._onError((t=>e&&e("CHANNEL_ERROR",t))),this._onClose((()=>e&&e("CLOSED")));const o={},a={broadcast:i,presence:n,postgres_changes:null!==(r=null===(s=this.bindings.postgres_changes)||void 0===s?void 0:s.map((e=>e.filter)))&&void 0!==r?r:[]};this.socket.accessToken&&(o.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:a},o)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",(({postgres_changes:t})=>{var s;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),void 0!==t){const r=this.bindings.postgres_changes,i=null!==(s=null==r?void 0:r.length)&&void 0!==s?s:0,n=[];for(let s=0;s<i;s++){const i=r[s],{filter:{event:o,schema:a,table:c,filter:h}}=i,l=t&&t[s];if(!l||l.event!==o||l.schema!==a||l.table!==c||l.filter!==h)return this.unsubscribe(),void(e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes")));n.push(Object.assign(Object.assign({},i),{id:l.id}))}return this.bindings.postgres_changes=n,void(e&&e("SUBSCRIBED"))}e&&e("SUBSCRIBED")})).receive("error",(t=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(t).join(", ")||"error")))})).receive("timeout",(()=>{e&&e("TIMED_OUT")}))}return this}presenceState(){return this.presence.state}track(e,t={}){return P(this,void 0,void 0,(function*(){return yield this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}))}untrack(e={}){return P(this,void 0,void 0,(function*(){return yield this.send({type:"presence",event:"untrack"},e)}))}on(e,t,s){return this._on(e,t,s)}send(e,t={}){return new Promise((s=>{var r,i,n;const o=this._push(e.type,e,t.timeout||this.timeout);o.rateLimited&&s("rate limited"),"broadcast"!==e.type||(null===(n=null===(i=null===(r=this.params)||void 0===r?void 0:r.config)||void 0===i?void 0:i.broadcast)||void 0===n?void 0:n.ack)||s("ok"),o.receive("ok",(()=>s("ok"))),o.receive("timeout",(()=>s("timed out")))}))}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=o.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(a.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise((s=>{const r=new p(this,a.leave,{},e);r.receive("ok",(()=>{t(),s("ok")})).receive("timeout",(()=>{t(),s("timed out")})).receive("error",(()=>{s("error")})),r.send(),this._canPush()||r.trigger("ok",{})}))}_push(e,t,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let r=new p(this,e,t,s);return this._canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}_onMessage(e,t,s){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,s){var r,i;const n=e.toLocaleLowerCase(),{close:o,error:c,leave:h,join:l}=a;if(s&&[o,c,h,l].indexOf(n)>=0&&s!==this._joinRef())return;let u=this._onMessage(n,t,s);if(t&&!u)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(n)?null===(r=this.bindings.postgres_changes)||void 0===r||r.filter((e=>{var t,s,r;return"*"===(null===(t=e.filter)||void 0===t?void 0:t.event)||(null===(r=null===(s=e.filter)||void 0===s?void 0:s.event)||void 0===r?void 0:r.toLocaleLowerCase())===n})).map((e=>e.callback(u,s))):null===(i=this.bindings[n])||void 0===i||i.filter((e=>{var s,r,i,o,a,c;if(["broadcast","presence","postgres_changes"].includes(n)){if("id"in e){const n=e.id,o=null===(s=e.filter)||void 0===s?void 0:s.event;return n&&(null===(r=t.ids)||void 0===r?void 0:r.includes(n))&&("*"===o||(null==o?void 0:o.toLocaleLowerCase())===(null===(i=t.data)||void 0===i?void 0:i.type.toLocaleLowerCase()))}{const s=null===(a=null===(o=null==e?void 0:e.filter)||void 0===o?void 0:o.event)||void 0===a?void 0:a.toLocaleLowerCase();return"*"===s||s===(null===(c=null==t?void 0:t.event)||void 0===c?void 0:c.toLocaleLowerCase())}}return e.type.toLocaleLowerCase()===n})).map((e=>{if("object"==typeof u&&"ids"in u){const e=u.data,{schema:t,table:s,commit_timestamp:r,type:i,errors:n}=e,o={schema:t,table:s,commit_timestamp:r,eventType:i,new:{},old:{},errors:n};u=Object.assign(Object.assign({},o),this._getPayloadRecords(e))}e.callback(u,s)}))}_isClosed(){return this.state===o.closed}_isJoined(){return this.state===o.joined}_isJoining(){return this.state===o.joining}_isLeaving(){return this.state===o.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,s){const r=e.toLocaleLowerCase(),i={type:r,filter:t,callback:s};return this.bindings[r]?this.bindings[r].push(i):this.bindings[r]=[i],this}_off(e,t){const s=e.toLocaleLowerCase();return this.bindings[s]=this.bindings[s].filter((e=>{var r;return!((null===(r=e.type)||void 0===r?void 0:r.toLocaleLowerCase())===s&&x.isEqual(e.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(a.close,{},e)}_onError(e){this._on(a.error,{},(t=>e(t)))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=o.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return"INSERT"!==e.type&&"UPDATE"!==e.type||(t.new=y(e.columns,e.record)),"UPDATE"!==e.type&&"DELETE"!==e.type||(t.old=y(e.columns,e.old_record)),t}}var $=function(e,t,s,r){return new(s||(s=Promise))((function(i,n){function o(e){try{c(r.next(e))}catch(e){n(e)}}function a(e){try{c(r.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};const C=()=>{};class A{constructor(e,t){var s,n;this.accessToken=null,this.channels=[],this.endPoint="",this.headers=i,this.params={},this.timeout=1e4,this.transport=r.w3cwebsocket,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=C,this.conn=null,this.sendBuffer=[],this.serializer=new f,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.eventsPerSecondLimitMs=100,this.inThrottle=!1,this.endPoint=`${e}/${c.websocket}`,(null==t?void 0:t.params)&&(this.params=t.params),(null==t?void 0:t.headers)&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),(null==t?void 0:t.timeout)&&(this.timeout=t.timeout),(null==t?void 0:t.logger)&&(this.logger=t.logger),(null==t?void 0:t.transport)&&(this.transport=t.transport),(null==t?void 0:t.heartbeatIntervalMs)&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);const o=null===(s=null==t?void 0:t.params)||void 0===s?void 0:s.eventsPerSecond;o&&(this.eventsPerSecondLimitMs=Math.floor(1e3/o));const a=null===(n=null==t?void 0:t.params)||void 0===n?void 0:n.apikey;a&&(this.accessToken=a),this.reconnectAfterMs=(null==t?void 0:t.reconnectAfterMs)?t.reconnectAfterMs:e=>[1e3,2e3,5e3,1e4][e-1]||1e4,this.encode=(null==t?void 0:t.encode)?t.encode:(e,t)=>t(JSON.stringify(e)),this.decode=(null==t?void 0:t.decode)?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new d((()=>$(this,void 0,void 0,(function*(){this.disconnect(),this.connect()}))),this.reconnectAfterMs)}connect(){this.conn||(this.conn=new this.transport(this._endPointURL(),[],null,this.headers),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)))}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,null!=t?t:""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}removeChannel(e){return $(this,void 0,void 0,(function*(){const t=yield e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}))}removeAllChannels(){return $(this,void 0,void 0,(function*(){const e=yield Promise.all(this.channels.map((e=>e.unsubscribe())));return this.disconnect(),e}))}log(e,t,s){this.logger(e,t,s)}connectionState(){switch(this.conn&&this.conn.readyState){case n.connecting:return h.Connecting;case n.open:return h.Open;case n.closing:return h.Closing;default:return h.Closed}}isConnected(){return this.connectionState()===h.Open}channel(e,t={config:{}}){this.isConnected()||this.connect();const s=new x(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){const{topic:t,event:s,payload:r,ref:i}=e;let n=()=>{this.encode(e,(e=>{var t;null===(t=this.conn)||void 0===t||t.send(e)}))};if(this.log("push",`${t} ${s} (${i})`,r),this.isConnected())if(["broadcast","presence","postgres_changes"].includes(s)){if(this._throttle(n)())return"rate limited"}else n();else this.sendBuffer.push(n)}setAuth(e){this.accessToken=e,this.channels.forEach((t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(a.access_token,{access_token:e})}))}_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._joinRef()!==e._joinRef()))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:"1.0.0"}))}_onConnMessage(e){this.decode(e.data,(e=>{let{topic:t,event:s,payload:r,ref:i}=e;(i&&i===this.pendingHeartbeatRef||s===(null==r?void 0:r.type))&&(this.pendingHeartbeatRef=null),this.log("receive",`${r.status||""} ${t} ${s} ${i&&"("+i+")"||""}`,r),this.channels.filter((e=>e._isMember(t))).forEach((e=>e._trigger(s,r,i))),this.stateChangeCallbacks.message.forEach((t=>t(e)))}))}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval((()=>this._sendHeartbeat()),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach((e=>e()))}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach((t=>t(e)))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach((t=>t(e)))}_triggerChanError(){this.channels.forEach((e=>e._trigger(a.error)))}_appendParams(e,t){if(0===Object.keys(t).length)return e;const s=e.match(/\?/)?"&":"?";return`${e}${s}${new URLSearchParams(t)}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach((e=>e())),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef)return this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),void(null===(e=this.conn)||void 0===e||e.close(1e3,"hearbeat timeout"));this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}_throttle(e,t=this.eventsPerSecondLimitMs){return()=>!!this.inThrottle||(e(),t>0&&(this.inThrottle=!0,setTimeout((()=>{this.inThrottle=!1}),t)),!1)}}},752:(e,t,s)=>{"use strict";s.r(t),s.d(t,{StorageApiError:()=>n,StorageClient:()=>S,StorageError:()=>r,StorageUnknownError:()=>o,isStorageError:()=>i});class r extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function i(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}class n extends r{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class o extends r{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}const a=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>Promise.resolve().then(s.t.bind(s,743,23)).then((({default:t})=>t(...e))):fetch),(...e)=>t(...e)};var c=function(e,t,s,r){return new(s||(s=Promise))((function(i,n){function o(e){try{c(r.next(e))}catch(e){n(e)}}function a(e){try{c(r.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};const h=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),l=(e,t)=>c(void 0,void 0,void 0,(function*(){const r=yield(i=void 0,a=void 0,c=void 0,l=function*(){return"undefined"==typeof Response?(yield Promise.resolve().then(s.t.bind(s,743,23))).Response:Response},new(c||(c=Promise))((function(e,t){function s(e){try{n(l.next(e))}catch(e){t(e)}}function r(e){try{n(l.throw(e))}catch(e){t(e)}}function n(t){var i;t.done?e(t.value):(i=t.value,i instanceof c?i:new c((function(e){e(i)}))).then(s,r)}n((l=l.apply(i,a||[])).next())})));var i,a,c,l;e instanceof r?e.json().then((s=>{t(new n(h(s),e.status||500))})).catch((e=>{t(new o(h(e),e))})):t(new o(h(e),e))})),u=(e,t,s,r)=>{const i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?i:(i.headers=Object.assign({"Content-Type":"application/json"},null==t?void 0:t.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),s))};function d(e,t,s,r,i,n){return c(this,void 0,void 0,(function*(){return new Promise(((o,a)=>{e(s,u(t,r,i,n)).then((e=>{if(!e.ok)throw e;return(null==r?void 0:r.noResolveJson)?e:e.json()})).then((e=>o(e))).catch((e=>l(e,a)))}))}))}function f(e,t,s,r){return c(this,void 0,void 0,(function*(){return d(e,"GET",t,s,r)}))}function p(e,t,s,r,i){return c(this,void 0,void 0,(function*(){return d(e,"POST",t,r,i,s)}))}function g(e,t,s,r,i){return c(this,void 0,void 0,(function*(){return d(e,"DELETE",t,r,i,s)}))}var y=function(e,t,s,r){return new(s||(s=Promise))((function(i,n){function o(e){try{c(r.next(e))}catch(e){n(e)}}function a(e){try{c(r.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};const v={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},m={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class _{constructor(e,t={},s,r){this.url=e,this.headers=t,this.bucketId=s,this.fetch=a(r)}uploadOrUpdate(e,t,s,r){return y(this,void 0,void 0,(function*(){try{let i;const n=Object.assign(Object.assign({},m),r),o=Object.assign(Object.assign({},this.headers),"POST"===e&&{"x-upsert":String(n.upsert)});"undefined"!=typeof Blob&&s instanceof Blob?(i=new FormData,i.append("cacheControl",n.cacheControl),i.append("",s)):"undefined"!=typeof FormData&&s instanceof FormData?(i=s,i.append("cacheControl",n.cacheControl)):(i=s,o["cache-control"]=`max-age=${n.cacheControl}`,o["content-type"]=n.contentType);const a=this._removeEmptyFolders(t),c=this._getFinalPath(a),h=yield this.fetch(`${this.url}/object/${c}`,Object.assign({method:e,body:i,headers:o},(null==n?void 0:n.duplex)?{duplex:n.duplex}:{}));return h.ok?{data:{path:a},error:null}:{data:null,error:yield h.json()}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}upload(e,t,s){return y(this,void 0,void 0,(function*(){return this.uploadOrUpdate("POST",e,t,s)}))}uploadToSignedUrl(e,t,s,r){return y(this,void 0,void 0,(function*(){const n=this._removeEmptyFolders(e),o=this._getFinalPath(n),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let e;const t=Object.assign({upsert:m.upsert},r),i=Object.assign(Object.assign({},this.headers),{"x-upsert":String(t.upsert)});"undefined"!=typeof Blob&&s instanceof Blob?(e=new FormData,e.append("cacheControl",t.cacheControl),e.append("",s)):"undefined"!=typeof FormData&&s instanceof FormData?(e=s,e.append("cacheControl",t.cacheControl)):(e=s,i["cache-control"]=`max-age=${t.cacheControl}`,i["content-type"]=t.contentType);const o=yield this.fetch(a.toString(),{method:"PUT",body:e,headers:i});return o.ok?{data:{path:n},error:null}:{data:null,error:yield o.json()}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}createSignedUploadUrl(e){return y(this,void 0,void 0,(function*(){try{let t=this._getFinalPath(e);const s=yield p(this.fetch,`${this.url}/object/upload/sign/${t}`,{},{headers:this.headers}),i=new URL(this.url+s.url),n=i.searchParams.get("token");if(!n)throw new r("No token returned by API");return{data:{signedUrl:i.toString(),path:e,token:n},error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}update(e,t,s){return y(this,void 0,void 0,(function*(){return this.uploadOrUpdate("PUT",e,t,s)}))}move(e,t){return y(this,void 0,void 0,(function*(){try{return{data:yield p(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t},{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}copy(e,t){return y(this,void 0,void 0,(function*(){try{return{data:{path:(yield p(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t},{headers:this.headers})).Key},error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}createSignedUrl(e,t,s){return y(this,void 0,void 0,(function*(){try{let r=this._getFinalPath(e),i=yield p(this.fetch,`${this.url}/object/sign/${r}`,Object.assign({expiresIn:t},(null==s?void 0:s.transform)?{transform:s.transform}:{}),{headers:this.headers});const n=(null==s?void 0:s.download)?`&download=${!0===s.download?"":s.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${n}`)},{data:i,error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}createSignedUrls(e,t,s){return y(this,void 0,void 0,(function*(){try{const r=yield p(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=(null==s?void 0:s.download)?`&download=${!0===s.download?"":s.download}`:"";return{data:r.map((e=>Object.assign(Object.assign({},e),{signedUrl:e.signedURL?encodeURI(`${this.url}${e.signedURL}${i}`):null}))),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}download(e,t){return y(this,void 0,void 0,(function*(){const s=void 0!==(null==t?void 0:t.transform)?"render/image/authenticated":"object",r=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),n=r?`?${r}`:"";try{const t=this._getFinalPath(e),r=yield f(this.fetch,`${this.url}/${s}/${t}${n}`,{headers:this.headers,noResolveJson:!0});return{data:yield r.blob(),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}getPublicUrl(e,t){const s=this._getFinalPath(e),r=[],i=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==i&&r.push(i);const n=void 0!==(null==t?void 0:t.transform)?"render/image":"object",o=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==o&&r.push(o);let a=r.join("&");return""!==a&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${n}/public/${s}${a}`)}}}remove(e){return y(this,void 0,void 0,(function*(){try{return{data:yield g(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}list(e,t,s){return y(this,void 0,void 0,(function*(){try{const r=Object.assign(Object.assign(Object.assign({},v),t),{prefix:e||""});return{data:yield p(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},s),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const 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("&")}}const b={"X-Client-Info":"storage-js/2.5.4"};var w=function(e,t,s,r){return new(s||(s=Promise))((function(i,n){function o(e){try{c(r.next(e))}catch(e){n(e)}}function a(e){try{c(r.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};class k{constructor(e,t={},s){this.url=e,this.headers=Object.assign(Object.assign({},b),t),this.fetch=a(s)}listBuckets(){return w(this,void 0,void 0,(function*(){try{return{data:yield f(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}getBucket(e){return w(this,void 0,void 0,(function*(){try{return{data:yield f(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}createBucket(e,t={public:!1}){return w(this,void 0,void 0,(function*(){try{return{data:yield p(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}updateBucket(e,t){return w(this,void 0,void 0,(function*(){try{const s=yield function(e,t,s,r,i){return c(this,void 0,void 0,(function*(){return d(e,"PUT",t,r,undefined,s)}))}(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers});return{data:s,error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}emptyBucket(e){return w(this,void 0,void 0,(function*(){try{return{data:yield p(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}deleteBucket(e){return w(this,void 0,void 0,(function*(){try{return{data:yield g(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}))}}class S extends k{constructor(e,t={},s){super(e,t,s)}from(e){return new _(this.url,this.headers,e,this.fetch)}}},284:e=>{var t=function(){if("object"==typeof self&&self)return self;if("object"==typeof window&&window)return window;throw new Error("Unable to resolve global `this`")};e.exports=function(){if(this)return this;if("object"==typeof globalThis&&globalThis)return globalThis;try{Object.defineProperty(Object.prototype,"__global__",{get:function(){return this},configurable:!0})}catch(e){return t()}try{return __global__||t()}finally{delete Object.prototype.__global__}}()},296:function(e,t,s){"use strict";var r=this&&this.__awaiter||function(e,t,s,r){return new(s||(s=Promise))((function(i,n){function o(e){try{c(r.next(e))}catch(e){n(e)}}function a(e){try{c(r.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0});const i=s(982),n=s(189),o=s(73),a=s(752),c=s(678),h=s(716),l=s(610),u=s(283),d={headers:c.DEFAULT_HEADERS},f={schema:"public"},p={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},g={};t.default=class{constructor(e,t,s){var r,i,o,a,c,u,y,v;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");const m=(0,l.stripTrailingSlash)(e);this.realtimeUrl=`${m}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${m}/auth/v1`,this.storageUrl=`${m}/storage/v1`,this.functionsUrl=`${m}/functions/v1`;const _=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,b={db:f,realtime:g,auth:Object.assign(Object.assign({},p),{storageKey:_}),global:d},w=(0,l.applySettingDefaults)(null!=s?s:{},b);this.storageKey=null!==(i=null===(r=w.auth)||void 0===r?void 0:r.storageKey)&&void 0!==i?i:"",this.headers=null!==(a=null===(o=w.global)||void 0===o?void 0:o.headers)&&void 0!==a?a:{},this.auth=this._initSupabaseAuthClient(null!==(c=w.auth)&&void 0!==c?c:{},this.headers,null===(u=w.global)||void 0===u?void 0:u.fetch),this.fetch=(0,h.fetchWithAuth)(t,this._getAccessToken.bind(this),null===(y=w.global)||void 0===y?void 0:y.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},w.realtime)),this.rest=new n.PostgrestClient(`${m}/rest/v1`,{headers:this.headers,schema:null===(v=w.db)||void 0===v?void 0:v.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new i.FunctionsClient(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new a.StorageClient(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},s){return this.rest.rpc(e,t,s)}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()}_getAccessToken(){var e,t;return r(this,void 0,void 0,(function*(){const{data:s}=yield this.auth.getSession();return null!==(t=null===(e=s.session)||void 0===e?void 0:e.access_token)&&void 0!==t?t:null}))}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,storageKey:i,flowType:n,debug:o},a,c){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new u.SupabaseAuthClient({url:this.authUrl,headers:Object.assign(Object.assign({},h),a),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,flowType:n,debug:o,fetch:c})}_initRealtimeClient(e){return new o.RealtimeClient(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({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,s){"TOKEN_REFRESHED"!==e&&"SIGNED_IN"!==e||this.changedAccessToken===s?"SIGNED_OUT"===e&&(this.realtime.setAuth(this.supabaseKey),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0):(this.realtime.setAuth(null!=s?s:null),this.changedAccessToken=s)}}},341:function(e,t,s){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,s,r){void 0===r&&(r=s);var i=Object.getOwnPropertyDescriptor(t,s);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[s]}}),Object.defineProperty(e,r,i)}:function(e,t,s,r){void 0===r&&(r=s),e[r]=t[s]}),i=this&&this.__exportStar||function(e,t){for(var s in e)"default"===s||Object.prototype.hasOwnProperty.call(t,s)||r(t,e,s)},n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.createClient=t.SupabaseClient=t.FunctionsError=t.FunctionsRelayError=t.FunctionsFetchError=t.FunctionsHttpError=void 0;const o=n(s(296));i(s(765),t);var a=s(982);Object.defineProperty(t,"FunctionsHttpError",{enumerable:!0,get:function(){return a.FunctionsHttpError}}),Object.defineProperty(t,"FunctionsFetchError",{enumerable:!0,get:function(){return a.FunctionsFetchError}}),Object.defineProperty(t,"FunctionsRelayError",{enumerable:!0,get:function(){return a.FunctionsRelayError}}),Object.defineProperty(t,"FunctionsError",{enumerable:!0,get:function(){return a.FunctionsError}}),i(s(73),t);var c=s(296);Object.defineProperty(t,"SupabaseClient",{enumerable:!0,get:function(){return n(c).default}}),t.createClient=(e,t,s)=>new o.default(e,t,s)},283:(e,t,s)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SupabaseAuthClient=void 0;const r=s(765);class i extends r.GoTrueClient{constructor(e){super(e)}}t.SupabaseAuthClient=i},678:(e,t,s)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_HEADERS=void 0;const r=s(506);t.DEFAULT_HEADERS={"X-Client-Info":`supabase-js/${r.version}`}},716:function(e,t,s){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,s,r){void 0===r&&(r=s);var i=Object.getOwnPropertyDescriptor(t,s);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[s]}}),Object.defineProperty(e,r,i)}:function(e,t,s,r){void 0===r&&(r=s),e[r]=t[s]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var s in e)"default"!==s&&Object.prototype.hasOwnProperty.call(e,s)&&r(t,e,s);return i(t,e),t},o=this&&this.__awaiter||function(e,t,s,r){return new(s||(s=Promise))((function(i,n){function o(e){try{c(r.next(e))}catch(e){n(e)}}function a(e){try{c(r.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.fetchWithAuth=t.resolveHeadersConstructor=t.resolveFetch=void 0;const a=n(s(743));t.resolveFetch=e=>{let t;return t=e||("undefined"==typeof fetch?a.default:fetch),(...e)=>t(...e)},t.resolveHeadersConstructor=()=>"undefined"==typeof Headers?a.Headers:Headers,t.fetchWithAuth=(e,s,r)=>{const i=(0,t.resolveFetch)(r),n=(0,t.resolveHeadersConstructor)();return(t,r)=>o(void 0,void 0,void 0,(function*(){var o;const a=null!==(o=yield s())&&void 0!==o?o:e;let c=new n(null==r?void 0:r.headers);return c.has("apikey")||c.set("apikey",e),c.has("Authorization")||c.set("Authorization",`Bearer ${a}`),i(t,Object.assign(Object.assign({},r),{headers:c}))}))}},610:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.applySettingDefaults=t.isBrowser=t.stripTrailingSlash=t.uuid=void 0,t.uuid=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}))},t.stripTrailingSlash=function(e){return e.replace(/\/$/,"")},t.isBrowser=()=>"undefined"!=typeof window,t.applySettingDefaults=function(e,t){const{db:s,auth:r,realtime:i,global:n}=e,{db:o,auth:a,realtime:c,global:h}=t;return{db:Object.assign(Object.assign({},o),s),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},c),i),global:Object.assign(Object.assign({},h),n)}}},506:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.version=void 0,t.version="2.33.2"},840:(e,t,s)=>{var r;if("object"==typeof globalThis)r=globalThis;else try{r=s(284)}catch(e){}finally{if(r||"undefined"==typeof window||(r=window),!r)throw new Error("Could not determine global this")}var i=r.WebSocket||r.MozWebSocket,n=s(387);function o(e,t){return t?new i(e,t):new i(e)}i&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach((function(e){Object.defineProperty(o,e,{get:function(){return i[e]}})})),e.exports={w3cwebsocket:i?o:null,version:n}},387:(e,t,s)=>{e.exports=s(794).version},794:e=>{"use strict";e.exports={version:"1.0.34"}}},r={};function i(e){var t=r[e];if(void 0!==t)return t.exports;var n=r[e]={exports:{}};return s[e].call(n.exports,n,n.exports,i),n.exports}return i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,i.t=function(s,r){if(1&r&&(s=this(s)),8&r)return s;if("object"==typeof s&&s){if(4&r&&s.__esModule)return s;if(16&r&&"function"==typeof s.then)return s}var n=Object.create(null);i.r(n);var o={};e=e||[null,t({}),t([]),t(t)];for(var a=2&r&&s;"object"==typeof a&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach((e=>o[e]=()=>s[e]));return o.default=()=>s,i.d(n,o),n},i.d=(e,t)=>{for(var s in t)i.o(t,s)&&!i.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i(341)})()));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supabase/supabase-js",
3
- "version": "2.33.0",
3
+ "version": "2.33.2",
4
4
  "description": "Isomorphic Javascript client for Supabase",
5
5
  "keywords": [
6
6
  "javascript",
@@ -37,12 +37,12 @@
37
37
  "docs:json": "typedoc --entryPoints src/index.ts --includes src/**/*.ts --json docs/v2/spec.json --excludeExternals"
38
38
  },
39
39
  "dependencies": {
40
- "@supabase/functions-js": "^2.1.0",
41
- "@supabase/gotrue-js": "^2.46.1",
42
- "@supabase/postgrest-js": "^1.8.0",
43
- "@supabase/realtime-js": "^2.7.3",
44
- "@supabase/storage-js": "^2.5.1",
45
- "cross-fetch": "^3.1.5"
40
+ "@supabase/functions-js": "^2.1.5",
41
+ "@supabase/gotrue-js": "^2.51.0",
42
+ "@supabase/node-fetch": "^2.6.14",
43
+ "@supabase/postgrest-js": "^1.8.4",
44
+ "@supabase/realtime-js": "^2.7.4",
45
+ "@supabase/storage-js": "^2.5.4"
46
46
  },
47
47
  "devDependencies": {
48
48
  "@types/jest": "^29.2.5",
package/src/lib/fetch.ts CHANGED
@@ -1,4 +1,5 @@
1
- import crossFetch, { Headers as CrossFetchHeaders } from 'cross-fetch'
1
+ // @ts-ignore
2
+ import nodeFetch, { Headers as NodeFetchHeaders } from '@supabase/node-fetch'
2
3
 
3
4
  type Fetch = typeof fetch
4
5
 
@@ -7,7 +8,7 @@ export const resolveFetch = (customFetch?: Fetch): Fetch => {
7
8
  if (customFetch) {
8
9
  _fetch = customFetch
9
10
  } else if (typeof fetch === 'undefined') {
10
- _fetch = crossFetch as unknown as Fetch
11
+ _fetch = nodeFetch as unknown as Fetch
11
12
  } else {
12
13
  _fetch = fetch
13
14
  }
@@ -16,7 +17,7 @@ export const resolveFetch = (customFetch?: Fetch): Fetch => {
16
17
 
17
18
  export const resolveHeadersConstructor = () => {
18
19
  if (typeof Headers === 'undefined') {
19
- return CrossFetchHeaders
20
+ return NodeFetchHeaders
20
21
  }
21
22
 
22
23
  return Headers
@@ -1 +1 @@
1
- export const version = '2.33.0'
1
+ export const version = '2.33.2'