@data-loom/js 0.4.5-alpha.1 → 0.4.6

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 +1 @@
1
- {"version":3,"file":"DataloomClient.d.ts","sourceRoot":"","sources":["../../src/DataloomClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AAEzD,OAAO,EACL,eAAe,EACf,sBAAsB,EACtB,qBAAqB,EACtB,MAAM,yBAAyB,CAAA;AAChC,OAAO,EACL,eAAe,EACf,sBAAsB,EACtB,cAAc,EAEf,MAAM,wBAAwB,CAAA;AAC/B,OAAO,eAAe,MAAM,uBAAuB,CAAA;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAA;AAUrD,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAA;AAC/D,OAAO,EACL,KAAK,EACL,aAAa,EACb,qBAAqB,EAEtB,MAAM,eAAe,CAAA;AACtB,OAAO,WAAW,MAAM,eAAe,CAAA;AAEvC;;;;GAIG;AACH,MAAM,CAAC,OAAO,OAAO,cAAc,CACjC,QAAQ,GAAG,GAAG,EACd,UAAU,SAAS,MAAM,GAAG,MAAM,QAAQ,GAAG,QAAQ,SAAS,MAAM,QAAQ,GACxE,QAAQ,GACR,MAAM,GAAG,MAAM,QAAQ,EAC3B,MAAM,SAAS,aAAa,GAAG,QAAQ,CAAC,UAAU,CAAC,SAAS,aAAa,GACrE,QAAQ,CAAC,UAAU,CAAC,GACpB,GAAG;IAsCL,SAAS,CAAC,WAAW,EAAE,MAAM;IAC7B,SAAS,CAAC,WAAW,EAAE,MAAM;IAC7B,SAAS,CAAC,WAAW,EAAE,MAAM;IAtC/B;;OAEG;IACH,IAAI,EAAE,kBAAkB,CAAA;IACxB,QAAQ,EAAE,cAAc,CAAA;IACxB,OAAO,EAAE,eAAe,CAAA;IACxB,OAAO,EAAE,aAAa,CAAA;IAEtB,SA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AIhC;;;;;OAKG;IACH,aAAa,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,GAAG,WAAW,GAAG,OAAO,CAAC;IAI9E;;OAEG;IACH,iBAAiB,IAAI,OAAO,CAAC,CAAC,IAAI,GAAG,WAAW,GAAG,OAAO,CAAC,EAAE,CAAC;YAIhD,eAAe;IAU7B,OAAO,CAAC,uBAAuB;IAqC/B,OAAO,CAAC,mBAAmB;IAO3B,OAAO,CAAC,oBAAoB;IAO5B,OAAO,CAAC,mBAAmB;CAgB5B"}
@@ -47,7 +47,7 @@ class SupabaseClient {
47
47
  this.supabaseKey = supabaseKey;
48
48
  this.workspaceId = workspaceId;
49
49
  if (!supabaseUrl)
50
- throw new Error('dataloomUrl is required.');
50
+ console.warn('[Dataloom] url is empty.');
51
51
  if (!supabaseKey)
52
52
  console.warn('[Dataloom] apiKey is empty.');
53
53
  if (!workspaceId)
@@ -58,12 +58,10 @@ class SupabaseClient {
58
58
  this.authUrl = `${_supabaseUrlWithWorkspace}/auth/v1`;
59
59
  this.storageUrl = `${_supabaseUrl}/storage`;
60
60
  this.functionsUrl = `${_supabaseUrlWithWorkspace}/functions/v1`;
61
- // default storage key uses the supabase project ref as a namespace
62
- const defaultStorageKey = `sb-${new URL(this.authUrl).hostname.split('.')[0]}-auth-token`;
63
61
  const DEFAULTS = {
64
62
  db: constants_1.DEFAULT_DB_OPTIONS,
65
63
  realtime: constants_1.DEFAULT_REALTIME_OPTIONS,
66
- auth: Object.assign(Object.assign({}, constants_1.DEFAULT_AUTH_OPTIONS), { storageKey: defaultStorageKey }),
64
+ auth: Object.assign({}, constants_1.DEFAULT_AUTH_OPTIONS),
67
65
  global: constants_1.DEFAULT_GLOBAL_OPTIONS,
68
66
  };
69
67
  const settings = (0, helpers_1.applySettingDefaults)(options !== null && options !== void 0 ? options : {}, DEFAULTS);
@@ -1 +1 @@
1
- {"version":3,"file":"DataloomClient.js","sourceRoot":"","sources":["../../src/DataloomClient.ts"],"names":[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;IAID;;;;;;OAMG;IACH,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,GAAE,sBAAuC,GAAG,eAAe;IAIrF;;OAEG;IACH,WAAW,IAAI,eAAe,EAAE;IAIhC;;;;;OAKG;IACH,aAAa,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,GAAG,WAAW,GAAG,OAAO,CAAC;IAI9E;;OAEG;IACH,iBAAiB,IAAI,OAAO,CAAC,CAAC,IAAI,GAAG,WAAW,GAAG,OAAO,CAAC,EAAE,CAAC;YAIhD,eAAe;IAU7B,OAAO,CAAC,uBAAuB;IAqC/B,OAAO,CAAC,mBAAmB;IAO3B,OAAO,CAAC,oBAAoB;IAO5B,OAAO,CAAC,mBAAmB;CAgB5B"}
@@ -42,7 +42,7 @@ export default class SupabaseClient {
42
42
  this.supabaseKey = supabaseKey;
43
43
  this.workspaceId = workspaceId;
44
44
  if (!supabaseUrl)
45
- throw new Error('dataloomUrl is required.');
45
+ console.warn('[Dataloom] url is empty.');
46
46
  if (!supabaseKey)
47
47
  console.warn('[Dataloom] apiKey is empty.');
48
48
  if (!workspaceId)
@@ -53,12 +53,10 @@ export default class SupabaseClient {
53
53
  this.authUrl = `${_supabaseUrlWithWorkspace}/auth/v1`;
54
54
  this.storageUrl = `${_supabaseUrl}/storage`;
55
55
  this.functionsUrl = `${_supabaseUrlWithWorkspace}/functions/v1`;
56
- // default storage key uses the supabase project ref as a namespace
57
- const defaultStorageKey = `sb-${new URL(this.authUrl).hostname.split('.')[0]}-auth-token`;
58
56
  const DEFAULTS = {
59
57
  db: DEFAULT_DB_OPTIONS,
60
58
  realtime: DEFAULT_REALTIME_OPTIONS,
61
- auth: Object.assign(Object.assign({}, DEFAULT_AUTH_OPTIONS), { storageKey: defaultStorageKey }),
59
+ auth: Object.assign({}, DEFAULT_AUTH_OPTIONS),
62
60
  global: DEFAULT_GLOBAL_OPTIONS,
63
61
  };
64
62
  const settings = applySettingDefaults(options !== null && options !== void 0 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;YACL,KAAK;YACL,wEAAwE;YACxE,gFAAgF;YAChF,4BAA4B,EAAE,eAAe,IAAI,IAAI,CAAC,OAAO;SAC9D,CAAC,CAAA;IACJ,CAAC;IAEO,mBAAmB,CAAC,OAA8B;QACxD,OAAO,IAAI,cAAc,CAAC,IAAI,CAAC,WAAW,kCACrC,OAAO,KACV,MAAM,gBAAO,EAAE,MAAM,EAAE,IAAI,CAAC,WAAW,EAAE,EAAK,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,MAAM,KAC7D,CAAA;IACJ,CAAC;IAEO,oBAAoB;QAC1B,IAAI,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE;YACxD,IAAI,CAAC,mBAAmB,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,CAAC,CAAA;QAClE,CAAC,CAAC,CAAA;QACF,OAAO,IAAI,CAAA;IACb,CAAC;IAEO,mBAAmB,CACzB,KAAsB,EACtB,MAA4B,EAC5B,KAAc;QAEd,IACE,CAAC,KAAK,KAAK,iBAAiB,IAAI,KAAK,KAAK,WAAW,CAAC;YACtD,IAAI,CAAC,kBAAkB,KAAK,KAAK,EACjC;YACA,IAAI,CAAC,kBAAkB,GAAG,KAAK,CAAA;SAChC;aAAM,IAAI,KAAK,KAAK,YAAY,EAAE;YACjC,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAA;YACvB,IAAI,MAAM,IAAI,SAAS;gBAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAA;YAC5C,IAAI,CAAC,kBAAkB,GAAG,SAAS,CAAA;SACpC;IACH,CAAC;CACF"}
@@ -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.dataloom=t():e.dataloom=t()}(self,()=>(()=>{"use strict";var e,t,s,r,i={93:function(e,t,s){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.DataloomClient=t.FunctionRegion=t.FunctionsError=t.FunctionsRelayError=t.FunctionsFetchError=t.FunctionsHttpError=t.PostgrestError=void 0;const o=n(s(399));i(s(650),t);var a=s(739);Object.defineProperty(t,"PostgrestError",{enumerable:!0,get:function(){return a.PostgrestError}});var l=s(231);Object.defineProperty(t,"FunctionsHttpError",{enumerable:!0,get:function(){return l.FunctionsHttpError}}),Object.defineProperty(t,"FunctionsFetchError",{enumerable:!0,get:function(){return l.FunctionsFetchError}}),Object.defineProperty(t,"FunctionsRelayError",{enumerable:!0,get:function(){return l.FunctionsRelayError}}),Object.defineProperty(t,"FunctionsError",{enumerable:!0,get:function(){return l.FunctionsError}}),Object.defineProperty(t,"FunctionRegion",{enumerable:!0,get:function(){return l.FunctionRegion}}),i(s(587),t);var c=s(399);Object.defineProperty(t,"DataloomClient",{enumerable:!0,get:function(){return n(c).default}}),t.createClient=(e,t,s,r)=>new o.default(e,t,s,r)},150:(e,t,s)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_REALTIME_OPTIONS=t.DEFAULT_AUTH_OPTIONS=t.DEFAULT_DB_OPTIONS=t.DEFAULT_GLOBAL_OPTIONS=t.DEFAULT_HEADERS=void 0;const r=s(946),i=s(755);let n="";n="undefined"!=typeof Deno?"deno":"undefined"!=typeof document?"web":"undefined"!=typeof navigator&&"ReactNative"===navigator.product?"react-native":"node",t.DEFAULT_HEADERS={"X-Client-Info":`dataloom-js-${n}/${i.version}`,"X-Suda-Token":(()=>{if(!(0,r.isBrowser)())return"";const e=window.location.host.replace(/\./g,"-"),t=(0,r.getQueryFromUrl)("suda_token");if(t)return localStorage.setItem(`suda_token_${e}`,`${t}`),(0,r.deleteQueryFromUrl)("suda_token"),t;return localStorage.getItem(`suda_token_${e}`)||""})(),"X-Suda-Referer":(0,r.isBrowser)()?window.location.href:""},t.DEFAULT_GLOBAL_OPTIONS={headers:t.DEFAULT_HEADERS,brandName:"",appId:""},t.DEFAULT_DB_OPTIONS={schema:""},t.DEFAULT_AUTH_OPTIONS={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},t.DEFAULT_REALTIME_OPTIONS={}},231:(e,t,s)=>{s.r(t),s.d(t,{FunctionRegion:()=>a,FunctionsClient:()=>l,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)}}var a;!function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"}(a||(a={}));class l{constructor(e,{headers:t={},customFetch:r,region:i=a.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=(e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>Promise.resolve().then(s.bind(s,663)).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)})(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s,r,a,l,c;return r=this,a=void 0,c=function*(){try{const{headers:r,method:a,body:l}=t;let c,u={},{region:h}=t;h||(h=this.region),h&&"any"!==h&&(u["x-region"]=h),l&&(r&&!Object.prototype.hasOwnProperty.call(r,"Content-Type")||!r)&&("undefined"!=typeof Blob&&l instanceof Blob||l instanceof ArrayBuffer?(u["Content-Type"]="application/octet-stream",c=l):"string"==typeof l?(u["Content-Type"]="text/plain",c=l):"undefined"!=typeof FormData&&l instanceof FormData?c=l:(u["Content-Type"]="application/json",c=JSON.stringify(l)));const d=yield this.fetch(`${this.url}/${e}`,{method:a||"POST",headers:Object.assign(Object.assign(Object.assign({},u),this.headers),r),body:c}).catch(e=>{throw new i(e)}),f=d.headers.get("x-relay-error");if(f&&"true"===f)throw new n(d);if(!d.ok)throw new o(d);let p,g=(null!==(s=d.headers.get("Content-Type"))&&void 0!==s?s:"text/plain").split(";")[0].trim();return p="application/json"===g?yield d.json():"application/octet-stream"===g?yield d.blob():"text/event-stream"===g?d:"multipart/form-data"===g?yield d.formData():yield d.text(),{data:p,error:null}}catch(e){return{data:null,error:e}}},new((l=void 0)||(l=Promise))(function(e,t){function s(e){try{n(c.next(e))}catch(e){t(e)}}function i(e){try{n(c.throw(e))}catch(e){t(e)}}function n(t){var r;t.done?e(t.value):(r=t.value,r instanceof l?r:new l(function(e){e(r)})).then(s,i)}n((c=c.apply(r,a||[])).next())})}}},299:function(e,t,s){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{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(o,a)}l((r=r.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.fetchWithAuth=t.resolveHeadersConstructor=t.resolveFetch=void 0;const a=n(s(663));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,i)=>{const n=(0,t.resolveFetch)(i),a=(0,t.resolveHeadersConstructor)();return(t,i)=>o(void 0,void 0,void 0,function*(){if(r&&!r.canRequest())return Promise.resolve(new Response(`{"limit": ${r.maxRequests}}`,{status:429,statusText:"Too Many Requests"}));yield s();let o=new a(null==i?void 0:i.headers);return e||console.warn("[Dataloom] api key is missing"),!o.has("apikey")&&e&&o.set("apikey",e),n(t,Object.assign(Object.assign({},i),{headers:o}))})}},399:function(e,t,s){var r=this&&this.__awaiter||function(e,t,s,r){return new(s||(s=Promise))(function(i,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(o,a)}l((r=r.apply(e,t||[])).next())})},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const n=s(231),o=s(739),a=s(587),l=i(s(479)),c=s(645),u=s(150),h=s(299),d=s(946),f=s(560),p=i(s(699));t.default=class{constructor(e,t,s,r){var i,n,a;if(this.supabaseUrl=e,this.supabaseKey=t,this.workspaceId=s,!e)throw new Error("dataloomUrl is required.");t||console.warn("[Dataloom] apiKey is empty."),s||console.warn("[Dataloom] workspaceId is empty.");const f=(0,d.stripTrailingSlash)(e),g=`${f}/workspaces/${s}`;this.realtimeUrl=`${g}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${g}/auth/v1`,this.storageUrl=`${f}/storage`,this.functionsUrl=`${g}/functions/v1`;const m=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,v={db:u.DEFAULT_DB_OPTIONS,realtime:u.DEFAULT_REALTIME_OPTIONS,auth:Object.assign(Object.assign({},u.DEFAULT_AUTH_OPTIONS),{storageKey:m}),global:u.DEFAULT_GLOBAL_OPTIONS},y=(0,d.applySettingDefaults)(null!=r?r:{},v);this.storageKey=null!==(i=y.auth.storageKey)&&void 0!==i?i:"",this.headers=null!==(n=y.global.headers)&&void 0!==n?n:{},this.onRequestError=e=>{y.global.onError&&y.global.onError(e,this)},y.accessToken?(this.accessToken=y.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw new Error(`@data-loom/js: Dataloom Client is configured with the accessToken option, accessing dataloom.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!==(a=y.auth)&&void 0!==a?a:{},this.headers,y.global.fetch),y.global.requestRateLimit&&y.global.requestRateLimit>0&&(this.rateLimiter=new p.default(y.global.requestRateLimit)),this.fetch=(0,h.fetchWithAuth)(t,this._getAccessToken.bind(this),this.rateLimiter,y.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},y.realtime)),this.rest=new o.PostgrestClient(`${g}/dataloom/data`,{headers:this.headers,schema:y.db.schema,fetch:this.fetch,logger:y.global.enableDataloomLog,onRequestError:this.onRequestError}),this.service=new l.default({headers:this.headers,fetch:this.fetch,logger:y.global.enableDataloomLog,brandName:y.global.brandName,appId:y.global.appId,onRequestError:this.onRequestError}),this.storage=new c.StorageClient(this.storageUrl,this.headers,this.fetch,{enableLogger:y.global.enableDataloomLog,onRequestError:this.onRequestError,appId:y.global.appId}),y.accessToken||this._listenForAuthEvents()}get functions(){return new n.FunctionsClient(this.functionsUrl,{headers:this.headers,customFetch: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*(){if(this.accessToken)return yield this.accessToken();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,lock:o,debug:a},l,c){const u={apikey:`${this.supabaseKey}`};return new f.SupabaseAuthClient({url:this.authUrl,headers:Object.assign(Object.assign({},u),l),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,flowType:n,lock:o,debug:a,fetch:c,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new a.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(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0):this.changedAccessToken=s}}},479:(e,t,s)=>{s.r(t),s.d(t,{default:()=>y});var r=s(663);class i{constructor(){this.counter=1}static getInstance(){return i.instance||(i.instance=new i),i.instance}next(){return this.counter++}getCurrent(){return this.counter}reset(){this.counter=1}}const n=i.getInstance(),o=(e,t,s="Service")=>{const{data:r,error:i,status:n}=t;i?console.error(`[Dataloom][${s}][Response ${i?"Failed":"Success"}]`,"trace id:",e,"statusCode:",n,"error:",i):console.log(`[Dataloom][${s}][Response ${i?"Failed":"Success"}]`,"trace id:",e,"statusCode:",n,"data:",r)};var a,l;!function(e){e[e.Unspecified=0]="Unspecified",e[e.Inactive=1]="Inactive",e[e.Active=2]="Active",e[e.Disabled=3]="Disabled",e[e.Terminated=4]="Terminated"}(a||(a={})),function(e){e[e.active=1]="active",e[e.inactive=2]="inactive"}(l||(l={}));const c=()=>"undefined"!=typeof window&&"undefined"!=typeof document,u=e=>{var t,s;return c()&&null!==(s=null===(t=document.cookie.split(";").find(t=>t.trim().startsWith(`${e}=`)))||void 0===t?void 0:t.split("=")[1])&&void 0!==s?s:""},h=e=>(null==e?void 0:e.zh_cn)||(null==e?void 0:e.en_us)||(null==e?void 0:e.ja_jp)||"",d=e=>e===a.Active||e===a.Inactive?l.active:e===a.Disabled||e===a.Terminated?l.inactive:l.active;var f;!function(e){e.DEFAULT="default",e.UserService="user-service",e.SessionService="session-service"}(f||(f={}));class p{constructor(e,t){var s;this.baseUrl=e,this.headers=Object.assign(Object.assign({},t.headers),{"X-Suda-Csrf-Token":u("suda-csrf-token")}),this.logger=null!==(s=t.logger)&&void 0!==s&&s,this.serviceName=f.DEFAULT,this.brandId="miaoda"===t.brandName?"1":"0",this.appId=t.appId,this.onRequestError=t.onRequestError,t.fetch?this.fetch=t.fetch:"undefined"==typeof fetch?this.fetch=r.default:this.fetch=fetch}async fetchData(e,t,s){var r,i;const a=`${this.baseUrl.toString()}${e}`;let l=-1;this.logger&&(l=n.next(),((e,t="Service")=>{const{traceId:s,url:r,method:i,body:n}=e,o=Array.from(new URL(r).searchParams.entries()).filter(([e])=>!["count","tx","missing","resolution","column"].includes(e)).map(([e,t])=>`${e}=${t}`);console.log(`[Dataloom][${t}][Request]`,"trace id:",s,"method:",i,"params:",o.join(","),"body:",n)})({traceId:l,url:a,method:t.method,body:t.body},null==s?void 0:s.psmName));try{const e=await this.fetch(a,{method:t.method,mode:"cors",redirect:"manual",credentials:"include",headers:this.headers,body:JSON.stringify(t.body)});let i=null,n=null,c=e.status,u=e.statusText;if(e.ok){const t=await e.text(),s=JSON.parse(t);s.status_code&&s.error_msg?(n=null,i={code:s.status_code||e.status,details:"",hint:"",message:s.error_msg||t}):(n=s.data,i=null)}else{const t=await e.text(),s=JSON.parse(t);try{i=429===e.status?{code:429,message:"Too many requests received within 5 seconds.",details:"",hint:"Retry after 5 seconds."}:{code:s.status_code||e.status,message:s.error_msg||t,details:"",hint:""}}catch(r){i={code:s.status_code||e.status,message:s.error_msg||t,details:"",hint:""},n=null,c=500,u="Dataloom Internal Error"}}const h={data:n,error:i,status:c,statusText:u};return i&&(null===(r=this.onRequestError)||void 0===r||r.call(this,Object.assign(Object.assign({},i),{status:c,statusText:u}))),this.logger&&o(l,h,null==s?void 0:s.psmName),h}catch(e){const t={error:{code:500,message:null==e?void 0:e.message,details:"",hint:""},status:500,statusText:"Dataloom Internal Error"};null===(i=this.onRequestError)||void 0===i||i.call(this,Object.assign(Object.assign({},t.error),{status:t.status,statusText:t.statusText}));const r=Object.assign({data:null},t);return this.logger&&o(l,r,null==s?void 0:s.psmName),r}}}class g extends p{constructor(){super(...arguments),this.serviceName=f.UserService}async search(e){var t,s,r;const{name:i,pageSize:n}=e,o=await this.fetchData(`/af/app/${this.appId}/runtime/api/v1/account/search_user`,{method:"POST",body:{query:i,page_size:n}},{psmName:"UserService.Search"});return o.error?o:Object.assign(Object.assign({},o),{data:{user_list:null!==(r=null===(s=null===(t=o.data)||void 0===t?void 0:t.userList)||void 0===s?void 0:s.map(e=>{var t,s,r,i;return{avatar:null!==(t=e.avatar)&&void 0!==t?t:"",email:null!==(s=e.email)&&void 0!==s?s:"",name:null!==(r=h(e.name))&&void 0!==r?r:"",status:d(e.userStatus),user_id:null!==(i=e.userID)&&void 0!==i?i:""}}))&&void 0!==r?r:[]}})}async getByIds(e){const t=await this.fetchData(`/af/app/${this.appId}/runtime/api/v1/account/list_users`,{method:"POST",body:{userIDList:e}},{psmName:"UserService.GetByIds"});return t.error?t:Object.assign(Object.assign({},t),{data:{user_list:e.map(e=>{var s,r,i,n,o,a,l;const c=null===(r=null===(s=t.data)||void 0===s?void 0:s.userInfoMap)||void 0===r?void 0:r[e];return{avatar:null!==(o=null===(n=null===(i=null==c?void 0:c.avatar)||void 0===i?void 0:i.image)||void 0===n?void 0:n.large)&&void 0!==o?o:"",email:null!==(a=null==c?void 0:c.email)&&void 0!==a?a:"",name:null!==(l=h(null==c?void 0:c.name))&&void 0!==l?l:"",status:d(null==c?void 0:c.userStatus),user_id:(null==c?void 0:c.userID)?String(c.userID):""}})}})}}const m={data:null,error:{code:400,message:"Incompatible runtime environment",hint:"Please check if the current environment is browser.",details:"This method can only be invoked in browser environment."},status:400,statusText:"Bad Request"};class v extends p{constructor(){super(...arguments),this.serviceName=f.SessionService}redirectToLogin(e){if(!c())return console.log("[Dataloom][SessionService.RedirectToLogin] dataloom.service.session.redirectToLogin can only be invoked in browser environment."),m;const{returnUrl:t,newTab:s=!1}=null!=e?e:{},r=encodeURIComponent(t||window.location.href),i=`/suda/login?brand=${this.brandId}&appId=${this.appId}&redirectUrl=${r}`;return s?window.open(i,"_blank"):window.location.href=i,{data:"success",error:null,status:200,statusText:"OK"}}async signOut(){return c()?this.fetchData(`/suda/api/runtime/v1/idp/logout?app_id=${this.appId}`,{method:"GET"},{psmName:"SessionService.SignOut"}):(console.log("[Dataloom][SessionService.SignOut] dataloom.service.session.signOut can only be invoked in browser environment."),m)}getUserInfo(){if(!c())return console.log("[Dataloom][SessionService.GetUserInfo] dataloom.service.session.getUserInfo can only be invoked in browser environment."),Promise.resolve(m);let e="/suda/api/session/v1/idp/user_info";const t=new URLSearchParams;return this.brandId&&t.append("brand",this.brandId),this.appId&&t.append("app_id",this.appId),(this.brandId||this.appId)&&(e+=`?${t.toString()}`),this.fetchData(e,{method:"GET"},{psmName:"SessionService.GetUserInfo"})}navigateToUserProfile(e){if(!c())return console.log("[Dataloom][SessionService.NavigateToUserProfile] dataloom.service.session.navigateToUserProfile can only be invoked in browser environment."),m;const{newTab:t=!1}=null!=e?e:{},s=encodeURIComponent(window.location.href),r=`/suda/user?brand=${this.brandId}&returnUrl=${s}`;return t?window.open(r,"_blank"):window.location.href=r,{data:"success",error:null,status:200,statusText:"OK"}}}class y{constructor(e){const t=c()?window.location.origin:"";this.user=new g(t,e),this.session=new v(t,e)}}},560:(e,t,s)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SupabaseAuthClient=void 0;const r=s(650);class i extends r.AuthClient{constructor(e){super(e)}}t.SupabaseAuthClient=i},587:(e,t,s)=>{s.r(t),s.d(t,{REALTIME_CHANNEL_STATES:()=>P,REALTIME_LISTEN_TYPES:()=>j,REALTIME_POSTGRES_CHANGES_LISTEN_EVENT:()=>T,REALTIME_PRESENCE_LISTEN_EVENTS:()=>E,REALTIME_SUBSCRIBE_STATES:()=>O,RealtimeChannel:()=>A,RealtimeClient:()=>$,RealtimePresence:()=>R});const r={"X-Client-Info":"realtime-js/0.0.0-automated"};var i,n,o,a,l,c,u;!function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"}(i||(i={})),function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"}(n||(n={})),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"}(o||(o={})),function(e){e.websocket="websocket"}(a||(a={})),function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"}(l||(l={})),function(e){e.Info="info",e.Warn="warn",e.Error="error"}(c||(c={}));class h{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 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))}}!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 f=(e,t,s={})=>{var r;const i=null!==(r=s.skipTypes)&&void 0!==r?r:[];return Object.keys(t).reduce((s,r)=>(s[r]=p(r,e,t,i),s),{})},p=(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)?g(n,o):m(o)},g=(e,t)=>{if("_"===e.charAt(0)){const s=e.slice(1,e.length);return _(t,s)}switch(e){case u.bool:return v(t);case u.float4:case u.float8:case u.int2:case u.int4:case u.int8:case u.numeric:case u.oid:return y(t);case u.json:case u.jsonb:return w(t);case u.timestamp:return b(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 m(t)}},m=e=>e,v=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},y=e=>{if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},w=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(t){return console.log(`JSON parse error: ${t}`),e}return e},_=(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=>g(t,e))}return e},b=e=>"string"==typeof e?e.replace(" ","T"):e,k=e=>{let t=e;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")};class S{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}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var 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}}var E,T,j,O;!function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"}(E||(E={}));class R{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=R.syncState(this.state,e,t,s),this.pendingDiffs.forEach(e=>{this.state=R.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=R.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),l=s.filter(e=>r.indexOf(e.presence_ref)<0);n.length>0&&(o[e]=n),l.length>0&&(a[e]=l)}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.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"}(T||(T={})),function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"}(j||(j={})),function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"}(O||(O={}));const P=n;class A{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=n.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new S(this,o.join,this.params,this.timeout),this.rejoinTimer=new d(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=n.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=n.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=n.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=n.errored,this.rejoinTimer.scheduleTimeout())}),this._on(o.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new R(this),this.broadcastEndpointURL=k(this.socket.endPoint)+"/api/broadcast",this.private=this.params.config.private||!1}subscribe(e,t=this.timeout){var s,r;if(this.socket.isConnected()||this.socket.connect(),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,private:o}}=this.params;this._onError(t=>null==e?void 0:e(O.CHANNEL_ERROR,t)),this._onClose(()=>null==e?void 0:e(O.CLOSED));const a={},l={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:[],private:o};this.socket.accessTokenValue&&(a.access_token=this.socket.accessTokenValue),this.updateJoinPayload(Object.assign({config:l},a)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:t})=>{var s;if(this.socket.setAuth(),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:l,filter:c}}=i,u=t&&t[s];if(!u||u.event!==o||u.schema!==a||u.table!==l||u.filter!==c)return this.unsubscribe(),void(null==e||e(O.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes")));n.push(Object.assign(Object.assign({},i),{id:u.id}))}return this.bindings.postgres_changes=n,void(e&&e(O.SUBSCRIBED))}null==e||e(O.SUBSCRIBED)}).receive("error",t=>{null==e||e(O.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{null==e||e(O.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,r;if(this._canPush()||"broadcast"!==e.type)return new Promise(s=>{var r,i,n;const o=this._push(e.type,e,t.timeout||this.timeout);"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("error",()=>s("error")),o.receive("timeout",()=>s("timed out"))});{const{event:i,payload:n}=e,o={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:n,private:this.private}]})};try{const e=await this._fetchWithTimeout(this.broadcastEndpointURL,o,null!==(s=t.timeout)&&void 0!==s?s:this.timeout);return await(null===(r=e.body)||void 0===r?void 0:r.cancel()),e.ok?"ok":"error"}catch(e){return"AbortError"===e.name?"timed out":"error"}}}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=n.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(o.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{const r=new S(this,o.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",{})})}async _fetchWithTimeout(e,t,s){const r=new AbortController,i=setTimeout(()=>r.abort(),s),n=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(i),n}_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 S(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:a,error:l,leave:c,join:u}=o;if(s&&[a,l,c,u].indexOf(n)>=0&&s!==this._joinRef())return;let h=this._onMessage(n,t,s);if(t&&!h)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(h,s)):null===(i=this.bindings[n])||void 0===i||i.filter(e=>{var s,r,i,o,a,l;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===(l=null==t?void 0:t.event)||void 0===l?void 0:l.toLocaleLowerCase())}}return e.type.toLocaleLowerCase()===n}).map(e=>{if("object"==typeof h&&"ids"in h){const e=h.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};h=Object.assign(Object.assign({},o),this._getPayloadRecords(e))}e.callback(h,s)})}_isClosed(){return this.state===n.closed}_isJoined(){return this.state===n.joined}_isJoining(){return this.state===n.joining}_isLeaving(){return this.state===n.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&&A.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(o.close,{},e)}_onError(e){this._on(o.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=n.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return"INSERT"!==e.type&&"UPDATE"!==e.type||(t.new=f(e.columns,e.record)),"UPDATE"!==e.type&&"DELETE"!==e.type||(t.old=f(e.columns,e.old_record)),t}}const I=()=>{},x="undefined"!=typeof WebSocket;class ${constructor(e,t){var i;this.accessTokenValue=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=r,this.params={},this.timeout=1e4,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=I,this.conn=null,this.sendBuffer=[],this.serializer=new h,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>Promise.resolve().then(s.bind(s,663)).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},this.endPoint=`${e}/${a.websocket}`,this.httpEndpoint=k(e),(null==t?void 0:t.transport)?this.transport=t.transport:this.transport=null,(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.logLevel)||(null==t?void 0:t.log_level))&&(this.logLevel=t.logLevel||t.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),(null==t?void 0:t.heartbeatIntervalMs)&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);const n=null===(i=null==t?void 0:t.params)||void 0===i?void 0:i.apikey;if(n&&(this.accessTokenValue=n,this.apiKey=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(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(null==t?void 0:t.fetch),null==t?void 0:t.worker){if("undefined"!=typeof window&&!window.Worker)throw new Error("Web Worker is not supported");this.worker=(null==t?void 0:t.worker)||!1,this.workerUrl=null==t?void 0:t.workerUrl}this.accessToken=(null==t?void 0:t.accessToken)||null}connect(){if(!this.conn){if(this.transport)return this.conn=new this.transport(this.endpointURL(),void 0,{headers:this.headers}),void this.setupConnection();if(x)return this.conn=new WebSocket(this.endpointURL()),void this.setupConnection();this.conn=new C(this.endpointURL(),void 0,{close:()=>{this.conn=null}}),s.e(387).then(s.t.bind(s,387,23)).then(({default:e})=>{this.conn=new e(this.endpointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:"1.0.0"}))}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}async removeChannel(e){const t=await e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}async removeAllChannels(){const e=await 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 i.connecting:return l.Connecting;case i.open:return l.Open;case i.closing:return l.Closing;default:return l.Closed}}isConnected(){return this.connectionState()===l.Open}channel(e,t={config:{}}){const s=new A(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){const{topic:t,event:s,payload:r,ref:i}=e,n=()=>{this.encode(e,e=>{var t;null===(t=this.conn)||void 0===t||t.send(e)})};this.log("push",`${t} ${s} (${i})`,r),this.isConnected()?n():this.sendBuffer.push(n)}async setAuth(e=null){let t=e||this.accessToken&&await this.accessToken()||this.accessTokenValue;this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{t&&e.updateJoinPayload({access_token:t,version:this.headers&&this.headers["X-Client-Info"]}),e.joinedOnce&&e._isJoined()&&e._push(o.access_token,{access_token:t})}))}async 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}),await this.setAuth()}}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){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))}_onConnMessage(e){this.decode(e.data,e=>{let{topic:t,event:s,payload:r,ref:i}=e;i&&i===this.pendingHeartbeatRef&&(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))})}async _onConnOpen(){if(this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this.reconnectTimer.reset(),this.worker){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this.workerRef.terminate()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}else 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(o.error))}_appendParams(e,t){if(0===Object.keys(t).length)return e;const s=e.match(/\?/)?"&":"?";return`${e}${s}${new URLSearchParams(t)}`}_workerObjectUrl(e){let t;if(e)t=e;else{const e=new Blob(['\n addEventListener("message", (e) => {\n if (e.data.event === "start") {\n setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);\n }\n });'],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}}class C{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=i.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}}},595:function(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(s(663)),n=r(s(886)),o=s(639);t.default=class{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,this.action=e.action,this.relation=e.relation,this.logger=e.logger,this.onRequestError=e.onRequestError,e.fetch?this.fetch=e.fetch:"undefined"==typeof fetch?this.fetch=i.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=Object.assign({},this.headers),this.headers[e]=t,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");const s=this.fetch;let r;this.logger&&(r=o.traceIdGenerator.next(),this.logRequest(r));let i=s(this.url.toString(),{method:this.method,mode:"cors",redirect:"manual",credentials:"include",headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{var t,s,i,o;let a=null,l=null,c=null,u=e.status,h=e.statusText;if(e.ok){const r=await e.text(),i=JSON.parse(r);if(i.status_code&&i.error_msg)l=null,a={code:i.status_code,details:"",hint:"",message:i.error_msg};else{if("HEAD"!==this.method)if(""===r);else if("text/csv"===this.headers.Accept)l=r;else if(this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text"))l=r;else try{l=JSON.parse(r).data}catch(e){l=null,a=JSON.parse(r)}const i=null===(t=this.headers.Prefer)||void 0===t?void 0:t.match(/count=(exact|planned|estimated)/),n=null===(s=e.headers.get("content-range"))||void 0===s?void 0:s.split("/");i&&n&&n.length>1&&(c=parseInt(n[1])),this.isMaybeSingle&&"GET"===this.method&&Array.isArray(l)&&(l.length>1?(a={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:"",message:"JSON object requested, multiple (or no) rows returned"},l=null,c=null,u=406,h="Not Acceptable"):l=1===l.length?l[0]:null)}}else{const t=await e.text();try{const s=JSON.parse(t);a={code:s.status_code||e.status,details:"",hint:"",message:s.error_msg||t},Array.isArray(a)&&404===e.status&&(l=[],a=null,u=200,h="OK"),429===e.status&&(a={code:429,message:"Too many requests received within 5 seconds.",details:"",hint:"Retry after 5 seconds."})}catch(s){404===e.status&&""===t?(u=204,h="No Content"):a={message:t}}if(a&&this.isMaybeSingle&&(null===(i=null==a?void 0:a.details)||void 0===i?void 0:i.includes("0 rows"))&&(a=null,u=200,h="OK"),a&&this.shouldThrowOnError)throw new n.default(a)}const d={error:a,data:l,count:c,status:u,statusText:h};return a&&(null===(o=this.onRequestError)||void 0===o||o.call(this,Object.assign(Object.assign({},a),{status:u,statusText:h}))),this.logger&&this.logResponse(r,d),d});return this.shouldThrowOnError||(i=i.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:""}})),i.then(e,t)}logResponse(e,t){const{status:s,data:r,error:i,count:n}=t;console[i?"error":"log"](`[Dataloom] [Response ${i?"Failed":"Success"}]`,"trace id:",e,"table name:",this.relation,"statusCode:",s,"data:",r,"error:",i,"count:",n)}logRequest(e){const t=Array.from(this.url.searchParams.entries()).filter(([e])=>!["count","tx","missing","resolution","column"].includes(e)).map(([e,t])=>`${e}=${t}`);console.log("[Dataloom] [Request]","trace id:",e,"table name:",this.relation,"method:",this.method,"action:",this.action,"params:",t.join(","),"preferHeaders:",this.headers.Prefer,"body:",this.body,"schema:",this.schema)}returns(){return this}overrideTypes(){return this}}},597:function(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(s(705)),n=r(s(973));class o{constructor(e,{headers:t={},schema:s,fetch:r,logger:i,onRequestError:n}={}){this.url=e,this.headers=Object.assign({},t),this.schemaName=s,this.fetch=r,this.logger=i,this.onRequestError=n}from(e){const t=new URL(`${this.url}/${e}`);return new i.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch,logger:this.logger,relation:e,onRequestError:this.onRequestError})}schema(e){return new o(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:r=!1,count:i}={}){let o;const a=new URL(`${this.url}/rpc/${e}`);let l;s||r?(o=s?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{a.searchParams.append(e,t)})):(o="POST",l=t);const c=Object.assign({},this.headers);return i&&(c.Prefer=`count=${i}`),new n.default({method:o,url:a,headers:c,schema:this.schemaName,body:l,fetch:this.fetch,allowEmpty:!1,logger:this.logger,action:"rpc"})}}t.default=o},639:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.traceIdGenerator=t.TraceIdGenerator=void 0;class s{constructor(){this.counter=1}static getInstance(){return s.instance||(s.instance=new s),s.instance}next(){return this.counter++}getCurrent(){return this.counter}reset(){this.counter=1}}t.TraceIdGenerator=s;const r=s.getInstance();t.traceIdGenerator=r},645:(e,t,s)=>{s.r(t),s.d(t,{StorageApiError:()=>n,StorageClient:()=>P,StorageError:()=>r,StorageUnknownError:()=>o,isCustomError:()=>c,isSdkRateLimited:()=>l,isServerCustomError:()=>a,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,s){super(e),this.name="StorageApiError",this.status=t,this.statusCode=s}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class o extends r{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}const a=(e,t)=>!(!t||"TosServer"===e.headers.get("server"))||e.error_msg,l=e=>429===e.status&&"Too Many Requests"===e.statusText,c=e=>a(e)||l(e),u=2592e3,h=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>Promise.resolve().then(s.bind(s,663)).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},d=e=>e<1?1:e>u?u:e,f=e=>{var t,s,r,i,n,o,a,l,c,u,h,d,f,p,g,m,v,y;return Object.assign(Object.assign({},e),{buckets:{allowed_mime_types:null!==(s=null===(t=null==e?void 0:e.buckets)||void 0===t?void 0:t.allowed_mime_types)&&void 0!==s?s:[],created_at:null!==(i=null===(r=null==e?void 0:e.buckets)||void 0===r?void 0:r.created_at)&&void 0!==i?i:"",file_size_limit:null!==(o=null===(n=null==e?void 0:e.buckets)||void 0===n?void 0:n.file_size_limit)&&void 0!==o?o:0,id:null!==(l=null===(a=null==e?void 0:e.buckets)||void 0===a?void 0:a.id)&&void 0!==l?l:"",name:null!==(u=null===(c=null==e?void 0:e.buckets)||void 0===c?void 0:c.name)&&void 0!==u?u:"",public:null!==(d=null===(h=null==e?void 0:e.buckets)||void 0===h?void 0:h.public)&&void 0!==d&&d,updated_at:null!==(p=null===(f=null==e?void 0:e.buckets)||void 0===f?void 0:f.updated_at)&&void 0!==p?p:"",updated_by:null!==(m=null===(g=null==e?void 0:e.buckets)||void 0===g?void 0:g.updated_by)&&void 0!==m?m:"",owner:null!==(y=null===(v=null==e?void 0:e.buckets)||void 0===v?void 0:v.created_by)&&void 0!==y?y:""}})},p=/^https:\/\/[\w-]+\.tos-cn-beijing\.volces\.com\/.+/,g=(e,t,s="Storage")=>{const{data:r,error:i,status:n}=t;i?console.error(`[Dataloom][${s}][Response Failed]`,"trace id:",e,"statusCode:",n,"error:",i):console.log(`[Dataloom][${s}][Response Success]`,"trace id:",e,"statusCode:",n,"data:",r)};class m{constructor(){this.counter=1}static getInstance(){return m.instance||(m.instance=new m),m.instance}next(){return this.counter++}getCurrent(){return this.counter}reset(){this.counter=1}}const v=m.getInstance(),y=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e);async function w(e,t,r,i,c,u,h){let d=-1,f=200;const p=null==h?void 0:h.psmName;return(null==i?void 0:i.logFetch)&&(d=v.next(),((e,t="Storage")=>{const{traceId:s,url:r,method:i,body:n}=e,o=Array.from(new URL(r).searchParams.entries()).filter(([e])=>!["count","tx","missing","resolution","column"].includes(e)).map(([e,t])=>`${e}=${t}`);console.log(`[Dataloom][${t}][Request]`,"trace id:",s,"method:",i,"params:",o.join(","),"body:",n)})({traceId:d,url:r,method:t,body:u},p)),new Promise((h,m)=>{e(r,((e,t,s,r)=>{const i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&r?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(r)?(i.headers=Object.assign({"Content-Type":"application/json"},null==t?void 0:t.headers),i.body=JSON.stringify(r)):i.body=r,(null==t?void 0:t.duplex)&&(i.duplex=t.duplex),Object.assign(Object.assign({},i),s)):i})(t,i,c,u)).then(e=>{if(f=e.status,!e.ok)throw e;return(null==i?void 0:i.noResolveJson)?e:e.json()}).then(async e=>{var t;if(a(e))return null===(t=null==i?void 0:i.onRequestError)||void 0===t||t.call(i,{status:200,statusText:"",code:(null==e?void 0:e.status_code)||200,message:(null==e?void 0:e.error_msg)||"",details:"",hint:""}),(null==i?void 0:i.logFetch)&&g(d,{data:null,error:e,status:f},p),m(e);if(null==i?void 0:i.logFetch){let t=null,s=null;if(null==i?void 0:i.noResolveJson)try{"TosServer"===e.headers.get("server")||e.headers.get("etag")?t=await e.clone().text():s=await e.clone().json()}catch(e){s=y(e)}else t=e;g(d,{data:t,error:s,status:f},p)}return h(e)}).catch(e=>{(null==i?void 0:i.logFetch)&&g(d,{data:null,error:y(e),status:null==e?void 0:e.status},p),(async(e,t,r)=>{var i;const a=await(async()=>"undefined"==typeof Response?(await Promise.resolve().then(s.bind(s,663))).Response:Response)();if(l(e)){const e={code:429,message:"Too many requests received within 5 seconds.",details:"",hint:"Retry after 5 seconds."};return null===(i=null==r?void 0:r.onRequestError)||void 0===i||i.call(r,Object.assign({status:429,statusText:"Too Many Requests"},e)),t(e)}e instanceof a&&!(null==r?void 0:r.noResolveJson)?e.json().then(s=>{var i;const o=e.status||500,a=(null==s?void 0:s.statusCode)||o+"";null===(i=null==r?void 0:r.onRequestError)||void 0===i||i.call(r,{status:o,statusText:a,code:(null==s?void 0:s.status_code)||o,message:(null==s?void 0:s.error_msg)||"",details:"",hint:""}),t(new n(y(s),o,a))}).catch(e=>{t(new o(y(e),e))}):t(new o(y(e),e))})(e,m,i)})})}async function _(e,t,s,r,i){return w(e,"GET",t,s,r,void 0,i)}async function b(e,t,s,r,i,n){return w(e,"POST",t,r,i,s,n)}async function k(e,t,s,r,i,n){return w(e,"PUT",t,r,i,s,n)}async function S(e,t,s,r,i,n){return w(e,"DELETE",t,r,i,s,n)}const E={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},T={upsert:!1};class j{constructor(e,t={},s,r,i,n,o){this.url=e,this.headers=t,this.bucketId=s,this.appId=r,this.fetch=h(i),this.loggerEnabled=n,this.onRequestError=o}async uploadOrUpdate(e,t,s){var n,a,l,u,h,d,f,p;try{const i=Object.assign(Object.assign({},T),s),o=this._removeEmptyFolders(e);let c=null;(null==i?void 0:i.contentDisposition)?c=null==i?void 0:i.contentDisposition:t instanceof File&&(c=null==t?void 0:t.name);const g={bucket_id:null!==(n=this.bucketId)&&void 0!==n?n:"",file_size:(p=t,"undefined"!=typeof File&&p instanceof File||p instanceof Blob||p instanceof URLSearchParams?p.size.toString():"string"==typeof p?p.length.toString():ArrayBuffer.isView(p)||p instanceof ArrayBuffer?p.byteLength.toString():"0"),upsert:null!==(a=i.upsert)&&void 0!==a&&a,file_path:o,file_name:t instanceof File?null==t?void 0:t.name:""},m=await b(this.fetch,`${this.url}/object/${this.bucketId}/pre_upload`,g,{headers:this.headers,logFetch:this.loggerEnabled,onRequestError:this.onRequestError},void 0,{psmName:"Storage.Upload.PreUpload"}),{upload_id:v,upload_url:y}=null!==(l=null==m?void 0:m.data)&&void 0!==l?l:{};if(y&&v){const e={};c&&(e["content-disposition"]=`attachment; filename="${f=c,encodeURIComponent(f.replace(/[\x00-\x1F\x7F:"\\/*?<>|,;]/g,""))||"download_file"}"`),(i.cacheControl||0===i.cacheControl)&&(e["cache-control"]=`max-age=${i.cacheControl}`),i.contentType&&(e["content-type"]=i.contentType);const s=await k(this.fetch,y,t,{noResolveJson:!0,headers:e,logFetch:this.loggerEnabled,onRequestError:this.onRequestError},void 0,{psmName:"Storage.Upload.TosUpload"}),r=null!==(h=null===(u=null==s?void 0:s.headers)||void 0===u?void 0:u.get("Etag"))&&void 0!==h?h:"",n=await b(this.fetch,`${this.url}/object/callback`,{upload_id:v,etag:r,app_id:this.appId},{headers:this.headers,logFetch:this.loggerEnabled,onRequestError:this.onRequestError},void 0,{psmName:"Storage.Upload.Callback"});return{data:null!==(d=null==n?void 0:n.data)&&void 0!==d?d:{},error:null}}return{data:null,error:new r("upload_url or upload_id is empty")}}catch(e){return c(e)||i(e)?{data:null,error:e}:{data:null,error:new o("upload file error",e)}}}async upload(e,t,s){var r;const i=null!==t&&"object"==typeof t&&"function"==typeof t.pipe&&"function"==typeof t.on,n=t instanceof Blob||t instanceof ArrayBuffer||"undefined"!=typeof File&&t instanceof File||t instanceof FormData||t instanceof URLSearchParams||"undefined"!=typeof Buffer&&t instanceof Buffer||"undefined"!=typeof ReadableStream&&t instanceof ReadableStream||i||ArrayBuffer.isView(t)||"string"==typeof t;if("string"==typeof e&&n)return this.uploadOrUpdate(e,t,s);const o=t;return this.uploadOrUpdate(null!==(r=null==o?void 0:o.filePath)&&void 0!==r?r:"",e,o)}async uploadFile(e,t){var s;return this.uploadOrUpdate(null!==(s=null==t?void 0:t.filePath)&&void 0!==s?s:"",e,t)}async update(e,t,s){return this.uploadOrUpdate(e,t,s)}async createSignedUrl(e,t,s){try{let s=this._getFinalPath(e);return{data:(await b(this.fetch,`${this.url}/object/sign/${s}`,{expires_in:d(t)},{headers:this.headers,logFetch:this.loggerEnabled,onRequestError:this.onRequestError},void 0,{psmName:"Storage.CreateSignedUrl"})).data,error:null}}catch(e){return c(e)||i(e)?{data:null,error:e}:{data:null,error:new o("create signed url error",e)}}}async createSignedUrls(e,t,s){try{const s=e.map(e=>this._retrieveFilePathFromDownloadUrl(e));return{data:(await b(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expires_in:d(t),paths:s},{headers:this.headers,logFetch:this.loggerEnabled,onRequestError:this.onRequestError},void 0,{psmName:"Storage.CreateSignedUrls"})).data,error:null}}catch(e){return c(e)||i(e)?{data:null,error:e}:{data:null,error:new o("create signed urls error",e)}}}async download(e,t){try{const t=this._retrieveFilePathFromDownloadUrl(e),s=await _(this.fetch,`${this.url}/object/${this.bucketId}/${t}`,{headers:this.headers,noResolveJson:!0,logFetch:this.loggerEnabled,onRequestError:this.onRequestError},void 0,{psmName:"Storage.Download"});let r;return s.redirected?(r=await s.blob(),{data:r,error:null}):(r=await s.json(),{data:null,error:r})}catch(e){if(e&&"object"==typeof e&&"originalError"in e){const t=e.originalError;if(t instanceof Response&&t.redirected)try{return{data:null,error:new r(await t.text())}}catch(t){return{data:null,error:new o("download file error",e)}}}return c(e)||i(e)?{data:null,error:e}:{data:null,error:new o("download file error",e)}}}async remove(e){try{const t=e.map(e=>this._retrieveFilePathFromDownloadUrl(e));return{data:(await S(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers,logFetch:this.loggerEnabled,onRequestError:this.onRequestError},void 0,{psmName:"Storage.Remove"})).data.map(e=>f(e)),error:null}}catch(e){return c(e)||i(e)?{data:null,error:e}:{data:null,error:new o("remove file error",e)}}}async uploadFromUrl(e){try{let t;try{t=new URL(e)}catch(e){return{data:null,error:new r("Invalid URL provided")}}if("http:"!==t.protocol&&"https:"!==t.protocol)return{data:null,error:new r("Only http and https protocols are supported")};if((e=>p.test(e))(e))return{data:await this._copyWithinVolcEngine(e),error:null};const s=await this.fetch(e);if(!s.ok)return{data:null,error:new r(`Failed to download file from URL: ${s.status} ${s.statusText}`)};const i=(s.headers.get("content-type")||"").split(";")[0].trim().toLowerCase(),n=s.headers.get("content-disposition"),o=s.headers.get("cache-control"),a=await s.blob();if(0===a.size)return{data:null,error:new r("Downloaded file is empty")};const l={};if(i&&(l.contentType=i),n&&(l.contentDisposition=n),o){const e=o.match(/max-age=(\d+)/i);e&&(l.cacheControl=parseInt(e[1],10))}return this.uploadOrUpdate("",a,l)}catch(e){return c(e)||i(e)?{data:null,error:e}:{data:null,error:new o("copy from url error",e)}}}async list(e,t,s){try{const r=Object.assign(Object.assign(Object.assign({},E),t),{prefix:e||""});return{data:(await b(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers,logFetch:this.loggerEnabled,onRequestError:this.onRequestError},s,{psmName:"Storage.List"})).data.map(e=>f(e)),error:null}}catch(e){return c(e)||i(e)?{data:null,error:e}:{data:null,error:new o("list file error",e)}}}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return"undefined"!=typeof Buffer?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){let t=this._retrieveFilePathFromDownloadUrl(e);return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e?e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/"):e}_isValidDownloadUrl(e){return/^\/spark\/app\/app_[\w]+\/runtime\/api\/v1\/storage/.test(e)}_retrieveFilePathFromDownloadUrl(e){if(!this._isValidDownloadUrl(e))return e;const t=e.indexOf("/object/");if(-1===t)return"";const s=e.slice(t+8),r=s.indexOf("/");if(-1!==r){const e=s.slice(r+1);return decodeURIComponent(e)}return""}async _copyWithinVolcEngine(e){var t,s,r,i,n;const o=await b(this.fetch,`${this.url}/runtime/app/${this.appId}/object/${this.bucketId}/copy`,{source:{type:"externalTOS",externalURL:e}},{headers:this.headers,logFetch:this.loggerEnabled,onRequestError:this.onRequestError},void 0,{psmName:"Storage.Copy"}),{metadata:a}=null!==(t=null==o?void 0:o.data)&&void 0!==t?t:{};return{id:null!==(s=null==a?void 0:a.id)&&void 0!==s?s:"",file_path:null!==(r=null==a?void 0:a.filePath)&&void 0!==r?r:"",bucket_id:null!==(i=null==a?void 0:a.bucketID)&&void 0!==i?i:"",download_url:null!==(n=null==a?void 0:a.downloadURL)&&void 0!==n?n:""}}}const O={"X-Client-Info":"storage-js/0.0.0"};class R{constructor(e,t={},s,r){const i=new URL(e);this.url=i.href,this.headers=Object.assign(Object.assign({},O),t),this.fetch=h(s),this.onRequestError=null==r?void 0:r.onRequestError,this.appId=null==r?void 0:r.appId,(null==r?void 0:r.enableLogger)&&(this.loggerEnabled=!0)}async listBuckets(){try{return{data:await _(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}async getBucket(e){try{return{data:await _(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}async createBucket(e,t={public:!1}){try{return{data:await b(this.fetch,`${this.url}/bucket`,{id:e,name:e,type:t.type,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}}async updateBucket(e,t){try{return{data:await k(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}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}async emptyBucket(e){try{return{data:await b(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}async deleteBucket(e){try{return{data:await S(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}}class P extends R{constructor(e,t={},s,r){super(e,t,s,r)}from(e){return new j(this.url,this.headers,e,this.appId,this.fetch,this.loggerEnabled,this.onRequestError)}}},650:(e,t,s)=>{s.r(t),s.d(t,{AuthAdminApi:()=>ge,AuthApiError:()=>d,AuthClient:()=>me,AuthError:()=>u,AuthImplicitGrantRedirectError:()=>_,AuthInvalidCredentialsError:()=>w,AuthInvalidJwtError:()=>O,AuthInvalidTokenResponseError:()=>y,AuthPKCEGrantCodeExchangeError:()=>k,AuthRetryableFetchError:()=>S,AuthSessionMissingError:()=>m,AuthUnknownError:()=>p,AuthWeakPasswordError:()=>T,CustomAuthError:()=>g,GoTrueAdminApi:()=>ne,GoTrueClient:()=>pe,NavigatorLockAcquireTimeoutError:()=>ue,isAuthApiError:()=>f,isAuthError:()=>h,isAuthImplicitGrantRedirectError:()=>b,isAuthRetryableFetchError:()=>E,isAuthSessionMissingError:()=>v,isAuthWeakPasswordError:()=>j,lockInternals:()=>le,navigatorLock:()=>he});const r="0.0.1",i=3e4,n={"X-Client-Info":`gotrue-js/${r}`},o="X-Supabase-Api-Version",a=Date.parse("2024-01-01T00:00:00.0Z"),l="2024-01-01",c=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class u extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}}function h(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class d extends u{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}}function f(e){return h(e)&&"AuthApiError"===e.name}class p extends u{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class g extends u{constructor(e,t,s,r){super(e,s,r),this.name=t,this.status=s}}class m extends g{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function v(e){return h(e)&&"AuthSessionMissingError"===e.name}class y extends g{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class w extends g{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class _ extends g{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function b(e){return h(e)&&"AuthImplicitGrantRedirectError"===e.name}class k extends g{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class S extends g{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function E(e){return h(e)&&"AuthRetryableFetchError"===e.name}class T extends g{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}}function j(e){return h(e)&&"AuthWeakPasswordError"===e.name}class O extends g{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const R="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),P=" \t\n\r=".split(""),A=(()=>{const e=new Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<P.length;t+=1)e[P[t].charCodeAt(0)]=-2;for(let t=0;t<R.length;t+=1)e[R[t].charCodeAt(0)]=t;return e})();function I(e,t,s){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;s(R[e]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;s(R[e]),t.queuedBits-=6}}function x(e,t,s){const r=A[e];if(!(r>-1)){if(-2===r)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}for(t.queue=t.queue<<6|r,t.queuedBits+=6;t.queuedBits>=8;)s(t.queue>>t.queuedBits-8&255),t.queuedBits-=8}function $(e){const t=[],s=e=>{t.push(String.fromCodePoint(e))},r={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},n=e=>{!function(e,t,s){if(0===t.utf8seq){if(e<=127)return void s(e);for(let s=1;s<6;s+=1)if(!(e>>7-s&1)){t.utf8seq=s;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else{if(4!==t.utf8seq)throw new Error("Invalid UTF-8 sequence");t.codepoint=7&e}t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&s(t.codepoint)}}(e,r,s)};for(let t=0;t<e.length;t+=1)x(e.charCodeAt(t),i,n);return t.join("")}function C(e,t){if(!(e<=127)){if(e<=2047)return t(192|e>>6),void t(128|63&e);if(e<=65535)return t(224|e>>12),t(128|e>>6&63),void t(128|63&e);if(e<=1114111)return t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),void t(128|63&e);throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}t(e)}function L(e){const t=[],s={queue:0,queuedBits:0},r=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)x(e.charCodeAt(t),s,r);return new Uint8Array(t)}function U(e){const t=[],s={queue:0,queuedBits:0},r=e=>{t.push(e)};return e.forEach(e=>I(e,s,r)),I(null,s,r),t.join("")}const D=()=>"undefined"!=typeof window&&"undefined"!=typeof document,q={tested:!1,writable:!1},N=()=>{if(!D())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(q.tested)return q.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),q.tested=!0,q.writable=!0}catch(e){q.tested=!0,q.writable=!1}return q.writable},F=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>Promise.resolve().then(s.bind(s,663)).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},M=async(e,t,s)=>{await e.setItem(t,JSON.stringify(s))},B=async(e,t)=>{const s=await e.getItem(t);if(!s)return null;try{return JSON.parse(s)}catch(e){return s}},W=async(e,t)=>{await e.removeItem(t)};class J{constructor(){this.promise=new J.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function z(e){const t=e.split(".");if(3!==t.length)throw new O("Invalid JWT structure");for(let e=0;e<t.length;e++)if(!c.test(t[e]))throw new O("JWT not in base64url format");return{header:JSON.parse($(t[0])),payload:JSON.parse($(t[1])),signature:L(t[2]),raw:{header:t[0],payload:t[1]}}}function G(e){return("0"+e.toString(16)).substr(-2)}async function H(e,t,s=!1){const r=function(){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,G).join("")}();let i=r;s&&(i+="/PASSWORD_RECOVERY"),await M(e,`${t}-code-verifier`,i);const n=await async function(e){if("undefined"==typeof crypto||void 0===crypto.subtle||"undefined"==typeof TextEncoder)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(/=+$/,"")}(r);return[n,r===n?"plain":"s256"]}J.promiseConstructor=Promise;const K=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;const V=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Y=[502,503,504];async function Q(e){var t,s;if(!("object"==typeof(s=e)&&null!==s&&"status"in s&&"ok"in s&&"json"in s&&"function"==typeof s.json))throw new S(V(e),0);if(Y.includes(e.status))throw new S(V(e),e.status);let r,i;try{r=await e.json()}catch(e){throw new p(V(e),e)}const n=function(e){const t=e.headers.get(o);if(!t)return null;if(!t.match(K))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(e){return null}}(e);if(n&&n.getTime()>=a&&"object"==typeof r&&r&&"string"==typeof r.code?i=r.code:"object"==typeof r&&r&&"string"==typeof r.error_code&&(i=r.error_code),i){if("weak_password"===i)throw new T(V(r),e.status,(null===(t=r.weak_password)||void 0===t?void 0:t.reasons)||[]);if("session_not_found"===i)throw new m}else if("object"==typeof r&&r&&"object"==typeof r.weak_password&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new T(V(r),e.status,r.weak_password.reasons);throw new d(V(r),e.status||500,i)}async function X(e,t,s,r){var i;const n=Object.assign({},null==r?void 0:r.headers);n[o]||(n[o]=l),(null==r?void 0:r.jwt)&&(n.Authorization=`Bearer ${r.jwt}`);const a=null!==(i=null==r?void 0:r.query)&&void 0!==i?i:{};(null==r?void 0:r.redirectTo)&&(a.redirect_to=r.redirectTo);const c=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",u=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,Object.assign({},o))}catch(e){throw console.error(e),new S(V(e),0)}if(a.ok||await Q(a),null==r?void 0:r.noResolveJson)return a;try{return await a.json()}catch(e){await Q(e)}}(e,t,s+c,{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(u):{data:Object.assign({},u),error:null}}function Z(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 ee(e){const t=Z(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function te(e){var t;return{data:{user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function se(e){return{data:e,error:null}}function re(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 ie(e){return e}class ne{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=F(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await X(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(h(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await X(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:te})}catch(e){if(h(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 X(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:re,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(h(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await X(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:te})}catch(e){if(h(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,s,r,i,n,o,a;try{const l={nextPage:null,lastPage:0,total:0},c=await X(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:ie});if(c.error)throw c.error;const u=await c.json(),h=null!==(n=c.headers.get("x-total-count"))&&void 0!==n?n:0,d=null!==(a=null===(o=c.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]);l[`${s}Page`]=t}),l.total=parseInt(h)),{data:Object.assign(Object.assign({},u),l),error:null}}catch(e){if(h(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){try{return await X(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:te})}catch(e){if(h(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){try{return await X(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:te})}catch(e){if(h(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){try{return await X(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:te})}catch(e){if(h(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){try{const{data:t,error:s}=await X(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(h(e))return{data:null,error:e};throw e}}async _deleteFactor(e){try{return{data:await X(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(h(e))return{data:null,error:e};throw e}}}const oe={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 ae(e={}){return{getItem:t=>e[t]||null,setItem:(t,s)=>{e[t]=s},removeItem:t=>{delete e[t]}}}const le={debug:!!(globalThis&&N()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"))};class ce extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class ue extends ce{}async function he(e,t,s){le.debug&&console.log("@data-loom/gotrue-js: navigatorLock: acquire lock",e,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),le.debug&&console.log("@data-loom/gotrue-js: navigatorLock acquire timed out",e)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async r=>{if(!r){if(0===t)throw le.debug&&console.log("@data-loom/gotrue-js: navigatorLock: not immediately available",e),new ue(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(le.debug)try{const e=await globalThis.navigator.locks.query();console.log("@data-loom/gotrue-js: Navigator LockManager state",JSON.stringify(e,null," "))}catch(e){console.warn("@data-loom/gotrue-js: Error when querying Navigator LockManager state",e)}return console.warn("@data-loom/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()}le.debug&&console.log("@data-loom/gotrue-js: navigatorLock: acquired",e,r.name);try{return await s()}finally{le.debug&&console.log("@data-loom/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 de={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:n,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function fe(e,t,s){return await s()}class pe{constructor(e){var t,s;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=pe.nextInstanceID,pe.nextInstanceID+=1,this.instanceID>0&&D()&&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({},de),e);if(this.logDebugMessages=!!r.debug,"function"==typeof r.debug&&(this.logger=r.debug),this.persistSession=r.persistSession,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.admin=new ne({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=F(r.fetch),this.lock=r.lock||fe,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,r.lock?this.lock=r.lock:D()&&(null===(t=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===t?void 0:t.locks)?this.lock=he:this.lock=fe,this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?r.storage?this.storage=r.storage:N()?this.storage=oe:(this.memoryStorage={},this.storage=ae(this.memoryStorage)):(this.memoryStorage={},this.storage=ae(this.memoryStorage)),D()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null===(s=this.broadcastChannel)||void 0===s||s.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&&this.logger(`GoTrueClient@${this.instanceID} (${r}) ${(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(){var e;try{const t=function(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}(window.location.href);let s="none";if(this._isImplicitGrantCallback(t)?s="implicit":await this._isPKCECallback(t)&&(s="pkce"),D()&&this.detectSessionInUrl&&"none"!==s){const{data:r,error:i}=await this._getSessionFromURL(t,s);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),b(i)){const t=null===(e=i.details)||void 0===e?void 0:e.code;if("identity_already_exists"===t||"identity_not_found"===t||"single_identity_not_deletable"===t)return{error:i}}return await this._removeSession(),{error:i}}const{session:n,redirectType:o}=r;return this._debug("#_initialize()","detected session in URL",n,"redirect type",o),await this._saveSession(n),setTimeout(async()=>{"recovery"===o?await this._notifyAllSubscribers("PASSWORD_RECOVERY",n):await this._notifyAllSubscribers("SIGNED_IN",n)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return h(e)?{error:e}:{error:new p("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,r;try{const i=await X(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!==(s=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.data)&&void 0!==s?s:{},gotrue_meta_security:{captcha_token:null===(r=null==e?void 0:e.options)||void 0===r?void 0:r.captchaToken}},xform:Z}),{data:n,error:o}=i;if(o||!n)return{data:{user:null,session:null},error:o};const a=n.session,l=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:l,session:a},error:null}}catch(e){if(h(e))return{data:{user:null,session:null},error:e};throw e}}async signUp(e){var t,s,r;try{let i;if("email"in e){const{email:s,password:r,options:n}=e;let o=null,a=null;"pkce"===this.flowType&&([o,a]=await H(this.storage,this.storageKey)),i=await X(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:Z})}else{if(!("phone"in e))throw new w("You must provide either an email or phone number and a password");{const{phone:t,password:n,options:o}=e;i=await X(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:Z})}}const{data:n,error:o}=i;if(o||!n)return{data:{user:null,session:null},error:o};const a=n.session,l=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:l,session:a},error:null}}catch(e){if(h(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithPassword(e){try{let t;if("email"in e){const{email:s,password:r,options:i}=e;t=await X(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:ee})}else{if(!("phone"in e))throw new w("You must provide either an email or phone number and a password");{const{phone:s,password:r,options:i}=e;t=await X(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:ee})}}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:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:r}):{data:{user:null,session:null},error:new y}}catch(e){if(h(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithOAuth(e){var t,s,r,i;return 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 signInWithWeb3(e){const{chain:t}=e;if("solana"===t)return await this.signInWithSolana(e);throw new Error(`@data-loom/auth-js: Unsupported chain "${t}"`)}async signInWithSolana(e){var t,s,r,i,n,o,a,l,c,u,d,f;let p,g;if("message"in e)p=e.message,g=e.signature;else{const{chain:h,wallet:d,statement:f,options:m}=e;let v;if(D())if("object"==typeof d)v=d;else{const e=window;if(!("solana"in e)||"object"!=typeof e.solana||!("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))throw new Error("@data-loom/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.");v=e.solana}else{if("object"!=typeof d||!(null==m?void 0:m.url))throw new Error("@data-loom/auth-js: Both wallet and url must be specified in non-browser environments.");v=d}const y=new URL(null!==(t=null==m?void 0:m.url)&&void 0!==t?t:window.location.href);if("signIn"in v&&v.signIn){const e=await v.signIn(Object.assign(Object.assign(Object.assign({issuedAt:(new Date).toISOString()},null==m?void 0:m.signInWithSolana),{version:"1",domain:y.host,uri:y.href}),f?{statement:f}:null));let t;if(Array.isArray(e)&&e[0]&&"object"==typeof e[0])t=e[0];else{if(!(e&&"object"==typeof e&&"signedMessage"in e&&"signature"in e))throw new Error("@data-loom/auth-js: Wallet method signIn() returned unrecognized value");t=e}if(!("signedMessage"in t&&"signature"in t&&("string"==typeof t.signedMessage||t.signedMessage instanceof Uint8Array)&&t.signature instanceof Uint8Array))throw new Error("@data-loom/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields");p="string"==typeof t.signedMessage?t.signedMessage:(new TextDecoder).decode(t.signedMessage),g=t.signature}else{if(!("signMessage"in v&&"function"==typeof v.signMessage&&"publicKey"in v&&"object"==typeof v&&v.publicKey&&"toBase58"in v.publicKey&&"function"==typeof v.publicKey.toBase58))throw new Error("@data-loom/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${y.host} wants you to sign in with your Solana account:`,v.publicKey.toBase58(),...f?["",f,""]:[""],"Version: 1",`URI: ${y.href}`,`Issued At: ${null!==(r=null===(s=null==m?void 0:m.signInWithSolana)||void 0===s?void 0:s.issuedAt)&&void 0!==r?r:(new Date).toISOString()}`,...(null===(i=null==m?void 0:m.signInWithSolana)||void 0===i?void 0:i.notBefore)?[`Not Before: ${m.signInWithSolana.notBefore}`]:[],...(null===(n=null==m?void 0:m.signInWithSolana)||void 0===n?void 0:n.expirationTime)?[`Expiration Time: ${m.signInWithSolana.expirationTime}`]:[],...(null===(o=null==m?void 0:m.signInWithSolana)||void 0===o?void 0:o.chainId)?[`Chain ID: ${m.signInWithSolana.chainId}`]:[],...(null===(a=null==m?void 0:m.signInWithSolana)||void 0===a?void 0:a.nonce)?[`Nonce: ${m.signInWithSolana.nonce}`]:[],...(null===(l=null==m?void 0:m.signInWithSolana)||void 0===l?void 0:l.requestId)?[`Request ID: ${m.signInWithSolana.requestId}`]:[],...(null===(u=null===(c=null==m?void 0:m.signInWithSolana)||void 0===c?void 0:c.resources)||void 0===u?void 0:u.length)?["Resources",...m.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");const e=await v.signMessage((new TextEncoder).encode(p),"utf8");if(!(e&&e instanceof Uint8Array))throw new Error("@data-loom/auth-js: Wallet signMessage() API returned an recognized value");g=e}}try{const{data:t,error:s}=await X(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:U(g)},(null===(d=e.options)||void 0===d?void 0:d.captchaToken)?{gotrue_meta_security:{captcha_token:null===(f=e.options)||void 0===f?void 0:f.captchaToken}}:null),xform:Z});if(s)throw s;return t&&t.session&&t.user?(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),{data:Object.assign({},t),error:s}):{data:{user:null,session:null},error:new y}}catch(e){if(h(e))return{data:{user:null,session:null},error:e};throw e}}async _exchangeCodeForSession(e){const t=await B(this.storage,`${this.storageKey}-code-verifier`),[s,r]=(null!=t?t:"").split("/");try{const{data:t,error:i}=await X(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:Z});if(await W(this.storage,`${this.storageKey}-code-verifier`),i)throw i;return t&&t.session&&t.user?(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),{data:Object.assign(Object.assign({},t),{redirectType:null!=r?r:null}),error:i}):{data:{user:null,session:null,redirectType:null},error:new y}}catch(e){if(h(e))return{data:{user:null,session:null,redirectType:null},error:e};throw e}}async signInWithIdToken(e){try{const{options:t,provider:s,token:r,access_token:i,nonce:n}=e,o=await X(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:Z}),{data:a,error:l}=o;return l?{data:{user:null,session:null},error:l}:a&&a.session&&a.user?(a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),{data:a,error:l}):{data:{user:null,session:null},error:new y}}catch(e){if(h(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithOtp(e){var t,s,r,i,n;try{if("email"in e){const{email:r,options:i}=e;let n=null,o=null;"pkce"===this.flowType&&([n,o]=await H(this.storage,this.storageKey));const{error:a}=await X(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 X(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 w("You must provide either an email or phone number.")}catch(e){if(h(e))return{data:{user:null,session:null},error:e};throw e}}async verifyOtp(e){var t,s;try{let r,i;"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 X(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:r,xform:Z});if(o)throw o;if(!n)throw new Error("An error occurred on token verification.");const a=n.session,l=n.user;return(null==a?void 0:a.access_token)&&(await this._saveSession(a),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",a)),{data:{user:l,session:a},error:null}}catch(e){if(h(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithSSO(e){var t,s,r;try{let i=null,n=null;return"pkce"===this.flowType&&([i,n]=await H(this.storage,this.storageKey)),await X(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,code_challenge:i,code_challenge_method:n}),headers:this.headers,xform:se})}catch(e){if(h(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 m;const{error:r}=await X(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:r}})}catch(e){if(h(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:s,type:r,options:i}=e,{error:n}=await X(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 X(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 w("You must provide either an email or phone number and a type")}catch(e){if(h(e))return{data:{user:null,session:null},error:e};throw e}}async getSession(){return await this.initializePromise,await 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;const t=await B(this.storage,this.storageKey);if(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())),!e)return{data:{session:null},error:null};const s=!!e.expires_at&&1e3*e.expires_at-Date.now()<9e4;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.storage.isServer){let t=this.suppressGetSessionWarning;e=new Proxy(e,{get:(e,s,r)=>(t||"user"!==s||(console.warn("Using the user object as returned from dataloom.auth.getSession() or from some dataloom.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use dataloom.auth.getUser() instead which authenticates the data by contacting the Dataloom Auth server."),t=!0,this.suppressGetSessionWarning=!0),Reflect.get(e,s,r))})}return{data:{session:e},error:null}}const{session:r,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{data:{session:r},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await X(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:te}):await this._useSession(async e=>{var t,s,r;const{data:i,error:n}=e;if(n)throw n;return(null===(t=i.session)||void 0===t?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await X(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(r=null===(s=i.session)||void 0===s?void 0:s.access_token)&&void 0!==r?r:void 0,xform:te}):{data:{user:null},error:new m}})}catch(e){if(h(e))return v(e)&&(await this._removeSession(),await W(this.storage,`${this.storageKey}-code-verifier`)),{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 m;const n=r.session;let o=null,a=null;"pkce"===this.flowType&&null!=e.email&&([o,a]=await H(this.storage,this.storageKey));const{data:l,error:c}=await X(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:te});if(c)throw c;return n.user=l.user,await this._saveSession(n),await this._notifyAllSubscribers("USER_UPDATED",n),{data:{user:n.user},error:null}})}catch(e){if(h(e))return{data:{user:null},error:e};throw 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 m;const t=Date.now()/1e3;let s=t,r=!0,i=null;const{payload:n}=z(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(h(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 m;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(h(e))return{data:{user:null,session:null},error:e};throw e}}async _getSessionFromURL(e,t){try{if(!D())throw new _("No browser detected.");if(e.error||e.error_description||e.error_code)throw new _(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if("pkce"===this.flowType)throw new k("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new _("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new k("No code detected.");const{data:t,error:s}=await this._exchangeCodeForSession(e.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:t.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:r,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!(n&&a&&o&&c))throw new _("No session defined in URL");const u=Math.round(Date.now()/1e3),h=parseInt(a);let d=u+h;l&&(d=parseInt(l));const f=d-u;1e3*f<=i&&console.warn(`@data-loom/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${h}s`);const p=d-h;u-p>=120?console.warn("@data-loom/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,d,u):u-p<0&&console.warn("@data-loom/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",p,d,u);const{data:g,error:m}=await this._getUser(n);if(m)throw m;const v={provider_token:s,provider_refresh_token:r,access_token:n,expires_in:h,expires_at:d,refresh_token:o,token_type:c,user:g.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:v,redirectType:e.type},error:null}}catch(e){if(h(e))return{data:{session:null,redirectType:null},error:e};throw e}}_isImplicitGrantCallback(e){return Boolean(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await B(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&&(!f(t)||404!==t.status&&401!==t.status&&403!==t.status))return{error:t}}return"others"!==e&&(await this._removeSession(),await W(this.storage,`${this.storageKey}-code-verifier`)),{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;"pkce"===this.flowType&&([s,r]=await H(this.storage,this.storageKey,!0));try{return await X(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(h(e))return{data:null,error:e};throw e}}async getUserIdentities(){var e;try{const{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:null!==(e=t.user.identities)&&void 0!==e?e:[]},error:null}}catch(e){if(h(e))return{data:null,error:e};throw e}}async linkIdentity(e){var t;try{const{data:s,error:r}=await this._useSession(async t=>{var s,r,i,n,o;const{data:a,error:l}=t;if(l)throw l;const c=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null===(s=e.options)||void 0===s?void 0:s.redirectTo,scopes:null===(r=e.options)||void 0===r?void 0:r.scopes,queryParams:null===(i=e.options)||void 0===i?void 0:i.queryParams,skipBrowserRedirect:!0});return await X(this.fetch,"GET",c,{headers:this.headers,jwt:null!==(o=null===(n=a.session)||void 0===n?void 0:n.access_token)&&void 0!==o?o:void 0})});if(r)throw r;return D()&&!(null===(t=e.options)||void 0===t?void 0:t.skipBrowserRedirect)&&window.location.assign(null==s?void 0:s.url),{data:{provider:e.provider,url:null==s?void 0:s.url},error:null}}catch(t){if(h(t))return{data:{provider:e.provider,url:null},error:t};throw t}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,r;const{data:i,error:n}=t;if(n)throw n;return await X(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!==(r=null===(s=i.session)||void 0===s?void 0:s.access_token)&&void 0!==r?r:void 0})})}catch(e){if(h(e))return{data:null,error:e};throw e}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const n=Date.now();return await(s=async s=>(s>0&&await async function(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await X(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Z})),r=(e,t)=>{const s=200*Math.pow(2,e);return t&&E(t)&&Date.now()+s-n<i},new Promise((e,t)=>{(async()=>{for(let i=0;i<1/0;i++)try{const t=await s(i);if(!r(i,null))return void e(t)}catch(e){if(!r(i,e))return void t(e)}})()}))}catch(e){if(this._debug(t,"error",e),h(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(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),D()&&!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 B(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=1e3*(null!==(e=s.expires_at)&&void 0!==e?e:1/0)-Date.now()<9e4;if(this._debug(t,`session has${r?"":" not"} expired with margin of 90000s`),r){if(this.autoRefreshToken&&s.refresh_token){const{error:e}=await this._callRefreshToken(s.refresh_token);e&&(console.error(e),E(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 m;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new J;const{data:t,error:s}=await this._refreshAccessToken(e);if(s)throw s;if(!t.session)throw new m;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),h(e)){const s={session:null,error:e};return E(e)||await this._removeSession(),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.suppressGetSessionWarning=!0,await M(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await W(this.storage,this.storageKey),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&D()&&(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(),i);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)/i);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 ce))throw e;this._debug("auto refresh token tick lock not available")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!D()||!(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,s){const r=[`provider=${encodeURIComponent(t)}`];if((null==s?void 0:s.redirectTo)&&r.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),(null==s?void 0:s.scopes)&&r.push(`scopes=${encodeURIComponent(s.scopes)}`),"pkce"===this.flowType){const[e,t]=await H(this.storage,this.storageKey),s=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});r.push(s.toString())}if(null==s?void 0:s.queryParams){const e=new URLSearchParams(s.queryParams);r.push(e.toString())}return(null==s?void 0:s.skipBrowserRedirect)&&r.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${r.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 X(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(h(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 o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:{issuer:e.issuer}),{data:a,error:l}=await X(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:null===(s=null==i?void 0:i.session)||void 0===s?void 0:s.access_token});return l?{data:null,error:l}:("totp"===e.factorType&&(null===(r=null==a?void 0:a.totp)||void 0===r?void 0:r.qr_code)&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(e){if(h(e))return{data:null,error:e};throw e}}async _verify(e){return this._acquireLock(-1,async()=>{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 X(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(h(e))return{data:null,error:e};throw e}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;const{data:r,error:i}=t;return i?{data:null,error:i}:await X(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},headers:this.headers,jwt:null===(s=null==r?void 0:r.session)||void 0===s?void 0:s.access_token})})}catch(e){if(h(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),i=s.filter(e=>"phone"===e.factor_type&&"verified"===e.status);return{data:{all:s,totp:r,phone:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>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{payload:n}=z(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}}))}async fetchJwk(e,t={keys:[]}){let s=t.keys.find(t=>t.kid===e);if(s)return s;if(s=this.jwks.keys.find(t=>t.kid===e),s&&this.jwks_cached_at+6e5>Date.now())return s;const{data:r,error:i}=await X(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;if(!r.keys||0===r.keys.length)throw new O("JWKS is empty");if(this.jwks=r,this.jwks_cached_at=Date.now(),s=r.keys.find(t=>t.kid===e),!s)throw new O("No matching signing key found in JWKS");return s}async getClaims(e,t={keys:[]}){try{let s=e;if(!s){const{data:e,error:t}=await this.getSession();if(t||!e.session)return{data:null,error:t};s=e.session.access_token}const{header:r,payload:i,signature:n,raw:{header:o,payload:a}}=z(s);if(function(e){if(!e)throw new Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw new Error("JWT has expired")}(i.exp),!r.kid||"HS256"===r.alg||!("crypto"in globalThis)||!("subtle"in globalThis.crypto)){const{error:e}=await this.getUser(s);if(e)throw e;return{data:{claims:i,header:r,signature:n},error:null}}const l=function(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}(r.alg),c=await this.fetchJwk(r.kid,t),u=await crypto.subtle.importKey("jwk",c,l,!0,["verify"]);if(!await crypto.subtle.verify(l,u,n,function(e){const t=[];return function(e,t){for(let s=0;s<e.length;s+=1){let r=e.charCodeAt(s);if(r>55295&&r<=56319){const t=1024*(r-55296)&65535;r=65536+(e.charCodeAt(s+1)-56320&65535|t),s+=1}C(r,t)}}(e,e=>t.push(e)),new Uint8Array(t)}(`${o}.${a}`)))throw new O("Invalid JWT signature");return{data:{claims:i,header:r,signature:n},error:null}}catch(e){if(h(e))return{data:null,error:e};throw e}}}pe.nextInstanceID=0;const ge=ne,me=pe},663:(e,t,s)=>{s.r(t),s.d(t,{Headers:()=>o,Request:()=>a,Response:()=>l,default:()=>n,fetch:()=>i});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")}();const i=r.fetch,n=r.fetch.bind(r),o=r.Headers,a=r.Request,l=r.Response},699:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0});class s{constructor(e){this.maxRequests=e,this.windowSizeMs=s.WINDOW_SIZE,this.requestCount=0,this.windowStart=Date.now()}checkAndResetWindow(){const e=Date.now();return e-this.windowStart>=this.windowSizeMs&&(this.requestCount=0,this.windowStart=e,!0)}canRequest(){return this.checkAndResetWindow(),this.requestCount<this.maxRequests&&(this.requestCount++,!0)}}s.WINDOW_SIZE=5e3,t.default=s},705:function(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(s(973));t.default=class{constructor(e,{headers:t={},schema:s,fetch:r,relation:i,logger:n,onRequestError:o}){this.url=e,this.headers=t,this.schema=s,this.fetch=r,this.relation=i,this.logger=n,this.onRequestError=o}select(e,{head:t=!1,count:s}={}){let r=!1;const n=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!r?"":('"'===e&&(r=!r),e)).join("");return this.url.searchParams.set("select",n),s&&(this.headers.Prefer=`count=${s}`),new i.default({method:"GET",url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1,logger:this.logger,onRequestError:this.onRequestError,relation:this.relation,action:"select"})}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 i.default({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1,logger:this.logger,onRequestError:this.onRequestError,relation:this.relation,action:"insert"})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:r,defaultToNull:n=!0}={}){const o=[`resolution=${s?"ignore":"merge"}-duplicates`];if(void 0!==t&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&o.push(this.headers.Prefer),r&&o.push(`count=${r}`),n||o.push("missing=default"),this.headers.Prefer=o.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 i.default({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1,logger:this.logger,onRequestError:this.onRequestError,relation:this.relation,action:"upsert"})}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 i.default({method:"PATCH",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1,logger:this.logger,onRequestError:this.onRequestError,relation:this.relation,action:"update"})}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 i.default({method:"DELETE",url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1,logger:this.logger,onRequestError:this.onRequestError,relation:this.relation,action:"delete"})}}},739:function(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PostgrestError=t.PostgrestBuilder=t.PostgrestTransformBuilder=t.PostgrestFilterBuilder=t.PostgrestQueryBuilder=t.PostgrestClient=void 0;const i=r(s(597));t.PostgrestClient=i.default;const n=r(s(705));t.PostgrestQueryBuilder=n.default;const o=r(s(973));t.PostgrestFilterBuilder=o.default;const a=r(s(817));t.PostgrestTransformBuilder=a.default;const l=r(s(595));t.PostgrestBuilder=l.default;const c=r(s(886));t.PostgrestError=c.default,t.default={PostgrestClient:i.default,PostgrestQueryBuilder:n.default,PostgrestFilterBuilder:o.default,PostgrestTransformBuilder:a.default,PostgrestBuilder:l.default,PostgrestError:c.default}},755:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.version=void 0,t.version="0.0.0-automated"},817:function(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(s(595));class n extends i.default{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,referencedTable:i=r}={}){const n=i?`${i}.order`:"order",o=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${o?`${o},`:""}${e}.${t?"asc":"desc"}${void 0===s?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){const r=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:r=s}={}){const i=void 0===r?"offset":`${r}.offset`,n=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(n,""+(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.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"}={}){var o;const a=[e?"analyze":null,t?"verbose":null,s?"settings":null,r?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=null!==(o=this.headers.Accept)&&void 0!==o?o:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${n}; for="${l}"; options=${a};`,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}}t.default=n},886:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0});class s extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}}t.default=s},946:function(e,t){var s=this&&this.__awaiter||function(e,t,s,r){return new(s||(s=Promise))(function(i,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(o,a)}l((r=r.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.applySettingDefaults=t.isBrowser=t.stripTrailingSlash=t.deleteQueryFromUrl=t.getQueryFromUrl=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.getQueryFromUrl=function(e){return new URLSearchParams(window.location.search).get(e)},t.deleteQueryFromUrl=function(e){const t=new URL(window.location),s=new URLSearchParams(t.search);s.delete(e),t.search=s.toString(),history.replaceState(null,"",t.toString())},t.stripTrailingSlash=function(e){return e.replace(/\/$/,"")},t.isBrowser=()=>"undefined"!=typeof window,t.applySettingDefaults=function(e,t){const{db:r,auth:i,realtime:n,global:o}=e,{db:a,auth:l,realtime:c,global:u}=t,h={db:Object.assign(Object.assign({},a),r),auth:Object.assign(Object.assign({},l),i),realtime:Object.assign(Object.assign({},c),n),global:Object.assign(Object.assign({brandName:"",appId:""},u),o),accessToken:()=>s(this,void 0,void 0,function*(){return""})};return e.accessToken?h.accessToken=e.accessToken:delete h.accessToken,h}},973:function(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(s(817));class n extends i.default{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=Array.from(new Set(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}group(){return console.error("[Dataloom] group is not supported"),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,referencedTable:s=t}={}){const r=s?`${s}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}}t.default=n}},n={};function o(e){var t=n[e];if(void 0!==t)return t.exports;var s=n[e]={exports:{}};return i[e].call(s.exports,s,s.exports,o),s.exports}return o.m=i,t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,o.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 i=Object.create(null);o.r(i);var n={};e=e||[null,t({}),t([]),t(t)];for(var a=2&r&&s;("object"==typeof a||"function"==typeof a)&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach(e=>n[e]=()=>s[e]);return n.default=()=>s,o.d(i,n),i},o.d=(e,t)=>{for(var s in t)o.o(t,s)&&!o.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},o.f={},o.e=e=>Promise.all(Object.keys(o.f).reduce((t,s)=>(o.f[s](e,t),t),[])),o.u=e=>e+".dataloom.js",o.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),s={},r="dataloom:",o.l=(e,t,i,n)=>{if(s[e])s[e].push(t);else{var a,l;if(void 0!==i)for(var c=document.getElementsByTagName("script"),u=0;u<c.length;u++){var h=c[u];if(h.getAttribute("src")==e||h.getAttribute("data-webpack")==r+i){a=h;break}}a||(l=!0,(a=document.createElement("script")).charset="utf-8",a.timeout=120,o.nc&&a.setAttribute("nonce",o.nc),a.setAttribute("data-webpack",r+i),a.src=e),s[e]=[t];var d=(t,r)=>{a.onerror=a.onload=null,clearTimeout(f);var i=s[e];if(delete s[e],a.parentNode&&a.parentNode.removeChild(a),i&&i.forEach(e=>e(r)),t)return t(r)},f=setTimeout(d.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=d.bind(null,a.onerror),a.onload=d.bind(null,a.onload),l&&document.head.appendChild(a)}},o.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;o.g.importScripts&&(e=o.g.location+"");var t=o.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var s=t.getElementsByTagName("script");if(s.length)for(var r=s.length-1;r>-1&&(!e||!/^http(s?):/.test(e));)e=s[r--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),o.p=e})(),(()=>{var e={792:0};o.f.j=(t,s)=>{var r=o.o(e,t)?e[t]:void 0;if(0!==r)if(r)s.push(r[2]);else{var i=new Promise((s,i)=>r=e[t]=[s,i]);s.push(r[2]=i);var n=o.p+o.u(t),a=new Error;o.l(n,s=>{if(o.o(e,t)&&(0!==(r=e[t])&&(e[t]=void 0),r)){var i=s&&("load"===s.type?"missing":s.type),n=s&&s.target&&s.target.src;a.message="Loading chunk "+t+" failed.\n("+i+": "+n+")",a.name="ChunkLoadError",a.type=i,a.request=n,r[1](a)}},"chunk-"+t,t)}};var t=(t,s)=>{var r,i,[n,a,l]=s,c=0;if(n.some(t=>0!==e[t])){for(r in a)o.o(a,r)&&(o.m[r]=a[r]);l&&l(o)}for(t&&t(s);c<n.length;c++)i=n[c],o.o(e,i)&&e[i]&&e[i][0](),e[i]=0},s=self.webpackChunkdataloom=self.webpackChunkdataloom||[];s.forEach(t.bind(null,0)),s.push=t.bind(null,s.push.bind(s))})(),o(93)})());
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.dataloom=t():e.dataloom=t()}(self,()=>(()=>{"use strict";var e,t,s,r,i={93:function(e,t,s){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.DataloomClient=t.FunctionRegion=t.FunctionsError=t.FunctionsRelayError=t.FunctionsFetchError=t.FunctionsHttpError=t.PostgrestError=void 0;const o=n(s(399));i(s(650),t);var a=s(739);Object.defineProperty(t,"PostgrestError",{enumerable:!0,get:function(){return a.PostgrestError}});var l=s(231);Object.defineProperty(t,"FunctionsHttpError",{enumerable:!0,get:function(){return l.FunctionsHttpError}}),Object.defineProperty(t,"FunctionsFetchError",{enumerable:!0,get:function(){return l.FunctionsFetchError}}),Object.defineProperty(t,"FunctionsRelayError",{enumerable:!0,get:function(){return l.FunctionsRelayError}}),Object.defineProperty(t,"FunctionsError",{enumerable:!0,get:function(){return l.FunctionsError}}),Object.defineProperty(t,"FunctionRegion",{enumerable:!0,get:function(){return l.FunctionRegion}}),i(s(587),t);var c=s(399);Object.defineProperty(t,"DataloomClient",{enumerable:!0,get:function(){return n(c).default}}),t.createClient=(e,t,s,r)=>new o.default(e,t,s,r)},150:(e,t,s)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_REALTIME_OPTIONS=t.DEFAULT_AUTH_OPTIONS=t.DEFAULT_DB_OPTIONS=t.DEFAULT_GLOBAL_OPTIONS=t.DEFAULT_HEADERS=void 0;const r=s(946),i=s(755);let n="";n="undefined"!=typeof Deno?"deno":"undefined"!=typeof document?"web":"undefined"!=typeof navigator&&"ReactNative"===navigator.product?"react-native":"node",t.DEFAULT_HEADERS={"X-Client-Info":`dataloom-js-${n}/${i.version}`,"X-Suda-Token":(()=>{if(!(0,r.isBrowser)())return"";const e=window.location.host.replace(/\./g,"-"),t=(0,r.getQueryFromUrl)("suda_token");if(t)return localStorage.setItem(`suda_token_${e}`,`${t}`),(0,r.deleteQueryFromUrl)("suda_token"),t;return localStorage.getItem(`suda_token_${e}`)||""})(),"X-Suda-Referer":(0,r.isBrowser)()?window.location.href:""},t.DEFAULT_GLOBAL_OPTIONS={headers:t.DEFAULT_HEADERS,brandName:"",appId:""},t.DEFAULT_DB_OPTIONS={schema:""},t.DEFAULT_AUTH_OPTIONS={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},t.DEFAULT_REALTIME_OPTIONS={}},231:(e,t,s)=>{s.r(t),s.d(t,{FunctionRegion:()=>a,FunctionsClient:()=>l,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)}}var a;!function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"}(a||(a={}));class l{constructor(e,{headers:t={},customFetch:r,region:i=a.Any}={}){this.url=e,this.headers=t,this.region=i,this.fetch=(e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>Promise.resolve().then(s.bind(s,663)).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)})(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var s,r,a,l,c;return r=this,a=void 0,c=function*(){try{const{headers:r,method:a,body:l}=t;let c,u={},{region:h}=t;h||(h=this.region),h&&"any"!==h&&(u["x-region"]=h),l&&(r&&!Object.prototype.hasOwnProperty.call(r,"Content-Type")||!r)&&("undefined"!=typeof Blob&&l instanceof Blob||l instanceof ArrayBuffer?(u["Content-Type"]="application/octet-stream",c=l):"string"==typeof l?(u["Content-Type"]="text/plain",c=l):"undefined"!=typeof FormData&&l instanceof FormData?c=l:(u["Content-Type"]="application/json",c=JSON.stringify(l)));const d=yield this.fetch(`${this.url}/${e}`,{method:a||"POST",headers:Object.assign(Object.assign(Object.assign({},u),this.headers),r),body:c}).catch(e=>{throw new i(e)}),f=d.headers.get("x-relay-error");if(f&&"true"===f)throw new n(d);if(!d.ok)throw new o(d);let p,g=(null!==(s=d.headers.get("Content-Type"))&&void 0!==s?s:"text/plain").split(";")[0].trim();return p="application/json"===g?yield d.json():"application/octet-stream"===g?yield d.blob():"text/event-stream"===g?d:"multipart/form-data"===g?yield d.formData():yield d.text(),{data:p,error:null}}catch(e){return{data:null,error:e}}},new((l=void 0)||(l=Promise))(function(e,t){function s(e){try{n(c.next(e))}catch(e){t(e)}}function i(e){try{n(c.throw(e))}catch(e){t(e)}}function n(t){var r;t.done?e(t.value):(r=t.value,r instanceof l?r:new l(function(e){e(r)})).then(s,i)}n((c=c.apply(r,a||[])).next())})}}},299:function(e,t,s){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{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(o,a)}l((r=r.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.fetchWithAuth=t.resolveHeadersConstructor=t.resolveFetch=void 0;const a=n(s(663));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,i)=>{const n=(0,t.resolveFetch)(i),a=(0,t.resolveHeadersConstructor)();return(t,i)=>o(void 0,void 0,void 0,function*(){if(r&&!r.canRequest())return Promise.resolve(new Response(`{"limit": ${r.maxRequests}}`,{status:429,statusText:"Too Many Requests"}));yield s();let o=new a(null==i?void 0:i.headers);return e||console.warn("[Dataloom] api key is missing"),!o.has("apikey")&&e&&o.set("apikey",e),n(t,Object.assign(Object.assign({},i),{headers:o}))})}},399:function(e,t,s){var r=this&&this.__awaiter||function(e,t,s,r){return new(s||(s=Promise))(function(i,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(o,a)}l((r=r.apply(e,t||[])).next())})},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const n=s(231),o=s(739),a=s(587),l=i(s(479)),c=s(645),u=s(150),h=s(299),d=s(946),f=s(560),p=i(s(699));t.default=class{constructor(e,t,s,r){var i,n,a;this.supabaseUrl=e,this.supabaseKey=t,this.workspaceId=s,e||console.warn("[Dataloom] url is empty."),t||console.warn("[Dataloom] apiKey is empty."),s||console.warn("[Dataloom] workspaceId is empty.");const f=(0,d.stripTrailingSlash)(e),g=`${f}/workspaces/${s}`;this.realtimeUrl=`${g}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${g}/auth/v1`,this.storageUrl=`${f}/storage`,this.functionsUrl=`${g}/functions/v1`;const m={db:u.DEFAULT_DB_OPTIONS,realtime:u.DEFAULT_REALTIME_OPTIONS,auth:Object.assign({},u.DEFAULT_AUTH_OPTIONS),global:u.DEFAULT_GLOBAL_OPTIONS},v=(0,d.applySettingDefaults)(null!=r?r:{},m);this.storageKey=null!==(i=v.auth.storageKey)&&void 0!==i?i:"",this.headers=null!==(n=v.global.headers)&&void 0!==n?n:{},this.onRequestError=e=>{v.global.onError&&v.global.onError(e,this)},v.accessToken?(this.accessToken=v.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw new Error(`@data-loom/js: Dataloom Client is configured with the accessToken option, accessing dataloom.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!==(a=v.auth)&&void 0!==a?a:{},this.headers,v.global.fetch),v.global.requestRateLimit&&v.global.requestRateLimit>0&&(this.rateLimiter=new p.default(v.global.requestRateLimit)),this.fetch=(0,h.fetchWithAuth)(t,this._getAccessToken.bind(this),this.rateLimiter,v.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},v.realtime)),this.rest=new o.PostgrestClient(`${g}/dataloom/data`,{headers:this.headers,schema:v.db.schema,fetch:this.fetch,logger:v.global.enableDataloomLog,onRequestError:this.onRequestError}),this.service=new l.default({headers:this.headers,fetch:this.fetch,logger:v.global.enableDataloomLog,brandName:v.global.brandName,appId:v.global.appId,onRequestError:this.onRequestError}),this.storage=new c.StorageClient(this.storageUrl,this.headers,this.fetch,{enableLogger:v.global.enableDataloomLog,onRequestError:this.onRequestError,appId:v.global.appId}),v.accessToken||this._listenForAuthEvents()}get functions(){return new n.FunctionsClient(this.functionsUrl,{headers:this.headers,customFetch: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*(){if(this.accessToken)return yield this.accessToken();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,lock:o,debug:a},l,c){const u={apikey:`${this.supabaseKey}`};return new f.SupabaseAuthClient({url:this.authUrl,headers:Object.assign(Object.assign({},u),l),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:s,storage:r,flowType:n,lock:o,debug:a,fetch:c,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new a.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(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0):this.changedAccessToken=s}}},479:(e,t,s)=>{s.r(t),s.d(t,{default:()=>y});var r=s(663);class i{constructor(){this.counter=1}static getInstance(){return i.instance||(i.instance=new i),i.instance}next(){return this.counter++}getCurrent(){return this.counter}reset(){this.counter=1}}const n=i.getInstance(),o=(e,t,s="Service")=>{const{data:r,error:i,status:n}=t;i?console.error(`[Dataloom][${s}][Response ${i?"Failed":"Success"}]`,"trace id:",e,"statusCode:",n,"error:",i):console.log(`[Dataloom][${s}][Response ${i?"Failed":"Success"}]`,"trace id:",e,"statusCode:",n,"data:",r)};var a,l;!function(e){e[e.Unspecified=0]="Unspecified",e[e.Inactive=1]="Inactive",e[e.Active=2]="Active",e[e.Disabled=3]="Disabled",e[e.Terminated=4]="Terminated"}(a||(a={})),function(e){e[e.active=1]="active",e[e.inactive=2]="inactive"}(l||(l={}));const c=()=>"undefined"!=typeof window&&"undefined"!=typeof document,u=e=>{var t,s;return c()&&null!==(s=null===(t=document.cookie.split(";").find(t=>t.trim().startsWith(`${e}=`)))||void 0===t?void 0:t.split("=")[1])&&void 0!==s?s:""},h=e=>(null==e?void 0:e.zh_cn)||(null==e?void 0:e.en_us)||(null==e?void 0:e.ja_jp)||"",d=e=>e===a.Active||e===a.Inactive?l.active:e===a.Disabled||e===a.Terminated?l.inactive:l.active;var f;!function(e){e.DEFAULT="default",e.UserService="user-service",e.SessionService="session-service"}(f||(f={}));class p{constructor(e,t){var s;this.baseUrl=e,this.headers=Object.assign(Object.assign({},t.headers),{"X-Suda-Csrf-Token":u("suda-csrf-token")}),this.logger=null!==(s=t.logger)&&void 0!==s&&s,this.serviceName=f.DEFAULT,this.brandId="miaoda"===t.brandName?"1":"0",this.appId=t.appId,this.onRequestError=t.onRequestError,t.fetch?this.fetch=t.fetch:"undefined"==typeof fetch?this.fetch=r.default:this.fetch=fetch}async fetchData(e,t,s){var r,i;const a=`${this.baseUrl.toString()}${e}`;let l=-1;this.logger&&(l=n.next(),((e,t="Service")=>{const{traceId:s,url:r,method:i,body:n}=e,o=Array.from(new URL(r).searchParams.entries()).filter(([e])=>!["count","tx","missing","resolution","column"].includes(e)).map(([e,t])=>`${e}=${t}`);console.log(`[Dataloom][${t}][Request]`,"trace id:",s,"method:",i,"params:",o.join(","),"body:",n)})({traceId:l,url:a,method:t.method,body:t.body},null==s?void 0:s.psmName));try{const e=await this.fetch(a,{method:t.method,mode:"cors",redirect:"manual",credentials:"include",headers:this.headers,body:JSON.stringify(t.body)});let i=null,n=null,c=e.status,u=e.statusText;if(e.ok){const t=await e.text(),s=JSON.parse(t);s.status_code&&s.error_msg?(n=null,i={code:s.status_code||e.status,details:"",hint:"",message:s.error_msg||t}):(n=s.data,i=null)}else{const t=await e.text(),s=JSON.parse(t);try{i=429===e.status?{code:429,message:"Too many requests received within 5 seconds.",details:"",hint:"Retry after 5 seconds."}:{code:s.status_code||e.status,message:s.error_msg||t,details:"",hint:""}}catch(r){i={code:s.status_code||e.status,message:s.error_msg||t,details:"",hint:""},n=null,c=500,u="Dataloom Internal Error"}}const h={data:n,error:i,status:c,statusText:u};return i&&(null===(r=this.onRequestError)||void 0===r||r.call(this,Object.assign(Object.assign({},i),{status:c,statusText:u}))),this.logger&&o(l,h,null==s?void 0:s.psmName),h}catch(e){const t={error:{code:500,message:null==e?void 0:e.message,details:"",hint:""},status:500,statusText:"Dataloom Internal Error"};null===(i=this.onRequestError)||void 0===i||i.call(this,Object.assign(Object.assign({},t.error),{status:t.status,statusText:t.statusText}));const r=Object.assign({data:null},t);return this.logger&&o(l,r,null==s?void 0:s.psmName),r}}}class g extends p{constructor(){super(...arguments),this.serviceName=f.UserService}async search(e){var t,s,r;const{name:i,pageSize:n}=e,o=await this.fetchData(`/af/app/${this.appId}/runtime/api/v1/account/search_user`,{method:"POST",body:{query:i,page_size:n}},{psmName:"UserService.Search"});return o.error?o:Object.assign(Object.assign({},o),{data:{user_list:null!==(r=null===(s=null===(t=o.data)||void 0===t?void 0:t.userList)||void 0===s?void 0:s.map(e=>{var t,s,r,i;return{avatar:null!==(t=e.avatar)&&void 0!==t?t:"",email:null!==(s=e.email)&&void 0!==s?s:"",name:null!==(r=h(e.name))&&void 0!==r?r:"",status:d(e.userStatus),user_id:null!==(i=e.userID)&&void 0!==i?i:""}}))&&void 0!==r?r:[]}})}async getByIds(e){const t=await this.fetchData(`/af/app/${this.appId}/runtime/api/v1/account/list_users`,{method:"POST",body:{userIDList:e}},{psmName:"UserService.GetByIds"});return t.error?t:Object.assign(Object.assign({},t),{data:{user_list:e.map(e=>{var s,r,i,n,o,a,l;const c=null===(r=null===(s=t.data)||void 0===s?void 0:s.userInfoMap)||void 0===r?void 0:r[e];return{avatar:null!==(o=null===(n=null===(i=null==c?void 0:c.avatar)||void 0===i?void 0:i.image)||void 0===n?void 0:n.large)&&void 0!==o?o:"",email:null!==(a=null==c?void 0:c.email)&&void 0!==a?a:"",name:null!==(l=h(null==c?void 0:c.name))&&void 0!==l?l:"",status:d(null==c?void 0:c.userStatus),user_id:(null==c?void 0:c.userID)?String(c.userID):""}})}})}}const m={data:null,error:{code:400,message:"Incompatible runtime environment",hint:"Please check if the current environment is browser.",details:"This method can only be invoked in browser environment."},status:400,statusText:"Bad Request"};class v extends p{constructor(){super(...arguments),this.serviceName=f.SessionService}redirectToLogin(e){if(!c())return console.log("[Dataloom][SessionService.RedirectToLogin] dataloom.service.session.redirectToLogin can only be invoked in browser environment."),m;const{returnUrl:t,newTab:s=!1}=null!=e?e:{},r=encodeURIComponent(t||window.location.href),i=`/suda/login?brand=${this.brandId}&appId=${this.appId}&redirectUrl=${r}`;return s?window.open(i,"_blank"):window.location.href=i,{data:"success",error:null,status:200,statusText:"OK"}}async signOut(){return c()?this.fetchData(`/suda/api/runtime/v1/idp/logout?app_id=${this.appId}`,{method:"GET"},{psmName:"SessionService.SignOut"}):(console.log("[Dataloom][SessionService.SignOut] dataloom.service.session.signOut can only be invoked in browser environment."),m)}getUserInfo(){if(!c())return console.log("[Dataloom][SessionService.GetUserInfo] dataloom.service.session.getUserInfo can only be invoked in browser environment."),Promise.resolve(m);let e="/suda/api/session/v1/idp/user_info";const t=new URLSearchParams;return this.brandId&&t.append("brand",this.brandId),this.appId&&t.append("app_id",this.appId),(this.brandId||this.appId)&&(e+=`?${t.toString()}`),this.fetchData(e,{method:"GET"},{psmName:"SessionService.GetUserInfo"})}navigateToUserProfile(e){if(!c())return console.log("[Dataloom][SessionService.NavigateToUserProfile] dataloom.service.session.navigateToUserProfile can only be invoked in browser environment."),m;const{newTab:t=!1}=null!=e?e:{},s=encodeURIComponent(window.location.href),r=`/suda/user?brand=${this.brandId}&returnUrl=${s}`;return t?window.open(r,"_blank"):window.location.href=r,{data:"success",error:null,status:200,statusText:"OK"}}}class y{constructor(e){const t=c()?window.location.origin:"";this.user=new g(t,e),this.session=new v(t,e)}}},560:(e,t,s)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SupabaseAuthClient=void 0;const r=s(650);class i extends r.AuthClient{constructor(e){super(e)}}t.SupabaseAuthClient=i},587:(e,t,s)=>{s.r(t),s.d(t,{REALTIME_CHANNEL_STATES:()=>P,REALTIME_LISTEN_TYPES:()=>j,REALTIME_POSTGRES_CHANGES_LISTEN_EVENT:()=>T,REALTIME_PRESENCE_LISTEN_EVENTS:()=>E,REALTIME_SUBSCRIBE_STATES:()=>O,RealtimeChannel:()=>A,RealtimeClient:()=>$,RealtimePresence:()=>R});const r={"X-Client-Info":"realtime-js/0.0.0-automated"};var i,n,o,a,l,c,u;!function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"}(i||(i={})),function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"}(n||(n={})),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"}(o||(o={})),function(e){e.websocket="websocket"}(a||(a={})),function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"}(l||(l={})),function(e){e.Info="info",e.Warn="warn",e.Error="error"}(c||(c={}));class h{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 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))}}!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 f=(e,t,s={})=>{var r;const i=null!==(r=s.skipTypes)&&void 0!==r?r:[];return Object.keys(t).reduce((s,r)=>(s[r]=p(r,e,t,i),s),{})},p=(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)?g(n,o):m(o)},g=(e,t)=>{if("_"===e.charAt(0)){const s=e.slice(1,e.length);return _(t,s)}switch(e){case u.bool:return v(t);case u.float4:case u.float8:case u.int2:case u.int4:case u.int8:case u.numeric:case u.oid:return y(t);case u.json:case u.jsonb:return w(t);case u.timestamp:return b(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 m(t)}},m=e=>e,v=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},y=e=>{if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},w=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(t){return console.log(`JSON parse error: ${t}`),e}return e},_=(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=>g(t,e))}return e},b=e=>"string"==typeof e?e.replace(" ","T"):e,k=e=>{let t=e;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")};class S{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}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var 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}}var E,T,j,O;!function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"}(E||(E={}));class R{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=R.syncState(this.state,e,t,s),this.pendingDiffs.forEach(e=>{this.state=R.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=R.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),l=s.filter(e=>r.indexOf(e.presence_ref)<0);n.length>0&&(o[e]=n),l.length>0&&(a[e]=l)}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.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"}(T||(T={})),function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"}(j||(j={})),function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"}(O||(O={}));const P=n;class A{constructor(e,t={config:{}},s){this.topic=e,this.params=t,this.socket=s,this.bindings={},this.state=n.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new S(this,o.join,this.params,this.timeout),this.rejoinTimer=new d(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=n.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=n.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=n.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=n.errored,this.rejoinTimer.scheduleTimeout())}),this._on(o.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new R(this),this.broadcastEndpointURL=k(this.socket.endPoint)+"/api/broadcast",this.private=this.params.config.private||!1}subscribe(e,t=this.timeout){var s,r;if(this.socket.isConnected()||this.socket.connect(),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,private:o}}=this.params;this._onError(t=>null==e?void 0:e(O.CHANNEL_ERROR,t)),this._onClose(()=>null==e?void 0:e(O.CLOSED));const a={},l={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:[],private:o};this.socket.accessTokenValue&&(a.access_token=this.socket.accessTokenValue),this.updateJoinPayload(Object.assign({config:l},a)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:t})=>{var s;if(this.socket.setAuth(),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:l,filter:c}}=i,u=t&&t[s];if(!u||u.event!==o||u.schema!==a||u.table!==l||u.filter!==c)return this.unsubscribe(),void(null==e||e(O.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes")));n.push(Object.assign(Object.assign({},i),{id:u.id}))}return this.bindings.postgres_changes=n,void(e&&e(O.SUBSCRIBED))}null==e||e(O.SUBSCRIBED)}).receive("error",t=>{null==e||e(O.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{null==e||e(O.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,s){return this._on(e,t,s)}async send(e,t={}){var s,r;if(this._canPush()||"broadcast"!==e.type)return new Promise(s=>{var r,i,n;const o=this._push(e.type,e,t.timeout||this.timeout);"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("error",()=>s("error")),o.receive("timeout",()=>s("timed out"))});{const{event:i,payload:n}=e,o={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:n,private:this.private}]})};try{const e=await this._fetchWithTimeout(this.broadcastEndpointURL,o,null!==(s=t.timeout)&&void 0!==s?s:this.timeout);return await(null===(r=e.body)||void 0===r?void 0:r.cancel()),e.ok?"ok":"error"}catch(e){return"AbortError"===e.name?"timed out":"error"}}}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=n.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(o.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(s=>{const r=new S(this,o.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",{})})}async _fetchWithTimeout(e,t,s){const r=new AbortController,i=setTimeout(()=>r.abort(),s),n=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(i),n}_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 S(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:a,error:l,leave:c,join:u}=o;if(s&&[a,l,c,u].indexOf(n)>=0&&s!==this._joinRef())return;let h=this._onMessage(n,t,s);if(t&&!h)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(h,s)):null===(i=this.bindings[n])||void 0===i||i.filter(e=>{var s,r,i,o,a,l;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===(l=null==t?void 0:t.event)||void 0===l?void 0:l.toLocaleLowerCase())}}return e.type.toLocaleLowerCase()===n}).map(e=>{if("object"==typeof h&&"ids"in h){const e=h.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};h=Object.assign(Object.assign({},o),this._getPayloadRecords(e))}e.callback(h,s)})}_isClosed(){return this.state===n.closed}_isJoined(){return this.state===n.joined}_isJoining(){return this.state===n.joining}_isLeaving(){return this.state===n.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&&A.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(o.close,{},e)}_onError(e){this._on(o.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=n.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return"INSERT"!==e.type&&"UPDATE"!==e.type||(t.new=f(e.columns,e.record)),"UPDATE"!==e.type&&"DELETE"!==e.type||(t.old=f(e.columns,e.old_record)),t}}const I=()=>{},x="undefined"!=typeof WebSocket;class ${constructor(e,t){var i;this.accessTokenValue=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=r,this.params={},this.timeout=1e4,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=I,this.conn=null,this.sendBuffer=[],this.serializer=new h,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>Promise.resolve().then(s.bind(s,663)).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},this.endPoint=`${e}/${a.websocket}`,this.httpEndpoint=k(e),(null==t?void 0:t.transport)?this.transport=t.transport:this.transport=null,(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.logLevel)||(null==t?void 0:t.log_level))&&(this.logLevel=t.logLevel||t.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),(null==t?void 0:t.heartbeatIntervalMs)&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);const n=null===(i=null==t?void 0:t.params)||void 0===i?void 0:i.apikey;if(n&&(this.accessTokenValue=n,this.apiKey=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(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(null==t?void 0:t.fetch),null==t?void 0:t.worker){if("undefined"!=typeof window&&!window.Worker)throw new Error("Web Worker is not supported");this.worker=(null==t?void 0:t.worker)||!1,this.workerUrl=null==t?void 0:t.workerUrl}this.accessToken=(null==t?void 0:t.accessToken)||null}connect(){if(!this.conn){if(this.transport)return this.conn=new this.transport(this.endpointURL(),void 0,{headers:this.headers}),void this.setupConnection();if(x)return this.conn=new WebSocket(this.endpointURL()),void this.setupConnection();this.conn=new C(this.endpointURL(),void 0,{close:()=>{this.conn=null}}),s.e(387).then(s.t.bind(s,387,23)).then(({default:e})=>{this.conn=new e(this.endpointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:"1.0.0"}))}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}async removeChannel(e){const t=await e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}async removeAllChannels(){const e=await 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 i.connecting:return l.Connecting;case i.open:return l.Open;case i.closing:return l.Closing;default:return l.Closed}}isConnected(){return this.connectionState()===l.Open}channel(e,t={config:{}}){const s=new A(`realtime:${e}`,t,this);return this.channels.push(s),s}push(e){const{topic:t,event:s,payload:r,ref:i}=e,n=()=>{this.encode(e,e=>{var t;null===(t=this.conn)||void 0===t||t.send(e)})};this.log("push",`${t} ${s} (${i})`,r),this.isConnected()?n():this.sendBuffer.push(n)}async setAuth(e=null){let t=e||this.accessToken&&await this.accessToken()||this.accessTokenValue;this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{t&&e.updateJoinPayload({access_token:t,version:this.headers&&this.headers["X-Client-Info"]}),e.joinedOnce&&e._isJoined()&&e._push(o.access_token,{access_token:t})}))}async 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}),await this.setAuth()}}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){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))}_onConnMessage(e){this.decode(e.data,e=>{let{topic:t,event:s,payload:r,ref:i}=e;i&&i===this.pendingHeartbeatRef&&(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))})}async _onConnOpen(){if(this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this.reconnectTimer.reset(),this.worker){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this.workerRef.terminate()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}else 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(o.error))}_appendParams(e,t){if(0===Object.keys(t).length)return e;const s=e.match(/\?/)?"&":"?";return`${e}${s}${new URLSearchParams(t)}`}_workerObjectUrl(e){let t;if(e)t=e;else{const e=new Blob(['\n addEventListener("message", (e) => {\n if (e.data.event === "start") {\n setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);\n }\n });'],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}}class C{constructor(e,t,s){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=i.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=s.close}}},595:function(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(s(663)),n=r(s(886)),o=s(639);t.default=class{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,this.action=e.action,this.relation=e.relation,this.logger=e.logger,this.onRequestError=e.onRequestError,e.fetch?this.fetch=e.fetch:"undefined"==typeof fetch?this.fetch=i.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=Object.assign({},this.headers),this.headers[e]=t,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");const s=this.fetch;let r;this.logger&&(r=o.traceIdGenerator.next(),this.logRequest(r));let i=s(this.url.toString(),{method:this.method,mode:"cors",redirect:"manual",credentials:"include",headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{var t,s,i,o;let a=null,l=null,c=null,u=e.status,h=e.statusText;if(e.ok){const r=await e.text(),i=JSON.parse(r);if(i.status_code&&i.error_msg)l=null,a={code:i.status_code,details:"",hint:"",message:i.error_msg};else{if("HEAD"!==this.method)if(""===r);else if("text/csv"===this.headers.Accept)l=r;else if(this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text"))l=r;else try{l=JSON.parse(r).data}catch(e){l=null,a=JSON.parse(r)}const i=null===(t=this.headers.Prefer)||void 0===t?void 0:t.match(/count=(exact|planned|estimated)/),n=null===(s=e.headers.get("content-range"))||void 0===s?void 0:s.split("/");i&&n&&n.length>1&&(c=parseInt(n[1])),this.isMaybeSingle&&"GET"===this.method&&Array.isArray(l)&&(l.length>1?(a={code:"PGRST116",details:`Results contain ${l.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:"",message:"JSON object requested, multiple (or no) rows returned"},l=null,c=null,u=406,h="Not Acceptable"):l=1===l.length?l[0]:null)}}else{const t=await e.text();try{const s=JSON.parse(t);a={code:s.status_code||e.status,details:"",hint:"",message:s.error_msg||t},Array.isArray(a)&&404===e.status&&(l=[],a=null,u=200,h="OK"),429===e.status&&(a={code:429,message:"Too many requests received within 5 seconds.",details:"",hint:"Retry after 5 seconds."})}catch(s){404===e.status&&""===t?(u=204,h="No Content"):a={message:t}}if(a&&this.isMaybeSingle&&(null===(i=null==a?void 0:a.details)||void 0===i?void 0:i.includes("0 rows"))&&(a=null,u=200,h="OK"),a&&this.shouldThrowOnError)throw new n.default(a)}const d={error:a,data:l,count:c,status:u,statusText:h};return a&&(null===(o=this.onRequestError)||void 0===o||o.call(this,Object.assign(Object.assign({},a),{status:u,statusText:h}))),this.logger&&this.logResponse(r,d),d});return this.shouldThrowOnError||(i=i.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:""}})),i.then(e,t)}logResponse(e,t){const{status:s,data:r,error:i,count:n}=t;console[i?"error":"log"](`[Dataloom] [Response ${i?"Failed":"Success"}]`,"trace id:",e,"table name:",this.relation,"statusCode:",s,"data:",r,"error:",i,"count:",n)}logRequest(e){const t=Array.from(this.url.searchParams.entries()).filter(([e])=>!["count","tx","missing","resolution","column"].includes(e)).map(([e,t])=>`${e}=${t}`);console.log("[Dataloom] [Request]","trace id:",e,"table name:",this.relation,"method:",this.method,"action:",this.action,"params:",t.join(","),"preferHeaders:",this.headers.Prefer,"body:",this.body,"schema:",this.schema)}returns(){return this}overrideTypes(){return this}}},597:function(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(s(705)),n=r(s(973));class o{constructor(e,{headers:t={},schema:s,fetch:r,logger:i,onRequestError:n}={}){this.url=e,this.headers=Object.assign({},t),this.schemaName=s,this.fetch=r,this.logger=i,this.onRequestError=n}from(e){const t=new URL(`${this.url}/${e}`);return new i.default(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch,logger:this.logger,relation:e,onRequestError:this.onRequestError})}schema(e){return new o(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:s=!1,get:r=!1,count:i}={}){let o;const a=new URL(`${this.url}/rpc/${e}`);let l;s||r?(o=s?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{a.searchParams.append(e,t)})):(o="POST",l=t);const c=Object.assign({},this.headers);return i&&(c.Prefer=`count=${i}`),new n.default({method:o,url:a,headers:c,schema:this.schemaName,body:l,fetch:this.fetch,allowEmpty:!1,logger:this.logger,action:"rpc"})}}t.default=o},639:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.traceIdGenerator=t.TraceIdGenerator=void 0;class s{constructor(){this.counter=1}static getInstance(){return s.instance||(s.instance=new s),s.instance}next(){return this.counter++}getCurrent(){return this.counter}reset(){this.counter=1}}t.TraceIdGenerator=s;const r=s.getInstance();t.traceIdGenerator=r},645:(e,t,s)=>{s.r(t),s.d(t,{StorageApiError:()=>n,StorageClient:()=>P,StorageError:()=>r,StorageUnknownError:()=>o,isCustomError:()=>c,isSdkRateLimited:()=>l,isServerCustomError:()=>a,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,s){super(e),this.name="StorageApiError",this.status=t,this.statusCode=s}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class o extends r{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}const a=(e,t)=>!(!t||"TosServer"===e.headers.get("server"))||e.error_msg,l=e=>429===e.status&&"Too Many Requests"===e.statusText,c=e=>a(e)||l(e),u=2592e3,h=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>Promise.resolve().then(s.bind(s,663)).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},d=e=>e<1?1:e>u?u:e,f=e=>{var t,s,r,i,n,o,a,l,c,u,h,d,f,p,g,m,v,y;return Object.assign(Object.assign({},e),{buckets:{allowed_mime_types:null!==(s=null===(t=null==e?void 0:e.buckets)||void 0===t?void 0:t.allowed_mime_types)&&void 0!==s?s:[],created_at:null!==(i=null===(r=null==e?void 0:e.buckets)||void 0===r?void 0:r.created_at)&&void 0!==i?i:"",file_size_limit:null!==(o=null===(n=null==e?void 0:e.buckets)||void 0===n?void 0:n.file_size_limit)&&void 0!==o?o:0,id:null!==(l=null===(a=null==e?void 0:e.buckets)||void 0===a?void 0:a.id)&&void 0!==l?l:"",name:null!==(u=null===(c=null==e?void 0:e.buckets)||void 0===c?void 0:c.name)&&void 0!==u?u:"",public:null!==(d=null===(h=null==e?void 0:e.buckets)||void 0===h?void 0:h.public)&&void 0!==d&&d,updated_at:null!==(p=null===(f=null==e?void 0:e.buckets)||void 0===f?void 0:f.updated_at)&&void 0!==p?p:"",updated_by:null!==(m=null===(g=null==e?void 0:e.buckets)||void 0===g?void 0:g.updated_by)&&void 0!==m?m:"",owner:null!==(y=null===(v=null==e?void 0:e.buckets)||void 0===v?void 0:v.created_by)&&void 0!==y?y:""}})},p=/^https:\/\/[\w-]+\.tos-cn-beijing\.volces\.com\/.+/,g=(e,t,s="Storage")=>{const{data:r,error:i,status:n}=t;i?console.error(`[Dataloom][${s}][Response Failed]`,"trace id:",e,"statusCode:",n,"error:",i):console.log(`[Dataloom][${s}][Response Success]`,"trace id:",e,"statusCode:",n,"data:",r)};class m{constructor(){this.counter=1}static getInstance(){return m.instance||(m.instance=new m),m.instance}next(){return this.counter++}getCurrent(){return this.counter}reset(){this.counter=1}}const v=m.getInstance(),y=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e);async function w(e,t,r,i,c,u,h){let d=-1,f=200;const p=null==h?void 0:h.psmName;return(null==i?void 0:i.logFetch)&&(d=v.next(),((e,t="Storage")=>{const{traceId:s,url:r,method:i,body:n}=e,o=Array.from(new URL(r).searchParams.entries()).filter(([e])=>!["count","tx","missing","resolution","column"].includes(e)).map(([e,t])=>`${e}=${t}`);console.log(`[Dataloom][${t}][Request]`,"trace id:",s,"method:",i,"params:",o.join(","),"body:",n)})({traceId:d,url:r,method:t,body:u},p)),new Promise((h,m)=>{e(r,((e,t,s,r)=>{const i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&r?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(r)?(i.headers=Object.assign({"Content-Type":"application/json"},null==t?void 0:t.headers),i.body=JSON.stringify(r)):i.body=r,(null==t?void 0:t.duplex)&&(i.duplex=t.duplex),Object.assign(Object.assign({},i),s)):i})(t,i,c,u)).then(e=>{if(f=e.status,!e.ok)throw e;return(null==i?void 0:i.noResolveJson)?e:e.json()}).then(async e=>{var t;if(a(e))return null===(t=null==i?void 0:i.onRequestError)||void 0===t||t.call(i,{status:200,statusText:"",code:(null==e?void 0:e.status_code)||200,message:(null==e?void 0:e.error_msg)||"",details:"",hint:""}),(null==i?void 0:i.logFetch)&&g(d,{data:null,error:e,status:f},p),m(e);if(null==i?void 0:i.logFetch){let t=null,s=null;if(null==i?void 0:i.noResolveJson)try{"TosServer"===e.headers.get("server")||e.headers.get("etag")?t=await e.clone().text():s=await e.clone().json()}catch(e){s=y(e)}else t=e;g(d,{data:t,error:s,status:f},p)}return h(e)}).catch(e=>{(null==i?void 0:i.logFetch)&&g(d,{data:null,error:y(e),status:null==e?void 0:e.status},p),(async(e,t,r)=>{var i;const a=await(async()=>"undefined"==typeof Response?(await Promise.resolve().then(s.bind(s,663))).Response:Response)();if(l(e)){const e={code:429,message:"Too many requests received within 5 seconds.",details:"",hint:"Retry after 5 seconds."};return null===(i=null==r?void 0:r.onRequestError)||void 0===i||i.call(r,Object.assign({status:429,statusText:"Too Many Requests"},e)),t(e)}e instanceof a&&!(null==r?void 0:r.noResolveJson)?e.json().then(s=>{var i;const o=e.status||500,a=(null==s?void 0:s.statusCode)||o+"";null===(i=null==r?void 0:r.onRequestError)||void 0===i||i.call(r,{status:o,statusText:a,code:(null==s?void 0:s.status_code)||o,message:(null==s?void 0:s.error_msg)||"",details:"",hint:""}),t(new n(y(s),o,a))}).catch(e=>{t(new o(y(e),e))}):t(new o(y(e),e))})(e,m,i)})})}async function _(e,t,s,r,i){return w(e,"GET",t,s,r,void 0,i)}async function b(e,t,s,r,i,n){return w(e,"POST",t,r,i,s,n)}async function k(e,t,s,r,i,n){return w(e,"PUT",t,r,i,s,n)}async function S(e,t,s,r,i,n){return w(e,"DELETE",t,r,i,s,n)}const E={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},T={upsert:!1};class j{constructor(e,t={},s,r,i,n,o){this.url=e,this.headers=t,this.bucketId=s,this.appId=r,this.fetch=h(i),this.loggerEnabled=n,this.onRequestError=o}async uploadOrUpdate(e,t,s){var n,a,l,u,h,d,f,p;try{const i=Object.assign(Object.assign({},T),s),o=this._removeEmptyFolders(e);let c=null;(null==i?void 0:i.contentDisposition)?c=null==i?void 0:i.contentDisposition:t instanceof File&&(c=null==t?void 0:t.name);const g={bucket_id:null!==(n=this.bucketId)&&void 0!==n?n:"",file_size:(p=t,"undefined"!=typeof File&&p instanceof File||p instanceof Blob||p instanceof URLSearchParams?p.size.toString():"string"==typeof p?p.length.toString():ArrayBuffer.isView(p)||p instanceof ArrayBuffer?p.byteLength.toString():"0"),upsert:null!==(a=i.upsert)&&void 0!==a&&a,file_path:o,file_name:t instanceof File?null==t?void 0:t.name:""},m=await b(this.fetch,`${this.url}/object/${this.bucketId}/pre_upload`,g,{headers:this.headers,logFetch:this.loggerEnabled,onRequestError:this.onRequestError},void 0,{psmName:"Storage.Upload.PreUpload"}),{upload_id:v,upload_url:y}=null!==(l=null==m?void 0:m.data)&&void 0!==l?l:{};if(y&&v){const e={};c&&(e["content-disposition"]=`attachment; filename="${f=c,encodeURIComponent(f.replace(/[\x00-\x1F\x7F:"\\/*?<>|,;]/g,""))||"download_file"}"`),(i.cacheControl||0===i.cacheControl)&&(e["cache-control"]=`max-age=${i.cacheControl}`),i.contentType&&(e["content-type"]=i.contentType);const s=await k(this.fetch,y,t,{noResolveJson:!0,headers:e,logFetch:this.loggerEnabled,onRequestError:this.onRequestError},void 0,{psmName:"Storage.Upload.TosUpload"}),r=null!==(h=null===(u=null==s?void 0:s.headers)||void 0===u?void 0:u.get("Etag"))&&void 0!==h?h:"",n=await b(this.fetch,`${this.url}/object/callback`,{upload_id:v,etag:r,app_id:this.appId},{headers:this.headers,logFetch:this.loggerEnabled,onRequestError:this.onRequestError},void 0,{psmName:"Storage.Upload.Callback"});return{data:null!==(d=null==n?void 0:n.data)&&void 0!==d?d:{},error:null}}return{data:null,error:new r("upload_url or upload_id is empty")}}catch(e){return c(e)||i(e)?{data:null,error:e}:{data:null,error:new o("upload file error",e)}}}async upload(e,t,s){var r;const i=null!==t&&"object"==typeof t&&"function"==typeof t.pipe&&"function"==typeof t.on,n=t instanceof Blob||t instanceof ArrayBuffer||"undefined"!=typeof File&&t instanceof File||t instanceof FormData||t instanceof URLSearchParams||"undefined"!=typeof Buffer&&t instanceof Buffer||"undefined"!=typeof ReadableStream&&t instanceof ReadableStream||i||ArrayBuffer.isView(t)||"string"==typeof t;if("string"==typeof e&&n)return this.uploadOrUpdate(e,t,s);const o=t;return this.uploadOrUpdate(null!==(r=null==o?void 0:o.filePath)&&void 0!==r?r:"",e,o)}async uploadFile(e,t){var s;return this.uploadOrUpdate(null!==(s=null==t?void 0:t.filePath)&&void 0!==s?s:"",e,t)}async update(e,t,s){return this.uploadOrUpdate(e,t,s)}async createSignedUrl(e,t,s){try{let s=this._getFinalPath(e);return{data:(await b(this.fetch,`${this.url}/object/sign/${s}`,{expires_in:d(t)},{headers:this.headers,logFetch:this.loggerEnabled,onRequestError:this.onRequestError},void 0,{psmName:"Storage.CreateSignedUrl"})).data,error:null}}catch(e){return c(e)||i(e)?{data:null,error:e}:{data:null,error:new o("create signed url error",e)}}}async createSignedUrls(e,t,s){try{const s=e.map(e=>this._retrieveFilePathFromDownloadUrl(e));return{data:(await b(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expires_in:d(t),paths:s},{headers:this.headers,logFetch:this.loggerEnabled,onRequestError:this.onRequestError},void 0,{psmName:"Storage.CreateSignedUrls"})).data,error:null}}catch(e){return c(e)||i(e)?{data:null,error:e}:{data:null,error:new o("create signed urls error",e)}}}async download(e,t){try{const t=this._retrieveFilePathFromDownloadUrl(e),s=await _(this.fetch,`${this.url}/object/${this.bucketId}/${t}`,{headers:this.headers,noResolveJson:!0,logFetch:this.loggerEnabled,onRequestError:this.onRequestError},void 0,{psmName:"Storage.Download"});let r;return s.redirected?(r=await s.blob(),{data:r,error:null}):(r=await s.json(),{data:null,error:r})}catch(e){if(e&&"object"==typeof e&&"originalError"in e){const t=e.originalError;if(t instanceof Response&&t.redirected)try{return{data:null,error:new r(await t.text())}}catch(t){return{data:null,error:new o("download file error",e)}}}return c(e)||i(e)?{data:null,error:e}:{data:null,error:new o("download file error",e)}}}async remove(e){try{const t=e.map(e=>this._retrieveFilePathFromDownloadUrl(e));return{data:(await S(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers,logFetch:this.loggerEnabled,onRequestError:this.onRequestError},void 0,{psmName:"Storage.Remove"})).data.map(e=>f(e)),error:null}}catch(e){return c(e)||i(e)?{data:null,error:e}:{data:null,error:new o("remove file error",e)}}}async uploadFromUrl(e){try{let t;try{t=new URL(e)}catch(e){return{data:null,error:new r("Invalid URL provided")}}if("http:"!==t.protocol&&"https:"!==t.protocol)return{data:null,error:new r("Only http and https protocols are supported")};if((e=>p.test(e))(e))return{data:await this._copyWithinVolcEngine(e),error:null};const s=await this.fetch(e);if(!s.ok)return{data:null,error:new r(`Failed to download file from URL: ${s.status} ${s.statusText}`)};const i=(s.headers.get("content-type")||"").split(";")[0].trim().toLowerCase(),n=s.headers.get("content-disposition"),o=s.headers.get("cache-control"),a=await s.blob();if(0===a.size)return{data:null,error:new r("Downloaded file is empty")};const l={};if(i&&(l.contentType=i),n&&(l.contentDisposition=n),o){const e=o.match(/max-age=(\d+)/i);e&&(l.cacheControl=parseInt(e[1],10))}return this.uploadOrUpdate("",a,l)}catch(e){return c(e)||i(e)?{data:null,error:e}:{data:null,error:new o("copy from url error",e)}}}async list(e,t,s){try{const r=Object.assign(Object.assign(Object.assign({},E),t),{prefix:e||""});return{data:(await b(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers,logFetch:this.loggerEnabled,onRequestError:this.onRequestError},s,{psmName:"Storage.List"})).data.map(e=>f(e)),error:null}}catch(e){return c(e)||i(e)?{data:null,error:e}:{data:null,error:new o("list file error",e)}}}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return"undefined"!=typeof Buffer?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){let t=this._retrieveFilePathFromDownloadUrl(e);return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e?e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/"):e}_isValidDownloadUrl(e){return/^\/spark\/app\/app_[\w]+\/runtime\/api\/v1\/storage/.test(e)}_retrieveFilePathFromDownloadUrl(e){if(!this._isValidDownloadUrl(e))return e;const t=e.indexOf("/object/");if(-1===t)return"";const s=e.slice(t+8),r=s.indexOf("/");if(-1!==r){const e=s.slice(r+1);return decodeURIComponent(e)}return""}async _copyWithinVolcEngine(e){var t,s,r,i,n;const o=await b(this.fetch,`${this.url}/runtime/app/${this.appId}/object/${this.bucketId}/copy`,{source:{type:"externalTOS",externalURL:e}},{headers:this.headers,logFetch:this.loggerEnabled,onRequestError:this.onRequestError},void 0,{psmName:"Storage.Copy"}),{metadata:a}=null!==(t=null==o?void 0:o.data)&&void 0!==t?t:{};return{id:null!==(s=null==a?void 0:a.id)&&void 0!==s?s:"",file_path:null!==(r=null==a?void 0:a.filePath)&&void 0!==r?r:"",bucket_id:null!==(i=null==a?void 0:a.bucketID)&&void 0!==i?i:"",download_url:null!==(n=null==a?void 0:a.downloadURL)&&void 0!==n?n:""}}}const O={"X-Client-Info":"storage-js/0.0.0"};class R{constructor(e,t={},s,r){this.url=e,this.headers=Object.assign(Object.assign({},O),t),this.fetch=h(s),this.onRequestError=null==r?void 0:r.onRequestError,this.appId=null==r?void 0:r.appId,(null==r?void 0:r.enableLogger)&&(this.loggerEnabled=!0)}async listBuckets(){try{return{data:await _(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}async getBucket(e){try{return{data:await _(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}async createBucket(e,t={public:!1}){try{return{data:await b(this.fetch,`${this.url}/bucket`,{id:e,name:e,type:t.type,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}}async updateBucket(e,t){try{return{data:await k(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}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}async emptyBucket(e){try{return{data:await b(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}async deleteBucket(e){try{return{data:await S(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(e){if(i(e))return{data:null,error:e};throw e}}}class P extends R{constructor(e,t={},s,r){super(e,t,s,r)}from(e){return new j(this.url,this.headers,e,this.appId,this.fetch,this.loggerEnabled,this.onRequestError)}}},650:(e,t,s)=>{s.r(t),s.d(t,{AuthAdminApi:()=>ge,AuthApiError:()=>d,AuthClient:()=>me,AuthError:()=>u,AuthImplicitGrantRedirectError:()=>_,AuthInvalidCredentialsError:()=>w,AuthInvalidJwtError:()=>O,AuthInvalidTokenResponseError:()=>y,AuthPKCEGrantCodeExchangeError:()=>k,AuthRetryableFetchError:()=>S,AuthSessionMissingError:()=>m,AuthUnknownError:()=>p,AuthWeakPasswordError:()=>T,CustomAuthError:()=>g,GoTrueAdminApi:()=>ne,GoTrueClient:()=>pe,NavigatorLockAcquireTimeoutError:()=>ue,isAuthApiError:()=>f,isAuthError:()=>h,isAuthImplicitGrantRedirectError:()=>b,isAuthRetryableFetchError:()=>E,isAuthSessionMissingError:()=>v,isAuthWeakPasswordError:()=>j,lockInternals:()=>le,navigatorLock:()=>he});const r="0.0.1",i=3e4,n={"X-Client-Info":`gotrue-js/${r}`},o="X-Supabase-Api-Version",a=Date.parse("2024-01-01T00:00:00.0Z"),l="2024-01-01",c=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class u extends Error{constructor(e,t,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=s}}function h(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class d extends u{constructor(e,t,s){super(e,t,s),this.name="AuthApiError",this.status=t,this.code=s}}function f(e){return h(e)&&"AuthApiError"===e.name}class p extends u{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class g extends u{constructor(e,t,s,r){super(e,s,r),this.name=t,this.status=s}}class m extends g{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function v(e){return h(e)&&"AuthSessionMissingError"===e.name}class y extends g{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class w extends g{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class _ extends g{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function b(e){return h(e)&&"AuthImplicitGrantRedirectError"===e.name}class k extends g{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class S extends g{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function E(e){return h(e)&&"AuthRetryableFetchError"===e.name}class T extends g{constructor(e,t,s){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=s}}function j(e){return h(e)&&"AuthWeakPasswordError"===e.name}class O extends g{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const R="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),P=" \t\n\r=".split(""),A=(()=>{const e=new Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<P.length;t+=1)e[P[t].charCodeAt(0)]=-2;for(let t=0;t<R.length;t+=1)e[R[t].charCodeAt(0)]=t;return e})();function I(e,t,s){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;s(R[e]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;s(R[e]),t.queuedBits-=6}}function x(e,t,s){const r=A[e];if(!(r>-1)){if(-2===r)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}for(t.queue=t.queue<<6|r,t.queuedBits+=6;t.queuedBits>=8;)s(t.queue>>t.queuedBits-8&255),t.queuedBits-=8}function $(e){const t=[],s=e=>{t.push(String.fromCodePoint(e))},r={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},n=e=>{!function(e,t,s){if(0===t.utf8seq){if(e<=127)return void s(e);for(let s=1;s<6;s+=1)if(!(e>>7-s&1)){t.utf8seq=s;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else{if(4!==t.utf8seq)throw new Error("Invalid UTF-8 sequence");t.codepoint=7&e}t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&s(t.codepoint)}}(e,r,s)};for(let t=0;t<e.length;t+=1)x(e.charCodeAt(t),i,n);return t.join("")}function C(e,t){if(!(e<=127)){if(e<=2047)return t(192|e>>6),void t(128|63&e);if(e<=65535)return t(224|e>>12),t(128|e>>6&63),void t(128|63&e);if(e<=1114111)return t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),void t(128|63&e);throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}t(e)}function L(e){const t=[],s={queue:0,queuedBits:0},r=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)x(e.charCodeAt(t),s,r);return new Uint8Array(t)}function U(e){const t=[],s={queue:0,queuedBits:0},r=e=>{t.push(e)};return e.forEach(e=>I(e,s,r)),I(null,s,r),t.join("")}const D=()=>"undefined"!=typeof window&&"undefined"!=typeof document,q={tested:!1,writable:!1},N=()=>{if(!D())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(q.tested)return q.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),q.tested=!0,q.writable=!0}catch(e){q.tested=!0,q.writable=!1}return q.writable},F=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>Promise.resolve().then(s.bind(s,663)).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},M=async(e,t,s)=>{await e.setItem(t,JSON.stringify(s))},B=async(e,t)=>{const s=await e.getItem(t);if(!s)return null;try{return JSON.parse(s)}catch(e){return s}},W=async(e,t)=>{await e.removeItem(t)};class J{constructor(){this.promise=new J.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function z(e){const t=e.split(".");if(3!==t.length)throw new O("Invalid JWT structure");for(let e=0;e<t.length;e++)if(!c.test(t[e]))throw new O("JWT not in base64url format");return{header:JSON.parse($(t[0])),payload:JSON.parse($(t[1])),signature:L(t[2]),raw:{header:t[0],payload:t[1]}}}function G(e){return("0"+e.toString(16)).substr(-2)}async function H(e,t,s=!1){const r=function(){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,G).join("")}();let i=r;s&&(i+="/PASSWORD_RECOVERY"),await M(e,`${t}-code-verifier`,i);const n=await async function(e){if("undefined"==typeof crypto||void 0===crypto.subtle||"undefined"==typeof TextEncoder)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(/=+$/,"")}(r);return[n,r===n?"plain":"s256"]}J.promiseConstructor=Promise;const K=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;const V=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Y=[502,503,504];async function Q(e){var t,s;if(!("object"==typeof(s=e)&&null!==s&&"status"in s&&"ok"in s&&"json"in s&&"function"==typeof s.json))throw new S(V(e),0);if(Y.includes(e.status))throw new S(V(e),e.status);let r,i;try{r=await e.json()}catch(e){throw new p(V(e),e)}const n=function(e){const t=e.headers.get(o);if(!t)return null;if(!t.match(K))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(e){return null}}(e);if(n&&n.getTime()>=a&&"object"==typeof r&&r&&"string"==typeof r.code?i=r.code:"object"==typeof r&&r&&"string"==typeof r.error_code&&(i=r.error_code),i){if("weak_password"===i)throw new T(V(r),e.status,(null===(t=r.weak_password)||void 0===t?void 0:t.reasons)||[]);if("session_not_found"===i)throw new m}else if("object"==typeof r&&r&&"object"==typeof r.weak_password&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new T(V(r),e.status,r.weak_password.reasons);throw new d(V(r),e.status||500,i)}async function X(e,t,s,r){var i;const n=Object.assign({},null==r?void 0:r.headers);n[o]||(n[o]=l),(null==r?void 0:r.jwt)&&(n.Authorization=`Bearer ${r.jwt}`);const a=null!==(i=null==r?void 0:r.query)&&void 0!==i?i:{};(null==r?void 0:r.redirectTo)&&(a.redirect_to=r.redirectTo);const c=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",u=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,Object.assign({},o))}catch(e){throw console.error(e),new S(V(e),0)}if(a.ok||await Q(a),null==r?void 0:r.noResolveJson)return a;try{return await a.json()}catch(e){await Q(e)}}(e,t,s+c,{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(u):{data:Object.assign({},u),error:null}}function Z(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 ee(e){const t=Z(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function te(e){var t;return{data:{user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function se(e){return{data:e,error:null}}function re(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 ie(e){return e}class ne{constructor({url:e="",headers:t={},fetch:s}){this.url=e,this.headers=t,this.fetch=F(s),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await X(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(h(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await X(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:te})}catch(e){if(h(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 X(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:re,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(h(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await X(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:te})}catch(e){if(h(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,s,r,i,n,o,a;try{const l={nextPage:null,lastPage:0,total:0},c=await X(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:ie});if(c.error)throw c.error;const u=await c.json(),h=null!==(n=c.headers.get("x-total-count"))&&void 0!==n?n:0,d=null!==(a=null===(o=c.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]);l[`${s}Page`]=t}),l.total=parseInt(h)),{data:Object.assign(Object.assign({},u),l),error:null}}catch(e){if(h(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){try{return await X(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:te})}catch(e){if(h(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){try{return await X(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:te})}catch(e){if(h(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){try{return await X(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:te})}catch(e){if(h(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){try{const{data:t,error:s}=await X(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(h(e))return{data:null,error:e};throw e}}async _deleteFactor(e){try{return{data:await X(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(h(e))return{data:null,error:e};throw e}}}const oe={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 ae(e={}){return{getItem:t=>e[t]||null,setItem:(t,s)=>{e[t]=s},removeItem:t=>{delete e[t]}}}const le={debug:!!(globalThis&&N()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"))};class ce extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class ue extends ce{}async function he(e,t,s){le.debug&&console.log("@data-loom/gotrue-js: navigatorLock: acquire lock",e,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),le.debug&&console.log("@data-loom/gotrue-js: navigatorLock acquire timed out",e)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async r=>{if(!r){if(0===t)throw le.debug&&console.log("@data-loom/gotrue-js: navigatorLock: not immediately available",e),new ue(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(le.debug)try{const e=await globalThis.navigator.locks.query();console.log("@data-loom/gotrue-js: Navigator LockManager state",JSON.stringify(e,null," "))}catch(e){console.warn("@data-loom/gotrue-js: Error when querying Navigator LockManager state",e)}return console.warn("@data-loom/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()}le.debug&&console.log("@data-loom/gotrue-js: navigatorLock: acquired",e,r.name);try{return await s()}finally{le.debug&&console.log("@data-loom/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 de={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:n,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function fe(e,t,s){return await s()}class pe{constructor(e){var t,s;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=pe.nextInstanceID,pe.nextInstanceID+=1,this.instanceID>0&&D()&&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({},de),e);if(this.logDebugMessages=!!r.debug,"function"==typeof r.debug&&(this.logger=r.debug),this.persistSession=r.persistSession,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.admin=new ne({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=F(r.fetch),this.lock=r.lock||fe,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,r.lock?this.lock=r.lock:D()&&(null===(t=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===t?void 0:t.locks)?this.lock=he:this.lock=fe,this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?r.storage?this.storage=r.storage:N()?this.storage=oe:(this.memoryStorage={},this.storage=ae(this.memoryStorage)):(this.memoryStorage={},this.storage=ae(this.memoryStorage)),D()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null===(s=this.broadcastChannel)||void 0===s||s.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&&this.logger(`GoTrueClient@${this.instanceID} (${r}) ${(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(){var e;try{const t=function(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}(window.location.href);let s="none";if(this._isImplicitGrantCallback(t)?s="implicit":await this._isPKCECallback(t)&&(s="pkce"),D()&&this.detectSessionInUrl&&"none"!==s){const{data:r,error:i}=await this._getSessionFromURL(t,s);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),b(i)){const t=null===(e=i.details)||void 0===e?void 0:e.code;if("identity_already_exists"===t||"identity_not_found"===t||"single_identity_not_deletable"===t)return{error:i}}return await this._removeSession(),{error:i}}const{session:n,redirectType:o}=r;return this._debug("#_initialize()","detected session in URL",n,"redirect type",o),await this._saveSession(n),setTimeout(async()=>{"recovery"===o?await this._notifyAllSubscribers("PASSWORD_RECOVERY",n):await this._notifyAllSubscribers("SIGNED_IN",n)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return h(e)?{error:e}:{error:new p("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,s,r;try{const i=await X(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!==(s=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.data)&&void 0!==s?s:{},gotrue_meta_security:{captcha_token:null===(r=null==e?void 0:e.options)||void 0===r?void 0:r.captchaToken}},xform:Z}),{data:n,error:o}=i;if(o||!n)return{data:{user:null,session:null},error:o};const a=n.session,l=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:l,session:a},error:null}}catch(e){if(h(e))return{data:{user:null,session:null},error:e};throw e}}async signUp(e){var t,s,r;try{let i;if("email"in e){const{email:s,password:r,options:n}=e;let o=null,a=null;"pkce"===this.flowType&&([o,a]=await H(this.storage,this.storageKey)),i=await X(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:Z})}else{if(!("phone"in e))throw new w("You must provide either an email or phone number and a password");{const{phone:t,password:n,options:o}=e;i=await X(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:Z})}}const{data:n,error:o}=i;if(o||!n)return{data:{user:null,session:null},error:o};const a=n.session,l=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",a)),{data:{user:l,session:a},error:null}}catch(e){if(h(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithPassword(e){try{let t;if("email"in e){const{email:s,password:r,options:i}=e;t=await X(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:ee})}else{if(!("phone"in e))throw new w("You must provide either an email or phone number and a password");{const{phone:s,password:r,options:i}=e;t=await X(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:ee})}}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:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:r}):{data:{user:null,session:null},error:new y}}catch(e){if(h(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithOAuth(e){var t,s,r,i;return 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 signInWithWeb3(e){const{chain:t}=e;if("solana"===t)return await this.signInWithSolana(e);throw new Error(`@data-loom/auth-js: Unsupported chain "${t}"`)}async signInWithSolana(e){var t,s,r,i,n,o,a,l,c,u,d,f;let p,g;if("message"in e)p=e.message,g=e.signature;else{const{chain:h,wallet:d,statement:f,options:m}=e;let v;if(D())if("object"==typeof d)v=d;else{const e=window;if(!("solana"in e)||"object"!=typeof e.solana||!("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))throw new Error("@data-loom/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.");v=e.solana}else{if("object"!=typeof d||!(null==m?void 0:m.url))throw new Error("@data-loom/auth-js: Both wallet and url must be specified in non-browser environments.");v=d}const y=new URL(null!==(t=null==m?void 0:m.url)&&void 0!==t?t:window.location.href);if("signIn"in v&&v.signIn){const e=await v.signIn(Object.assign(Object.assign(Object.assign({issuedAt:(new Date).toISOString()},null==m?void 0:m.signInWithSolana),{version:"1",domain:y.host,uri:y.href}),f?{statement:f}:null));let t;if(Array.isArray(e)&&e[0]&&"object"==typeof e[0])t=e[0];else{if(!(e&&"object"==typeof e&&"signedMessage"in e&&"signature"in e))throw new Error("@data-loom/auth-js: Wallet method signIn() returned unrecognized value");t=e}if(!("signedMessage"in t&&"signature"in t&&("string"==typeof t.signedMessage||t.signedMessage instanceof Uint8Array)&&t.signature instanceof Uint8Array))throw new Error("@data-loom/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields");p="string"==typeof t.signedMessage?t.signedMessage:(new TextDecoder).decode(t.signedMessage),g=t.signature}else{if(!("signMessage"in v&&"function"==typeof v.signMessage&&"publicKey"in v&&"object"==typeof v&&v.publicKey&&"toBase58"in v.publicKey&&"function"==typeof v.publicKey.toBase58))throw new Error("@data-loom/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${y.host} wants you to sign in with your Solana account:`,v.publicKey.toBase58(),...f?["",f,""]:[""],"Version: 1",`URI: ${y.href}`,`Issued At: ${null!==(r=null===(s=null==m?void 0:m.signInWithSolana)||void 0===s?void 0:s.issuedAt)&&void 0!==r?r:(new Date).toISOString()}`,...(null===(i=null==m?void 0:m.signInWithSolana)||void 0===i?void 0:i.notBefore)?[`Not Before: ${m.signInWithSolana.notBefore}`]:[],...(null===(n=null==m?void 0:m.signInWithSolana)||void 0===n?void 0:n.expirationTime)?[`Expiration Time: ${m.signInWithSolana.expirationTime}`]:[],...(null===(o=null==m?void 0:m.signInWithSolana)||void 0===o?void 0:o.chainId)?[`Chain ID: ${m.signInWithSolana.chainId}`]:[],...(null===(a=null==m?void 0:m.signInWithSolana)||void 0===a?void 0:a.nonce)?[`Nonce: ${m.signInWithSolana.nonce}`]:[],...(null===(l=null==m?void 0:m.signInWithSolana)||void 0===l?void 0:l.requestId)?[`Request ID: ${m.signInWithSolana.requestId}`]:[],...(null===(u=null===(c=null==m?void 0:m.signInWithSolana)||void 0===c?void 0:c.resources)||void 0===u?void 0:u.length)?["Resources",...m.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");const e=await v.signMessage((new TextEncoder).encode(p),"utf8");if(!(e&&e instanceof Uint8Array))throw new Error("@data-loom/auth-js: Wallet signMessage() API returned an recognized value");g=e}}try{const{data:t,error:s}=await X(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:U(g)},(null===(d=e.options)||void 0===d?void 0:d.captchaToken)?{gotrue_meta_security:{captcha_token:null===(f=e.options)||void 0===f?void 0:f.captchaToken}}:null),xform:Z});if(s)throw s;return t&&t.session&&t.user?(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),{data:Object.assign({},t),error:s}):{data:{user:null,session:null},error:new y}}catch(e){if(h(e))return{data:{user:null,session:null},error:e};throw e}}async _exchangeCodeForSession(e){const t=await B(this.storage,`${this.storageKey}-code-verifier`),[s,r]=(null!=t?t:"").split("/");try{const{data:t,error:i}=await X(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:Z});if(await W(this.storage,`${this.storageKey}-code-verifier`),i)throw i;return t&&t.session&&t.user?(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),{data:Object.assign(Object.assign({},t),{redirectType:null!=r?r:null}),error:i}):{data:{user:null,session:null,redirectType:null},error:new y}}catch(e){if(h(e))return{data:{user:null,session:null,redirectType:null},error:e};throw e}}async signInWithIdToken(e){try{const{options:t,provider:s,token:r,access_token:i,nonce:n}=e,o=await X(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:Z}),{data:a,error:l}=o;return l?{data:{user:null,session:null},error:l}:a&&a.session&&a.user?(a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),{data:a,error:l}):{data:{user:null,session:null},error:new y}}catch(e){if(h(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithOtp(e){var t,s,r,i,n;try{if("email"in e){const{email:r,options:i}=e;let n=null,o=null;"pkce"===this.flowType&&([n,o]=await H(this.storage,this.storageKey));const{error:a}=await X(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 X(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 w("You must provide either an email or phone number.")}catch(e){if(h(e))return{data:{user:null,session:null},error:e};throw e}}async verifyOtp(e){var t,s;try{let r,i;"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 X(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:r,xform:Z});if(o)throw o;if(!n)throw new Error("An error occurred on token verification.");const a=n.session,l=n.user;return(null==a?void 0:a.access_token)&&(await this._saveSession(a),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",a)),{data:{user:l,session:a},error:null}}catch(e){if(h(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithSSO(e){var t,s,r;try{let i=null,n=null;return"pkce"===this.flowType&&([i,n]=await H(this.storage,this.storageKey)),await X(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,code_challenge:i,code_challenge_method:n}),headers:this.headers,xform:se})}catch(e){if(h(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 m;const{error:r}=await X(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:r}})}catch(e){if(h(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:s,type:r,options:i}=e,{error:n}=await X(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 X(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 w("You must provide either an email or phone number and a type")}catch(e){if(h(e))return{data:{user:null,session:null},error:e};throw e}}async getSession(){return await this.initializePromise,await 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;const t=await B(this.storage,this.storageKey);if(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())),!e)return{data:{session:null},error:null};const s=!!e.expires_at&&1e3*e.expires_at-Date.now()<9e4;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.storage.isServer){let t=this.suppressGetSessionWarning;e=new Proxy(e,{get:(e,s,r)=>(t||"user"!==s||(console.warn("Using the user object as returned from dataloom.auth.getSession() or from some dataloom.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use dataloom.auth.getUser() instead which authenticates the data by contacting the Dataloom Auth server."),t=!0,this.suppressGetSessionWarning=!0),Reflect.get(e,s,r))})}return{data:{session:e},error:null}}const{session:r,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{data:{session:r},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await X(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:te}):await this._useSession(async e=>{var t,s,r;const{data:i,error:n}=e;if(n)throw n;return(null===(t=i.session)||void 0===t?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await X(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(r=null===(s=i.session)||void 0===s?void 0:s.access_token)&&void 0!==r?r:void 0,xform:te}):{data:{user:null},error:new m}})}catch(e){if(h(e))return v(e)&&(await this._removeSession(),await W(this.storage,`${this.storageKey}-code-verifier`)),{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 m;const n=r.session;let o=null,a=null;"pkce"===this.flowType&&null!=e.email&&([o,a]=await H(this.storage,this.storageKey));const{data:l,error:c}=await X(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:te});if(c)throw c;return n.user=l.user,await this._saveSession(n),await this._notifyAllSubscribers("USER_UPDATED",n),{data:{user:n.user},error:null}})}catch(e){if(h(e))return{data:{user:null},error:e};throw 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 m;const t=Date.now()/1e3;let s=t,r=!0,i=null;const{payload:n}=z(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(h(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 m;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(h(e))return{data:{user:null,session:null},error:e};throw e}}async _getSessionFromURL(e,t){try{if(!D())throw new _("No browser detected.");if(e.error||e.error_description||e.error_code)throw new _(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if("pkce"===this.flowType)throw new k("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new _("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new k("No code detected.");const{data:t,error:s}=await this._exchangeCodeForSession(e.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:t.session,redirectType:null},error:null}}const{provider_token:s,provider_refresh_token:r,access_token:n,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!(n&&a&&o&&c))throw new _("No session defined in URL");const u=Math.round(Date.now()/1e3),h=parseInt(a);let d=u+h;l&&(d=parseInt(l));const f=d-u;1e3*f<=i&&console.warn(`@data-loom/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${h}s`);const p=d-h;u-p>=120?console.warn("@data-loom/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,d,u):u-p<0&&console.warn("@data-loom/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",p,d,u);const{data:g,error:m}=await this._getUser(n);if(m)throw m;const v={provider_token:s,provider_refresh_token:r,access_token:n,expires_in:h,expires_at:d,refresh_token:o,token_type:c,user:g.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:v,redirectType:e.type},error:null}}catch(e){if(h(e))return{data:{session:null,redirectType:null},error:e};throw e}}_isImplicitGrantCallback(e){return Boolean(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await B(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&&(!f(t)||404!==t.status&&401!==t.status&&403!==t.status))return{error:t}}return"others"!==e&&(await this._removeSession(),await W(this.storage,`${this.storageKey}-code-verifier`)),{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;"pkce"===this.flowType&&([s,r]=await H(this.storage,this.storageKey,!0));try{return await X(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(h(e))return{data:null,error:e};throw e}}async getUserIdentities(){var e;try{const{data:t,error:s}=await this.getUser();if(s)throw s;return{data:{identities:null!==(e=t.user.identities)&&void 0!==e?e:[]},error:null}}catch(e){if(h(e))return{data:null,error:e};throw e}}async linkIdentity(e){var t;try{const{data:s,error:r}=await this._useSession(async t=>{var s,r,i,n,o;const{data:a,error:l}=t;if(l)throw l;const c=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null===(s=e.options)||void 0===s?void 0:s.redirectTo,scopes:null===(r=e.options)||void 0===r?void 0:r.scopes,queryParams:null===(i=e.options)||void 0===i?void 0:i.queryParams,skipBrowserRedirect:!0});return await X(this.fetch,"GET",c,{headers:this.headers,jwt:null!==(o=null===(n=a.session)||void 0===n?void 0:n.access_token)&&void 0!==o?o:void 0})});if(r)throw r;return D()&&!(null===(t=e.options)||void 0===t?void 0:t.skipBrowserRedirect)&&window.location.assign(null==s?void 0:s.url),{data:{provider:e.provider,url:null==s?void 0:s.url},error:null}}catch(t){if(h(t))return{data:{provider:e.provider,url:null},error:t};throw t}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var s,r;const{data:i,error:n}=t;if(n)throw n;return await X(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!==(r=null===(s=i.session)||void 0===s?void 0:s.access_token)&&void 0!==r?r:void 0})})}catch(e){if(h(e))return{data:null,error:e};throw e}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const n=Date.now();return await(s=async s=>(s>0&&await async function(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await X(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Z})),r=(e,t)=>{const s=200*Math.pow(2,e);return t&&E(t)&&Date.now()+s-n<i},new Promise((e,t)=>{(async()=>{for(let i=0;i<1/0;i++)try{const t=await s(i);if(!r(i,null))return void e(t)}catch(e){if(!r(i,e))return void t(e)}})()}))}catch(e){if(this._debug(t,"error",e),h(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(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",s),D()&&!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 B(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=1e3*(null!==(e=s.expires_at)&&void 0!==e?e:1/0)-Date.now()<9e4;if(this._debug(t,`session has${r?"":" not"} expired with margin of 90000s`),r){if(this.autoRefreshToken&&s.refresh_token){const{error:e}=await this._callRefreshToken(s.refresh_token);e&&(console.error(e),E(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 m;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new J;const{data:t,error:s}=await this._refreshAccessToken(e);if(s)throw s;if(!t.session)throw new m;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),h(e)){const s={session:null,error:e};return E(e)||await this._removeSession(),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.suppressGetSessionWarning=!0,await M(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await W(this.storage,this.storageKey),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&D()&&(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(),i);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)/i);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 ce))throw e;this._debug("auto refresh token tick lock not available")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!D()||!(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,s){const r=[`provider=${encodeURIComponent(t)}`];if((null==s?void 0:s.redirectTo)&&r.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),(null==s?void 0:s.scopes)&&r.push(`scopes=${encodeURIComponent(s.scopes)}`),"pkce"===this.flowType){const[e,t]=await H(this.storage,this.storageKey),s=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});r.push(s.toString())}if(null==s?void 0:s.queryParams){const e=new URLSearchParams(s.queryParams);r.push(e.toString())}return(null==s?void 0:s.skipBrowserRedirect)&&r.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${r.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 X(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(h(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 o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:{issuer:e.issuer}),{data:a,error:l}=await X(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:null===(s=null==i?void 0:i.session)||void 0===s?void 0:s.access_token});return l?{data:null,error:l}:("totp"===e.factorType&&(null===(r=null==a?void 0:a.totp)||void 0===r?void 0:r.qr_code)&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(e){if(h(e))return{data:null,error:e};throw e}}async _verify(e){return this._acquireLock(-1,async()=>{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 X(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(h(e))return{data:null,error:e};throw e}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var s;const{data:r,error:i}=t;return i?{data:null,error:i}:await X(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},headers:this.headers,jwt:null===(s=null==r?void 0:r.session)||void 0===s?void 0:s.access_token})})}catch(e){if(h(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),i=s.filter(e=>"phone"===e.factor_type&&"verified"===e.status);return{data:{all:s,totp:r,phone:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>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{payload:n}=z(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}}))}async fetchJwk(e,t={keys:[]}){let s=t.keys.find(t=>t.kid===e);if(s)return s;if(s=this.jwks.keys.find(t=>t.kid===e),s&&this.jwks_cached_at+6e5>Date.now())return s;const{data:r,error:i}=await X(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;if(!r.keys||0===r.keys.length)throw new O("JWKS is empty");if(this.jwks=r,this.jwks_cached_at=Date.now(),s=r.keys.find(t=>t.kid===e),!s)throw new O("No matching signing key found in JWKS");return s}async getClaims(e,t={keys:[]}){try{let s=e;if(!s){const{data:e,error:t}=await this.getSession();if(t||!e.session)return{data:null,error:t};s=e.session.access_token}const{header:r,payload:i,signature:n,raw:{header:o,payload:a}}=z(s);if(function(e){if(!e)throw new Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw new Error("JWT has expired")}(i.exp),!r.kid||"HS256"===r.alg||!("crypto"in globalThis)||!("subtle"in globalThis.crypto)){const{error:e}=await this.getUser(s);if(e)throw e;return{data:{claims:i,header:r,signature:n},error:null}}const l=function(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}(r.alg),c=await this.fetchJwk(r.kid,t),u=await crypto.subtle.importKey("jwk",c,l,!0,["verify"]);if(!await crypto.subtle.verify(l,u,n,function(e){const t=[];return function(e,t){for(let s=0;s<e.length;s+=1){let r=e.charCodeAt(s);if(r>55295&&r<=56319){const t=1024*(r-55296)&65535;r=65536+(e.charCodeAt(s+1)-56320&65535|t),s+=1}C(r,t)}}(e,e=>t.push(e)),new Uint8Array(t)}(`${o}.${a}`)))throw new O("Invalid JWT signature");return{data:{claims:i,header:r,signature:n},error:null}}catch(e){if(h(e))return{data:null,error:e};throw e}}}pe.nextInstanceID=0;const ge=ne,me=pe},663:(e,t,s)=>{s.r(t),s.d(t,{Headers:()=>o,Request:()=>a,Response:()=>l,default:()=>n,fetch:()=>i});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")}();const i=r.fetch,n=r.fetch.bind(r),o=r.Headers,a=r.Request,l=r.Response},699:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0});class s{constructor(e){this.maxRequests=e,this.windowSizeMs=s.WINDOW_SIZE,this.requestCount=0,this.windowStart=Date.now()}checkAndResetWindow(){const e=Date.now();return e-this.windowStart>=this.windowSizeMs&&(this.requestCount=0,this.windowStart=e,!0)}canRequest(){return this.checkAndResetWindow(),this.requestCount<this.maxRequests&&(this.requestCount++,!0)}}s.WINDOW_SIZE=5e3,t.default=s},705:function(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(s(973));t.default=class{constructor(e,{headers:t={},schema:s,fetch:r,relation:i,logger:n,onRequestError:o}){this.url=e,this.headers=t,this.schema=s,this.fetch=r,this.relation=i,this.logger=n,this.onRequestError=o}select(e,{head:t=!1,count:s}={}){let r=!1;const n=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!r?"":('"'===e&&(r=!r),e)).join("");return this.url.searchParams.set("select",n),s&&(this.headers.Prefer=`count=${s}`),new i.default({method:"GET",url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1,logger:this.logger,onRequestError:this.onRequestError,relation:this.relation,action:"select"})}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 i.default({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1,logger:this.logger,onRequestError:this.onRequestError,relation:this.relation,action:"insert"})}upsert(e,{onConflict:t,ignoreDuplicates:s=!1,count:r,defaultToNull:n=!0}={}){const o=[`resolution=${s?"ignore":"merge"}-duplicates`];if(void 0!==t&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&o.push(this.headers.Prefer),r&&o.push(`count=${r}`),n||o.push("missing=default"),this.headers.Prefer=o.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 i.default({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1,logger:this.logger,onRequestError:this.onRequestError,relation:this.relation,action:"upsert"})}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 i.default({method:"PATCH",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1,logger:this.logger,onRequestError:this.onRequestError,relation:this.relation,action:"update"})}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 i.default({method:"DELETE",url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1,logger:this.logger,onRequestError:this.onRequestError,relation:this.relation,action:"delete"})}}},739:function(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.PostgrestError=t.PostgrestBuilder=t.PostgrestTransformBuilder=t.PostgrestFilterBuilder=t.PostgrestQueryBuilder=t.PostgrestClient=void 0;const i=r(s(597));t.PostgrestClient=i.default;const n=r(s(705));t.PostgrestQueryBuilder=n.default;const o=r(s(973));t.PostgrestFilterBuilder=o.default;const a=r(s(817));t.PostgrestTransformBuilder=a.default;const l=r(s(595));t.PostgrestBuilder=l.default;const c=r(s(886));t.PostgrestError=c.default,t.default={PostgrestClient:i.default,PostgrestQueryBuilder:n.default,PostgrestFilterBuilder:o.default,PostgrestTransformBuilder:a.default,PostgrestBuilder:l.default,PostgrestError:c.default}},755:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.version=void 0,t.version="0.0.0-automated"},817:function(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(s(595));class n extends i.default{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,referencedTable:i=r}={}){const n=i?`${i}.order`:"order",o=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${o?`${o},`:""}${e}.${t?"asc":"desc"}${void 0===s?"":s?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:s=t}={}){const r=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:s,referencedTable:r=s}={}){const i=void 0===r?"offset":`${r}.offset`,n=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(n,""+(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.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"}={}){var o;const a=[e?"analyze":null,t?"verbose":null,s?"settings":null,r?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=null!==(o=this.headers.Accept)&&void 0!==o?o:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${n}; for="${l}"; options=${a};`,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}}t.default=n},886:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0});class s extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}}t.default=s},946:function(e,t){var s=this&&this.__awaiter||function(e,t,s,r){return new(s||(s=Promise))(function(i,n){function o(e){try{l(r.next(e))}catch(e){n(e)}}function a(e){try{l(r.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s(function(e){e(t)})).then(o,a)}l((r=r.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.applySettingDefaults=t.isBrowser=t.stripTrailingSlash=t.deleteQueryFromUrl=t.getQueryFromUrl=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.getQueryFromUrl=function(e){return new URLSearchParams(window.location.search).get(e)},t.deleteQueryFromUrl=function(e){const t=new URL(window.location),s=new URLSearchParams(t.search);s.delete(e),t.search=s.toString(),history.replaceState(null,"",t.toString())},t.stripTrailingSlash=function(e){return e.replace(/\/$/,"")},t.isBrowser=()=>"undefined"!=typeof window,t.applySettingDefaults=function(e,t){const{db:r,auth:i,realtime:n,global:o}=e,{db:a,auth:l,realtime:c,global:u}=t,h={db:Object.assign(Object.assign({},a),r),auth:Object.assign(Object.assign({},l),i),realtime:Object.assign(Object.assign({},c),n),global:Object.assign(Object.assign({brandName:"",appId:""},u),o),accessToken:()=>s(this,void 0,void 0,function*(){return""})};return e.accessToken?h.accessToken=e.accessToken:delete h.accessToken,h}},973:function(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(s(817));class n extends i.default{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=Array.from(new Set(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}group(){return console.error("[Dataloom] group is not supported"),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,referencedTable:s=t}={}){const r=s?`${s}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,s){return this.url.searchParams.append(e,`${t}.${s}`),this}}t.default=n}},n={};function o(e){var t=n[e];if(void 0!==t)return t.exports;var s=n[e]={exports:{}};return i[e].call(s.exports,s,s.exports,o),s.exports}return o.m=i,t=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,o.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 i=Object.create(null);o.r(i);var n={};e=e||[null,t({}),t([]),t(t)];for(var a=2&r&&s;("object"==typeof a||"function"==typeof a)&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach(e=>n[e]=()=>s[e]);return n.default=()=>s,o.d(i,n),i},o.d=(e,t)=>{for(var s in t)o.o(t,s)&&!o.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},o.f={},o.e=e=>Promise.all(Object.keys(o.f).reduce((t,s)=>(o.f[s](e,t),t),[])),o.u=e=>e+".dataloom.js",o.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),s={},r="dataloom:",o.l=(e,t,i,n)=>{if(s[e])s[e].push(t);else{var a,l;if(void 0!==i)for(var c=document.getElementsByTagName("script"),u=0;u<c.length;u++){var h=c[u];if(h.getAttribute("src")==e||h.getAttribute("data-webpack")==r+i){a=h;break}}a||(l=!0,(a=document.createElement("script")).charset="utf-8",a.timeout=120,o.nc&&a.setAttribute("nonce",o.nc),a.setAttribute("data-webpack",r+i),a.src=e),s[e]=[t];var d=(t,r)=>{a.onerror=a.onload=null,clearTimeout(f);var i=s[e];if(delete s[e],a.parentNode&&a.parentNode.removeChild(a),i&&i.forEach(e=>e(r)),t)return t(r)},f=setTimeout(d.bind(null,void 0,{type:"timeout",target:a}),12e4);a.onerror=d.bind(null,a.onerror),a.onload=d.bind(null,a.onload),l&&document.head.appendChild(a)}},o.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;o.g.importScripts&&(e=o.g.location+"");var t=o.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var s=t.getElementsByTagName("script");if(s.length)for(var r=s.length-1;r>-1&&(!e||!/^http(s?):/.test(e));)e=s[r--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),o.p=e})(),(()=>{var e={792:0};o.f.j=(t,s)=>{var r=o.o(e,t)?e[t]:void 0;if(0!==r)if(r)s.push(r[2]);else{var i=new Promise((s,i)=>r=e[t]=[s,i]);s.push(r[2]=i);var n=o.p+o.u(t),a=new Error;o.l(n,s=>{if(o.o(e,t)&&(0!==(r=e[t])&&(e[t]=void 0),r)){var i=s&&("load"===s.type?"missing":s.type),n=s&&s.target&&s.target.src;a.message="Loading chunk "+t+" failed.\n("+i+": "+n+")",a.name="ChunkLoadError",a.type=i,a.request=n,r[1](a)}},"chunk-"+t,t)}};var t=(t,s)=>{var r,i,[n,a,l]=s,c=0;if(n.some(t=>0!==e[t])){for(r in a)o.o(a,r)&&(o.m[r]=a[r]);l&&l(o)}for(t&&t(s);c<n.length;c++)i=n[c],o.o(e,i)&&e[i]&&e[i][0](),e[i]=0},s=self.webpackChunkdataloom=self.webpackChunkdataloom||[];s.forEach(t.bind(null,0)),s.push=t.bind(null,s.push.bind(s))})(),o(93)})());
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@data-loom/js",
3
- "version": "0.4.5-alpha.1",
3
+ "version": "0.4.6",
4
4
  "description": "Isomorphic Javascript client for dataloom",
5
5
  "keywords": [
6
6
  "javascript",
@@ -37,13 +37,13 @@
37
37
  "serve:coverage": "npm run test:coverage && serve test/coverage"
38
38
  },
39
39
  "dependencies": {
40
- "@data-loom/auth-js": "0.4.5-alpha.1",
41
- "@data-loom/functions-js": "0.4.5-alpha.1",
42
- "@data-loom/node-fetch": "0.4.5-alpha.1",
43
- "@data-loom/postgrest-js": "0.4.5-alpha.1",
44
- "@data-loom/realtime-js": "0.4.5-alpha.1",
45
- "@data-loom/service-js": "0.4.5-alpha.1",
46
- "@data-loom/storage-js": "0.4.5-alpha.1"
40
+ "@data-loom/auth-js": "0.4.6",
41
+ "@data-loom/functions-js": "0.4.6",
42
+ "@data-loom/node-fetch": "0.4.6",
43
+ "@data-loom/postgrest-js": "0.4.6",
44
+ "@data-loom/realtime-js": "0.4.6",
45
+ "@data-loom/service-js": "0.4.6",
46
+ "@data-loom/storage-js": "0.4.6"
47
47
  },
48
48
  "devDependencies": {
49
49
  "@sebbo2002/semantic-release-jsr": "^1.0.0",