@pipelab/ui 2.0.0-beta.13 → 2.0.0-beta.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/assets/Layout-B-d3pxLP.js +298 -0
  2. package/assets/Layout-B4Y735hD.css +1 -0
  3. package/assets/{_plugin-vue_export-helper-DnUyRaRw.js → _plugin-vue_export-helper-DUvwmBqA.js} +1 -1
  4. package/assets/{accordion-D4pUR6oQ.js → accordion-CQHckkZB.js} +3 -3
  5. package/assets/checkbox-eE332h0t.js +142 -0
  6. package/assets/chevronright-CEOejICc.js +2 -0
  7. package/assets/connections-Bdn_SgRp.js +1 -0
  8. package/assets/connections-BeiEoaIH.css +1 -0
  9. package/assets/connections-CwgnMXsx.js +1 -0
  10. package/assets/editor-4NEin_NW.js +833 -0
  11. package/assets/editor-kSbnHXEq.css +1 -0
  12. package/assets/{emscripten-module-VHMWRAJ2-Cwd_19tX.js → emscripten-module-VHMWRAJ2-CzPuSaDz.js} +2 -2
  13. package/assets/index-CQ_uXHBu.css +1 -0
  14. package/assets/index-DP0T554c.js +764 -0
  15. package/assets/integrations-Cj1Vx59E.js +1 -0
  16. package/assets/integrations-DpXXW15s.css +1 -0
  17. package/assets/pages--YhhgGhJ.js +84 -0
  18. package/assets/pages-DxKiJJcA.css +1 -0
  19. package/assets/purify-Bi8etzni.js +3 -0
  20. package/assets/{radiobutton-9nNGO2-U.js → radiobutton-BzHJ-AQ-.js} +2 -2
  21. package/assets/scenarios-DZDVqLVy.js +1 -0
  22. package/assets/simple-editor-0Dmm-XdQ.js +1 -0
  23. package/assets/{src-VdpIHE4l.js → src-BjlUGrlv.js} +24 -24
  24. package/assets/tab-DXf4QtpC.js +150 -0
  25. package/assets/tag-Dpy3ystz.js +54 -0
  26. package/assets/team-HizKvSLh.js +1 -0
  27. package/assets/timescircle-cuYPa8ek.js +2 -0
  28. package/assets/toast-BL5hqRSf.js +280 -0
  29. package/assets/useTour-B1K1Ws1_.js +520 -0
  30. package/assets/useconfirm-Ds_TUlek.js +51 -0
  31. package/assets/usetoast-C1jmabqX.js +1735 -0
  32. package/assets/usetoast-bLNjwPI1.css +1 -0
  33. package/index.html +14 -10
  34. package/package.json +1 -1
  35. package/assets/Layout-B_ltqHnP.css +0 -1
  36. package/assets/Layout-Cr2_KAY5.js +0 -379
  37. package/assets/column-B4FcWIPk.js +0 -763
  38. package/assets/editor-BfSyH8v6.js +0 -833
  39. package/assets/editor-BsJqCx3h.css +0 -1
  40. package/assets/index-BTE2TTYB.css +0 -1
  41. package/assets/index-DUnNK5WW.js +0 -281
  42. package/assets/pages-DQdNphm0.js +0 -192
  43. package/assets/pages-Dp-OFXOW.css +0 -1
  44. package/assets/purify-D9mRGG16.js +0 -3
  45. package/assets/scenarios-LRTev2Ey.js +0 -1
  46. package/assets/simple-editor-qKdGmchp.js +0 -1
  47. package/assets/team-XL0bcZYO.js +0 -1
  48. package/assets/useTour-BaahCpXp.js +0 -669
  49. package/assets/useconfirm-DyXrgL_D.js +0 -52
  50. package/assets/usetoast-7I0RTgek.css +0 -1
  51. package/assets/usetoast-B8qjYDh_.js +0 -1877
  52. /package/assets/{__vite-browser-external-Dt3FoyYZ.js → __vite-browser-external-B0s46rwe.js} +0 -0
  53. /package/assets/{emscripten-module.browser-Pl-O77_z.js → emscripten-module.browser-eyQyO1-u.js} +0 -0
  54. /package/assets/{ffi-CJJc982W.js → ffi-BCdwDTfq.js} +0 -0
  55. /package/assets/{ffi-CoLfSXkO.js → ffi-DBzMjVua.js} +0 -0
  56. /package/assets/{module-6F3E5H7Y-D7eKX8Yv.js → module-6F3E5H7Y-DUb8SKDP.js} +0 -0
@@ -1,45 +1,45 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/module-6F3E5H7Y-D7eKX8Yv.js","assets/chunk-JTKJZQYV-BARLZAHU.js","assets/emscripten-module-VHMWRAJ2-Cwd_19tX.js","assets/chunk-DECur_0Z.js","assets/preload-helper-Dd-HcVz_.js"])))=>i.map(i=>d[i]);
2
- import{n as e,r as t,t as n}from"./chunk-DECur_0Z.js";import{S as r}from"./reactivity.esm-bundler-yhMxlGFU.js";import{o as i,t as a}from"./chunk-JTKJZQYV-BARLZAHU.js";import{t as o}from"./preload-helper-Dd-HcVz_.js";function s(e){return{version:e.version,up:async(t,n)=>{let r=e.up?await e.up(t,n):t;return r.version=n,r}}}var c=()=>{throw Error(`Unable to go up on the final version!`)},l=n(((e,t)=>{var n=`2.0.0`,r=256;t.exports={MAX_LENGTH:r,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:r-6,MAX_SAFE_INTEGER:2**53-1||9007199254740991,RELEASE_TYPES:[`major`,`premajor`,`minor`,`preminor`,`patch`,`prepatch`,`prerelease`],SEMVER_SPEC_VERSION:n,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}})),u=n(((e,t)=>{t.exports=typeof process==`object`&&{}.NODE_DEBUG&&/\bsemver\b/i.test({}.NODE_DEBUG)?(...e)=>console.error(`SEMVER`,...e):()=>{}})),d=n(((e,t)=>{var{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=l(),a=u();e=t.exports={};var o=e.re=[],s=e.safeRe=[],c=e.src=[],d=e.safeSrc=[],f=e.t={},p=0,m=`[a-zA-Z0-9-]`,h=[[`\\s`,1],[`\\d`,i],[m,r]],g=e=>{for(let[t,n]of h)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e},_=(e,t,n)=>{let r=g(t),i=p++;a(e,i,t),f[e]=i,c[i]=t,d[i]=r,o[i]=new RegExp(t,n?`g`:void 0),s[i]=new RegExp(r,n?`g`:void 0)};_(`NUMERICIDENTIFIER`,`0|[1-9]\\d*`),_(`NUMERICIDENTIFIERLOOSE`,`\\d+`),_(`NONNUMERICIDENTIFIER`,`\\d*[a-zA-Z-]${m}*`),_(`MAINVERSION`,`(${c[f.NUMERICIDENTIFIER]})\\.(${c[f.NUMERICIDENTIFIER]})\\.(${c[f.NUMERICIDENTIFIER]})`),_(`MAINVERSIONLOOSE`,`(${c[f.NUMERICIDENTIFIERLOOSE]})\\.(${c[f.NUMERICIDENTIFIERLOOSE]})\\.(${c[f.NUMERICIDENTIFIERLOOSE]})`),_(`PRERELEASEIDENTIFIER`,`(?:${c[f.NONNUMERICIDENTIFIER]}|${c[f.NUMERICIDENTIFIER]})`),_(`PRERELEASEIDENTIFIERLOOSE`,`(?:${c[f.NONNUMERICIDENTIFIER]}|${c[f.NUMERICIDENTIFIERLOOSE]})`),_(`PRERELEASE`,`(?:-(${c[f.PRERELEASEIDENTIFIER]}(?:\\.${c[f.PRERELEASEIDENTIFIER]})*))`),_(`PRERELEASELOOSE`,`(?:-?(${c[f.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[f.PRERELEASEIDENTIFIERLOOSE]})*))`),_(`BUILDIDENTIFIER`,`${m}+`),_(`BUILD`,`(?:\\+(${c[f.BUILDIDENTIFIER]}(?:\\.${c[f.BUILDIDENTIFIER]})*))`),_(`FULLPLAIN`,`v?${c[f.MAINVERSION]}${c[f.PRERELEASE]}?${c[f.BUILD]}?`),_(`FULL`,`^${c[f.FULLPLAIN]}$`),_(`LOOSEPLAIN`,`[v=\\s]*${c[f.MAINVERSIONLOOSE]}${c[f.PRERELEASELOOSE]}?${c[f.BUILD]}?`),_(`LOOSE`,`^${c[f.LOOSEPLAIN]}$`),_(`GTLT`,`((?:<|>)?=?)`),_(`XRANGEIDENTIFIERLOOSE`,`${c[f.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),_(`XRANGEIDENTIFIER`,`${c[f.NUMERICIDENTIFIER]}|x|X|\\*`),_(`XRANGEPLAIN`,`[v=\\s]*(${c[f.XRANGEIDENTIFIER]})(?:\\.(${c[f.XRANGEIDENTIFIER]})(?:\\.(${c[f.XRANGEIDENTIFIER]})(?:${c[f.PRERELEASE]})?${c[f.BUILD]}?)?)?`),_(`XRANGEPLAINLOOSE`,`[v=\\s]*(${c[f.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[f.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[f.XRANGEIDENTIFIERLOOSE]})(?:${c[f.PRERELEASELOOSE]})?${c[f.BUILD]}?)?)?`),_(`XRANGE`,`^${c[f.GTLT]}\\s*${c[f.XRANGEPLAIN]}$`),_(`XRANGELOOSE`,`^${c[f.GTLT]}\\s*${c[f.XRANGEPLAINLOOSE]}$`),_(`COERCEPLAIN`,`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),_(`COERCE`,`${c[f.COERCEPLAIN]}(?:$|[^\\d])`),_(`COERCEFULL`,c[f.COERCEPLAIN]+`(?:${c[f.PRERELEASE]})?(?:${c[f.BUILD]})?(?:$|[^\\d])`),_(`COERCERTL`,c[f.COERCE],!0),_(`COERCERTLFULL`,c[f.COERCEFULL],!0),_(`LONETILDE`,`(?:~>?)`),_(`TILDETRIM`,`(\\s*)${c[f.LONETILDE]}\\s+`,!0),e.tildeTrimReplace=`$1~`,_(`TILDE`,`^${c[f.LONETILDE]}${c[f.XRANGEPLAIN]}$`),_(`TILDELOOSE`,`^${c[f.LONETILDE]}${c[f.XRANGEPLAINLOOSE]}$`),_(`LONECARET`,`(?:\\^)`),_(`CARETTRIM`,`(\\s*)${c[f.LONECARET]}\\s+`,!0),e.caretTrimReplace=`$1^`,_(`CARET`,`^${c[f.LONECARET]}${c[f.XRANGEPLAIN]}$`),_(`CARETLOOSE`,`^${c[f.LONECARET]}${c[f.XRANGEPLAINLOOSE]}$`),_(`COMPARATORLOOSE`,`^${c[f.GTLT]}\\s*(${c[f.LOOSEPLAIN]})$|^$`),_(`COMPARATOR`,`^${c[f.GTLT]}\\s*(${c[f.FULLPLAIN]})$|^$`),_(`COMPARATORTRIM`,`(\\s*)${c[f.GTLT]}\\s*(${c[f.LOOSEPLAIN]}|${c[f.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace=`$1$2$3`,_(`HYPHENRANGE`,`^\\s*(${c[f.XRANGEPLAIN]})\\s+-\\s+(${c[f.XRANGEPLAIN]})\\s*$`),_(`HYPHENRANGELOOSE`,`^\\s*(${c[f.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[f.XRANGEPLAINLOOSE]})\\s*$`),_(`STAR`,`(<|>)?=?\\s*\\*`),_(`GTE0`,`^\\s*>=\\s*0\\.0\\.0\\s*$`),_(`GTE0PRE`,`^\\s*>=\\s*0\\.0\\.0-0\\s*$`)})),f=n(((e,t)=>{var n=Object.freeze({loose:!0}),r=Object.freeze({});t.exports=e=>e?typeof e==`object`?e:n:r})),p=n(((e,t)=>{var n=/^[0-9]+$/,r=(e,t)=>{if(typeof e==`number`&&typeof t==`number`)return e===t?0:e<t?-1:1;let r=n.test(e),i=n.test(t);return r&&i&&(e=+e,t=+t),e===t?0:r&&!i?-1:i&&!r?1:e<t?-1:1};t.exports={compareIdentifiers:r,rcompareIdentifiers:(e,t)=>r(t,e)}})),m=n(((e,t)=>{var n=u(),{MAX_LENGTH:r,MAX_SAFE_INTEGER:i}=l(),{safeRe:a,t:o}=d(),s=f(),{compareIdentifiers:c}=p();t.exports=class e{constructor(t,c){if(c=s(c),t instanceof e){if(t.loose===!!c.loose&&t.includePrerelease===!!c.includePrerelease)return t;t=t.version}else if(typeof t!=`string`)throw TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>r)throw TypeError(`version is longer than ${r} characters`);n(`SemVer`,t,c),this.options=c,this.loose=!!c.loose,this.includePrerelease=!!c.includePrerelease;let l=t.trim().match(c.loose?a[o.LOOSE]:a[o.FULL]);if(!l)throw TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+l[1],this.minor=+l[2],this.patch=+l[3],this.major>i||this.major<0)throw TypeError(`Invalid major version`);if(this.minor>i||this.minor<0)throw TypeError(`Invalid minor version`);if(this.patch>i||this.patch<0)throw TypeError(`Invalid patch version`);l[4]?this.prerelease=l[4].split(`.`).map(e=>{if(/^[0-9]+$/.test(e)){let t=+e;if(t>=0&&t<i)return t}return e}):this.prerelease=[],this.build=l[5]?l[5].split(`.`):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(`.`)}`),this.version}toString(){return this.version}compare(t){if(n(`SemVer.compare`,this.version,this.options,t),!(t instanceof e)){if(typeof t==`string`&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:+(this.patch>t.patch)}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let e=this.prerelease[r],i=t.prerelease[r];if(n(`prerelease compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e===i)continue;return c(e,i)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let e=this.build[r],i=t.build[r];if(n(`build compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e===i)continue;return c(e,i)}while(++r)}inc(e,t,n){if(e.startsWith(`pre`)){if(!t&&n===!1)throw Error(`invalid increment argument: identifier is empty`);if(t){let e=`-${t}`.match(this.options.loose?a[o.PRERELEASELOOSE]:a[o.PRERELEASE]);if(!e||e[1]!==t)throw Error(`invalid identifier: ${t}`)}}switch(e){case`premajor`:this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc(`pre`,t,n);break;case`preminor`:this.prerelease.length=0,this.patch=0,this.minor++,this.inc(`pre`,t,n);break;case`prepatch`:this.prerelease.length=0,this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`prerelease`:this.prerelease.length===0&&this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`release`:if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case`major`:(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case`minor`:(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case`patch`:this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case`pre`:{let e=+!!Number(n);if(this.prerelease.length===0)this.prerelease=[e];else{let r=this.prerelease.length;for(;--r>=0;)typeof this.prerelease[r]==`number`&&(this.prerelease[r]++,r=-2);if(r===-1){if(t===this.prerelease.join(`.`)&&n===!1)throw Error(`invalid increment argument: identifier already exists`);this.prerelease.push(e)}}if(t){let r=[t,e];n===!1&&(r=[t]),c(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=r):this.prerelease=r}break}default:throw Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(`.`)}`),this}}})),h=n(((e,t)=>{var n=m();t.exports=(e,t,r=!1)=>{if(e instanceof n)return e;try{return new n(e,t)}catch(e){if(!r)return null;throw e}}})),g=n(((e,t)=>{var n=h();t.exports=(e,t)=>{let r=n(e,t);return r?r.version:null}})),_=n(((e,t)=>{var n=h();t.exports=(e,t)=>{let r=n(e.trim().replace(/^[=v]+/,``),t);return r?r.version:null}})),v=n(((e,t)=>{var n=m();t.exports=(e,t,r,i,a)=>{typeof r==`string`&&(a=i,i=r,r=void 0);try{return new n(e instanceof n?e.version:e,r).inc(t,i,a).version}catch{return null}}})),y=n(((e,t)=>{var n=h();t.exports=(e,t)=>{let r=n(e,null,!0),i=n(t,null,!0),a=r.compare(i);if(a===0)return null;let o=a>0,s=o?r:i,c=o?i:r,l=!!s.prerelease.length;if(c.prerelease.length&&!l){if(!c.patch&&!c.minor)return`major`;if(c.compareMain(s)===0)return c.minor&&!c.patch?`minor`:`patch`}let u=l?`pre`:``;return r.major===i.major?r.minor===i.minor?r.patch===i.patch?`prerelease`:u+`patch`:u+`minor`:u+`major`}})),ee=n(((e,t)=>{var n=m();t.exports=(e,t)=>new n(e,t).major})),te=n(((e,t)=>{var n=m();t.exports=(e,t)=>new n(e,t).minor})),ne=n(((e,t)=>{var n=m();t.exports=(e,t)=>new n(e,t).patch})),re=n(((e,t)=>{var n=h();t.exports=(e,t)=>{let r=n(e,t);return r&&r.prerelease.length?r.prerelease:null}})),b=n(((e,t)=>{var n=m();t.exports=(e,t,r)=>new n(e,r).compare(new n(t,r))})),ie=n(((e,t)=>{var n=b();t.exports=(e,t,r)=>n(t,e,r)})),ae=n(((e,t)=>{var n=b();t.exports=(e,t)=>n(e,t,!0)})),oe=n(((e,t)=>{var n=m();t.exports=(e,t,r)=>{let i=new n(e,r),a=new n(t,r);return i.compare(a)||i.compareBuild(a)}})),se=n(((e,t)=>{var n=oe();t.exports=(e,t)=>e.sort((e,r)=>n(e,r,t))})),ce=n(((e,t)=>{var n=oe();t.exports=(e,t)=>e.sort((e,r)=>n(r,e,t))})),le=n(((e,t)=>{var n=b();t.exports=(e,t,r)=>n(e,t,r)>0})),ue=n(((e,t)=>{var n=b();t.exports=(e,t,r)=>n(e,t,r)<0})),de=n(((e,t)=>{var n=b();t.exports=(e,t,r)=>n(e,t,r)===0})),fe=n(((e,t)=>{var n=b();t.exports=(e,t,r)=>n(e,t,r)!==0})),pe=n(((e,t)=>{var n=b();t.exports=(e,t,r)=>n(e,t,r)>=0})),me=n(((e,t)=>{var n=b();t.exports=(e,t,r)=>n(e,t,r)<=0})),he=n(((e,t)=>{var n=de(),r=fe(),i=le(),a=pe(),o=ue(),s=me();t.exports=(e,t,c,l)=>{switch(t){case`===`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e===c;case`!==`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e!==c;case``:case`=`:case`==`:return n(e,c,l);case`!=`:return r(e,c,l);case`>`:return i(e,c,l);case`>=`:return a(e,c,l);case`<`:return o(e,c,l);case`<=`:return s(e,c,l);default:throw TypeError(`Invalid operator: ${t}`)}}})),ge=n(((e,t)=>{var n=m(),r=h(),{safeRe:i,t:a}=d();t.exports=(e,t)=>{if(e instanceof n)return e;if(typeof e==`number`&&(e=String(e)),typeof e!=`string`)return null;t||={};let o=null;if(!t.rtl)o=e.match(t.includePrerelease?i[a.COERCEFULL]:i[a.COERCE]);else{let n=t.includePrerelease?i[a.COERCERTLFULL]:i[a.COERCERTL],r;for(;(r=n.exec(e))&&(!o||o.index+o[0].length!==e.length);)(!o||r.index+r[0].length!==o.index+o[0].length)&&(o=r),n.lastIndex=r.index+r[1].length+r[2].length;n.lastIndex=-1}if(o===null)return null;let s=o[2];return r(`${s}.${o[3]||`0`}.${o[4]||`0`}${t.includePrerelease&&o[5]?`-${o[5]}`:``}${t.includePrerelease&&o[6]?`+${o[6]}`:``}`,t)}})),_e=n(((e,t)=>{t.exports=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}})),x=n(((e,t)=>{var n=/\s+/g;t.exports=class e{constructor(t,r){if(r=i(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof a)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(n,` `),this.set=this.raw.split(`||`).map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let e=this.set[0];if(this.set=this.set.filter(e=>!ee(e[0])),this.set.length===0)this.set=[e];else if(this.set.length>1){for(let e of this.set)if(e.length===1&&te(e[0])){this.set=[e];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted=``;for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+=`||`);let t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=` `),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let t=((this.options.includePrerelease&&v)|(this.options.loose&&y))+`:`+e,n=r.get(t);if(n)return n;let i=this.options.loose,s=i?c[p.HYPHENRANGELOOSE]:c[p.HYPHENRANGE];e=e.replace(s,fe(this.options.includePrerelease)),o(`hyphen replace`,e),e=e.replace(c[p.COMPARATORTRIM],h),o(`comparator trim`,e),e=e.replace(c[p.TILDETRIM],g),o(`tilde trim`,e),e=e.replace(c[p.CARETTRIM],_),o(`caret trim`,e);let l=e.split(` `).map(e=>re(e,this.options)).join(` `).split(/\s+/).map(e=>de(e,this.options));i&&(l=l.filter(e=>(o(`loose invalid filter`,e,this.options),!!e.match(c[p.COMPARATORLOOSE])))),o(`range list`,l);let u=new Map,d=l.map(e=>new a(e,this.options));for(let e of d){if(ee(e))return[e];u.set(e.value,e)}u.size>1&&u.has(``)&&u.delete(``);let f=[...u.values()];return r.set(t,f),f}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Range is required`);return this.set.some(e=>ne(e,n)&&t.set.some(t=>ne(t,n)&&e.every(e=>t.every(t=>e.intersects(t,n)))))}test(e){if(!e)return!1;if(typeof e==`string`)try{e=new s(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(pe(this.set[t],e,this.options))return!0;return!1}};var r=new(_e()),i=f(),a=ve(),o=u(),s=m(),{safeRe:c,t:p,comparatorTrimReplace:h,tildeTrimReplace:g,caretTrimReplace:_}=d(),{FLAG_INCLUDE_PRERELEASE:v,FLAG_LOOSE:y}=l(),ee=e=>e.value===`<0.0.0-0`,te=e=>e.value===``,ne=(e,t)=>{let n=!0,r=e.slice(),i=r.pop();for(;n&&r.length;)n=r.every(e=>i.intersects(e,t)),i=r.pop();return n},re=(e,t)=>(e=e.replace(c[p.BUILD],``),o(`comp`,e,t),e=oe(e,t),o(`caret`,e),e=ie(e,t),o(`tildes`,e),e=ce(e,t),o(`xrange`,e),e=ue(e,t),o(`stars`,e),e),b=e=>!e||e.toLowerCase()===`x`||e===`*`,ie=(e,t)=>e.trim().split(/\s+/).map(e=>ae(e,t)).join(` `),ae=(e,t)=>{let n=t.loose?c[p.TILDELOOSE]:c[p.TILDE];return e.replace(n,(t,n,r,i,a)=>{o(`tilde`,e,t,n,r,i,a);let s;return b(n)?s=``:b(r)?s=`>=${n}.0.0 <${+n+1}.0.0-0`:b(i)?s=`>=${n}.${r}.0 <${n}.${+r+1}.0-0`:a?(o(`replaceTilde pr`,a),s=`>=${n}.${r}.${i}-${a} <${n}.${+r+1}.0-0`):s=`>=${n}.${r}.${i} <${n}.${+r+1}.0-0`,o(`tilde return`,s),s})},oe=(e,t)=>e.trim().split(/\s+/).map(e=>se(e,t)).join(` `),se=(e,t)=>{o(`caret`,e,t);let n=t.loose?c[p.CARETLOOSE]:c[p.CARET],r=t.includePrerelease?`-0`:``;return e.replace(n,(t,n,i,a,s)=>{o(`caret`,e,t,n,i,a,s);let c;return b(n)?c=``:b(i)?c=`>=${n}.0.0${r} <${+n+1}.0.0-0`:b(a)?c=n===`0`?`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.0${r} <${+n+1}.0.0-0`:s?(o(`replaceCaret pr`,s),c=n===`0`?i===`0`?`>=${n}.${i}.${a}-${s} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}-${s} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a}-${s} <${+n+1}.0.0-0`):(o(`no pr`),c=n===`0`?i===`0`?`>=${n}.${i}.${a}${r} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a} <${+n+1}.0.0-0`),o(`caret return`,c),c})},ce=(e,t)=>(o(`replaceXRanges`,e,t),e.split(/\s+/).map(e=>le(e,t)).join(` `)),le=(e,t)=>{e=e.trim();let n=t.loose?c[p.XRANGELOOSE]:c[p.XRANGE];return e.replace(n,(n,r,i,a,s,c)=>{o(`xRange`,e,n,r,i,a,s,c);let l=b(i),u=l||b(a),d=u||b(s),f=d;return r===`=`&&f&&(r=``),c=t.includePrerelease?`-0`:``,l?n=r===`>`||r===`<`?`<0.0.0-0`:`*`:r&&f?(u&&(a=0),s=0,r===`>`?(r=`>=`,u?(i=+i+1,a=0,s=0):(a=+a+1,s=0)):r===`<=`&&(r=`<`,u?i=+i+1:a=+a+1),r===`<`&&(c=`-0`),n=`${r+i}.${a}.${s}${c}`):u?n=`>=${i}.0.0${c} <${+i+1}.0.0-0`:d&&(n=`>=${i}.${a}.0${c} <${i}.${+a+1}.0-0`),o(`xRange return`,n),n})},ue=(e,t)=>(o(`replaceStars`,e,t),e.trim().replace(c[p.STAR],``)),de=(e,t)=>(o(`replaceGTE0`,e,t),e.trim().replace(c[t.includePrerelease?p.GTE0PRE:p.GTE0],``)),fe=e=>(t,n,r,i,a,o,s,c,l,u,d,f)=>(n=b(r)?``:b(i)?`>=${r}.0.0${e?`-0`:``}`:b(a)?`>=${r}.${i}.0${e?`-0`:``}`:o?`>=${n}`:`>=${n}${e?`-0`:``}`,c=b(l)?``:b(u)?`<${+l+1}.0.0-0`:b(d)?`<${l}.${+u+1}.0-0`:f?`<=${l}.${u}.${d}-${f}`:e?`<${l}.${u}.${+d+1}-0`:`<=${c}`,`${n} ${c}`.trim()),pe=(e,t,n)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(let n=0;n<e.length;n++)if(o(e[n].semver),e[n].semver!==a.ANY&&e[n].semver.prerelease.length>0){let r=e[n].semver;if(r.major===t.major&&r.minor===t.minor&&r.patch===t.patch)return!0}return!1}return!0}})),ve=n(((e,t)=>{var n=Symbol(`SemVer ANY`);t.exports=class e{static get ANY(){return n}constructor(t,i){if(i=r(i),t instanceof e){if(t.loose===!!i.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(` `),s(`comparator`,t,i),this.options=i,this.loose=!!i.loose,this.parse(t),this.semver===n?this.value=``:this.value=this.operator+this.semver.version,s(`comp`,this)}parse(e){let t=this.options.loose?i[a.COMPARATORLOOSE]:i[a.COMPARATOR],r=e.match(t);if(!r)throw TypeError(`Invalid comparator: ${e}`);this.operator=r[1]===void 0?``:r[1],this.operator===`=`&&(this.operator=``),r[2]?this.semver=new c(r[2],this.options.loose):this.semver=n}toString(){return this.value}test(e){if(s(`Comparator.test`,e,this.options.loose),this.semver===n||e===n)return!0;if(typeof e==`string`)try{e=new c(e,this.options)}catch{return!1}return o(e,this.operator,this.semver,this.options)}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Comparator is required`);return this.operator===``?this.value===``?!0:new l(t.value,n).test(this.value):t.operator===``?t.value===``?!0:new l(this.value,n).test(t.semver):(n=r(n),n.includePrerelease&&(this.value===`<0.0.0-0`||t.value===`<0.0.0-0`)||!n.includePrerelease&&(this.value.startsWith(`<0.0.0`)||t.value.startsWith(`<0.0.0`))?!1:!!(this.operator.startsWith(`>`)&&t.operator.startsWith(`>`)||this.operator.startsWith(`<`)&&t.operator.startsWith(`<`)||this.semver.version===t.semver.version&&this.operator.includes(`=`)&&t.operator.includes(`=`)||o(this.semver,`<`,t.semver,n)&&this.operator.startsWith(`>`)&&t.operator.startsWith(`<`)||o(this.semver,`>`,t.semver,n)&&this.operator.startsWith(`<`)&&t.operator.startsWith(`>`)))}};var r=f(),{safeRe:i,t:a}=d(),o=he(),s=u(),c=m(),l=x()})),ye=n(((e,t)=>{var n=x();t.exports=(e,t,r)=>{try{t=new n(t,r)}catch{return!1}return t.test(e)}})),be=n(((e,t)=>{var n=x();t.exports=(e,t)=>new n(e,t).set.map(e=>e.map(e=>e.value).join(` `).trim().split(` `))})),xe=n(((e,t)=>{var n=m(),r=x();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===-1)&&(a=e,o=new n(a,i))}),a}})),Se=n(((e,t)=>{var n=m(),r=x();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===1)&&(a=e,o=new n(a,i))}),a}})),Ce=n(((e,t)=>{var n=m(),r=x(),i=le();t.exports=(e,t)=>{e=new r(e,t);let a=new n(`0.0.0`);if(e.test(a)||(a=new n(`0.0.0-0`),e.test(a)))return a;a=null;for(let t=0;t<e.set.length;++t){let r=e.set[t],o=null;r.forEach(e=>{let t=new n(e.semver.version);switch(e.operator){case`>`:t.prerelease.length===0?t.patch++:t.prerelease.push(0),t.raw=t.format();case``:case`>=`:(!o||i(t,o))&&(o=t);break;case`<`:case`<=`:break;default:throw Error(`Unexpected operation: ${e.operator}`)}}),o&&(!a||i(a,o))&&(a=o)}return a&&e.test(a)?a:null}})),we=n(((e,t)=>{var n=x();t.exports=(e,t)=>{try{return new n(e,t).range||`*`}catch{return null}}})),Te=n(((e,t)=>{var n=m(),r=ve(),{ANY:i}=r,a=x(),o=ye(),s=le(),c=ue(),l=me(),u=pe();t.exports=(e,t,d,f)=>{e=new n(e,f),t=new a(t,f);let p,m,h,g,_;switch(d){case`>`:p=s,m=l,h=c,g=`>`,_=`>=`;break;case`<`:p=c,m=u,h=s,g=`<`,_=`<=`;break;default:throw TypeError(`Must provide a hilo val of "<" or ">"`)}if(o(e,t,f))return!1;for(let n=0;n<t.set.length;++n){let a=t.set[n],o=null,s=null;if(a.forEach(e=>{e.semver===i&&(e=new r(`>=0.0.0`)),o||=e,s||=e,p(e.semver,o.semver,f)?o=e:h(e.semver,s.semver,f)&&(s=e)}),o.operator===g||o.operator===_||(!s.operator||s.operator===g)&&m(e,s.semver)||s.operator===_&&h(e,s.semver))return!1}return!0}})),Ee=n(((e,t)=>{var n=Te();t.exports=(e,t,r)=>n(e,t,`>`,r)})),De=n(((e,t)=>{var n=Te();t.exports=(e,t,r)=>n(e,t,`<`,r)})),Oe=n(((e,t)=>{var n=x();t.exports=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r))})),ke=n(((e,t)=>{var n=ye(),r=b();t.exports=(e,t,i)=>{let a=[],o=null,s=null,c=e.sort((e,t)=>r(e,t,i));for(let e of c)n(e,t,i)?(s=e,o||=e):(s&&a.push([o,s]),s=null,o=null);o&&a.push([o,null]);let l=[];for(let[e,t]of a)e===t?l.push(e):!t&&e===c[0]?l.push(`*`):t?e===c[0]?l.push(`<=${t}`):l.push(`${e} - ${t}`):l.push(`>=${e}`);let u=l.join(` || `),d=typeof t.raw==`string`?t.raw:String(t);return u.length<d.length?u:t}})),Ae=n(((e,t)=>{var n=x(),r=ve(),{ANY:i}=r,a=ye(),o=b(),s=(e,t,r={})=>{if(e===t)return!0;e=new n(e,r),t=new n(t,r);let i=!1;OUTER:for(let n of e.set){for(let e of t.set){let t=u(n,e,r);if(i||=t!==null,t)continue OUTER}if(i)return!1}return!0},c=[new r(`>=0.0.0-0`)],l=[new r(`>=0.0.0`)],u=(e,t,n)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===i){if(t.length===1&&t[0].semver===i)return!0;e=n.includePrerelease?c:l}if(t.length===1&&t[0].semver===i){if(n.includePrerelease)return!0;t=l}let r=new Set,s,u;for(let t of e)t.operator===`>`||t.operator===`>=`?s=d(s,t,n):t.operator===`<`||t.operator===`<=`?u=f(u,t,n):r.add(t.semver);if(r.size>1)return null;let p;if(s&&u&&(p=o(s.semver,u.semver,n),p>0||p===0&&(s.operator!==`>=`||u.operator!==`<=`)))return null;for(let e of r){if(s&&!a(e,String(s),n)||u&&!a(e,String(u),n))return null;for(let r of t)if(!a(e,String(r),n))return!1;return!0}let m,h,g,_,v=u&&!n.includePrerelease&&u.semver.prerelease.length?u.semver:!1,y=s&&!n.includePrerelease&&s.semver.prerelease.length?s.semver:!1;v&&v.prerelease.length===1&&u.operator===`<`&&v.prerelease[0]===0&&(v=!1);for(let e of t){if(_=_||e.operator===`>`||e.operator===`>=`,g=g||e.operator===`<`||e.operator===`<=`,s){if(y&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===y.major&&e.semver.minor===y.minor&&e.semver.patch===y.patch&&(y=!1),e.operator===`>`||e.operator===`>=`){if(m=d(s,e,n),m===e&&m!==s)return!1}else if(s.operator===`>=`&&!a(s.semver,String(e),n))return!1}if(u){if(v&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===v.major&&e.semver.minor===v.minor&&e.semver.patch===v.patch&&(v=!1),e.operator===`<`||e.operator===`<=`){if(h=f(u,e,n),h===e&&h!==u)return!1}else if(u.operator===`<=`&&!a(u.semver,String(e),n))return!1}if(!e.operator&&(u||s)&&p!==0)return!1}return!(s&&g&&!u&&p!==0||u&&_&&!s&&p!==0||y||v)},d=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r>0?e:r<0||t.operator===`>`&&e.operator===`>=`?t:e},f=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r<0?e:r>0||t.operator===`<`&&e.operator===`<=`?t:e};t.exports=s})),je=t(n(((e,t)=>{var n=d(),r=l(),i=m(),a=p();t.exports={parse:h(),valid:g(),clean:_(),inc:v(),diff:y(),major:ee(),minor:te(),patch:ne(),prerelease:re(),compare:b(),rcompare:ie(),compareLoose:ae(),compareBuild:oe(),sort:se(),rsort:ce(),gt:le(),lt:ue(),eq:de(),neq:fe(),gte:pe(),lte:me(),cmp:he(),coerce:ge(),Comparator:ve(),Range:x(),satisfies:ye(),toComparators:be(),maxSatisfying:xe(),minSatisfying:Se(),minVersion:Ce(),validRange:we(),outside:Te(),gtr:Ee(),ltr:De(),intersects:Oe(),simplifyRange:ke(),subset:Ae(),SemVer:i,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:r.SEMVER_SPEC_VERSION,RELEASE_TYPES:r.RELEASE_TYPES,compareIdentifiers:a.compareIdentifiers,rcompareIdentifiers:a.rcompareIdentifiers}}))(),1),Me=Object.keys;function S(e){if(typeof e!=`object`)return e;var t,n,r=Object.prototype.toString.call(e);if(r===`[object Object]`){if(e.constructor!==Object&&typeof e.constructor==`function`)for(t in n=new e.constructor,e)e.hasOwnProperty(t)&&n[t]!==e[t]&&(n[t]=S(e[t]));else for(t in n={},e)t===`__proto__`?Object.defineProperty(n,t,{value:S(e[t]),configurable:!0,enumerable:!0,writable:!0}):n[t]=S(e[t]);return n}if(r===`[object Array]`){for(t=e.length,n=Array(t);t--;)n[t]=S(e[t]);return n}return r===`[object Set]`?(n=new Set,e.forEach(function(e){n.add(S(e))}),n):r===`[object Map]`?(n=new Map,e.forEach(function(e,t){n.set(S(t),S(e))}),n):r===`[object Date]`?new Date(+e):r===`[object RegExp]`?(n=new RegExp(e.source,e.flags),n.lastIndex=e.lastIndex,n):r===`[object DataView]`?new e.constructor(S(e.buffer)):r===`[object ArrayBuffer]`?e.slice(0):r.slice(-6)===`Array]`?new e.constructor(e):e}var Ne=/^[\w+-]+(?:\.[\w+-]+)*@[\da-z]+(?:[.-][\da-z]+)*\.[a-z]{2,}$/iu,Pe;function Fe(e){return{lang:e?.lang??Pe?.lang,message:e?.message,abortEarly:e?.abortEarly??Pe?.abortEarly,abortPipeEarly:e?.abortPipeEarly??Pe?.abortPipeEarly}}var Ie;function Le(e){return Ie?.get(e)}var Re;function ze(e){return Re?.get(e)}var Be;function Ve(e,t){return Be?.get(e)?.get(t)}function He(e){let t=typeof e;return t===`string`?`"${e}"`:t===`number`||t===`bigint`||t===`boolean`?`${e}`:t===`object`||t===`function`?(e&&Object.getPrototypeOf(e)?.constructor?.name)??`null`:t}function C(e,t,n,r,i){let a=i&&`input`in i?i.input:n.value,o=i?.expected??e.expects??null,s=i?.received??He(a),c={kind:e.kind,type:e.type,input:a,expected:o,received:s,message:`Invalid ${t}: ${o?`Expected ${o} but r`:`R`}eceived ${s}`,requirement:e.requirement,path:i?.path,issues:i?.issues,lang:r.lang,abortEarly:r.abortEarly,abortPipeEarly:r.abortPipeEarly},l=e.kind===`schema`,u=i?.message??e.message??Ve(e.reference,c.lang)??(l?ze(c.lang):null)??r.message??Le(c.lang);u&&(c.message=typeof u==`function`?u(c):u),l&&(n.typed=!1),n.issues?n.issues.push(c):n.issues=[c]}function Ue(e,t){return Object.hasOwn(e,t)&&t!==`__proto__`&&t!==`prototype`&&t!==`constructor`}function We(e,t){let n=[...new Set(e)];return n.length>1?`(${n.join(` ${t} `)})`:n[0]??`never`}var Ge=class extends Error{issues;constructor(e){super(e[0].message),this.name=`ValiError`,this.issues=e}};function Ke(e){return{kind:`metadata`,type:`description`,reference:Ke,description:e}}function qe(e){return{kind:`validation`,type:`email`,reference:qe,expects:null,async:!1,requirement:Ne,message:e,_run(e,t){return e.typed&&!this.requirement.test(e.value)&&C(this,`email`,e,t),e}}}function Je(e,t){return{kind:`validation`,type:`min_length`,reference:Je,async:!1,expects:`>=${e}`,requirement:e,message:t,_run(e,t){return e.typed&&e.value.length<this.requirement&&C(this,`length`,e,t,{received:`${e.value.length}`}),e}}}function Ye(e){return{kind:`validation`,type:`non_empty`,reference:Ye,async:!1,expects:`!0`,message:e,_run(e,t){return e.typed&&e.value.length===0&&C(this,`length`,e,t,{received:`0`}),e}}}function Xe(e,t){return{kind:`validation`,type:`regex`,reference:Xe,async:!1,expects:`${e}`,requirement:e,message:t,_run(e,t){return e.typed&&!this.requirement.test(e.value)&&C(this,`format`,e,t),e}}}function Ze(e,t,n){return typeof e.default==`function`?e.default(t,n):e.default}function Qe(){return{kind:`schema`,type:`any`,reference:Qe,expects:`any`,async:!1,_run(e){return e.typed=!0,e}}}function w(e,t){return{kind:`schema`,type:`array`,reference:w,expects:`Array`,async:!1,item:e,message:t,_run(e,t){let n=e.value;if(Array.isArray(n)){e.typed=!0,e.value=[];for(let r=0;r<n.length;r++){let i=n[r],a=this.item._run({typed:!1,value:i},t);if(a.issues){let o={type:`array`,origin:`value`,input:n,key:r,value:i};for(let t of a.issues)t.path?t.path.unshift(o):t.path=[o],e.issues?.push(t);if(e.issues||=a.issues,t.abortEarly){e.typed=!1;break}}a.typed||(e.typed=!1),e.value.push(a.value)}}else C(this,`type`,e,t);return e}}}function T(e){return{kind:`schema`,type:`boolean`,reference:T,expects:`boolean`,async:!1,message:e,_run(e,t){return typeof e.value==`boolean`?e.typed=!0:C(this,`type`,e,t),e}}}function $e(e,t){return{kind:`schema`,type:`custom`,reference:$e,expects:`unknown`,async:!1,check:e,message:t,_run(e,t){return this.check(e.value)?e.typed=!0:C(this,`type`,e,t),e}}}function E(e,t){return{kind:`schema`,type:`literal`,reference:E,expects:He(e),async:!1,literal:e,message:t,_run(e,t){return e.value===this.literal?e.typed=!0:C(this,`type`,e,t),e}}}function et(e){return{kind:`schema`,type:`number`,reference:et,expects:`number`,async:!1,message:e,_run(e,t){return typeof e.value==`number`&&!isNaN(e.value)?e.typed=!0:C(this,`type`,e,t),e}}}function D(e,t){return{kind:`schema`,type:`object`,reference:D,expects:`Object`,async:!1,entries:e,message:t,_run(e,t){let n=e.value;if(n&&typeof n==`object`){e.typed=!0,e.value={};for(let r in this.entries){let i=n[r],a=this.entries[r]._run({typed:!1,value:i},t);if(a.issues){let o={type:`object`,origin:`value`,input:n,key:r,value:i};for(let t of a.issues)t.path?t.path.unshift(o):t.path=[o],e.issues?.push(t);if(e.issues||=a.issues,t.abortEarly){e.typed=!1;break}}a.typed||(e.typed=!1),(a.value!==void 0||r in n)&&(e.value[r]=a.value)}}else C(this,`type`,e,t);return e}}}function O(e,...t){let n={kind:`schema`,type:`optional`,reference:O,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,_run(e,t){return e.value===void 0&&(`default`in this&&(e.value=Ze(this,e,t)),e.value===void 0)?(e.typed=!0,e):this.wrapped._run(e,t)}};return 0 in t&&(n.default=t[0]),n}function tt(e,t,n){return{kind:`schema`,type:`record`,reference:tt,expects:`Object`,async:!1,key:e,value:t,message:n,_run(e,t){let n=e.value;if(n&&typeof n==`object`){e.typed=!0,e.value={};for(let r in n)if(Ue(n,r)){let i=n[r],a=this.key._run({typed:!1,value:r},t);if(a.issues){let o={type:`object`,origin:`key`,input:n,key:r,value:i};for(let t of a.issues)t.path=[o],e.issues?.push(t);if(e.issues||=a.issues,t.abortEarly){e.typed=!1;break}}let o=this.value._run({typed:!1,value:i},t);if(o.issues){let a={type:`object`,origin:`value`,input:n,key:r,value:i};for(let t of o.issues)t.path?t.path.unshift(a):t.path=[a],e.issues?.push(t);if(e.issues||=o.issues,t.abortEarly){e.typed=!1;break}}(!a.typed||!o.typed)&&(e.typed=!1),a.typed&&(e.value[a.value]=o.value)}}else C(this,`type`,e,t);return e}}}function k(e){return{kind:`schema`,type:`string`,reference:k,expects:`string`,async:!1,message:e,_run(e,t){return typeof e.value==`string`?e.typed=!0:C(this,`type`,e,t),e}}}function nt(e){let t;if(e)for(let n of e)t?t.push(...n.issues):t=n.issues;return t}function A(e,t){return{kind:`schema`,type:`union`,reference:A,expects:We(e.map(e=>e.expects),`|`),async:!1,options:e,message:t,_run(e,t){let n,r,i;for(let a of this.options){let o=a._run({typed:!1,value:e.value},t);if(o.typed)if(o.issues)r?r.push(o):r=[o];else{n=o;break}else i?i.push(o):i=[o]}if(n)return n;if(r){if(r.length===1)return r[0];C(this,`type`,e,t,{issues:nt(r)}),e.typed=!0}else if(i?.length===1)return i[0];else C(this,`type`,e,t,{issues:nt(i)});return e}}}function rt(){return{kind:`schema`,type:`unknown`,reference:rt,expects:`unknown`,async:!1,_run(e){return e.typed=!0,e}}}function it(e,t,n){return{kind:`schema`,type:`variant`,reference:it,expects:`Object`,async:!1,key:e,options:t,message:n,_run(e,t){let n=e.value;if(n&&typeof n==`object`){let r,i=0,a=this.key,o=[],s=(e,c)=>{for(let l of e.options){if(l.type===`variant`)s(l,new Set(c).add(l.key));else{let e=!0,s=0;for(let r of c){if(l.entries[r]._run({typed:!1,value:n[r]},t).issues){e=!1,a!==r&&(i<s||i===s&&r in n&&!(a in n))&&(i=s,a=r,o=[]),a===r&&o.push(l.entries[r].expects);break}s++}if(e){let e=l._run({typed:!1,value:n},t);(!r||!r.typed&&e.typed)&&(r=e)}}if(r&&!r.issues)break}};if(s(this,new Set([this.key])),r)return r;C(this,`type`,e,t,{input:n[a],expected:We(o,`|`),path:[{type:`object`,origin:`value`,input:n,key:a,value:n[a]}]})}else C(this,`type`,e,t);return e}}}function at(e,t,n){let r=e._run({typed:!1,value:t},Fe(n));if(r.issues)throw new Ge(r.issues);return r.value}function ot(...e){return{...e[0],pipe:e,_run(t,n){for(let r of e)if(r.kind!==`metadata`){if(t.issues&&(r.kind===`schema`||r.kind===`transformation`)){t.typed=!1;break}(!t.issues||!n.abortEarly&&!n.abortPipeEarly)&&(t=r._run(t,n))}return t}}}var st=class{current;migrations={};coerce;defaultValue;constructor(e){e.migrations.forEach(e=>{this.migrations[e.version]=e}),this.defaultValue=e?.defaultValue??{};let t=this.getVersions();this.current=t[t.length-1],this.coerce=e?.coerce??!0}getVersions(){let e=Me(this.migrations);return je.sort(e)}async migrate(e,t){let n=e??this.defaultValue,r=this.tryCoerce(n.version),i=this.tryCoerce(t?.target??this.current);t?.debug&&console.log(`Migrating from`,r,`to`,i);let a=S(n),o=this.getVersions(),s=o.indexOf(r),c=o.indexOf(i);if(s===-1)throw Error(`Current version "${r}" not found in migrations`);if(c===-1)throw Error(`Target version "${i}" not found in migrations`);if(s===c||!(s<c))return a;for(let e=s;e<c;e++){let n=o[e],r=o[e+1];t?.debug&&console.log(` Migrating to version:`,r);let i=n,s=this.migrations[i],{version:c,...l}=a;a={...await s.up(l,n),version:r},t?.onStep&&await t.onStep(a,r),t?.debug&&console.log(` Migrated state:`,a)}return a}tryCoerce(e){return this.coerce?(0,je.coerce)(e)?.version??e:e}needMigration(e){let t=this.tryCoerce(e);return je.lt(t,this.current)}},ct=()=>({createDefault(e){return e},createMigrations(e){return new st(e)}}),lt=[{name:`@pipelab/plugin-construct`,enabled:!0,description:`Construct 3 export & packaging`},{name:`@pipelab/plugin-filesystem`,enabled:!0,description:`Filesystem utilities`},{name:`@pipelab/plugin-system`,enabled:!0,description:`System & shell commands`},{name:`@pipelab/plugin-steam`,enabled:!0,description:`Steam publishing`},{name:`@pipelab/plugin-itch`,enabled:!0,description:`Itch.io publishing`},{name:`@pipelab/plugin-electron`,enabled:!0,description:`Electron packaging`},{name:`@pipelab/plugin-discord`,enabled:!0,description:`Discord Rich Presence`},{name:`@pipelab/plugin-poki`,enabled:!0,description:`Poki publishing`},{name:`@pipelab/plugin-nvpatch`,enabled:!0,description:`NW.js patching`},{name:`@pipelab/plugin-tauri`,enabled:!0,description:`Tauri packaging`},{name:`@pipelab/plugin-minify`,enabled:!0,description:`Asset minification`},{name:`@pipelab/plugin-netlify`,enabled:!0,description:`Netlify deployment`}],j=e=>s(e),ut=ct(),dt=ut.createDefault({locale:`en-US`,theme:`light`,version:`8.0.0`,autosave:!0,agents:[],tours:{dashboard:{step:0,completed:!1},editor:{step:0,completed:!1}},buildHistory:{retentionPolicy:{enabled:!1,maxEntries:50,maxAge:30}},plugins:lt,isInternalMigrationBannerClosed:!1});ut.createMigrations({defaultValue:dt,migrations:[j({version:`1.0.0`,up:e=>e}),j({version:`2.0.0`,up:e=>({...e,clearTemporaryFoldersOnPipelineEnd:!1})}),j({version:`3.0.0`,up:e=>({...e,locale:`en-US`})}),j({version:`4.0.0`,up:e=>({...e,tours:{dashboard:{step:0,completed:!1},editor:{step:0,completed:!1}}})}),j({version:`5.0.0`,up:e=>({...e,autosave:!0})}),j({version:`6.0.0`,up:e=>{let{cacheFolder:t,clearTemporaryFoldersOnPipelineEnd:n,...r}=e;return{...r,agents:[],buildHistory:{retentionPolicy:{enabled:!1,maxEntries:50,maxAge:30}},plugins:lt,isInternalMigrationBannerClosed:!1}}}),j({version:`8.0.0`,up:c})]});var ft=ct(),pt=ft.createDefault({version:`2.0.0`,projects:[{id:`main`,name:`Default project`,description:`The initial default project`}],pipelines:[]});ft.createMigrations({defaultValue:pt,migrations:[j({version:`1.0.0`,up:e=>{let t=Object.entries(e.data||{}).map(([e,t])=>({...t,id:e,project:`main`}));return{...e,projects:[{id:`main`,name:`Default project`,description:`The initial default project`}],pipelines:t}}}),j({version:`2.0.0`,up:c})]});var mt=ct(),ht=mt.createDefault({canvas:{triggers:[],blocks:[]},description:``,name:``,variables:[],version:`5.0.0`});mt.createMigrations({defaultValue:ht,migrations:[j({version:`1.0.0`,up:e=>{let t=e.canvas.blocks,n=[],r=[];for(let e of t)e.type===`event`?n.push(e):r.push(e);return{...e,canvas:{...e.canvas,blocks:r,triggers:n}}}}),j({version:`2.0.0`,up:e=>{let{canvas:t}=e,{blocks:n,triggers:r}=t,i=[];for(let e of n){let t={};for(let n of Object.entries(e.params))if(n===void 0)throw Error(`Can't migrate block with undefined params`);else{let[e,r]=n;t[e]={editor:`editor`,value:r}}i.push({...e,params:t})}return{...e,canvas:{...t,triggers:r,blocks:i}}}}),j({version:`3.0.0`,up:e=>({...e,type:`default`})}),j({version:`4.0.0`,up:e=>{let t=e;if(t.type===`simple`)return{name:t.name,description:t.description,canvas:{blocks:[],triggers:[]},variables:[]};let n=(e,t)=>{e&&e.origin?.pluginId&&(e.origin.pluginId=_t(e.origin.pluginId),e.origin.version=t[e.origin.pluginId]??`latest`)},r={};if(t.plugins)for(let[e,n]of Object.entries(t.plugins))r[_t(e)]=n;if(t.canvas){for(let e of t.canvas.blocks??[])n(e,r);for(let e of t.canvas.triggers??[])n(e,r)}let{plugins:i,type:a,...o}=t;return o}}),j({version:`5.0.0`,up:c})]});var gt={construct:`@pipelab/plugin-construct`,filesystem:`@pipelab/plugin-filesystem`,system:`@pipelab/plugin-system`,steam:`@pipelab/plugin-steam`,itch:`@pipelab/plugin-itch`,electron:`@pipelab/plugin-electron`,discord:`@pipelab/plugin-discord`,dicord:`@pipelab/plugin-discord`,"@pipelab/plugin-dicord":`@pipelab/plugin-discord`,poki:`@pipelab/plugin-poki`,nvpatch:`@pipelab/plugin-nvpatch`,tauri:`@pipelab/plugin-tauri`,minify:`@pipelab/plugin-minify`,netlify:`@pipelab/plugin-netlify`},_t=e=>{if(!e)return e;if(gt[e])return gt[e];if(e.startsWith(`@`)||e.includes(`/`)||e.startsWith(`pipelab-plugin-`))return e;let t=`@pipelab/plugin-${e}`;return gt[t]||t},vt=[`dialog:showOpenDialog`,`dialog:showSaveDialog`];A([E(`light`),E(`dark`)]),E(`1.0.0`),A([E(`light`),E(`dark`)]),E(`2.0.0`),A([E(`light`),E(`dark`)]),E(`3.0.0`),A([E(`light`),E(`dark`)]),E(`4.0.0`),A([E(`en-US`),E(`fr-FR`),E(`pt-BR`),E(`zh-CN`),E(`es-ES`),E(`de-DE`)]),A([E(`light`),E(`dark`)]),E(`5.0.0`),A([E(`en-US`),E(`fr-FR`),E(`pt-BR`),E(`zh-CN`),E(`es-ES`),E(`de-DE`)]),A([E(`light`),E(`dark`)]),E(`6.0.0`),A([E(`en-US`),E(`fr-FR`),E(`pt-BR`),E(`zh-CN`),E(`es-ES`),E(`de-DE`)]),A([E(`light`),E(`dark`)]),E(`7.0.0`),A([E(`en-US`),E(`fr-FR`),E(`pt-BR`),E(`zh-CN`),E(`es-ES`),E(`de-DE`)]),A([E(`light`),E(`dark`)]),E(`8.0.0`),A([E(`en-US`),E(`fr-FR`),E(`pt-BR`),E(`zh-CN`),E(`es-ES`),E(`de-DE`)]),O(T(),!1);var yt={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]};function bt(e,t,n,r=!1){let i=String(t),a=(e,t)=>`\u001b[${t[0]}m${e}\u001b[${t[1]}m`,o=(e,t)=>t!=null&&typeof t==`string`?a(e,yt[t]):t!=null&&Array.isArray(t)?t.reduce((e,t)=>o(e,t),e):t!=null&&t[e.trim()]!=null?o(e,t[e.trim()]):t!=null&&t[`*`]!=null?o(e,t[`*`]):e;return i.replace(/{{(.+?)}}/g,(t,i)=>{let s=n[i]==null?r?``:t:String(n[i]);return e.stylePrettyLogs?o(s,e?.prettyLogStyles?.[i]??null)+a(``,yt.reset):s})}function M(e,t=2,n=0){return e!=null&&isNaN(e)?``:(e=e==null?e:e+n,t===2?e==null?`--`:e<10?`0`+e:e.toString():e==null?`---`:e<10?`00`+e:e<100?`0`+e:e.toString())}function xt(e){return{href:e.href,protocol:e.protocol,username:e.username,password:e.password,host:e.host,hostname:e.hostname,port:e.port,pathname:e.pathname,search:e.search,searchParams:[...e.searchParams].map(([e,t])=>({key:e,value:t})),hash:e.hash,origin:e.origin}}function St(e){let t=new Set;return JSON.stringify(e,(e,n)=>{if(typeof n==`object`&&n){if(t.has(n))return`[Circular]`;t.add(n)}return typeof n==`bigint`?`${n}`:n})}function N(e,t){let n={seen:[],stylize:Tt};return t!=null&&Wt(n,t),wt(n.showHidden)&&(n.showHidden=!1),wt(n.depth)&&(n.depth=2),wt(n.colors)&&(n.colors=!0),wt(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=Et),Bt(n,e,n.depth)}N.colors=yt,N.styles={special:`cyan`,number:`yellow`,boolean:`yellow`,undefined:`grey`,null:`bold`,string:`green`,date:`magenta`,regexp:`red`};function Ct(e){return typeof e==`boolean`}function wt(e){return e===void 0}function Tt(e){return e}function Et(e,t){let n=N.styles[t];return n!=null&&N?.colors?.[n]?.[0]!=null&&N?.colors?.[n]?.[1]!=null?`\x1B[`+N.colors[n][0]+`m`+e+`\x1B[`+N.colors[n][1]+`m`:e}function Dt(e){return typeof e==`function`}function Ot(e){return typeof e==`string`}function kt(e){return typeof e==`number`}function At(e){return e===null}function jt(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Mt(e){return Nt(e)&&It(e)===`[object RegExp]`}function Nt(e){return typeof e==`object`&&!!e}function Pt(e){return Nt(e)&&(It(e)===`[object Error]`||e instanceof Error)}function Ft(e){return Nt(e)&&It(e)===`[object Date]`}function It(e){return Object.prototype.toString.call(e)}function Lt(e){let t={};return e.forEach(e=>{t[e]=!0}),t}function Rt(e,t,n,r,i){let a=[];for(let i=0,o=t.length;i<o;++i)jt(t,String(i))?a.push(Vt(e,t,n,r,String(i),!0)):a.push(``);return i.forEach(i=>{i.match(/^\d+$/)||a.push(Vt(e,t,n,r,i,!0))}),a}function zt(e){return`[`+Error.prototype.toString.call(e)+`]`}function Bt(e,t,n=0){if(e.customInspect&&t!=null&&Dt(t)&&t?.inspect!==N&&!(t?.constructor&&t?.constructor.prototype===t)){if(typeof t.inspect!=`function`&&t.toString!=null)return t.toString();let r=t?.inspect(n,e);return Ot(r)||(r=Bt(e,r,n)),r}let r=Ht(e,t);if(r)return r;let i=Object.keys(t),a=Lt(i);try{e.showHidden&&Object.getOwnPropertyNames&&(i=Object.getOwnPropertyNames(t))}catch{}if(Pt(t)&&(i.indexOf(`message`)>=0||i.indexOf(`description`)>=0))return zt(t);if(i.length===0)if(Dt(e.stylize)){if(Dt(t)){let n=t.name?`: `+t.name:``;return e.stylize(`[Function`+n+`]`,`special`)}if(Mt(t))return e.stylize(RegExp.prototype.toString.call(t),`regexp`);if(Ft(t))return e.stylize(Date.prototype.toISOString.call(t),`date`);if(Pt(t))return zt(t)}else return t;let o=``,s=!1,c=[`{
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/module-6F3E5H7Y-DUb8SKDP.js","assets/chunk-JTKJZQYV-BARLZAHU.js","assets/emscripten-module-VHMWRAJ2-CzPuSaDz.js","assets/chunk-DECur_0Z.js","assets/preload-helper-Dd-HcVz_.js"])))=>i.map(i=>d[i]);
2
+ import{n as e,r as t,t as n}from"./chunk-DECur_0Z.js";import{S as r}from"./reactivity.esm-bundler-yhMxlGFU.js";import{o as i,t as a}from"./chunk-JTKJZQYV-BARLZAHU.js";import{t as o}from"./preload-helper-Dd-HcVz_.js";function s(e){return{version:e.version,up:async(t,n)=>{let r=e.up?await e.up(t,n):t;return r.version=n,r}}}var c=()=>{throw Error(`Unable to go up on the final version!`)},l=n(((e,t)=>{var n=`2.0.0`,r=256;t.exports={MAX_LENGTH:r,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:r-6,MAX_SAFE_INTEGER:2**53-1||9007199254740991,RELEASE_TYPES:[`major`,`premajor`,`minor`,`preminor`,`patch`,`prepatch`,`prerelease`],SEMVER_SPEC_VERSION:n,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}})),u=n(((e,t)=>{t.exports=typeof process==`object`&&{}.NODE_DEBUG&&/\bsemver\b/i.test({}.NODE_DEBUG)?(...e)=>console.error(`SEMVER`,...e):()=>{}})),d=n(((e,t)=>{var{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=l(),a=u();e=t.exports={};var o=e.re=[],s=e.safeRe=[],c=e.src=[],d=e.safeSrc=[],f=e.t={},p=0,m=`[a-zA-Z0-9-]`,h=[[`\\s`,1],[`\\d`,i],[m,r]],g=e=>{for(let[t,n]of h)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e},_=(e,t,n)=>{let r=g(t),i=p++;a(e,i,t),f[e]=i,c[i]=t,d[i]=r,o[i]=new RegExp(t,n?`g`:void 0),s[i]=new RegExp(r,n?`g`:void 0)};_(`NUMERICIDENTIFIER`,`0|[1-9]\\d*`),_(`NUMERICIDENTIFIERLOOSE`,`\\d+`),_(`NONNUMERICIDENTIFIER`,`\\d*[a-zA-Z-]${m}*`),_(`MAINVERSION`,`(${c[f.NUMERICIDENTIFIER]})\\.(${c[f.NUMERICIDENTIFIER]})\\.(${c[f.NUMERICIDENTIFIER]})`),_(`MAINVERSIONLOOSE`,`(${c[f.NUMERICIDENTIFIERLOOSE]})\\.(${c[f.NUMERICIDENTIFIERLOOSE]})\\.(${c[f.NUMERICIDENTIFIERLOOSE]})`),_(`PRERELEASEIDENTIFIER`,`(?:${c[f.NONNUMERICIDENTIFIER]}|${c[f.NUMERICIDENTIFIER]})`),_(`PRERELEASEIDENTIFIERLOOSE`,`(?:${c[f.NONNUMERICIDENTIFIER]}|${c[f.NUMERICIDENTIFIERLOOSE]})`),_(`PRERELEASE`,`(?:-(${c[f.PRERELEASEIDENTIFIER]}(?:\\.${c[f.PRERELEASEIDENTIFIER]})*))`),_(`PRERELEASELOOSE`,`(?:-?(${c[f.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[f.PRERELEASEIDENTIFIERLOOSE]})*))`),_(`BUILDIDENTIFIER`,`${m}+`),_(`BUILD`,`(?:\\+(${c[f.BUILDIDENTIFIER]}(?:\\.${c[f.BUILDIDENTIFIER]})*))`),_(`FULLPLAIN`,`v?${c[f.MAINVERSION]}${c[f.PRERELEASE]}?${c[f.BUILD]}?`),_(`FULL`,`^${c[f.FULLPLAIN]}$`),_(`LOOSEPLAIN`,`[v=\\s]*${c[f.MAINVERSIONLOOSE]}${c[f.PRERELEASELOOSE]}?${c[f.BUILD]}?`),_(`LOOSE`,`^${c[f.LOOSEPLAIN]}$`),_(`GTLT`,`((?:<|>)?=?)`),_(`XRANGEIDENTIFIERLOOSE`,`${c[f.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),_(`XRANGEIDENTIFIER`,`${c[f.NUMERICIDENTIFIER]}|x|X|\\*`),_(`XRANGEPLAIN`,`[v=\\s]*(${c[f.XRANGEIDENTIFIER]})(?:\\.(${c[f.XRANGEIDENTIFIER]})(?:\\.(${c[f.XRANGEIDENTIFIER]})(?:${c[f.PRERELEASE]})?${c[f.BUILD]}?)?)?`),_(`XRANGEPLAINLOOSE`,`[v=\\s]*(${c[f.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[f.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[f.XRANGEIDENTIFIERLOOSE]})(?:${c[f.PRERELEASELOOSE]})?${c[f.BUILD]}?)?)?`),_(`XRANGE`,`^${c[f.GTLT]}\\s*${c[f.XRANGEPLAIN]}$`),_(`XRANGELOOSE`,`^${c[f.GTLT]}\\s*${c[f.XRANGEPLAINLOOSE]}$`),_(`COERCEPLAIN`,`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),_(`COERCE`,`${c[f.COERCEPLAIN]}(?:$|[^\\d])`),_(`COERCEFULL`,c[f.COERCEPLAIN]+`(?:${c[f.PRERELEASE]})?(?:${c[f.BUILD]})?(?:$|[^\\d])`),_(`COERCERTL`,c[f.COERCE],!0),_(`COERCERTLFULL`,c[f.COERCEFULL],!0),_(`LONETILDE`,`(?:~>?)`),_(`TILDETRIM`,`(\\s*)${c[f.LONETILDE]}\\s+`,!0),e.tildeTrimReplace=`$1~`,_(`TILDE`,`^${c[f.LONETILDE]}${c[f.XRANGEPLAIN]}$`),_(`TILDELOOSE`,`^${c[f.LONETILDE]}${c[f.XRANGEPLAINLOOSE]}$`),_(`LONECARET`,`(?:\\^)`),_(`CARETTRIM`,`(\\s*)${c[f.LONECARET]}\\s+`,!0),e.caretTrimReplace=`$1^`,_(`CARET`,`^${c[f.LONECARET]}${c[f.XRANGEPLAIN]}$`),_(`CARETLOOSE`,`^${c[f.LONECARET]}${c[f.XRANGEPLAINLOOSE]}$`),_(`COMPARATORLOOSE`,`^${c[f.GTLT]}\\s*(${c[f.LOOSEPLAIN]})$|^$`),_(`COMPARATOR`,`^${c[f.GTLT]}\\s*(${c[f.FULLPLAIN]})$|^$`),_(`COMPARATORTRIM`,`(\\s*)${c[f.GTLT]}\\s*(${c[f.LOOSEPLAIN]}|${c[f.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace=`$1$2$3`,_(`HYPHENRANGE`,`^\\s*(${c[f.XRANGEPLAIN]})\\s+-\\s+(${c[f.XRANGEPLAIN]})\\s*$`),_(`HYPHENRANGELOOSE`,`^\\s*(${c[f.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[f.XRANGEPLAINLOOSE]})\\s*$`),_(`STAR`,`(<|>)?=?\\s*\\*`),_(`GTE0`,`^\\s*>=\\s*0\\.0\\.0\\s*$`),_(`GTE0PRE`,`^\\s*>=\\s*0\\.0\\.0-0\\s*$`)})),f=n(((e,t)=>{var n=Object.freeze({loose:!0}),r=Object.freeze({});t.exports=e=>e?typeof e==`object`?e:n:r})),p=n(((e,t)=>{var n=/^[0-9]+$/,r=(e,t)=>{if(typeof e==`number`&&typeof t==`number`)return e===t?0:e<t?-1:1;let r=n.test(e),i=n.test(t);return r&&i&&(e=+e,t=+t),e===t?0:r&&!i?-1:i&&!r?1:e<t?-1:1};t.exports={compareIdentifiers:r,rcompareIdentifiers:(e,t)=>r(t,e)}})),m=n(((e,t)=>{var n=u(),{MAX_LENGTH:r,MAX_SAFE_INTEGER:i}=l(),{safeRe:a,t:o}=d(),s=f(),{compareIdentifiers:c}=p();t.exports=class e{constructor(t,c){if(c=s(c),t instanceof e){if(t.loose===!!c.loose&&t.includePrerelease===!!c.includePrerelease)return t;t=t.version}else if(typeof t!=`string`)throw TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>r)throw TypeError(`version is longer than ${r} characters`);n(`SemVer`,t,c),this.options=c,this.loose=!!c.loose,this.includePrerelease=!!c.includePrerelease;let l=t.trim().match(c.loose?a[o.LOOSE]:a[o.FULL]);if(!l)throw TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+l[1],this.minor=+l[2],this.patch=+l[3],this.major>i||this.major<0)throw TypeError(`Invalid major version`);if(this.minor>i||this.minor<0)throw TypeError(`Invalid minor version`);if(this.patch>i||this.patch<0)throw TypeError(`Invalid patch version`);l[4]?this.prerelease=l[4].split(`.`).map(e=>{if(/^[0-9]+$/.test(e)){let t=+e;if(t>=0&&t<i)return t}return e}):this.prerelease=[],this.build=l[5]?l[5].split(`.`):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(`.`)}`),this.version}toString(){return this.version}compare(t){if(n(`SemVer.compare`,this.version,this.options,t),!(t instanceof e)){if(typeof t==`string`&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:+(this.patch>t.patch)}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let e=this.prerelease[r],i=t.prerelease[r];if(n(`prerelease compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e===i)continue;return c(e,i)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let e=this.build[r],i=t.build[r];if(n(`build compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e===i)continue;return c(e,i)}while(++r)}inc(e,t,n){if(e.startsWith(`pre`)){if(!t&&n===!1)throw Error(`invalid increment argument: identifier is empty`);if(t){let e=`-${t}`.match(this.options.loose?a[o.PRERELEASELOOSE]:a[o.PRERELEASE]);if(!e||e[1]!==t)throw Error(`invalid identifier: ${t}`)}}switch(e){case`premajor`:this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc(`pre`,t,n);break;case`preminor`:this.prerelease.length=0,this.patch=0,this.minor++,this.inc(`pre`,t,n);break;case`prepatch`:this.prerelease.length=0,this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`prerelease`:this.prerelease.length===0&&this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`release`:if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case`major`:(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case`minor`:(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case`patch`:this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case`pre`:{let e=+!!Number(n);if(this.prerelease.length===0)this.prerelease=[e];else{let r=this.prerelease.length;for(;--r>=0;)typeof this.prerelease[r]==`number`&&(this.prerelease[r]++,r=-2);if(r===-1){if(t===this.prerelease.join(`.`)&&n===!1)throw Error(`invalid increment argument: identifier already exists`);this.prerelease.push(e)}}if(t){let r=[t,e];n===!1&&(r=[t]),c(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=r):this.prerelease=r}break}default:throw Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(`.`)}`),this}}})),h=n(((e,t)=>{var n=m();t.exports=(e,t,r=!1)=>{if(e instanceof n)return e;try{return new n(e,t)}catch(e){if(!r)return null;throw e}}})),g=n(((e,t)=>{var n=h();t.exports=(e,t)=>{let r=n(e,t);return r?r.version:null}})),_=n(((e,t)=>{var n=h();t.exports=(e,t)=>{let r=n(e.trim().replace(/^[=v]+/,``),t);return r?r.version:null}})),v=n(((e,t)=>{var n=m();t.exports=(e,t,r,i,a)=>{typeof r==`string`&&(a=i,i=r,r=void 0);try{return new n(e instanceof n?e.version:e,r).inc(t,i,a).version}catch{return null}}})),y=n(((e,t)=>{var n=h();t.exports=(e,t)=>{let r=n(e,null,!0),i=n(t,null,!0),a=r.compare(i);if(a===0)return null;let o=a>0,s=o?r:i,c=o?i:r,l=!!s.prerelease.length;if(c.prerelease.length&&!l){if(!c.patch&&!c.minor)return`major`;if(c.compareMain(s)===0)return c.minor&&!c.patch?`minor`:`patch`}let u=l?`pre`:``;return r.major===i.major?r.minor===i.minor?r.patch===i.patch?`prerelease`:u+`patch`:u+`minor`:u+`major`}})),ee=n(((e,t)=>{var n=m();t.exports=(e,t)=>new n(e,t).major})),te=n(((e,t)=>{var n=m();t.exports=(e,t)=>new n(e,t).minor})),ne=n(((e,t)=>{var n=m();t.exports=(e,t)=>new n(e,t).patch})),re=n(((e,t)=>{var n=h();t.exports=(e,t)=>{let r=n(e,t);return r&&r.prerelease.length?r.prerelease:null}})),b=n(((e,t)=>{var n=m();t.exports=(e,t,r)=>new n(e,r).compare(new n(t,r))})),ie=n(((e,t)=>{var n=b();t.exports=(e,t,r)=>n(t,e,r)})),ae=n(((e,t)=>{var n=b();t.exports=(e,t)=>n(e,t,!0)})),oe=n(((e,t)=>{var n=m();t.exports=(e,t,r)=>{let i=new n(e,r),a=new n(t,r);return i.compare(a)||i.compareBuild(a)}})),se=n(((e,t)=>{var n=oe();t.exports=(e,t)=>e.sort((e,r)=>n(e,r,t))})),ce=n(((e,t)=>{var n=oe();t.exports=(e,t)=>e.sort((e,r)=>n(r,e,t))})),le=n(((e,t)=>{var n=b();t.exports=(e,t,r)=>n(e,t,r)>0})),ue=n(((e,t)=>{var n=b();t.exports=(e,t,r)=>n(e,t,r)<0})),de=n(((e,t)=>{var n=b();t.exports=(e,t,r)=>n(e,t,r)===0})),fe=n(((e,t)=>{var n=b();t.exports=(e,t,r)=>n(e,t,r)!==0})),pe=n(((e,t)=>{var n=b();t.exports=(e,t,r)=>n(e,t,r)>=0})),me=n(((e,t)=>{var n=b();t.exports=(e,t,r)=>n(e,t,r)<=0})),he=n(((e,t)=>{var n=de(),r=fe(),i=le(),a=pe(),o=ue(),s=me();t.exports=(e,t,c,l)=>{switch(t){case`===`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e===c;case`!==`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e!==c;case``:case`=`:case`==`:return n(e,c,l);case`!=`:return r(e,c,l);case`>`:return i(e,c,l);case`>=`:return a(e,c,l);case`<`:return o(e,c,l);case`<=`:return s(e,c,l);default:throw TypeError(`Invalid operator: ${t}`)}}})),ge=n(((e,t)=>{var n=m(),r=h(),{safeRe:i,t:a}=d();t.exports=(e,t)=>{if(e instanceof n)return e;if(typeof e==`number`&&(e=String(e)),typeof e!=`string`)return null;t||={};let o=null;if(!t.rtl)o=e.match(t.includePrerelease?i[a.COERCEFULL]:i[a.COERCE]);else{let n=t.includePrerelease?i[a.COERCERTLFULL]:i[a.COERCERTL],r;for(;(r=n.exec(e))&&(!o||o.index+o[0].length!==e.length);)(!o||r.index+r[0].length!==o.index+o[0].length)&&(o=r),n.lastIndex=r.index+r[1].length+r[2].length;n.lastIndex=-1}if(o===null)return null;let s=o[2];return r(`${s}.${o[3]||`0`}.${o[4]||`0`}${t.includePrerelease&&o[5]?`-${o[5]}`:``}${t.includePrerelease&&o[6]?`+${o[6]}`:``}`,t)}})),_e=n(((e,t)=>{t.exports=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}})),x=n(((e,t)=>{var n=/\s+/g;t.exports=class e{constructor(t,r){if(r=i(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof a)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(n,` `),this.set=this.raw.split(`||`).map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let e=this.set[0];if(this.set=this.set.filter(e=>!ee(e[0])),this.set.length===0)this.set=[e];else if(this.set.length>1){for(let e of this.set)if(e.length===1&&te(e[0])){this.set=[e];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted=``;for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+=`||`);let t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=` `),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let t=((this.options.includePrerelease&&v)|(this.options.loose&&y))+`:`+e,n=r.get(t);if(n)return n;let i=this.options.loose,s=i?c[p.HYPHENRANGELOOSE]:c[p.HYPHENRANGE];e=e.replace(s,fe(this.options.includePrerelease)),o(`hyphen replace`,e),e=e.replace(c[p.COMPARATORTRIM],h),o(`comparator trim`,e),e=e.replace(c[p.TILDETRIM],g),o(`tilde trim`,e),e=e.replace(c[p.CARETTRIM],_),o(`caret trim`,e);let l=e.split(` `).map(e=>re(e,this.options)).join(` `).split(/\s+/).map(e=>de(e,this.options));i&&(l=l.filter(e=>(o(`loose invalid filter`,e,this.options),!!e.match(c[p.COMPARATORLOOSE])))),o(`range list`,l);let u=new Map,d=l.map(e=>new a(e,this.options));for(let e of d){if(ee(e))return[e];u.set(e.value,e)}u.size>1&&u.has(``)&&u.delete(``);let f=[...u.values()];return r.set(t,f),f}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Range is required`);return this.set.some(e=>ne(e,n)&&t.set.some(t=>ne(t,n)&&e.every(e=>t.every(t=>e.intersects(t,n)))))}test(e){if(!e)return!1;if(typeof e==`string`)try{e=new s(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(pe(this.set[t],e,this.options))return!0;return!1}};var r=new(_e()),i=f(),a=ve(),o=u(),s=m(),{safeRe:c,t:p,comparatorTrimReplace:h,tildeTrimReplace:g,caretTrimReplace:_}=d(),{FLAG_INCLUDE_PRERELEASE:v,FLAG_LOOSE:y}=l(),ee=e=>e.value===`<0.0.0-0`,te=e=>e.value===``,ne=(e,t)=>{let n=!0,r=e.slice(),i=r.pop();for(;n&&r.length;)n=r.every(e=>i.intersects(e,t)),i=r.pop();return n},re=(e,t)=>(e=e.replace(c[p.BUILD],``),o(`comp`,e,t),e=oe(e,t),o(`caret`,e),e=ie(e,t),o(`tildes`,e),e=ce(e,t),o(`xrange`,e),e=ue(e,t),o(`stars`,e),e),b=e=>!e||e.toLowerCase()===`x`||e===`*`,ie=(e,t)=>e.trim().split(/\s+/).map(e=>ae(e,t)).join(` `),ae=(e,t)=>{let n=t.loose?c[p.TILDELOOSE]:c[p.TILDE];return e.replace(n,(t,n,r,i,a)=>{o(`tilde`,e,t,n,r,i,a);let s;return b(n)?s=``:b(r)?s=`>=${n}.0.0 <${+n+1}.0.0-0`:b(i)?s=`>=${n}.${r}.0 <${n}.${+r+1}.0-0`:a?(o(`replaceTilde pr`,a),s=`>=${n}.${r}.${i}-${a} <${n}.${+r+1}.0-0`):s=`>=${n}.${r}.${i} <${n}.${+r+1}.0-0`,o(`tilde return`,s),s})},oe=(e,t)=>e.trim().split(/\s+/).map(e=>se(e,t)).join(` `),se=(e,t)=>{o(`caret`,e,t);let n=t.loose?c[p.CARETLOOSE]:c[p.CARET],r=t.includePrerelease?`-0`:``;return e.replace(n,(t,n,i,a,s)=>{o(`caret`,e,t,n,i,a,s);let c;return b(n)?c=``:b(i)?c=`>=${n}.0.0${r} <${+n+1}.0.0-0`:b(a)?c=n===`0`?`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.0${r} <${+n+1}.0.0-0`:s?(o(`replaceCaret pr`,s),c=n===`0`?i===`0`?`>=${n}.${i}.${a}-${s} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}-${s} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a}-${s} <${+n+1}.0.0-0`):(o(`no pr`),c=n===`0`?i===`0`?`>=${n}.${i}.${a}${r} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a} <${+n+1}.0.0-0`),o(`caret return`,c),c})},ce=(e,t)=>(o(`replaceXRanges`,e,t),e.split(/\s+/).map(e=>le(e,t)).join(` `)),le=(e,t)=>{e=e.trim();let n=t.loose?c[p.XRANGELOOSE]:c[p.XRANGE];return e.replace(n,(n,r,i,a,s,c)=>{o(`xRange`,e,n,r,i,a,s,c);let l=b(i),u=l||b(a),d=u||b(s),f=d;return r===`=`&&f&&(r=``),c=t.includePrerelease?`-0`:``,l?n=r===`>`||r===`<`?`<0.0.0-0`:`*`:r&&f?(u&&(a=0),s=0,r===`>`?(r=`>=`,u?(i=+i+1,a=0,s=0):(a=+a+1,s=0)):r===`<=`&&(r=`<`,u?i=+i+1:a=+a+1),r===`<`&&(c=`-0`),n=`${r+i}.${a}.${s}${c}`):u?n=`>=${i}.0.0${c} <${+i+1}.0.0-0`:d&&(n=`>=${i}.${a}.0${c} <${i}.${+a+1}.0-0`),o(`xRange return`,n),n})},ue=(e,t)=>(o(`replaceStars`,e,t),e.trim().replace(c[p.STAR],``)),de=(e,t)=>(o(`replaceGTE0`,e,t),e.trim().replace(c[t.includePrerelease?p.GTE0PRE:p.GTE0],``)),fe=e=>(t,n,r,i,a,o,s,c,l,u,d,f)=>(n=b(r)?``:b(i)?`>=${r}.0.0${e?`-0`:``}`:b(a)?`>=${r}.${i}.0${e?`-0`:``}`:o?`>=${n}`:`>=${n}${e?`-0`:``}`,c=b(l)?``:b(u)?`<${+l+1}.0.0-0`:b(d)?`<${l}.${+u+1}.0-0`:f?`<=${l}.${u}.${d}-${f}`:e?`<${l}.${u}.${+d+1}-0`:`<=${c}`,`${n} ${c}`.trim()),pe=(e,t,n)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(let n=0;n<e.length;n++)if(o(e[n].semver),e[n].semver!==a.ANY&&e[n].semver.prerelease.length>0){let r=e[n].semver;if(r.major===t.major&&r.minor===t.minor&&r.patch===t.patch)return!0}return!1}return!0}})),ve=n(((e,t)=>{var n=Symbol(`SemVer ANY`);t.exports=class e{static get ANY(){return n}constructor(t,i){if(i=r(i),t instanceof e){if(t.loose===!!i.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(` `),s(`comparator`,t,i),this.options=i,this.loose=!!i.loose,this.parse(t),this.semver===n?this.value=``:this.value=this.operator+this.semver.version,s(`comp`,this)}parse(e){let t=this.options.loose?i[a.COMPARATORLOOSE]:i[a.COMPARATOR],r=e.match(t);if(!r)throw TypeError(`Invalid comparator: ${e}`);this.operator=r[1]===void 0?``:r[1],this.operator===`=`&&(this.operator=``),r[2]?this.semver=new c(r[2],this.options.loose):this.semver=n}toString(){return this.value}test(e){if(s(`Comparator.test`,e,this.options.loose),this.semver===n||e===n)return!0;if(typeof e==`string`)try{e=new c(e,this.options)}catch{return!1}return o(e,this.operator,this.semver,this.options)}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Comparator is required`);return this.operator===``?this.value===``?!0:new l(t.value,n).test(this.value):t.operator===``?t.value===``?!0:new l(this.value,n).test(t.semver):(n=r(n),n.includePrerelease&&(this.value===`<0.0.0-0`||t.value===`<0.0.0-0`)||!n.includePrerelease&&(this.value.startsWith(`<0.0.0`)||t.value.startsWith(`<0.0.0`))?!1:!!(this.operator.startsWith(`>`)&&t.operator.startsWith(`>`)||this.operator.startsWith(`<`)&&t.operator.startsWith(`<`)||this.semver.version===t.semver.version&&this.operator.includes(`=`)&&t.operator.includes(`=`)||o(this.semver,`<`,t.semver,n)&&this.operator.startsWith(`>`)&&t.operator.startsWith(`<`)||o(this.semver,`>`,t.semver,n)&&this.operator.startsWith(`<`)&&t.operator.startsWith(`>`)))}};var r=f(),{safeRe:i,t:a}=d(),o=he(),s=u(),c=m(),l=x()})),ye=n(((e,t)=>{var n=x();t.exports=(e,t,r)=>{try{t=new n(t,r)}catch{return!1}return t.test(e)}})),be=n(((e,t)=>{var n=x();t.exports=(e,t)=>new n(e,t).set.map(e=>e.map(e=>e.value).join(` `).trim().split(` `))})),xe=n(((e,t)=>{var n=m(),r=x();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===-1)&&(a=e,o=new n(a,i))}),a}})),Se=n(((e,t)=>{var n=m(),r=x();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===1)&&(a=e,o=new n(a,i))}),a}})),Ce=n(((e,t)=>{var n=m(),r=x(),i=le();t.exports=(e,t)=>{e=new r(e,t);let a=new n(`0.0.0`);if(e.test(a)||(a=new n(`0.0.0-0`),e.test(a)))return a;a=null;for(let t=0;t<e.set.length;++t){let r=e.set[t],o=null;r.forEach(e=>{let t=new n(e.semver.version);switch(e.operator){case`>`:t.prerelease.length===0?t.patch++:t.prerelease.push(0),t.raw=t.format();case``:case`>=`:(!o||i(t,o))&&(o=t);break;case`<`:case`<=`:break;default:throw Error(`Unexpected operation: ${e.operator}`)}}),o&&(!a||i(a,o))&&(a=o)}return a&&e.test(a)?a:null}})),we=n(((e,t)=>{var n=x();t.exports=(e,t)=>{try{return new n(e,t).range||`*`}catch{return null}}})),Te=n(((e,t)=>{var n=m(),r=ve(),{ANY:i}=r,a=x(),o=ye(),s=le(),c=ue(),l=me(),u=pe();t.exports=(e,t,d,f)=>{e=new n(e,f),t=new a(t,f);let p,m,h,g,_;switch(d){case`>`:p=s,m=l,h=c,g=`>`,_=`>=`;break;case`<`:p=c,m=u,h=s,g=`<`,_=`<=`;break;default:throw TypeError(`Must provide a hilo val of "<" or ">"`)}if(o(e,t,f))return!1;for(let n=0;n<t.set.length;++n){let a=t.set[n],o=null,s=null;if(a.forEach(e=>{e.semver===i&&(e=new r(`>=0.0.0`)),o||=e,s||=e,p(e.semver,o.semver,f)?o=e:h(e.semver,s.semver,f)&&(s=e)}),o.operator===g||o.operator===_||(!s.operator||s.operator===g)&&m(e,s.semver)||s.operator===_&&h(e,s.semver))return!1}return!0}})),Ee=n(((e,t)=>{var n=Te();t.exports=(e,t,r)=>n(e,t,`>`,r)})),De=n(((e,t)=>{var n=Te();t.exports=(e,t,r)=>n(e,t,`<`,r)})),Oe=n(((e,t)=>{var n=x();t.exports=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r))})),ke=n(((e,t)=>{var n=ye(),r=b();t.exports=(e,t,i)=>{let a=[],o=null,s=null,c=e.sort((e,t)=>r(e,t,i));for(let e of c)n(e,t,i)?(s=e,o||=e):(s&&a.push([o,s]),s=null,o=null);o&&a.push([o,null]);let l=[];for(let[e,t]of a)e===t?l.push(e):!t&&e===c[0]?l.push(`*`):t?e===c[0]?l.push(`<=${t}`):l.push(`${e} - ${t}`):l.push(`>=${e}`);let u=l.join(` || `),d=typeof t.raw==`string`?t.raw:String(t);return u.length<d.length?u:t}})),Ae=n(((e,t)=>{var n=x(),r=ve(),{ANY:i}=r,a=ye(),o=b(),s=(e,t,r={})=>{if(e===t)return!0;e=new n(e,r),t=new n(t,r);let i=!1;OUTER:for(let n of e.set){for(let e of t.set){let t=u(n,e,r);if(i||=t!==null,t)continue OUTER}if(i)return!1}return!0},c=[new r(`>=0.0.0-0`)],l=[new r(`>=0.0.0`)],u=(e,t,n)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===i){if(t.length===1&&t[0].semver===i)return!0;e=n.includePrerelease?c:l}if(t.length===1&&t[0].semver===i){if(n.includePrerelease)return!0;t=l}let r=new Set,s,u;for(let t of e)t.operator===`>`||t.operator===`>=`?s=d(s,t,n):t.operator===`<`||t.operator===`<=`?u=f(u,t,n):r.add(t.semver);if(r.size>1)return null;let p;if(s&&u&&(p=o(s.semver,u.semver,n),p>0||p===0&&(s.operator!==`>=`||u.operator!==`<=`)))return null;for(let e of r){if(s&&!a(e,String(s),n)||u&&!a(e,String(u),n))return null;for(let r of t)if(!a(e,String(r),n))return!1;return!0}let m,h,g,_,v=u&&!n.includePrerelease&&u.semver.prerelease.length?u.semver:!1,y=s&&!n.includePrerelease&&s.semver.prerelease.length?s.semver:!1;v&&v.prerelease.length===1&&u.operator===`<`&&v.prerelease[0]===0&&(v=!1);for(let e of t){if(_=_||e.operator===`>`||e.operator===`>=`,g=g||e.operator===`<`||e.operator===`<=`,s){if(y&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===y.major&&e.semver.minor===y.minor&&e.semver.patch===y.patch&&(y=!1),e.operator===`>`||e.operator===`>=`){if(m=d(s,e,n),m===e&&m!==s)return!1}else if(s.operator===`>=`&&!a(s.semver,String(e),n))return!1}if(u){if(v&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===v.major&&e.semver.minor===v.minor&&e.semver.patch===v.patch&&(v=!1),e.operator===`<`||e.operator===`<=`){if(h=f(u,e,n),h===e&&h!==u)return!1}else if(u.operator===`<=`&&!a(u.semver,String(e),n))return!1}if(!e.operator&&(u||s)&&p!==0)return!1}return!(s&&g&&!u&&p!==0||u&&_&&!s&&p!==0||y||v)},d=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r>0?e:r<0||t.operator===`>`&&e.operator===`>=`?t:e},f=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r<0?e:r>0||t.operator===`<`&&e.operator===`<=`?t:e};t.exports=s})),je=t(n(((e,t)=>{var n=d(),r=l(),i=m(),a=p();t.exports={parse:h(),valid:g(),clean:_(),inc:v(),diff:y(),major:ee(),minor:te(),patch:ne(),prerelease:re(),compare:b(),rcompare:ie(),compareLoose:ae(),compareBuild:oe(),sort:se(),rsort:ce(),gt:le(),lt:ue(),eq:de(),neq:fe(),gte:pe(),lte:me(),cmp:he(),coerce:ge(),Comparator:ve(),Range:x(),satisfies:ye(),toComparators:be(),maxSatisfying:xe(),minSatisfying:Se(),minVersion:Ce(),validRange:we(),outside:Te(),gtr:Ee(),ltr:De(),intersects:Oe(),simplifyRange:ke(),subset:Ae(),SemVer:i,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:r.SEMVER_SPEC_VERSION,RELEASE_TYPES:r.RELEASE_TYPES,compareIdentifiers:a.compareIdentifiers,rcompareIdentifiers:a.rcompareIdentifiers}}))(),1),Me=Object.keys;function S(e){if(typeof e!=`object`)return e;var t,n,r=Object.prototype.toString.call(e);if(r===`[object Object]`){if(e.constructor!==Object&&typeof e.constructor==`function`)for(t in n=new e.constructor,e)e.hasOwnProperty(t)&&n[t]!==e[t]&&(n[t]=S(e[t]));else for(t in n={},e)t===`__proto__`?Object.defineProperty(n,t,{value:S(e[t]),configurable:!0,enumerable:!0,writable:!0}):n[t]=S(e[t]);return n}if(r===`[object Array]`){for(t=e.length,n=Array(t);t--;)n[t]=S(e[t]);return n}return r===`[object Set]`?(n=new Set,e.forEach(function(e){n.add(S(e))}),n):r===`[object Map]`?(n=new Map,e.forEach(function(e,t){n.set(S(t),S(e))}),n):r===`[object Date]`?new Date(+e):r===`[object RegExp]`?(n=new RegExp(e.source,e.flags),n.lastIndex=e.lastIndex,n):r===`[object DataView]`?new e.constructor(S(e.buffer)):r===`[object ArrayBuffer]`?e.slice(0):r.slice(-6)===`Array]`?new e.constructor(e):e}var Ne=/^[\w+-]+(?:\.[\w+-]+)*@[\da-z]+(?:[.-][\da-z]+)*\.[a-z]{2,}$/iu,Pe;function Fe(e){return{lang:e?.lang??Pe?.lang,message:e?.message,abortEarly:e?.abortEarly??Pe?.abortEarly,abortPipeEarly:e?.abortPipeEarly??Pe?.abortPipeEarly}}var Ie;function Le(e){return Ie?.get(e)}var Re;function ze(e){return Re?.get(e)}var Be;function Ve(e,t){return Be?.get(e)?.get(t)}function He(e){let t=typeof e;return t===`string`?`"${e}"`:t===`number`||t===`bigint`||t===`boolean`?`${e}`:t===`object`||t===`function`?(e&&Object.getPrototypeOf(e)?.constructor?.name)??`null`:t}function C(e,t,n,r,i){let a=i&&`input`in i?i.input:n.value,o=i?.expected??e.expects??null,s=i?.received??He(a),c={kind:e.kind,type:e.type,input:a,expected:o,received:s,message:`Invalid ${t}: ${o?`Expected ${o} but r`:`R`}eceived ${s}`,requirement:e.requirement,path:i?.path,issues:i?.issues,lang:r.lang,abortEarly:r.abortEarly,abortPipeEarly:r.abortPipeEarly},l=e.kind===`schema`,u=i?.message??e.message??Ve(e.reference,c.lang)??(l?ze(c.lang):null)??r.message??Le(c.lang);u&&(c.message=typeof u==`function`?u(c):u),l&&(n.typed=!1),n.issues?n.issues.push(c):n.issues=[c]}function Ue(e,t){return Object.hasOwn(e,t)&&t!==`__proto__`&&t!==`prototype`&&t!==`constructor`}function We(e,t){let n=[...new Set(e)];return n.length>1?`(${n.join(` ${t} `)})`:n[0]??`never`}var Ge=class extends Error{issues;constructor(e){super(e[0].message),this.name=`ValiError`,this.issues=e}};function Ke(e){return{kind:`metadata`,type:`description`,reference:Ke,description:e}}function qe(e){return{kind:`validation`,type:`email`,reference:qe,expects:null,async:!1,requirement:Ne,message:e,_run(e,t){return e.typed&&!this.requirement.test(e.value)&&C(this,`email`,e,t),e}}}function Je(e,t){return{kind:`validation`,type:`min_length`,reference:Je,async:!1,expects:`>=${e}`,requirement:e,message:t,_run(e,t){return e.typed&&e.value.length<this.requirement&&C(this,`length`,e,t,{received:`${e.value.length}`}),e}}}function Ye(e){return{kind:`validation`,type:`non_empty`,reference:Ye,async:!1,expects:`!0`,message:e,_run(e,t){return e.typed&&e.value.length===0&&C(this,`length`,e,t,{received:`0`}),e}}}function Xe(e,t){return{kind:`validation`,type:`regex`,reference:Xe,async:!1,expects:`${e}`,requirement:e,message:t,_run(e,t){return e.typed&&!this.requirement.test(e.value)&&C(this,`format`,e,t),e}}}function Ze(e,t,n){return typeof e.default==`function`?e.default(t,n):e.default}function Qe(){return{kind:`schema`,type:`any`,reference:Qe,expects:`any`,async:!1,_run(e){return e.typed=!0,e}}}function w(e,t){return{kind:`schema`,type:`array`,reference:w,expects:`Array`,async:!1,item:e,message:t,_run(e,t){let n=e.value;if(Array.isArray(n)){e.typed=!0,e.value=[];for(let r=0;r<n.length;r++){let i=n[r],a=this.item._run({typed:!1,value:i},t);if(a.issues){let o={type:`array`,origin:`value`,input:n,key:r,value:i};for(let t of a.issues)t.path?t.path.unshift(o):t.path=[o],e.issues?.push(t);if(e.issues||=a.issues,t.abortEarly){e.typed=!1;break}}a.typed||(e.typed=!1),e.value.push(a.value)}}else C(this,`type`,e,t);return e}}}function T(e){return{kind:`schema`,type:`boolean`,reference:T,expects:`boolean`,async:!1,message:e,_run(e,t){return typeof e.value==`boolean`?e.typed=!0:C(this,`type`,e,t),e}}}function $e(e,t){return{kind:`schema`,type:`custom`,reference:$e,expects:`unknown`,async:!1,check:e,message:t,_run(e,t){return this.check(e.value)?e.typed=!0:C(this,`type`,e,t),e}}}function E(e,t){return{kind:`schema`,type:`literal`,reference:E,expects:He(e),async:!1,literal:e,message:t,_run(e,t){return e.value===this.literal?e.typed=!0:C(this,`type`,e,t),e}}}function et(e,t){return{kind:`schema`,type:`loose_object`,reference:et,expects:`Object`,async:!1,entries:e,message:t,_run(e,t){let n=e.value;if(n&&typeof n==`object`){e.typed=!0,e.value={};for(let r in this.entries){let i=n[r],a=this.entries[r]._run({typed:!1,value:i},t);if(a.issues){let o={type:`object`,origin:`value`,input:n,key:r,value:i};for(let t of a.issues)t.path?t.path.unshift(o):t.path=[o],e.issues?.push(t);if(e.issues||=a.issues,t.abortEarly){e.typed=!1;break}}a.typed||(e.typed=!1),(a.value!==void 0||r in n)&&(e.value[r]=a.value)}if(!e.issues||!t.abortEarly)for(let t in n)Ue(n,t)&&!(t in this.entries)&&(e.value[t]=n[t])}else C(this,`type`,e,t);return e}}}function tt(e){return{kind:`schema`,type:`number`,reference:tt,expects:`number`,async:!1,message:e,_run(e,t){return typeof e.value==`number`&&!isNaN(e.value)?e.typed=!0:C(this,`type`,e,t),e}}}function D(e,t){return{kind:`schema`,type:`object`,reference:D,expects:`Object`,async:!1,entries:e,message:t,_run(e,t){let n=e.value;if(n&&typeof n==`object`){e.typed=!0,e.value={};for(let r in this.entries){let i=n[r],a=this.entries[r]._run({typed:!1,value:i},t);if(a.issues){let o={type:`object`,origin:`value`,input:n,key:r,value:i};for(let t of a.issues)t.path?t.path.unshift(o):t.path=[o],e.issues?.push(t);if(e.issues||=a.issues,t.abortEarly){e.typed=!1;break}}a.typed||(e.typed=!1),(a.value!==void 0||r in n)&&(e.value[r]=a.value)}}else C(this,`type`,e,t);return e}}}function O(e,...t){let n={kind:`schema`,type:`optional`,reference:O,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,_run(e,t){return e.value===void 0&&(`default`in this&&(e.value=Ze(this,e,t)),e.value===void 0)?(e.typed=!0,e):this.wrapped._run(e,t)}};return 0 in t&&(n.default=t[0]),n}function nt(e,t,n){return{kind:`schema`,type:`record`,reference:nt,expects:`Object`,async:!1,key:e,value:t,message:n,_run(e,t){let n=e.value;if(n&&typeof n==`object`){e.typed=!0,e.value={};for(let r in n)if(Ue(n,r)){let i=n[r],a=this.key._run({typed:!1,value:r},t);if(a.issues){let o={type:`object`,origin:`key`,input:n,key:r,value:i};for(let t of a.issues)t.path=[o],e.issues?.push(t);if(e.issues||=a.issues,t.abortEarly){e.typed=!1;break}}let o=this.value._run({typed:!1,value:i},t);if(o.issues){let a={type:`object`,origin:`value`,input:n,key:r,value:i};for(let t of o.issues)t.path?t.path.unshift(a):t.path=[a],e.issues?.push(t);if(e.issues||=o.issues,t.abortEarly){e.typed=!1;break}}(!a.typed||!o.typed)&&(e.typed=!1),a.typed&&(e.value[a.value]=o.value)}}else C(this,`type`,e,t);return e}}}function k(e){return{kind:`schema`,type:`string`,reference:k,expects:`string`,async:!1,message:e,_run(e,t){return typeof e.value==`string`?e.typed=!0:C(this,`type`,e,t),e}}}function rt(e){let t;if(e)for(let n of e)t?t.push(...n.issues):t=n.issues;return t}function A(e,t){return{kind:`schema`,type:`union`,reference:A,expects:We(e.map(e=>e.expects),`|`),async:!1,options:e,message:t,_run(e,t){let n,r,i;for(let a of this.options){let o=a._run({typed:!1,value:e.value},t);if(o.typed)if(o.issues)r?r.push(o):r=[o];else{n=o;break}else i?i.push(o):i=[o]}if(n)return n;if(r){if(r.length===1)return r[0];C(this,`type`,e,t,{issues:rt(r)}),e.typed=!0}else if(i?.length===1)return i[0];else C(this,`type`,e,t,{issues:rt(i)});return e}}}function it(){return{kind:`schema`,type:`unknown`,reference:it,expects:`unknown`,async:!1,_run(e){return e.typed=!0,e}}}function at(e,t,n){return{kind:`schema`,type:`variant`,reference:at,expects:`Object`,async:!1,key:e,options:t,message:n,_run(e,t){let n=e.value;if(n&&typeof n==`object`){let r,i=0,a=this.key,o=[],s=(e,c)=>{for(let l of e.options){if(l.type===`variant`)s(l,new Set(c).add(l.key));else{let e=!0,s=0;for(let r of c){if(l.entries[r]._run({typed:!1,value:n[r]},t).issues){e=!1,a!==r&&(i<s||i===s&&r in n&&!(a in n))&&(i=s,a=r,o=[]),a===r&&o.push(l.entries[r].expects);break}s++}if(e){let e=l._run({typed:!1,value:n},t);(!r||!r.typed&&e.typed)&&(r=e)}}if(r&&!r.issues)break}};if(s(this,new Set([this.key])),r)return r;C(this,`type`,e,t,{input:n[a],expected:We(o,`|`),path:[{type:`object`,origin:`value`,input:n,key:a,value:n[a]}]})}else C(this,`type`,e,t);return e}}}function ot(e,t,n){let r=e._run({typed:!1,value:t},Fe(n));if(r.issues)throw new Ge(r.issues);return r.value}function st(...e){return{...e[0],pipe:e,_run(t,n){for(let r of e)if(r.kind!==`metadata`){if(t.issues&&(r.kind===`schema`||r.kind===`transformation`)){t.typed=!1;break}(!t.issues||!n.abortEarly&&!n.abortPipeEarly)&&(t=r._run(t,n))}return t}}}var ct=class{current;migrations={};coerce;defaultValue;constructor(e){e.migrations.forEach(e=>{this.migrations[e.version]=e}),this.defaultValue=e?.defaultValue??{};let t=this.getVersions();this.current=t[t.length-1],this.coerce=e?.coerce??!0}getVersions(){let e=Me(this.migrations);return je.sort(e)}async migrate(e,t){let n=e??this.defaultValue,r=this.tryCoerce(n.version),i=this.tryCoerce(t?.target??this.current);t?.debug&&console.log(`Migrating from`,r,`to`,i);let a=S(n),o=this.getVersions(),s=o.indexOf(r),c=o.indexOf(i);if(s===-1)throw Error(`Current version "${r}" not found in migrations`);if(c===-1)throw Error(`Target version "${i}" not found in migrations`);if(s===c||!(s<c))return a;for(let e=s;e<c;e++){let n=o[e],r=o[e+1];t?.debug&&console.log(` Migrating to version:`,r);let i=n,s=this.migrations[i],{version:c,...l}=a;a={...await s.up(l,n),version:r},t?.onStep&&await t.onStep(a,r),t?.debug&&console.log(` Migrated state:`,a)}return a}tryCoerce(e){return this.coerce?(0,je.coerce)(e)?.version??e:e}needMigration(e){let t=this.tryCoerce(e);return je.lt(t,this.current)}},lt=()=>({createDefault(e){return e},createMigrations(e){return new ct(e)}}),ut=[{name:`@pipelab/plugin-construct`,enabled:!0,description:`Construct 3 export & packaging`},{name:`@pipelab/plugin-filesystem`,enabled:!0,description:`Filesystem utilities`},{name:`@pipelab/plugin-system`,enabled:!0,description:`System & shell commands`},{name:`@pipelab/plugin-steam`,enabled:!0,description:`Steam publishing`},{name:`@pipelab/plugin-itch`,enabled:!0,description:`Itch.io publishing`},{name:`@pipelab/plugin-electron`,enabled:!0,description:`Electron packaging`},{name:`@pipelab/plugin-discord`,enabled:!0,description:`Discord Rich Presence`},{name:`@pipelab/plugin-poki`,enabled:!0,description:`Poki publishing`},{name:`@pipelab/plugin-nvpatch`,enabled:!0,description:`NW.js patching`},{name:`@pipelab/plugin-tauri`,enabled:!0,description:`Tauri packaging`},{name:`@pipelab/plugin-minify`,enabled:!0,description:`Asset minification`},{name:`@pipelab/plugin-netlify`,enabled:!0,description:`Netlify deployment`}],j=e=>s(e),dt=lt(),ft=dt.createDefault({locale:`en-US`,theme:`light`,version:`8.0.0`,autosave:!0,agents:[],tours:{dashboard:{step:0,completed:!1},editor:{step:0,completed:!1}},buildHistory:{retentionPolicy:{enabled:!1,maxEntries:50,maxAge:30}},plugins:ut,isInternalMigrationBannerClosed:!1});dt.createMigrations({defaultValue:ft,migrations:[j({version:`1.0.0`,up:e=>e}),j({version:`2.0.0`,up:e=>({...e,clearTemporaryFoldersOnPipelineEnd:!1})}),j({version:`3.0.0`,up:e=>({...e,locale:`en-US`})}),j({version:`4.0.0`,up:e=>({...e,tours:{dashboard:{step:0,completed:!1},editor:{step:0,completed:!1}}})}),j({version:`5.0.0`,up:e=>({...e,autosave:!0})}),j({version:`6.0.0`,up:e=>{let{cacheFolder:t,clearTemporaryFoldersOnPipelineEnd:n,...r}=e;return{...r,agents:[],buildHistory:{retentionPolicy:{enabled:!1,maxEntries:50,maxAge:30}},plugins:ut,isInternalMigrationBannerClosed:!1}}}),j({version:`8.0.0`,up:c})]});var pt=lt(),mt=pt.createDefault({version:`1.0.0`,connections:[]});pt.createMigrations({defaultValue:mt,migrations:[j({version:`1.0.0`,up:c})]});var ht=lt(),gt=ht.createDefault({version:`2.0.0`,projects:[{id:`main`,name:`Default project`,description:`The initial default project`}],pipelines:[]});ht.createMigrations({defaultValue:gt,migrations:[j({version:`1.0.0`,up:e=>{let t=Object.entries(e.data||{}).map(([e,t])=>({...t,id:e,project:`main`}));return{...e,projects:[{id:`main`,name:`Default project`,description:`The initial default project`}],pipelines:t}}}),j({version:`2.0.0`,up:c})]});var _t=lt(),vt=_t.createDefault({canvas:{triggers:[],blocks:[]},description:``,name:``,variables:[],version:`5.0.0`});_t.createMigrations({defaultValue:vt,migrations:[j({version:`1.0.0`,up:e=>{let t=e.canvas.blocks,n=[],r=[];for(let e of t)e.type===`event`?n.push(e):r.push(e);return{...e,canvas:{...e.canvas,blocks:r,triggers:n}}}}),j({version:`2.0.0`,up:e=>{let{canvas:t}=e,{blocks:n,triggers:r}=t,i=[];for(let e of n){let t={};for(let n of Object.entries(e.params))if(n===void 0)throw Error(`Can't migrate block with undefined params`);else{let[e,r]=n;t[e]={editor:`editor`,value:r}}i.push({...e,params:t})}return{...e,canvas:{...t,triggers:r,blocks:i}}}}),j({version:`3.0.0`,up:e=>({...e,type:`default`})}),j({version:`4.0.0`,up:e=>{let t=e;if(t.type===`simple`)return{name:t.name,description:t.description,canvas:{blocks:[],triggers:[]},variables:[]};let n=(e,t)=>{e&&e.origin?.pluginId&&(e.origin.pluginId=bt(e.origin.pluginId),e.origin.version=t[e.origin.pluginId]??`latest`)},r={};if(t.plugins)for(let[e,n]of Object.entries(t.plugins))r[bt(e)]=n;if(t.canvas){for(let e of t.canvas.blocks??[])n(e,r);for(let e of t.canvas.triggers??[])n(e,r)}let{plugins:i,type:a,...o}=t;return o}}),j({version:`5.0.0`,up:c})]});var yt={construct:`@pipelab/plugin-construct`,filesystem:`@pipelab/plugin-filesystem`,system:`@pipelab/plugin-system`,steam:`@pipelab/plugin-steam`,itch:`@pipelab/plugin-itch`,electron:`@pipelab/plugin-electron`,discord:`@pipelab/plugin-discord`,dicord:`@pipelab/plugin-discord`,"@pipelab/plugin-dicord":`@pipelab/plugin-discord`,poki:`@pipelab/plugin-poki`,nvpatch:`@pipelab/plugin-nvpatch`,tauri:`@pipelab/plugin-tauri`,minify:`@pipelab/plugin-minify`,netlify:`@pipelab/plugin-netlify`},bt=e=>e&&(yt[e]||e),xt=D({id:k(),project:k(),lastModified:k(),type:E(`internal`),configName:k()}),St=D({id:k(),project:k(),path:k(),lastModified:k(),type:E(`external`),summary:D({plugins:w(k()),name:k(),description:k()})}),Ct=D({id:k(),project:k(),type:E(`pipelab-cloud`)}),wt=A([St,xt,Ct]);E(`1.0.0`),O(nt(k(),wt),{}),E(`2.0.0`),O(w(wt),[]);var Tt=[`dialog:showOpenDialog`,`dialog:showSaveDialog`];A([E(`light`),E(`dark`)]),E(`1.0.0`),A([E(`light`),E(`dark`)]),E(`2.0.0`),A([E(`light`),E(`dark`)]),E(`3.0.0`),A([E(`light`),E(`dark`)]),E(`4.0.0`),A([E(`en-US`),E(`fr-FR`),E(`pt-BR`),E(`zh-CN`),E(`es-ES`),E(`de-DE`)]),A([E(`light`),E(`dark`)]),E(`5.0.0`),A([E(`en-US`),E(`fr-FR`),E(`pt-BR`),E(`zh-CN`),E(`es-ES`),E(`de-DE`)]),A([E(`light`),E(`dark`)]),E(`6.0.0`),A([E(`en-US`),E(`fr-FR`),E(`pt-BR`),E(`zh-CN`),E(`es-ES`),E(`de-DE`)]),A([E(`light`),E(`dark`)]),E(`7.0.0`),A([E(`en-US`),E(`fr-FR`),E(`pt-BR`),E(`zh-CN`),E(`es-ES`),E(`de-DE`)]),A([E(`light`),E(`dark`)]),E(`8.0.0`),A([E(`en-US`),E(`fr-FR`),E(`pt-BR`),E(`zh-CN`),E(`es-ES`),E(`de-DE`)]),O(T(),!1);var Et=et({id:k(),pluginName:k(),name:k(),createdAt:k(),isDefault:T()});E(`1.0.0`);var Dt={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]};function Ot(e,t,n,r=!1){let i=String(t),a=(e,t)=>`\u001b[${t[0]}m${e}\u001b[${t[1]}m`,o=(e,t)=>t!=null&&typeof t==`string`?a(e,Dt[t]):t!=null&&Array.isArray(t)?t.reduce((e,t)=>o(e,t),e):t!=null&&t[e.trim()]!=null?o(e,t[e.trim()]):t!=null&&t[`*`]!=null?o(e,t[`*`]):e;return i.replace(/{{(.+?)}}/g,(t,i)=>{let s=n[i]==null?r?``:t:String(n[i]);return e.stylePrettyLogs?o(s,e?.prettyLogStyles?.[i]??null)+a(``,Dt.reset):s})}function M(e,t=2,n=0){return e!=null&&isNaN(e)?``:(e=e==null?e:e+n,t===2?e==null?`--`:e<10?`0`+e:e.toString():e==null?`---`:e<10?`00`+e:e<100?`0`+e:e.toString())}function kt(e){return{href:e.href,protocol:e.protocol,username:e.username,password:e.password,host:e.host,hostname:e.hostname,port:e.port,pathname:e.pathname,search:e.search,searchParams:[...e.searchParams].map(([e,t])=>({key:e,value:t})),hash:e.hash,origin:e.origin}}function At(e){let t=new Set;return JSON.stringify(e,(e,n)=>{if(typeof n==`object`&&n){if(t.has(n))return`[Circular]`;t.add(n)}return typeof n==`bigint`?`${n}`:n})}function N(e,t){let n={seen:[],stylize:Nt};return t!=null&&Qt(n,t),Mt(n.showHidden)&&(n.showHidden=!1),Mt(n.depth)&&(n.depth=2),Mt(n.colors)&&(n.colors=!0),Mt(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=Pt),Jt(n,e,n.depth)}N.colors=Dt,N.styles={special:`cyan`,number:`yellow`,boolean:`yellow`,undefined:`grey`,null:`bold`,string:`green`,date:`magenta`,regexp:`red`};function jt(e){return typeof e==`boolean`}function Mt(e){return e===void 0}function Nt(e){return e}function Pt(e,t){let n=N.styles[t];return n!=null&&N?.colors?.[n]?.[0]!=null&&N?.colors?.[n]?.[1]!=null?`\x1B[`+N.colors[n][0]+`m`+e+`\x1B[`+N.colors[n][1]+`m`:e}function Ft(e){return typeof e==`function`}function It(e){return typeof e==`string`}function Lt(e){return typeof e==`number`}function Rt(e){return e===null}function zt(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Bt(e){return Vt(e)&&Wt(e)===`[object RegExp]`}function Vt(e){return typeof e==`object`&&!!e}function Ht(e){return Vt(e)&&(Wt(e)===`[object Error]`||e instanceof Error)}function Ut(e){return Vt(e)&&Wt(e)===`[object Date]`}function Wt(e){return Object.prototype.toString.call(e)}function Gt(e){let t={};return e.forEach(e=>{t[e]=!0}),t}function Kt(e,t,n,r,i){let a=[];for(let i=0,o=t.length;i<o;++i)zt(t,String(i))?a.push(Yt(e,t,n,r,String(i),!0)):a.push(``);return i.forEach(i=>{i.match(/^\d+$/)||a.push(Yt(e,t,n,r,i,!0))}),a}function qt(e){return`[`+Error.prototype.toString.call(e)+`]`}function Jt(e,t,n=0){if(e.customInspect&&t!=null&&Ft(t)&&t?.inspect!==N&&!(t?.constructor&&t?.constructor.prototype===t)){if(typeof t.inspect!=`function`&&t.toString!=null)return t.toString();let r=t?.inspect(n,e);return It(r)||(r=Jt(e,r,n)),r}let r=Xt(e,t);if(r)return r;let i=Object.keys(t),a=Gt(i);try{e.showHidden&&Object.getOwnPropertyNames&&(i=Object.getOwnPropertyNames(t))}catch{}if(Ht(t)&&(i.indexOf(`message`)>=0||i.indexOf(`description`)>=0))return qt(t);if(i.length===0)if(Ft(e.stylize)){if(Ft(t)){let n=t.name?`: `+t.name:``;return e.stylize(`[Function`+n+`]`,`special`)}if(Bt(t))return e.stylize(RegExp.prototype.toString.call(t),`regexp`);if(Ut(t))return e.stylize(Date.prototype.toISOString.call(t),`date`);if(Ht(t))return qt(t)}else return t;let o=``,s=!1,c=[`{
3
3
  `,`
4
4
  }`];if(Array.isArray(t)&&(s=!0,c=[`[
5
5
  `,`
6
- ]`]),Dt(t)&&(o=` [Function`+(t.name?`: `+t.name:``)+`]`),Mt(t)&&(o=` `+RegExp.prototype.toString.call(t)),Ft(t)&&(o=` `+Date.prototype.toUTCString.call(t)),Pt(t)&&(o=` `+zt(t)),i.length===0&&(!s||t.length==0))return c[0]+o+c[1];if(n<0)return Mt(t)?e.stylize(RegExp.prototype.toString.call(t),`regexp`):e.stylize(`[Object]`,`special`);e.seen.push(t);let l;return l=s?Rt(e,t,n,a,i):i.map(r=>Vt(e,t,n,a,r,s)),e.seen.pop(),Ut(l,o,c)}function Vt(e,t,n,r,i,a){let o,s,c={value:void 0};try{c.value=t[i]}catch{}try{Object.getOwnPropertyDescriptor&&(c=Object.getOwnPropertyDescriptor(t,i)||c)}catch{}if(c.get?s=c.set?e.stylize(`[Getter/Setter]`,`special`):e.stylize(`[Getter]`,`special`):c.set&&(s=e.stylize(`[Setter]`,`special`)),jt(r,i)||(o=`[`+i+`]`),s||(e.seen.indexOf(c.value)<0?(s=At(n)?Bt(e,c.value,void 0):Bt(e,c.value,n-1),s.indexOf(`
6
+ ]`]),Ft(t)&&(o=` [Function`+(t.name?`: `+t.name:``)+`]`),Bt(t)&&(o=` `+RegExp.prototype.toString.call(t)),Ut(t)&&(o=` `+Date.prototype.toUTCString.call(t)),Ht(t)&&(o=` `+qt(t)),i.length===0&&(!s||t.length==0))return c[0]+o+c[1];if(n<0)return Bt(t)?e.stylize(RegExp.prototype.toString.call(t),`regexp`):e.stylize(`[Object]`,`special`);e.seen.push(t);let l;return l=s?Kt(e,t,n,a,i):i.map(r=>Yt(e,t,n,a,r,s)),e.seen.pop(),Zt(l,o,c)}function Yt(e,t,n,r,i,a){let o,s,c={value:void 0};try{c.value=t[i]}catch{}try{Object.getOwnPropertyDescriptor&&(c=Object.getOwnPropertyDescriptor(t,i)||c)}catch{}if(c.get?s=c.set?e.stylize(`[Getter/Setter]`,`special`):e.stylize(`[Getter]`,`special`):c.set&&(s=e.stylize(`[Setter]`,`special`)),zt(r,i)||(o=`[`+i+`]`),s||(e.seen.indexOf(c.value)<0?(s=Rt(n)?Jt(e,c.value,void 0):Jt(e,c.value,n-1),s.indexOf(`
7
7
  `)>-1&&(s=a?s.split(`
8
8
  `).map(e=>` `+e).join(`
9
9
  `).substr(2):`
10
10
  `+s.split(`
11
11
  `).map(e=>` `+e).join(`
12
- `))):s=e.stylize(`[Circular]`,`special`)),wt(o)){if(a&&i.match(/^\d+$/))return s;o=JSON.stringify(``+i),o.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,`name`)):(o=o.replace(/'/g,`\\'`).replace(/\\"/g,`\\'`).replace(/(^"|"$)/g,`'`),o=e.stylize(o,`string`))}return o+`: `+s}function Ht(e,t){if(wt(t))return e.stylize(`undefined`,`undefined`);if(Ot(t)){let n=`'`+JSON.stringify(t).replace(/^"|"$/g,``).replace(/'/g,`\\'`).replace(/\\"/g,`\\'`)+`'`;return e.stylize(n,`string`)}if(kt(t))return e.stylize(``+t,`number`);if(Ct(t))return e.stylize(``+t,`boolean`);if(At(t))return e.stylize(`null`,`null`)}function Ut(e,t,n){return n[0]+(t===``?``:t+`
12
+ `))):s=e.stylize(`[Circular]`,`special`)),Mt(o)){if(a&&i.match(/^\d+$/))return s;o=JSON.stringify(``+i),o.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,`name`)):(o=o.replace(/'/g,`\\'`).replace(/\\"/g,`\\'`).replace(/(^"|"$)/g,`'`),o=e.stylize(o,`string`))}return o+`: `+s}function Xt(e,t){if(Mt(t))return e.stylize(`undefined`,`undefined`);if(It(t)){let n=`'`+JSON.stringify(t).replace(/^"|"$/g,``).replace(/'/g,`\\'`).replace(/\\"/g,`\\'`)+`'`;return e.stylize(n,`string`)}if(Lt(t))return e.stylize(``+t,`number`);if(jt(t))return e.stylize(``+t,`boolean`);if(Rt(t))return e.stylize(`null`,`null`)}function Zt(e,t,n){return n[0]+(t===``?``:t+`
13
13
  `)+` `+e.join(`,
14
- `)+` `+n[1]}function Wt(e,t){let n={...e};if(!t||!Nt(t))return e;let r={...t},i=Object.keys(t),a=i.length;for(;a--;)n[i[a]]=r[i[a]];return n}function Gt(e,...t){let n={seen:[],stylize:Tt};e!=null&&Wt(n,e);let r=t[0],i=0,a=``,o=``;if(typeof r==`string`){if(t.length===1)return r;let s,c=0;for(let o=0;o<r.length-1;o++)if(r.charCodeAt(o)===37){let l=r.charCodeAt(++o);if(i+1!==t.length){switch(l){case 115:{let r=t[++i];s=typeof r==`number`||typeof r==`bigint`?Ht(n,r):typeof r!=`object`||!r?String(r):N(r,{...e,compact:3,colors:!1,depth:0});break}case 106:s=St(t[++i]);break;case 100:{let e=t[++i];s=typeof e==`bigint`?Ht(n,e):typeof e==`symbol`?`NaN`:Ht(n,e);break}case 79:s=N(t[++i],e);break;case 111:s=N(t[++i],{...e,showHidden:!0,showProxy:!0,depth:4});break;case 105:{let e=t[++i];s=typeof e==`bigint`?Ht(n,e):typeof e==`symbol`?`NaN`:Ht(n,parseInt(s));break}case 102:{let e=t[++i];s=typeof e==`symbol`?`NaN`:Ht(n,parseInt(e));break}case 99:i+=1,s=``;break;case 37:a+=r.slice(c,o),c=o+1;continue;default:continue}c!==o-1&&(a+=r.slice(c,o-1)),a+=s,c=o+1}else l===37&&(a+=r.slice(c,o),c=o+1)}c!==0&&(i++,o=` `,c<r.length&&(a+=r.slice(c)))}for(;i<t.length;){let n=t[i];a+=o,a+=typeof n==`string`?n:N(n,e),o=` `,i++}return a}var Kt={getCallerStackFrame:Xt,getErrorTrace:Zt,getMeta:Yt,transportJSON:rn,transportFormatted:nn,isBuffer:an,isError:$t,prettyFormatLogObj:en,prettyFormatErrorObj:tn},qt={runtime:[typeof window,typeof document].includes(`undefined`)?`Generic`:`Browser`,browser:globalThis?.navigator?.userAgent},Jt=/(?:(?:file|https?|global code|[^@]+)@)?(?:file:)?((?:\/[^:/]+){2,})(?::(\d+))?(?::(\d+))?/;function Yt(e,t,n,r,i,a){return Object.assign({},qt,{name:i,parentNames:a,date:new Date,logLevelId:e,logLevelName:t,path:r?void 0:Xt(n)})}function Xt(e,t=Error()){return Qt(t?.stack?.split(`
15
- `)?.filter(e=>!e.includes(`Error: `))?.[e])}function Zt(e){return(e?.stack?.split(`
16
- `)??[])?.filter(e=>!e.includes(`Error: `))?.reduce((e,t)=>(e.push(Qt(t)),e),[])}function Qt(e){let t=globalThis?.location?.origin,n={fullFilePath:void 0,fileName:void 0,fileNameWithLine:void 0,fileColumn:void 0,fileLine:void 0,filePath:void 0,filePathWithLine:void 0,method:void 0};if(e!=null){let r=e.match(Jt);if(r){n.filePath=r[1].replace(/\?.*$/,``),n.fullFilePath=`${t}${n.filePath}`;let e=n.filePath.split(`/`);n.fileName=e[e.length-1],n.fileLine=r[2],n.fileColumn=r[3],n.filePathWithLine=`${n.filePath}:${n.fileLine}`,n.fileNameWithLine=`${n.fileName}:${n.fileLine}`}}return n}function $t(e){return e instanceof Error}function en(e,t){return e.reduce((e,n)=>($t(n)?e.errors.push(tn(n,t)):e.args.push(n),e),{args:[],errors:[]})}function tn(e,t){let n=Zt(e).map(e=>bt(t,t.prettyErrorStackTemplate,{...e},!0)),r={errorName:` ${e.name} `,errorMessage:Object.getOwnPropertyNames(e).reduce((t,n)=>(n!==`stack`&&t.push(e[n]),t),[]).join(`, `),errorStack:n.join(`
17
- `)};return bt(t,t.prettyErrorTemplate,r)}function nn(e,t,n,r){let i=(n.length>0&&t.length>0?`
14
+ `)+` `+n[1]}function Qt(e,t){let n={...e};if(!t||!Vt(t))return e;let r={...t},i=Object.keys(t),a=i.length;for(;a--;)n[i[a]]=r[i[a]];return n}function $t(e,...t){let n={seen:[],stylize:Nt};e!=null&&Qt(n,e);let r=t[0],i=0,a=``,o=``;if(typeof r==`string`){if(t.length===1)return r;let s,c=0;for(let o=0;o<r.length-1;o++)if(r.charCodeAt(o)===37){let l=r.charCodeAt(++o);if(i+1!==t.length){switch(l){case 115:{let r=t[++i];s=typeof r==`number`||typeof r==`bigint`?Xt(n,r):typeof r!=`object`||!r?String(r):N(r,{...e,compact:3,colors:!1,depth:0});break}case 106:s=At(t[++i]);break;case 100:{let e=t[++i];s=typeof e==`bigint`?Xt(n,e):typeof e==`symbol`?`NaN`:Xt(n,e);break}case 79:s=N(t[++i],e);break;case 111:s=N(t[++i],{...e,showHidden:!0,showProxy:!0,depth:4});break;case 105:{let e=t[++i];s=typeof e==`bigint`?Xt(n,e):typeof e==`symbol`?`NaN`:Xt(n,parseInt(s));break}case 102:{let e=t[++i];s=typeof e==`symbol`?`NaN`:Xt(n,parseInt(e));break}case 99:i+=1,s=``;break;case 37:a+=r.slice(c,o),c=o+1;continue;default:continue}c!==o-1&&(a+=r.slice(c,o-1)),a+=s,c=o+1}else l===37&&(a+=r.slice(c,o),c=o+1)}c!==0&&(i++,o=` `,c<r.length&&(a+=r.slice(c)))}for(;i<t.length;){let n=t[i];a+=o,a+=typeof n==`string`?n:N(n,e),o=` `,i++}return a}var en={getCallerStackFrame:an,getErrorTrace:on,getMeta:rn,transportJSON:fn,transportFormatted:dn,isBuffer:pn,isError:cn,prettyFormatLogObj:ln,prettyFormatErrorObj:un},tn={runtime:[typeof window,typeof document].includes(`undefined`)?`Generic`:`Browser`,browser:globalThis?.navigator?.userAgent},nn=/(?:(?:file|https?|global code|[^@]+)@)?(?:file:)?((?:\/[^:/]+){2,})(?::(\d+))?(?::(\d+))?/;function rn(e,t,n,r,i,a){return Object.assign({},tn,{name:i,parentNames:a,date:new Date,logLevelId:e,logLevelName:t,path:r?void 0:an(n)})}function an(e,t=Error()){return sn(t?.stack?.split(`
15
+ `)?.filter(e=>!e.includes(`Error: `))?.[e])}function on(e){return(e?.stack?.split(`
16
+ `)??[])?.filter(e=>!e.includes(`Error: `))?.reduce((e,t)=>(e.push(sn(t)),e),[])}function sn(e){let t=globalThis?.location?.origin,n={fullFilePath:void 0,fileName:void 0,fileNameWithLine:void 0,fileColumn:void 0,fileLine:void 0,filePath:void 0,filePathWithLine:void 0,method:void 0};if(e!=null){let r=e.match(nn);if(r){n.filePath=r[1].replace(/\?.*$/,``),n.fullFilePath=`${t}${n.filePath}`;let e=n.filePath.split(`/`);n.fileName=e[e.length-1],n.fileLine=r[2],n.fileColumn=r[3],n.filePathWithLine=`${n.filePath}:${n.fileLine}`,n.fileNameWithLine=`${n.fileName}:${n.fileLine}`}}return n}function cn(e){return e instanceof Error}function ln(e,t){return e.reduce((e,n)=>(cn(n)?e.errors.push(un(n,t)):e.args.push(n),e),{args:[],errors:[]})}function un(e,t){let n=on(e).map(e=>Ot(t,t.prettyErrorStackTemplate,{...e},!0)),r={errorName:` ${e.name} `,errorMessage:Object.getOwnPropertyNames(e).reduce((t,n)=>(n!==`stack`&&t.push(e[n]),t),[]).join(`, `),errorStack:n.join(`
17
+ `)};return Ot(t,t.prettyErrorTemplate,r)}function dn(e,t,n,r){let i=(n.length>0&&t.length>0?`
18
18
  `:``)+n.join(`
19
- `);r.prettyInspectOptions.colors=r.stylePrettyLogs,console.log(e+Gt(r.prettyInspectOptions,...t)+i)}function rn(e){console.log(St(e))}function an(e){return!1}var on=class{constructor(e,t,n=4){this.logObj=t,this.stackDepthLevel=n,this.runtime=Kt,this.settings={type:e?.type??`pretty`,name:e?.name,parentNames:e?.parentNames,minLevel:e?.minLevel??0,argumentsArrayName:e?.argumentsArrayName,hideLogPositionForProduction:e?.hideLogPositionForProduction??!1,prettyLogTemplate:e?.prettyLogTemplate??`{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}} {{logLevelName}} {{filePathWithLine}}{{nameWithDelimiterPrefix}} `,prettyErrorTemplate:e?.prettyErrorTemplate??`
19
+ `);r.prettyInspectOptions.colors=r.stylePrettyLogs,console.log(e+$t(r.prettyInspectOptions,...t)+i)}function fn(e){console.log(At(e))}function pn(e){return!1}var mn=class{constructor(e,t,n=4){this.logObj=t,this.stackDepthLevel=n,this.runtime=en,this.settings={type:e?.type??`pretty`,name:e?.name,parentNames:e?.parentNames,minLevel:e?.minLevel??0,argumentsArrayName:e?.argumentsArrayName,hideLogPositionForProduction:e?.hideLogPositionForProduction??!1,prettyLogTemplate:e?.prettyLogTemplate??`{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}} {{logLevelName}} {{filePathWithLine}}{{nameWithDelimiterPrefix}} `,prettyErrorTemplate:e?.prettyErrorTemplate??`
20
20
  {{errorName}} {{errorMessage}}
21
21
  error stack:
22
22
  {{errorStack}}`,prettyErrorStackTemplate:e?.prettyErrorStackTemplate??` • {{fileName}} {{method}}
23
- {{filePathWithLine}}`,prettyErrorParentNamesSeparator:e?.prettyErrorParentNamesSeparator??`:`,prettyErrorLoggerNameDelimiter:e?.prettyErrorLoggerNameDelimiter??` `,stylePrettyLogs:e?.stylePrettyLogs??!0,prettyLogTimeZone:e?.prettyLogTimeZone??`UTC`,prettyLogStyles:e?.prettyLogStyles??{logLevelName:{"*":[`bold`,`black`,`bgWhiteBright`,`dim`],SILLY:[`bold`,`white`],TRACE:[`bold`,`whiteBright`],DEBUG:[`bold`,`green`],INFO:[`bold`,`blue`],WARN:[`bold`,`yellow`],ERROR:[`bold`,`red`],FATAL:[`bold`,`redBright`]},dateIsoStr:`white`,filePathWithLine:`white`,name:[`white`,`bold`],nameWithDelimiterPrefix:[`white`,`bold`],nameWithDelimiterSuffix:[`white`,`bold`],errorName:[`bold`,`bgRedBright`,`whiteBright`],fileName:[`yellow`],fileNameWithLine:`white`},prettyInspectOptions:e?.prettyInspectOptions??{colors:!0,compact:!1,depth:1/0},metaProperty:e?.metaProperty??`_meta`,maskPlaceholder:e?.maskPlaceholder??`[***]`,maskValuesOfKeys:e?.maskValuesOfKeys??[`password`],maskValuesOfKeysCaseInsensitive:e?.maskValuesOfKeysCaseInsensitive??!1,maskValuesRegEx:e?.maskValuesRegEx,prefix:[...e?.prefix??[]],attachedTransports:[...e?.attachedTransports??[]],overwrite:{mask:e?.overwrite?.mask,toLogObj:e?.overwrite?.toLogObj,addMeta:e?.overwrite?.addMeta,addPlaceholders:e?.overwrite?.addPlaceholders,formatMeta:e?.overwrite?.formatMeta,formatLogObj:e?.overwrite?.formatLogObj,transportFormatted:e?.overwrite?.transportFormatted,transportJSON:e?.overwrite?.transportJSON}}}log(e,t,...n){if(e<this.settings.minLevel)return;let r=[...this.settings.prefix,...n],i=this.settings.overwrite?.mask==null?this.settings.maskValuesOfKeys!=null&&this.settings.maskValuesOfKeys.length>0?this._mask(r):r:this.settings.overwrite?.mask(r),a=this.logObj==null?void 0:this._recursiveCloneAndExecuteFunctions(this.logObj),o=this.settings.overwrite?.toLogObj==null?this._toLogObj(i,a):this.settings.overwrite?.toLogObj(i,a),s=this.settings.overwrite?.addMeta==null?this._addMetaToLogObj(o,e,t):this.settings.overwrite?.addMeta(o,e,t),c,l;return this.settings.overwrite?.formatMeta!=null&&(c=this.settings.overwrite?.formatMeta(s?.[this.settings.metaProperty])),this.settings.overwrite?.formatLogObj!=null&&(l=this.settings.overwrite?.formatLogObj(i,this.settings)),this.settings.type===`pretty`&&(c??=this._prettyFormatLogObjMeta(s?.[this.settings.metaProperty]),l??=this.runtime.prettyFormatLogObj(i,this.settings)),c!=null&&l!=null?this.settings.overwrite?.transportFormatted==null?this.runtime.transportFormatted(c,l.args,l.errors,this.settings):this.settings.overwrite?.transportFormatted(c,l.args,l.errors,this.settings):this.settings.overwrite?.transportJSON==null?this.settings.type!==`hidden`&&this.runtime.transportJSON(s):this.settings.overwrite?.transportJSON(s),this.settings.attachedTransports!=null&&this.settings.attachedTransports.length>0&&this.settings.attachedTransports.forEach(e=>{e(s)}),s}attachTransport(e){this.settings.attachedTransports.push(e)}getSubLogger(e,t){let n={...this.settings,...e,parentNames:this.settings?.parentNames!=null&&this.settings?.name!=null?[...this.settings.parentNames,this.settings.name]:this.settings?.name==null?void 0:[this.settings.name],prefix:[...this.settings.prefix,...e?.prefix??[]]};return new this.constructor(n,t??this.logObj,this.stackDepthLevel)}_mask(e){let t=this.settings.maskValuesOfKeysCaseInsensitive===!0?this.settings.maskValuesOfKeys.map(e=>e.toLowerCase()):this.settings.maskValuesOfKeys;return e?.map(e=>this._recursiveCloneAndMaskValuesOfKeys(e,t))}_recursiveCloneAndMaskValuesOfKeys(e,t,n=[]){if(n.includes(e))return{...e};if(typeof e==`object`&&e&&n.push(e),this.runtime.isError(e)||this.runtime.isBuffer(e))return e;if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);if(Array.isArray(e))return e.map(e=>this._recursiveCloneAndMaskValuesOfKeys(e,t,n));if(e instanceof Date)return new Date(e.getTime());if(e instanceof URL)return xt(e);if(typeof e==`object`&&e){let r=this.runtime.isError(e)?this._cloneError(e):Object.create(Object.getPrototypeOf(e));return Object.getOwnPropertyNames(e).reduce((r,i)=>(r[i]=t.includes(this.settings?.maskValuesOfKeysCaseInsensitive===!0?i.toLowerCase():i)?this.settings.maskPlaceholder:(()=>{try{return this._recursiveCloneAndMaskValuesOfKeys(e[i],t,n)}catch{return null}})(),r),r)}else{if(typeof e==`string`){let t=e;for(let e of this.settings?.maskValuesRegEx||[])t=t.replace(e,this.settings?.maskPlaceholder||``);return t}return e}}_recursiveCloneAndExecuteFunctions(e,t=[]){return this.isObjectOrArray(e)&&t.includes(e)?this.shallowCopy(e):(this.isObjectOrArray(e)&&t.push(e),Array.isArray(e)?e.map(e=>this._recursiveCloneAndExecuteFunctions(e,t)):e instanceof Date?new Date(e.getTime()):this.isObject(e)?Object.getOwnPropertyNames(e).reduce((n,r)=>{let i=Object.getOwnPropertyDescriptor(e,r);if(i){Object.defineProperty(n,r,i);let a=e[r];n[r]=typeof a==`function`?a():this._recursiveCloneAndExecuteFunctions(a,t)}return n},Object.create(Object.getPrototypeOf(e))):e)}isObjectOrArray(e){return typeof e==`object`&&!!e}isObject(e){return typeof e==`object`&&!Array.isArray(e)&&e!==null}shallowCopy(e){return Array.isArray(e)?[...e]:{...e}}_toLogObj(e,t={}){return e=e?.map(e=>this.runtime.isError(e)?this._toErrorObject(e):e),t=this.settings.argumentsArrayName==null?e.length===1&&!Array.isArray(e[0])&&this.runtime.isBuffer(e[0])!==!0&&!(e[0]instanceof Date)?typeof e[0]==`object`&&e[0]!=null?{...e[0],...t}:{0:e[0],...t}:{...t,...e}:{...t,[this.settings.argumentsArrayName]:e},t}_cloneError(e){let t=new e.constructor;return Object.getOwnPropertyNames(e).forEach(n=>{t[n]=e[n]}),t}_toErrorObject(e){return{nativeError:e,name:e.name??`Error`,message:e.message,stack:this.runtime.getErrorTrace(e)}}_addMetaToLogObj(e,t,n){return{...e,[this.settings.metaProperty]:this.runtime.getMeta(t,n,this.stackDepthLevel,this.settings.hideLogPositionForProduction,this.settings.name,this.settings.parentNames)}}_prettyFormatLogObjMeta(e){if(e==null)return``;let t=this.settings.prettyLogTemplate,n={};t.includes(`{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}`)?t=t.replace(`{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}`,`{{dateIsoStr}}`):this.settings.prettyLogTimeZone===`UTC`?(n.yyyy=e?.date?.getUTCFullYear()??`----`,n.mm=M(e?.date?.getUTCMonth(),2,1),n.dd=M(e?.date?.getUTCDate(),2),n.hh=M(e?.date?.getUTCHours(),2),n.MM=M(e?.date?.getUTCMinutes(),2),n.ss=M(e?.date?.getUTCSeconds(),2),n.ms=M(e?.date?.getUTCMilliseconds(),3)):(n.yyyy=e?.date?.getFullYear()??`----`,n.mm=M(e?.date?.getMonth(),2,1),n.dd=M(e?.date?.getDate(),2),n.hh=M(e?.date?.getHours(),2),n.MM=M(e?.date?.getMinutes(),2),n.ss=M(e?.date?.getSeconds(),2),n.ms=M(e?.date?.getMilliseconds(),3));let r=this.settings.prettyLogTimeZone===`UTC`?e?.date:new Date(e?.date?.getTime()-e?.date?.getTimezoneOffset()*6e4);n.rawIsoStr=r?.toISOString(),n.dateIsoStr=r?.toISOString().replace(`T`,` `).replace(`Z`,``),n.logLevelName=e?.logLevelName,n.fileNameWithLine=e?.path?.fileNameWithLine??``,n.filePathWithLine=e?.path?.filePathWithLine??``,n.fullFilePath=e?.path?.fullFilePath??``;let i=this.settings.parentNames?.join(this.settings.prettyErrorParentNamesSeparator);return i=i!=null&&e?.name!=null?i+this.settings.prettyErrorParentNamesSeparator:void 0,n.name=e?.name!=null||i!=null?(i??``)+e?.name??``:``,n.nameWithDelimiterPrefix=n.name.length>0?this.settings.prettyErrorLoggerNameDelimiter+n.name:``,n.nameWithDelimiterSuffix=n.name.length>0?n.name+this.settings.prettyErrorLoggerNameDelimiter:``,this.settings.overwrite?.addPlaceholders!=null&&this.settings.overwrite?.addPlaceholders(e,n),bt(this.settings,t,n)}},sn=new class extends on{constructor(e,t){let n=typeof window<`u`&&typeof document<`u`,r=n?window.chrome!==void 0&&window.CSS!==void 0&&window.CSS.supports(`color`,`green`):!1,i=n?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1;e||={},e.stylePrettyLogs=e.stylePrettyLogs&&n&&!r?!1:e.stylePrettyLogs,super(e,t,i?4:5)}log(e,t,...n){return super.log(e,t,...n)}silly(...e){return super.log(0,`SILLY`,...e)}trace(...e){return super.log(1,`TRACE`,...e)}debug(...e){return super.log(2,`DEBUG`,...e)}info(...e){return super.log(3,`INFO`,...e)}warn(...e){return super.log(4,`WARN`,...e)}error(...e){return super.log(5,`ERROR`,...e)}fatal(...e){return super.log(6,`FATAL`,...e)}getSubLogger(e,t){return super.getSubLogger(e,t)}}({minLevel:3,hideLogPositionForProduction:!1}),cn=()=>({logger:()=>sn,attachTransport:e=>{sn.attachTransport(e)}});async function ln(e){let t=un(await e),[n,r,{QuickJSWASMModule:i}]=await Promise.all([t.importModuleLoader().then(un),t.importFFI(),o(()=>import(`./module-6F3E5H7Y-D7eKX8Yv.js`).then(un),__vite__mapDeps([0,1]))]),a=await n();return a.type=`sync`,new i(a,new r(a))}function un(e){return e&&`default`in e&&e.default?e.default&&`default`in e.default&&e.default.default?e.default.default:e.default:e}function dn(e,t){return{...e,async importModuleLoader(){let n=un(await e.importModuleLoader());return async function(){let e=t.emscriptenModule?{...t.emscriptenModule}:{},r=t.log??((...e)=>i(`newVariant moduleLoader:`,...e)),o=(e,t)=>(r(...e,t),t),s=e=>typeof e==`function`?e():e;(t.wasmLocation||t.wasmSourceMapLocation||t.locateFile)&&(e.locateFile=(e,n)=>{let r={fileName:e,relativeTo:n};if(e.endsWith(`.wasm`)&&t.wasmLocation!==void 0)return o([`locateFile .wasm: provide wasmLocation`,r],t.wasmLocation);if(e.endsWith(`.map`)){if(t.wasmSourceMapLocation!==void 0)return o([`locateFile .map: provide wasmSourceMapLocation`,r],t.wasmSourceMapLocation);if(t.wasmLocation&&!t.locateFile)return o([`locateFile .map: infer from wasmLocation`,r],t.wasmLocation+`.map`)}return t.locateFile?o([`locateFile: use provided fn`,r],t.locateFile(e,n)):o([`locateFile: unhandled, passthrough`,r],e)}),t.wasmBinary&&(e.wasmBinary=await s(t.wasmBinary)),t.wasmMemory&&(e.wasmMemory=await s(t.wasmMemory));let c=t.wasmModule,l;c&&(e.instantiateWasm=async(e,t)=>{l??=Promise.resolve(s(c));let n=await l;if(!n)throw new a(`options.wasmModule returned ${String(n)}`);let r=await WebAssembly.instantiate(n,e);return t(r),r.exports}),e.monitorRunDependencies=e=>{r(`monitorRunDependencies:`,e)},e.quickjsEmscriptenInit=()=>fn(r);let u=n(e),d=e.quickjsEmscriptenInit?.(r);if(c&&d?.receiveWasmOffsetConverter&&!d.existingWasmOffsetConverter){let e=await s(t.wasmBinary)??new ArrayBuffer(0);l??=Promise.resolve(s(c));let n=await l;if(!n)throw new a(`options.wasmModule returned ${String(n)}`);d.receiveWasmOffsetConverter(e,n)}if(d?.receiveSourceMapJSON){let e=await s(t.wasmSourceMapData);typeof e==`string`?d.receiveSourceMapJSON(JSON.parse(e)):e?d.receiveSourceMapJSON(e):d.receiveSourceMapJSON({version:3,names:[],sources:[],mappings:``})}return u}}}}function fn(e){let t=`mock called, emscripten module may not be initialized yet`;return{mock:!0,removeRunDependency(n){e(`${t}: removeRunDependency called:`,n)},receiveSourceMapJSON(n){e(`${t}: receiveSourceMapJSON called:`,n)},WasmOffsetConverter:void 0,receiveWasmOffsetConverter(n,r){e(`${t}: receiveWasmOffsetConverter called:`,n,r)}}}var pn=Object.defineProperty,mn=(e,t,n)=>t in e?pn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,P=(e,t,n)=>mn(e,typeof t==`symbol`?t:t+``,n),hn=e=>{let t=new gn(e);return new Proxy(e,{get(e,n,r){return n in t?t[n]:Reflect.get(e,n,r)}})},gn=class{constructor(e){P(this,`context`),P(this,`fn`),P(this,`fnGenerator`),P(this,`fnCounter`,-(2**53-1)),P(this,`fnMap`,new Map),P(this,`newFunction`,(e,t)=>{this.fnCounter++;let n=this.fnCounter;return this.fnMap.set(n,t),this.context.unwrapResult(this.context.callFunction(this.fnGenerator,this.context.undefined,this.context.newString(e),this.context.newNumber(t.length),this.context.newNumber(n),this.fn))}),this.context=e;let t=this.fnMap;this.fn=this.context.newFunction(``,function(n,...r){let i=e.getNumber(n),a=t.get(i);if(!a)throw Error(`function is not registered`);return a.call(this,...r)}),this.fnGenerator=e.unwrapResult(e.evalCode(`((name, length, id, f) => {
23
+ {{filePathWithLine}}`,prettyErrorParentNamesSeparator:e?.prettyErrorParentNamesSeparator??`:`,prettyErrorLoggerNameDelimiter:e?.prettyErrorLoggerNameDelimiter??` `,stylePrettyLogs:e?.stylePrettyLogs??!0,prettyLogTimeZone:e?.prettyLogTimeZone??`UTC`,prettyLogStyles:e?.prettyLogStyles??{logLevelName:{"*":[`bold`,`black`,`bgWhiteBright`,`dim`],SILLY:[`bold`,`white`],TRACE:[`bold`,`whiteBright`],DEBUG:[`bold`,`green`],INFO:[`bold`,`blue`],WARN:[`bold`,`yellow`],ERROR:[`bold`,`red`],FATAL:[`bold`,`redBright`]},dateIsoStr:`white`,filePathWithLine:`white`,name:[`white`,`bold`],nameWithDelimiterPrefix:[`white`,`bold`],nameWithDelimiterSuffix:[`white`,`bold`],errorName:[`bold`,`bgRedBright`,`whiteBright`],fileName:[`yellow`],fileNameWithLine:`white`},prettyInspectOptions:e?.prettyInspectOptions??{colors:!0,compact:!1,depth:1/0},metaProperty:e?.metaProperty??`_meta`,maskPlaceholder:e?.maskPlaceholder??`[***]`,maskValuesOfKeys:e?.maskValuesOfKeys??[`password`],maskValuesOfKeysCaseInsensitive:e?.maskValuesOfKeysCaseInsensitive??!1,maskValuesRegEx:e?.maskValuesRegEx,prefix:[...e?.prefix??[]],attachedTransports:[...e?.attachedTransports??[]],overwrite:{mask:e?.overwrite?.mask,toLogObj:e?.overwrite?.toLogObj,addMeta:e?.overwrite?.addMeta,addPlaceholders:e?.overwrite?.addPlaceholders,formatMeta:e?.overwrite?.formatMeta,formatLogObj:e?.overwrite?.formatLogObj,transportFormatted:e?.overwrite?.transportFormatted,transportJSON:e?.overwrite?.transportJSON}}}log(e,t,...n){if(e<this.settings.minLevel)return;let r=[...this.settings.prefix,...n],i=this.settings.overwrite?.mask==null?this.settings.maskValuesOfKeys!=null&&this.settings.maskValuesOfKeys.length>0?this._mask(r):r:this.settings.overwrite?.mask(r),a=this.logObj==null?void 0:this._recursiveCloneAndExecuteFunctions(this.logObj),o=this.settings.overwrite?.toLogObj==null?this._toLogObj(i,a):this.settings.overwrite?.toLogObj(i,a),s=this.settings.overwrite?.addMeta==null?this._addMetaToLogObj(o,e,t):this.settings.overwrite?.addMeta(o,e,t),c,l;return this.settings.overwrite?.formatMeta!=null&&(c=this.settings.overwrite?.formatMeta(s?.[this.settings.metaProperty])),this.settings.overwrite?.formatLogObj!=null&&(l=this.settings.overwrite?.formatLogObj(i,this.settings)),this.settings.type===`pretty`&&(c??=this._prettyFormatLogObjMeta(s?.[this.settings.metaProperty]),l??=this.runtime.prettyFormatLogObj(i,this.settings)),c!=null&&l!=null?this.settings.overwrite?.transportFormatted==null?this.runtime.transportFormatted(c,l.args,l.errors,this.settings):this.settings.overwrite?.transportFormatted(c,l.args,l.errors,this.settings):this.settings.overwrite?.transportJSON==null?this.settings.type!==`hidden`&&this.runtime.transportJSON(s):this.settings.overwrite?.transportJSON(s),this.settings.attachedTransports!=null&&this.settings.attachedTransports.length>0&&this.settings.attachedTransports.forEach(e=>{e(s)}),s}attachTransport(e){this.settings.attachedTransports.push(e)}getSubLogger(e,t){let n={...this.settings,...e,parentNames:this.settings?.parentNames!=null&&this.settings?.name!=null?[...this.settings.parentNames,this.settings.name]:this.settings?.name==null?void 0:[this.settings.name],prefix:[...this.settings.prefix,...e?.prefix??[]]};return new this.constructor(n,t??this.logObj,this.stackDepthLevel)}_mask(e){let t=this.settings.maskValuesOfKeysCaseInsensitive===!0?this.settings.maskValuesOfKeys.map(e=>e.toLowerCase()):this.settings.maskValuesOfKeys;return e?.map(e=>this._recursiveCloneAndMaskValuesOfKeys(e,t))}_recursiveCloneAndMaskValuesOfKeys(e,t,n=[]){if(n.includes(e))return{...e};if(typeof e==`object`&&e&&n.push(e),this.runtime.isError(e)||this.runtime.isBuffer(e))return e;if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);if(Array.isArray(e))return e.map(e=>this._recursiveCloneAndMaskValuesOfKeys(e,t,n));if(e instanceof Date)return new Date(e.getTime());if(e instanceof URL)return kt(e);if(typeof e==`object`&&e){let r=this.runtime.isError(e)?this._cloneError(e):Object.create(Object.getPrototypeOf(e));return Object.getOwnPropertyNames(e).reduce((r,i)=>(r[i]=t.includes(this.settings?.maskValuesOfKeysCaseInsensitive===!0?i.toLowerCase():i)?this.settings.maskPlaceholder:(()=>{try{return this._recursiveCloneAndMaskValuesOfKeys(e[i],t,n)}catch{return null}})(),r),r)}else{if(typeof e==`string`){let t=e;for(let e of this.settings?.maskValuesRegEx||[])t=t.replace(e,this.settings?.maskPlaceholder||``);return t}return e}}_recursiveCloneAndExecuteFunctions(e,t=[]){return this.isObjectOrArray(e)&&t.includes(e)?this.shallowCopy(e):(this.isObjectOrArray(e)&&t.push(e),Array.isArray(e)?e.map(e=>this._recursiveCloneAndExecuteFunctions(e,t)):e instanceof Date?new Date(e.getTime()):this.isObject(e)?Object.getOwnPropertyNames(e).reduce((n,r)=>{let i=Object.getOwnPropertyDescriptor(e,r);if(i){Object.defineProperty(n,r,i);let a=e[r];n[r]=typeof a==`function`?a():this._recursiveCloneAndExecuteFunctions(a,t)}return n},Object.create(Object.getPrototypeOf(e))):e)}isObjectOrArray(e){return typeof e==`object`&&!!e}isObject(e){return typeof e==`object`&&!Array.isArray(e)&&e!==null}shallowCopy(e){return Array.isArray(e)?[...e]:{...e}}_toLogObj(e,t={}){return e=e?.map(e=>this.runtime.isError(e)?this._toErrorObject(e):e),t=this.settings.argumentsArrayName==null?e.length===1&&!Array.isArray(e[0])&&this.runtime.isBuffer(e[0])!==!0&&!(e[0]instanceof Date)?typeof e[0]==`object`&&e[0]!=null?{...e[0],...t}:{0:e[0],...t}:{...t,...e}:{...t,[this.settings.argumentsArrayName]:e},t}_cloneError(e){let t=new e.constructor;return Object.getOwnPropertyNames(e).forEach(n=>{t[n]=e[n]}),t}_toErrorObject(e){return{nativeError:e,name:e.name??`Error`,message:e.message,stack:this.runtime.getErrorTrace(e)}}_addMetaToLogObj(e,t,n){return{...e,[this.settings.metaProperty]:this.runtime.getMeta(t,n,this.stackDepthLevel,this.settings.hideLogPositionForProduction,this.settings.name,this.settings.parentNames)}}_prettyFormatLogObjMeta(e){if(e==null)return``;let t=this.settings.prettyLogTemplate,n={};t.includes(`{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}`)?t=t.replace(`{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}`,`{{dateIsoStr}}`):this.settings.prettyLogTimeZone===`UTC`?(n.yyyy=e?.date?.getUTCFullYear()??`----`,n.mm=M(e?.date?.getUTCMonth(),2,1),n.dd=M(e?.date?.getUTCDate(),2),n.hh=M(e?.date?.getUTCHours(),2),n.MM=M(e?.date?.getUTCMinutes(),2),n.ss=M(e?.date?.getUTCSeconds(),2),n.ms=M(e?.date?.getUTCMilliseconds(),3)):(n.yyyy=e?.date?.getFullYear()??`----`,n.mm=M(e?.date?.getMonth(),2,1),n.dd=M(e?.date?.getDate(),2),n.hh=M(e?.date?.getHours(),2),n.MM=M(e?.date?.getMinutes(),2),n.ss=M(e?.date?.getSeconds(),2),n.ms=M(e?.date?.getMilliseconds(),3));let r=this.settings.prettyLogTimeZone===`UTC`?e?.date:new Date(e?.date?.getTime()-e?.date?.getTimezoneOffset()*6e4);n.rawIsoStr=r?.toISOString(),n.dateIsoStr=r?.toISOString().replace(`T`,` `).replace(`Z`,``),n.logLevelName=e?.logLevelName,n.fileNameWithLine=e?.path?.fileNameWithLine??``,n.filePathWithLine=e?.path?.filePathWithLine??``,n.fullFilePath=e?.path?.fullFilePath??``;let i=this.settings.parentNames?.join(this.settings.prettyErrorParentNamesSeparator);return i=i!=null&&e?.name!=null?i+this.settings.prettyErrorParentNamesSeparator:void 0,n.name=e?.name!=null||i!=null?(i??``)+e?.name??``:``,n.nameWithDelimiterPrefix=n.name.length>0?this.settings.prettyErrorLoggerNameDelimiter+n.name:``,n.nameWithDelimiterSuffix=n.name.length>0?n.name+this.settings.prettyErrorLoggerNameDelimiter:``,this.settings.overwrite?.addPlaceholders!=null&&this.settings.overwrite?.addPlaceholders(e,n),Ot(this.settings,t,n)}},hn=new class extends mn{constructor(e,t){let n=typeof window<`u`&&typeof document<`u`,r=n?window.chrome!==void 0&&window.CSS!==void 0&&window.CSS.supports(`color`,`green`):!1,i=n?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1;e||={},e.stylePrettyLogs=e.stylePrettyLogs&&n&&!r?!1:e.stylePrettyLogs,super(e,t,i?4:5)}log(e,t,...n){return super.log(e,t,...n)}silly(...e){return super.log(0,`SILLY`,...e)}trace(...e){return super.log(1,`TRACE`,...e)}debug(...e){return super.log(2,`DEBUG`,...e)}info(...e){return super.log(3,`INFO`,...e)}warn(...e){return super.log(4,`WARN`,...e)}error(...e){return super.log(5,`ERROR`,...e)}fatal(...e){return super.log(6,`FATAL`,...e)}getSubLogger(e,t){return super.getSubLogger(e,t)}}({minLevel:3,hideLogPositionForProduction:!1}),gn=()=>({logger:()=>hn,attachTransport:e=>{hn.attachTransport(e)}});async function _n(e){let t=vn(await e),[n,r,{QuickJSWASMModule:i}]=await Promise.all([t.importModuleLoader().then(vn),t.importFFI(),o(()=>import(`./module-6F3E5H7Y-DUb8SKDP.js`).then(vn),__vite__mapDeps([0,1]))]),a=await n();return a.type=`sync`,new i(a,new r(a))}function vn(e){return e&&`default`in e&&e.default?e.default&&`default`in e.default&&e.default.default?e.default.default:e.default:e}function yn(e,t){return{...e,async importModuleLoader(){let n=vn(await e.importModuleLoader());return async function(){let e=t.emscriptenModule?{...t.emscriptenModule}:{},r=t.log??((...e)=>i(`newVariant moduleLoader:`,...e)),o=(e,t)=>(r(...e,t),t),s=e=>typeof e==`function`?e():e;(t.wasmLocation||t.wasmSourceMapLocation||t.locateFile)&&(e.locateFile=(e,n)=>{let r={fileName:e,relativeTo:n};if(e.endsWith(`.wasm`)&&t.wasmLocation!==void 0)return o([`locateFile .wasm: provide wasmLocation`,r],t.wasmLocation);if(e.endsWith(`.map`)){if(t.wasmSourceMapLocation!==void 0)return o([`locateFile .map: provide wasmSourceMapLocation`,r],t.wasmSourceMapLocation);if(t.wasmLocation&&!t.locateFile)return o([`locateFile .map: infer from wasmLocation`,r],t.wasmLocation+`.map`)}return t.locateFile?o([`locateFile: use provided fn`,r],t.locateFile(e,n)):o([`locateFile: unhandled, passthrough`,r],e)}),t.wasmBinary&&(e.wasmBinary=await s(t.wasmBinary)),t.wasmMemory&&(e.wasmMemory=await s(t.wasmMemory));let c=t.wasmModule,l;c&&(e.instantiateWasm=async(e,t)=>{l??=Promise.resolve(s(c));let n=await l;if(!n)throw new a(`options.wasmModule returned ${String(n)}`);let r=await WebAssembly.instantiate(n,e);return t(r),r.exports}),e.monitorRunDependencies=e=>{r(`monitorRunDependencies:`,e)},e.quickjsEmscriptenInit=()=>bn(r);let u=n(e),d=e.quickjsEmscriptenInit?.(r);if(c&&d?.receiveWasmOffsetConverter&&!d.existingWasmOffsetConverter){let e=await s(t.wasmBinary)??new ArrayBuffer(0);l??=Promise.resolve(s(c));let n=await l;if(!n)throw new a(`options.wasmModule returned ${String(n)}`);d.receiveWasmOffsetConverter(e,n)}if(d?.receiveSourceMapJSON){let e=await s(t.wasmSourceMapData);typeof e==`string`?d.receiveSourceMapJSON(JSON.parse(e)):e?d.receiveSourceMapJSON(e):d.receiveSourceMapJSON({version:3,names:[],sources:[],mappings:``})}return u}}}}function bn(e){let t=`mock called, emscripten module may not be initialized yet`;return{mock:!0,removeRunDependency(n){e(`${t}: removeRunDependency called:`,n)},receiveSourceMapJSON(n){e(`${t}: receiveSourceMapJSON called:`,n)},WasmOffsetConverter:void 0,receiveWasmOffsetConverter(n,r){e(`${t}: receiveWasmOffsetConverter called:`,n,r)}}}var xn=Object.defineProperty,Sn=(e,t,n)=>t in e?xn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,P=(e,t,n)=>Sn(e,typeof t==`symbol`?t:t+``,n),Cn=e=>{let t=new wn(e);return new Proxy(e,{get(e,n,r){return n in t?t[n]:Reflect.get(e,n,r)}})},wn=class{constructor(e){P(this,`context`),P(this,`fn`),P(this,`fnGenerator`),P(this,`fnCounter`,-(2**53-1)),P(this,`fnMap`,new Map),P(this,`newFunction`,(e,t)=>{this.fnCounter++;let n=this.fnCounter;return this.fnMap.set(n,t),this.context.unwrapResult(this.context.callFunction(this.fnGenerator,this.context.undefined,this.context.newString(e),this.context.newNumber(t.length),this.context.newNumber(n),this.fn))}),this.context=e;let t=this.fnMap;this.fn=this.context.newFunction(``,function(n,...r){let i=e.getNumber(n),a=t.get(i);if(!a)throw Error(`function is not registered`);return a.call(this,...r)}),this.fnGenerator=e.unwrapResult(e.evalCode(`((name, length, id, f) => {
24
24
  const fn = function(...args) {
25
25
  return f.call(this, id, ...args);
26
26
  };
27
27
  fn.name = name;
28
28
  fn.length = length;
29
29
  return fn;
30
- })`))}disposeEx(){this.fnGenerator.dispose(),this.fn.dispose()}},_n=[[Symbol,`Symbol`],[Symbol.prototype,`Symbol.prototype`],[Object,`Object`],[Object.prototype,`Object.prototype`],[Function,`Function`],[Function.prototype,`Function.prototype`],[Boolean,`Boolean`],[Boolean.prototype,`Boolean.prototype`],[Array,`Array`],[Array.prototype,`Array.prototype`],[Error,`Error`],[Error.prototype,`Error.prototype`],[EvalError,`EvalError`],[EvalError.prototype,`EvalError.prototype`],[RangeError,`RangeError`],[RangeError.prototype,`RangeError.prototype`],[ReferenceError,`ReferenceError`],[ReferenceError.prototype,`ReferenceError.prototype`],[SyntaxError,`SyntaxError`],[SyntaxError.prototype,`SyntaxError.prototype`],[TypeError,`TypeError`],[TypeError.prototype,`TypeError.prototype`],[URIError,`URIError`],[URIError.prototype,`URIError.prototype`],...Object.getOwnPropertyNames(Symbol).filter(e=>typeof Symbol[e]==`symbol`).map(e=>[Symbol[e],`Symbol.${e}`])];function vn(e,t){let n=e.unwrapResult(e.evalCode(t)),r=(t,...r)=>e.unwrapResult(e.callFunction(n,t??e.undefined,...r));return r.dispose=()=>n.dispose(),r.alive=!0,Object.defineProperty(r,`alive`,{get:()=>n.alive}),r}function F(e,t,n,...r){let i=vn(e,t);try{return i(n,...r)}finally{i.dispose()}}function yn(e,t,n){return e.dump(F(e,`Object.is`,void 0,t,n))}function bn(e,t,n){return e.dump(F(e,`(a, b) => a instanceof b`,void 0,t,n))}function xn(e,t){return e.dump(F(e,`a => typeof a === "object" && a !== null || typeof a === "function"`,void 0,t))}function Sn(e,t){let n=JSON.stringify(t);return n?F(e,`JSON.parse`,void 0,e.newString(n)):e.undefined}function Cn([e,t],n){try{return n(e)}finally{t&&e.dispose()}}function wn(e,t){try{return t(...e.map(e=>e[0]))}finally{for(let[t,n]of e)n&&t.dispose()}}function Tn(e){return`handle`in e}function En(e){return Tn(e)?e.handle:e}function Dn(e,t,n,r){let i;for(let n of r)if(i=n(t,e),i)break;return i?n(t,i)??i:void 0}function On(e,t){return typeof e==`symbol`?F(t,`d => Symbol(d)`,void 0,e.description?t.newString(e.description):t.undefined):void 0}function kn(e,t){return e instanceof Date?F(t,`d => new Date(d)`,void 0,t.newNumber(e.getTime())):void 0}var An=[On,kn];function jn(e){return typeof e==`function`&&/^class\s/.test(Function.prototype.toString.call(e))}function Mn(e){return typeof e==`function`||typeof e==`object`&&!!e}function Nn(e,t){let n=new Set,r=e=>{if(!(!Mn(e)||n.has(e)||t?.(e,n)===!1)){if(n.add(e),Array.isArray(e)){for(let t of e)r(t);return}if(typeof e==`object`){let t=Object.getPrototypeOf(e);t&&t!==Object.prototype&&r(t)}for(let t of Object.values(Object.getOwnPropertyDescriptors(e)))`value`in t&&r(t.value),`get`in t&&r(t.get),`set`in t&&r(t.set)}};return r(e),n}function Pn(){let e=()=>{},t=()=>{};return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}function Fn(e,t,n,r){let i=e.newObject(),a=(t,n)=>{let a=r(t),o=n.value===void 0?void 0:r(n.value),s=n.get===void 0?void 0:r(n.get),c=n.set===void 0?void 0:r(n.set);e.newObject().consume(t=>{Object.entries(n).forEach(([n,r])=>{let i=n===`value`?o:n===`get`?s:n===`set`?c:r?e.true:e.false;i&&e.setProp(t,n,i)}),e.setProp(i,a,t)})},o=Object.getOwnPropertyDescriptors(t);Object.entries(o).forEach(([e,t])=>a(e,t)),Object.getOwnPropertySymbols(o).forEach(e=>a(e,o[e])),F(e,`Object.defineProperties`,void 0,n,i).dispose(),i.dispose()}function In(e,t,n,r,i,a){if(typeof t!=`function`)return;let o=e.newFunction(t.name,function(...i){let o=r(this),s=i.map(e=>r(e));if(jn(t)&&Mn(o)){let r=new t(...s);return Object.entries(r).forEach(([t,r])=>{e.setProp(this,t,n(r))}),this}return n(a?a(t,o,s):t.apply(o,s))}).consume(t=>F(e,`Cls => {
30
+ })`))}disposeEx(){this.fnGenerator.dispose(),this.fn.dispose()}},Tn=[[Symbol,`Symbol`],[Symbol.prototype,`Symbol.prototype`],[Object,`Object`],[Object.prototype,`Object.prototype`],[Function,`Function`],[Function.prototype,`Function.prototype`],[Boolean,`Boolean`],[Boolean.prototype,`Boolean.prototype`],[Array,`Array`],[Array.prototype,`Array.prototype`],[Error,`Error`],[Error.prototype,`Error.prototype`],[EvalError,`EvalError`],[EvalError.prototype,`EvalError.prototype`],[RangeError,`RangeError`],[RangeError.prototype,`RangeError.prototype`],[ReferenceError,`ReferenceError`],[ReferenceError.prototype,`ReferenceError.prototype`],[SyntaxError,`SyntaxError`],[SyntaxError.prototype,`SyntaxError.prototype`],[TypeError,`TypeError`],[TypeError.prototype,`TypeError.prototype`],[URIError,`URIError`],[URIError.prototype,`URIError.prototype`],...Object.getOwnPropertyNames(Symbol).filter(e=>typeof Symbol[e]==`symbol`).map(e=>[Symbol[e],`Symbol.${e}`])];function En(e,t){let n=e.unwrapResult(e.evalCode(t)),r=(t,...r)=>e.unwrapResult(e.callFunction(n,t??e.undefined,...r));return r.dispose=()=>n.dispose(),r.alive=!0,Object.defineProperty(r,`alive`,{get:()=>n.alive}),r}function F(e,t,n,...r){let i=En(e,t);try{return i(n,...r)}finally{i.dispose()}}function Dn(e,t,n){return e.dump(F(e,`Object.is`,void 0,t,n))}function On(e,t,n){return e.dump(F(e,`(a, b) => a instanceof b`,void 0,t,n))}function kn(e,t){return e.dump(F(e,`a => typeof a === "object" && a !== null || typeof a === "function"`,void 0,t))}function An(e,t){let n=JSON.stringify(t);return n?F(e,`JSON.parse`,void 0,e.newString(n)):e.undefined}function jn([e,t],n){try{return n(e)}finally{t&&e.dispose()}}function Mn(e,t){try{return t(...e.map(e=>e[0]))}finally{for(let[t,n]of e)n&&t.dispose()}}function Nn(e){return`handle`in e}function Pn(e){return Nn(e)?e.handle:e}function Fn(e,t,n,r){let i;for(let n of r)if(i=n(t,e),i)break;return i?n(t,i)??i:void 0}function In(e,t){return typeof e==`symbol`?F(t,`d => Symbol(d)`,void 0,e.description?t.newString(e.description):t.undefined):void 0}function Ln(e,t){return e instanceof Date?F(t,`d => new Date(d)`,void 0,t.newNumber(e.getTime())):void 0}var Rn=[In,Ln];function zn(e){return typeof e==`function`&&/^class\s/.test(Function.prototype.toString.call(e))}function Bn(e){return typeof e==`function`||typeof e==`object`&&!!e}function Vn(e,t){let n=new Set,r=e=>{if(!(!Bn(e)||n.has(e)||t?.(e,n)===!1)){if(n.add(e),Array.isArray(e)){for(let t of e)r(t);return}if(typeof e==`object`){let t=Object.getPrototypeOf(e);t&&t!==Object.prototype&&r(t)}for(let t of Object.values(Object.getOwnPropertyDescriptors(e)))`value`in t&&r(t.value),`get`in t&&r(t.get),`set`in t&&r(t.set)}};return r(e),n}function Hn(){let e=()=>{},t=()=>{};return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}function Un(e,t,n,r){let i=e.newObject(),a=(t,n)=>{let a=r(t),o=n.value===void 0?void 0:r(n.value),s=n.get===void 0?void 0:r(n.get),c=n.set===void 0?void 0:r(n.set);e.newObject().consume(t=>{Object.entries(n).forEach(([n,r])=>{let i=n===`value`?o:n===`get`?s:n===`set`?c:r?e.true:e.false;i&&e.setProp(t,n,i)}),e.setProp(i,a,t)})},o=Object.getOwnPropertyDescriptors(t);Object.entries(o).forEach(([e,t])=>a(e,t)),Object.getOwnPropertySymbols(o).forEach(e=>a(e,o[e])),F(e,`Object.defineProperties`,void 0,n,i).dispose(),i.dispose()}function Wn(e,t,n,r,i,a){if(typeof t!=`function`)return;let o=e.newFunction(t.name,function(...i){let o=r(this),s=i.map(e=>r(e));if(zn(t)&&Bn(o)){let r=new t(...s);return Object.entries(r).forEach(([t,r])=>{e.setProp(this,t,n(r))}),this}return n(a?a(t,o,s):t.apply(o,s))}).consume(t=>F(e,`Cls => {
31
31
  const fn = function(...args) { return Cls.apply(this, args); };
32
32
  fn.name = Cls.name;
33
33
  fn.length = Cls.length;
34
34
  return fn;
35
- }`,void 0,t)),s=i(t,o)??o;return Fn(e,t,o,n),s}function Ln(e,t,n){let r=Sn(e,t);return n(t,r)??r}function Rn(e,t,n,r){if(typeof t!=`object`||!t)return;let i=Array.isArray(t)?e.newArray():e.newObject(),a=r(t,i)??i,o=Object.getPrototypeOf(t),s=o&&o!==Object.prototype&&o!==Array.prototype?n(o):void 0;return s&&F(e,`Object.setPrototypeOf`,void 0,a,s).dispose(),Fn(e,t,i,n),a}function zn(e,t){switch(typeof t){case`undefined`:return e.undefined;case`number`:return e.newNumber(t);case`string`:return e.newString(t);case`boolean`:return t?e.true:e.false;case`object`:return t===null?e.null:void 0}}function Bn(e,t,n,r){if(!(t instanceof Promise))return;let i=e.newPromise();return t.then(e=>i.resolve(n(e)),e=>i.reject(n(e))),r(t,i)??i.handle}function Vn(e,t){let{ctx:n,unmarshal:r,isMarshalable:i,find:a,pre:o}=t;{let t=zn(n,e);if(t)return t}{let t=a(e);if(t)return t}let s=i?.(e);if(s===!1)return n.undefined;let c=(e,t)=>o(e,t,s);if(s===`json`)return Ln(n,e,c);let l=e=>Vn(e,t);return Dn(n,e,c,[...An,...t.custom??[]])??Bn(n,e,l,c)??In(n,e,l,r,c,t.preApply)??Rn(n,e,l,c)??n.undefined}function Hn(e,t,n,r){let i;for(let n of r)if(i=n(t,e),i)break;return i?n(i,t)??i:void 0}function Un(e,t){if(t.typeof(e)!==`symbol`)return;let n=t.getString(t.getProp(e,`description`));return Symbol(n)}function Wn(e,t){if(!t.dump(F(t,`a => a instanceof Date`,void 0,e)))return;let n=t.getNumber(F(t,`a => a.getTime()`,void 0,e));return new Date(n)}var Gn=[Un,Wn];function Kn(e,t,n,r){e.newFunction(``,(t,i)=>{let[a]=r(t);if(typeof a!=`string`&&typeof a!=`number`&&typeof a!=`symbol`)return;let o=[[`value`,!0],[`get`,!0],[`set`,!0],[`configurable`,!1],[`enumerable`,!1],[`writable`,!1]].reduce((t,[n,a])=>{let o=e.getProp(i,n),s=e.typeof(o);if(s===`undefined`)return t;if(!a&&s===`boolean`)return t[n]=e.dump(e.getProp(i,n)),t;let[c,l]=r(o);return l&&o.dispose(),t[n]=c,t},{});Object.defineProperty(n,a,o)}).consume(n=>{F(e,`(o, fn) => {
35
+ }`,void 0,t)),s=i(t,o)??o;return Un(e,t,o,n),s}function Gn(e,t,n){let r=An(e,t);return n(t,r)??r}function Kn(e,t,n,r){if(typeof t!=`object`||!t)return;let i=Array.isArray(t)?e.newArray():e.newObject(),a=r(t,i)??i,o=Object.getPrototypeOf(t),s=o&&o!==Object.prototype&&o!==Array.prototype?n(o):void 0;return s&&F(e,`Object.setPrototypeOf`,void 0,a,s).dispose(),Un(e,t,i,n),a}function qn(e,t){switch(typeof t){case`undefined`:return e.undefined;case`number`:return e.newNumber(t);case`string`:return e.newString(t);case`boolean`:return t?e.true:e.false;case`object`:return t===null?e.null:void 0}}function Jn(e,t,n,r){if(!(t instanceof Promise))return;let i=e.newPromise();return t.then(e=>i.resolve(n(e)),e=>i.reject(n(e))),r(t,i)??i.handle}function Yn(e,t){let{ctx:n,unmarshal:r,isMarshalable:i,find:a,pre:o}=t;{let t=qn(n,e);if(t)return t}{let t=a(e);if(t)return t}let s=i?.(e);if(s===!1)return n.undefined;let c=(e,t)=>o(e,t,s);if(s===`json`)return Gn(n,e,c);let l=e=>Yn(e,t);return Fn(n,e,c,[...Rn,...t.custom??[]])??Jn(n,e,l,c)??Wn(n,e,l,r,c,t.preApply)??Kn(n,e,l,c)??n.undefined}function Xn(e,t,n,r){let i;for(let n of r)if(i=n(t,e),i)break;return i?n(i,t)??i:void 0}function Zn(e,t){if(t.typeof(e)!==`symbol`)return;let n=t.getString(t.getProp(e,`description`));return Symbol(n)}function Qn(e,t){if(!t.dump(F(t,`a => a instanceof Date`,void 0,e)))return;let n=t.getNumber(F(t,`a => a.getTime()`,void 0,e));return new Date(n)}var $n=[Zn,Qn];function er(e,t,n,r){e.newFunction(``,(t,i)=>{let[a]=r(t);if(typeof a!=`string`&&typeof a!=`number`&&typeof a!=`symbol`)return;let o=[[`value`,!0],[`get`,!0],[`set`,!0],[`configurable`,!1],[`enumerable`,!1],[`writable`,!1]].reduce((t,[n,a])=>{let o=e.getProp(i,n),s=e.typeof(o);if(s===`undefined`)return t;if(!a&&s===`boolean`)return t[n]=e.dump(e.getProp(i,n)),t;let[c,l]=r(o);return l&&o.dispose(),t[n]=c,t},{});Object.defineProperty(n,a,o)}).consume(n=>{F(e,`(o, fn) => {
36
36
  const descs = Object.getOwnPropertyDescriptors(o);
37
37
  Object.entries(descs).forEach(([k, v]) => fn(k, v));
38
38
  Object.getOwnPropertySymbols(descs).forEach(k => fn(k, descs[k]));
39
- }`,void 0,t,n).dispose()})}function qn(e,t,n,r,i){if(e.typeof(t)!==`function`)return;let a=function(...i){return wn([n(this),...i.map(e=>n(e))],(n,...i)=>{if(new.target){let[a]=r(F(e,`(Cls, ...args) => new Cls(...args)`,n,t,...i));return Object.defineProperties(this,Object.getOwnPropertyDescriptors(a)),this}let a=e.unwrapResult(e.callFunction(t,n,...i)),[o,s]=r(a);return s&&a.dispose(),o})},o=i(a,t)??a;return Kn(e,t,a,r),o}function Jn(e,t,n,r){if(e.typeof(t)!==`object`||e.unwrapResult(e.evalCode(`o => o === null`)).consume(n=>e.dump(e.unwrapResult(e.callFunction(n,e.undefined,t)))))return;let i=F(e,`Array.isArray`,void 0,t).consume(t=>e.dump(t))?[]:{},a=r(i,t)??i,o=F(e,`o => {
39
+ }`,void 0,t,n).dispose()})}function tr(e,t,n,r,i){if(e.typeof(t)!==`function`)return;let a=function(...i){return Mn([n(this),...i.map(e=>n(e))],(n,...i)=>{if(new.target){let[a]=r(F(e,`(Cls, ...args) => new Cls(...args)`,n,t,...i));return Object.defineProperties(this,Object.getOwnPropertyDescriptors(a)),this}let a=e.unwrapResult(e.callFunction(t,n,...i)),[o,s]=r(a);return s&&a.dispose(),o})},o=i(a,t)??a;return er(e,t,a,r),o}function nr(e,t,n,r){if(e.typeof(t)!==`object`||e.unwrapResult(e.evalCode(`o => o === null`)).consume(n=>e.dump(e.unwrapResult(e.callFunction(n,e.undefined,t)))))return;let i=F(e,`Array.isArray`,void 0,t).consume(t=>e.dump(t))?[]:{},a=r(i,t)??i,o=F(e,`o => {
40
40
  const p = Object.getPrototypeOf(o);
41
41
  return !p || p === Object.prototype || p === Array.prototype ? undefined : p;
42
- }`,void 0,t).consume(t=>{if(e.typeof(t)===`undefined`)return;let[r]=n(t);return r});return typeof o==`object`&&Object.setPrototypeOf(a,o),Kn(e,t,i,n),a}function Yn(e,t){let n=e.typeof(t);return n===`undefined`||n===`number`||n===`string`||n===`boolean`?[e.dump(t),!0]:n===`object`&&e.unwrapResult(e.evalCode(`a => a === null`)).consume(n=>e.dump(e.unwrapResult(e.callFunction(n,e.undefined,t))))?[null,!0]:[void 0,!1]}function Xn(e,t,n,r){if(!Zn(e,t))return;let i=Pn(),[a,o]=n(i.resolve),[s,c]=n(i.reject);return F(e,`(p, res, rej) => { p.then(res, rej); }`,void 0,t,a,s),o&&a.dispose(),c&&s.dispose(),r(i.promise,t)??i.promise}function Zn(e,t){return t.owner?e.unwrapResult(e.evalCode(`Promise`)).consume(n=>t.owner?bn(e,t,n):!1):!1}function Qn(e,t){let[n]=$n(e,t);return n}function $n(e,t){let{ctx:n,marshal:r,find:i,pre:a}=t;{let[t,r]=Yn(n,e);if(r)return[t,!1]}{let t=i(e);if(t)return[t,!0]}let o=e=>$n(e,t);return[Hn(n,e,a,[...Gn,...t.custom??[]])??Xn(n,e,r,a)??qn(n,e,r,o,a)??Jn(n,e,o,a),!1]}var er=class{constructor(e){P(this,`ctx`),P(this,`_map1`,new Map),P(this,`_map2`,new Map),P(this,`_map3`,new Map),P(this,`_map4`,new Map),P(this,`_counterMap`,new Map),P(this,`_disposables`,new Set),P(this,`_mapGet`),P(this,`_mapSet`),P(this,`_mapDelete`),P(this,`_mapClear`),P(this,`_counter`,-(2**53-1)),this.ctx=e;let t=e.unwrapResult(e.evalCode(`() => {
42
+ }`,void 0,t).consume(t=>{if(e.typeof(t)===`undefined`)return;let[r]=n(t);return r});return typeof o==`object`&&Object.setPrototypeOf(a,o),er(e,t,i,n),a}function rr(e,t){let n=e.typeof(t);return n===`undefined`||n===`number`||n===`string`||n===`boolean`?[e.dump(t),!0]:n===`object`&&e.unwrapResult(e.evalCode(`a => a === null`)).consume(n=>e.dump(e.unwrapResult(e.callFunction(n,e.undefined,t))))?[null,!0]:[void 0,!1]}function ir(e,t,n,r){if(!ar(e,t))return;let i=Hn(),[a,o]=n(i.resolve),[s,c]=n(i.reject);return F(e,`(p, res, rej) => { p.then(res, rej); }`,void 0,t,a,s),o&&a.dispose(),c&&s.dispose(),r(i.promise,t)??i.promise}function ar(e,t){return t.owner?e.unwrapResult(e.evalCode(`Promise`)).consume(n=>t.owner?On(e,t,n):!1):!1}function or(e,t){let[n]=sr(e,t);return n}function sr(e,t){let{ctx:n,marshal:r,find:i,pre:a}=t;{let[t,r]=rr(n,e);if(r)return[t,!1]}{let t=i(e);if(t)return[t,!0]}let o=e=>sr(e,t);return[Xn(n,e,a,[...$n,...t.custom??[]])??ir(n,e,r,a)??tr(n,e,r,o,a)??nr(n,e,o,a),!1]}var cr=class{constructor(e){P(this,`ctx`),P(this,`_map1`,new Map),P(this,`_map2`,new Map),P(this,`_map3`,new Map),P(this,`_map4`,new Map),P(this,`_counterMap`,new Map),P(this,`_disposables`,new Set),P(this,`_mapGet`),P(this,`_mapSet`),P(this,`_mapDelete`),P(this,`_mapClear`),P(this,`_counter`,-(2**53-1)),this.ctx=e;let t=e.unwrapResult(e.evalCode(`() => {
43
43
  const mapSym = new Map();
44
44
  let map = new WeakMap();
45
45
  let map2 = new WeakMap();
@@ -62,7 +62,7 @@ error stack:
62
62
  map2 = new WeakMap();
63
63
  }
64
64
  };
65
- }`)).consume(e=>this._call(e,void 0));this._mapGet=e.getProp(t,`get`),this._mapSet=e.getProp(t,`set`),this._mapDelete=e.getProp(t,`delete`),this._mapClear=e.getProp(t,`clear`),t.dispose(),this._disposables.add(this._mapGet),this._disposables.add(this._mapSet),this._disposables.add(this._mapDelete),this._disposables.add(this._mapClear)}set(e,t,n,r){if(!t.alive||r&&!r.alive)return!1;let i=this.get(e)??this.get(n);if(i)return i===t||i===r;let a=this._counter++;return this._map1.set(e,a),this._map3.set(a,t),this._counterMap.set(a,e),n&&(this._map2.set(n,a),r&&this._map4.set(a,r)),this.ctx.newNumber(a).consume(e=>{this._call(this._mapSet,void 0,t,e,r??this.ctx.undefined)}),!0}merge(e){if(e)for(let t of e)t&&t[1]&&this.set(t[0],t[1],t[2],t[3])}get(e){let t=this._map1.get(e)??this._map2.get(e),n=typeof t==`number`?this._map3.get(t):void 0;if(n){if(!n.alive){this.delete(e);return}return n}}getByHandle(e){if(e.alive)return this._counterMap.get(this.ctx.getNumber(this._call(this._mapGet,void 0,e)))}has(e){return!!this.get(e)}hasHandle(e){return this.getByHandle(e)!==void 0}keys(){return this._map1.keys()}delete(e,t){let n=this._map1.get(e)??this._map2.get(e);if(n===void 0)return;let r=this._map3.get(n),i=this._map4.get(n);this._call(this._mapDelete,void 0,...[r,i].filter(e=>!!(e!=null&&e.alive))),this._map1.delete(e),this._map2.delete(e),this._map3.delete(n),this._map4.delete(n);for(let[e,t]of this._map1)if(t===n){this._map1.delete(e);break}for(let[e,t]of this._map2)if(t===n){this._map2.delete(e);break}for(let[t,n]of this._counterMap)if(n===e){this._counterMap.delete(t);break}t&&(r!=null&&r.alive&&r.dispose(),i!=null&&i.alive&&i.dispose())}deleteByHandle(e,t){let n=this.getByHandle(e);n!==void 0&&this.delete(n,t)}clear(){this._counter=0,this._map1.clear(),this._map2.clear(),this._map3.clear(),this._map4.clear(),this._counterMap.clear(),this._mapClear.alive&&this._call(this._mapClear,void 0)}dispose(){for(let e of this._disposables.values())e.alive&&e.dispose();for(let e of this._map3.values())e.alive&&e.dispose();for(let e of this._map4.values())e.alive&&e.dispose();this._disposables.clear(),this.clear()}get size(){return this._map1.size}[Symbol.iterator](){let e=this._map1.keys();return{next:()=>{for(;;){let t=e.next();if(t.done)return{value:void 0,done:!0};let n=this._map1.get(t.value);if(n===void 0)continue;let r=this._map3.get(n),i=this._map4.get(n);if(!r)continue;let a=this._get2(n);return{value:[t.value,r,a,i],done:!1}}}}}_get2(e){for(let[t,n]of this._map2)if(n===e)return t}_call(e,t,...n){return this.ctx.unwrapResult(this.ctx.callFunction(e,t===void 0?this.ctx.undefined:t,...n))}};function tr(e,t,n,r,i,a,o){if(!Mn(t)||t instanceof Promise||t instanceof Date||o&&!o(t))return;if(ar(t,n))return t;let s=new Proxy(t,{get(e,t){return t===n?e:Reflect.get(e,t)},set(t,o,s,c){let l=rr(s,n),u=a?.(c)??`host`;return u!==`vm`&&!Reflect.set(t,o,l,c)||u===`host`||!e.alive||wn([i(c),i(o),i(l)],(t,n,i)=>{let[a,o]=ir(e,t,r);o?a.consume(t=>e.setProp(t,n,i)):e.setProp(a,n,i)}),!0},deleteProperty(t,n){let o=a?.(s)??`host`;return wn([i(s),i(n)],(i,a)=>{let[s,c]=ir(e,i,r);if(o===`vm`||Reflect.deleteProperty(t,n)){if(o===`host`||!e.alive)return!0;c?s.consume(t=>F(e,`(a, b) => delete a[b]`,void 0,t,a)):F(e,`(a, b) => delete a[b]`,void 0,s,a)}return!0})}});return s}function nr(e,t,n,r,i,a,o){if(!xn(e,t)||o&&!o(t,e))return[void 0,!1];if(or(e,t,r))return[t,!1];let s=t=>{let n=a?.(i(t));return typeof n==`string`?e.newString(n):e.undefined},c=(e,t,r)=>{let a=i(e);if(!a)return;let o=i(t);if(o===`__proto__`)return;let s=i(r);rr(a,n)[o]=s},l=(e,t)=>{let r=i(e);if(!r)return;let a=i(t);delete rr(r,n)[a]};return e.newFunction(`proxyFuncs`,(t,...n)=>{switch(e.getNumber(t)){case 1:return s(n[0]);case 2:return c(n[0],n[1],n[2]);case 3:return l(n[0],n[1])}return e.undefined}).consume(n=>[F(e,`(target, sym, proxyFuncs) => {
65
+ }`)).consume(e=>this._call(e,void 0));this._mapGet=e.getProp(t,`get`),this._mapSet=e.getProp(t,`set`),this._mapDelete=e.getProp(t,`delete`),this._mapClear=e.getProp(t,`clear`),t.dispose(),this._disposables.add(this._mapGet),this._disposables.add(this._mapSet),this._disposables.add(this._mapDelete),this._disposables.add(this._mapClear)}set(e,t,n,r){if(!t.alive||r&&!r.alive)return!1;let i=this.get(e)??this.get(n);if(i)return i===t||i===r;let a=this._counter++;return this._map1.set(e,a),this._map3.set(a,t),this._counterMap.set(a,e),n&&(this._map2.set(n,a),r&&this._map4.set(a,r)),this.ctx.newNumber(a).consume(e=>{this._call(this._mapSet,void 0,t,e,r??this.ctx.undefined)}),!0}merge(e){if(e)for(let t of e)t&&t[1]&&this.set(t[0],t[1],t[2],t[3])}get(e){let t=this._map1.get(e)??this._map2.get(e),n=typeof t==`number`?this._map3.get(t):void 0;if(n){if(!n.alive){this.delete(e);return}return n}}getByHandle(e){if(e.alive)return this._counterMap.get(this.ctx.getNumber(this._call(this._mapGet,void 0,e)))}has(e){return!!this.get(e)}hasHandle(e){return this.getByHandle(e)!==void 0}keys(){return this._map1.keys()}delete(e,t){let n=this._map1.get(e)??this._map2.get(e);if(n===void 0)return;let r=this._map3.get(n),i=this._map4.get(n);this._call(this._mapDelete,void 0,...[r,i].filter(e=>!!(e!=null&&e.alive))),this._map1.delete(e),this._map2.delete(e),this._map3.delete(n),this._map4.delete(n);for(let[e,t]of this._map1)if(t===n){this._map1.delete(e);break}for(let[e,t]of this._map2)if(t===n){this._map2.delete(e);break}for(let[t,n]of this._counterMap)if(n===e){this._counterMap.delete(t);break}t&&(r!=null&&r.alive&&r.dispose(),i!=null&&i.alive&&i.dispose())}deleteByHandle(e,t){let n=this.getByHandle(e);n!==void 0&&this.delete(n,t)}clear(){this._counter=0,this._map1.clear(),this._map2.clear(),this._map3.clear(),this._map4.clear(),this._counterMap.clear(),this._mapClear.alive&&this._call(this._mapClear,void 0)}dispose(){for(let e of this._disposables.values())e.alive&&e.dispose();for(let e of this._map3.values())e.alive&&e.dispose();for(let e of this._map4.values())e.alive&&e.dispose();this._disposables.clear(),this.clear()}get size(){return this._map1.size}[Symbol.iterator](){let e=this._map1.keys();return{next:()=>{for(;;){let t=e.next();if(t.done)return{value:void 0,done:!0};let n=this._map1.get(t.value);if(n===void 0)continue;let r=this._map3.get(n),i=this._map4.get(n);if(!r)continue;let a=this._get2(n);return{value:[t.value,r,a,i],done:!1}}}}}_get2(e){for(let[t,n]of this._map2)if(n===e)return t}_call(e,t,...n){return this.ctx.unwrapResult(this.ctx.callFunction(e,t===void 0?this.ctx.undefined:t,...n))}};function lr(e,t,n,r,i,a,o){if(!Bn(t)||t instanceof Promise||t instanceof Date||o&&!o(t))return;if(pr(t,n))return t;let s=new Proxy(t,{get(e,t){return t===n?e:Reflect.get(e,t)},set(t,o,s,c){let l=dr(s,n),u=a?.(c)??`host`;return u!==`vm`&&!Reflect.set(t,o,l,c)||u===`host`||!e.alive||Mn([i(c),i(o),i(l)],(t,n,i)=>{let[a,o]=fr(e,t,r);o?a.consume(t=>e.setProp(t,n,i)):e.setProp(a,n,i)}),!0},deleteProperty(t,n){let o=a?.(s)??`host`;return Mn([i(s),i(n)],(i,a)=>{let[s,c]=fr(e,i,r);if(o===`vm`||Reflect.deleteProperty(t,n)){if(o===`host`||!e.alive)return!0;c?s.consume(t=>F(e,`(a, b) => delete a[b]`,void 0,t,a)):F(e,`(a, b) => delete a[b]`,void 0,s,a)}return!0})}});return s}function ur(e,t,n,r,i,a,o){if(!kn(e,t)||o&&!o(t,e))return[void 0,!1];if(mr(e,t,r))return[t,!1];let s=t=>{let n=a?.(i(t));return typeof n==`string`?e.newString(n):e.undefined},c=(e,t,r)=>{let a=i(e);if(!a)return;let o=i(t);if(o===`__proto__`)return;let s=i(r);dr(a,n)[o]=s},l=(e,t)=>{let r=i(e);if(!r)return;let a=i(t);delete dr(r,n)[a]};return e.newFunction(`proxyFuncs`,(t,...n)=>{switch(e.getNumber(t)){case 1:return s(n[0]);case 2:return c(n[0],n[1],n[2]);case 3:return l(n[0],n[1])}return e.undefined}).consume(n=>[F(e,`(target, sym, proxyFuncs) => {
66
66
  const rec = new Proxy(target, {
67
67
  get(obj, key, receiver) {
68
68
  return key === sym ? obj : Reflect.get(obj, key, receiver)
@@ -90,16 +90,16 @@ error stack:
90
90
  },
91
91
  });
92
92
  return rec;
93
- }`,void 0,t,r,n),!0])}function rr(e,t){var n;return Mn(e)&&(n=e[t])!=null?n:e}function ir(e,t,n){return or(e,t,n)?[e.getProp(t,n),!0]:[t,!1]}function ar(e,t){return Mn(e)&&!!e[t]}function or(e,t,n){return!!e.dump(F(e,`(a, s) => (a instanceof Promise) || (a instanceof Date) || (typeof a === "object" && a !== null || typeof a === "function") && !!a[s]`,void 0,t,n))}var sr=class{constructor(e,t){P(this,`context`),P(this,`_map`),P(this,`_registeredMap`),P(this,`_registeredMapDispose`,new Set),P(this,`_sync`,new Set),P(this,`_temporalSync`,new Set),P(this,`_symbol`,Symbol()),P(this,`_symbolHandle`),P(this,`_options`),P(this,`_isMarshalable`,e=>{let t=this._options?.isMarshalable;return(typeof t==`function`?t(this._unwrap(e)):t)??`json`}),P(this,`_marshalFind`,e=>{let t=this._unwrap(e);return this._registeredMap.get(e)??(t===e?void 0:this._registeredMap.get(t))??this._map.get(e)??(t===e?void 0:this._map.get(t))}),P(this,`_marshalPre`,(e,t,n)=>{if(n!==`json`)return this._register(e,En(t),this._map)?.[1]}),P(this,`_marshalPreApply`,(e,t,n)=>{let r=Mn(t)?this._unwrap(t):void 0;r&&this._temporalSync.add(r);try{return e.apply(t,n)}finally{r&&this._temporalSync.delete(r)}}),P(this,`_marshal`,e=>{let t=this._registeredMap.get(e);if(t)return[t,!1];let n=Vn(this._wrap(e)??e,{ctx:this.context,unmarshal:this._unmarshal,isMarshalable:this._isMarshalable,find:this._marshalFind,pre:this._marshalPre,preApply:this._marshalPreApply,custom:this._options?.customMarshaller});return[n,!this._map.hasHandle(n)]}),P(this,`_preUnmarshal`,(e,t)=>this._register(e,t,void 0,!0)?.[0]),P(this,`_unmarshalFind`,e=>this._registeredMap.getByHandle(e)??this._map.getByHandle(e)),P(this,`_unmarshal`,e=>{let t=this._registeredMap.getByHandle(e);if(t!==void 0)return t;let[n]=this._wrapHandle(e);return Qn(n??e,{ctx:this.context,marshal:this._marshal,find:this._unmarshalFind,pre:this._preUnmarshal,custom:this._options?.customUnmarshaller})}),P(this,`_syncMode`,e=>{let t=this._unwrap(e);return this._sync.has(t)||this._temporalSync.has(t)?`both`:void 0}),P(this,`_unwrapIfNotSynced`,e=>{let t=this._unwrap(e);return t instanceof Promise||!this._sync.has(t)?t:e}),t!=null&&t.compat&&!(`runtime`in e)&&(e.runtime={hasPendingJob:()=>e.hasPendingJob(),executePendingJobs:t=>e.executePendingJobs(t)}),this.context=t!=null&&t.experimentalContextEx?hn(e):e,this._options=t,this._symbolHandle=e.unwrapResult(e.evalCode(`Symbol()`)),this._map=new er(e),this._registeredMap=new er(e),this.registerAll(t?.registeredObjects??_n)}dispose(){var e,t;this._map.dispose(),this._registeredMap.dispose(),this._symbolHandle.dispose(),(t=(e=this.context).disposeEx)==null||t.call(e)}evalCode(e){let t=this.context.evalCode(e);return this._unwrapResultAndUnmarshal(t)}evalModule(e,t=`module.js`){let n=this.context.evalCode(e,t,{type:`module`});this._unwrapResultAndUnmarshal(n)}executePendingJobs(e){let t=this.context.runtime.executePendingJobs(e);if(`value`in t)return t.value;throw this._unwrapIfNotSynced(t.error.consume(this._unmarshal))}setMemoryLimit(e){this.context.runtime.setMemoryLimit(e)}setMaxStackSize(e){this.context.runtime.setMaxStackSize(e)}getMemoryUsage(){let e=this.context.runtime.computeMemoryUsage();try{return this.context.dump(e)}finally{e.dispose()}}dumpMemoryUsage(){return this.context.runtime.dumpMemoryUsage()}expose(e){for(let[t,n]of Object.entries(e))Cn(this._marshal(n),e=>{this.context.setProp(this.context.global,t,e)})}sync(e){let t=this._wrap(e);return t===void 0?e:(Nn(t,e=>{let t=this._unwrap(e);this._sync.add(t)}),t)}register(e,t){if(this._registeredMap.has(e))return;let n=typeof t==`string`?this._unwrapResult(this.context.evalCode(t)):t;yn(this.context,n,this.context.undefined)||(typeof t==`string`&&this._registeredMapDispose.add(e),this._registeredMap.set(e,n))}registerAll(e){for(let[t,n]of e)this.register(t,n)}unregister(e,t){this._registeredMap.delete(e,this._registeredMapDispose.has(e)||t),this._registeredMapDispose.delete(e)}unregisterAll(e,t){for(let n of e)this.unregister(n,t)}startSync(e){if(!Mn(e))return;let t=this._unwrap(e);this._sync.add(t)}endSync(e){this._sync.delete(this._unwrap(e))}_unwrapResult(e){if(`value`in e)return e.value;throw this._unwrapIfNotSynced(e.error.consume(this._unmarshal))}_unwrapResultAndUnmarshal(e){if(e)return this._unwrapIfNotSynced(this._unwrapResult(e).consume(this._unmarshal))}_register(e,t,n=this._map,r){if(this._registeredMap.has(e)||this._registeredMap.hasHandle(t))return;let i=this._wrap(e),[a]=this._wrapHandle(t),o=e instanceof Promise;if(!a||!i&&!o)return;o&&(i=e);let s=this._unwrap(e),[c,l]=this._unwrapHandle(t);if(n.set(i,a,s,c))r&&this._sync.add(s);else throw l&&c.dispose(),Error(`already registered`);return[i,a]}_wrap(e){return tr(this.context,e,this._symbol,this._symbolHandle,this._marshal,this._syncMode,this._options?.isWrappable)}_unwrap(e){return rr(e,this._symbol)}_wrapHandle(e){return nr(this.context,e,this._symbol,this._symbolHandle,this._unmarshal,this._syncMode,this._options?.isHandleWrappable)}_unwrapHandle(e){return ir(this.context,e,this._symbolHandle)}},cr={param:(e,t,n=``)=>`<span class="param ${t||``}">${e||n}</span>`},lr={type:`sync`,importFFI:()=>o(()=>import(`./ffi-CJJc982W.js`).then(e=>e.QuickJSFFI),[]),importModuleLoader:()=>o(()=>import(`./emscripten-module-VHMWRAJ2-Cwd_19tX.js`).then(e=>e.default),__vite__mapDeps([2,3,4]))},ur=class extends Error{constructor(e,t){super(t),this.name=e,this.description=t,this.name=e}},dr=async e=>{let{logger:t}=cn(),n=await ln(e),r=()=>{let e=n.newContext(),r=new sr(e,{isMarshalable:!0});return{run:(e,n)=>{let i={fmt:cr,...n};r.expose(i);let a=`(() => {
93
+ }`,void 0,t,r,n),!0])}function dr(e,t){var n;return Bn(e)&&(n=e[t])!=null?n:e}function fr(e,t,n){return mr(e,t,n)?[e.getProp(t,n),!0]:[t,!1]}function pr(e,t){return Bn(e)&&!!e[t]}function mr(e,t,n){return!!e.dump(F(e,`(a, s) => (a instanceof Promise) || (a instanceof Date) || (typeof a === "object" && a !== null || typeof a === "function") && !!a[s]`,void 0,t,n))}var hr=class{constructor(e,t){P(this,`context`),P(this,`_map`),P(this,`_registeredMap`),P(this,`_registeredMapDispose`,new Set),P(this,`_sync`,new Set),P(this,`_temporalSync`,new Set),P(this,`_symbol`,Symbol()),P(this,`_symbolHandle`),P(this,`_options`),P(this,`_isMarshalable`,e=>{let t=this._options?.isMarshalable;return(typeof t==`function`?t(this._unwrap(e)):t)??`json`}),P(this,`_marshalFind`,e=>{let t=this._unwrap(e);return this._registeredMap.get(e)??(t===e?void 0:this._registeredMap.get(t))??this._map.get(e)??(t===e?void 0:this._map.get(t))}),P(this,`_marshalPre`,(e,t,n)=>{if(n!==`json`)return this._register(e,Pn(t),this._map)?.[1]}),P(this,`_marshalPreApply`,(e,t,n)=>{let r=Bn(t)?this._unwrap(t):void 0;r&&this._temporalSync.add(r);try{return e.apply(t,n)}finally{r&&this._temporalSync.delete(r)}}),P(this,`_marshal`,e=>{let t=this._registeredMap.get(e);if(t)return[t,!1];let n=Yn(this._wrap(e)??e,{ctx:this.context,unmarshal:this._unmarshal,isMarshalable:this._isMarshalable,find:this._marshalFind,pre:this._marshalPre,preApply:this._marshalPreApply,custom:this._options?.customMarshaller});return[n,!this._map.hasHandle(n)]}),P(this,`_preUnmarshal`,(e,t)=>this._register(e,t,void 0,!0)?.[0]),P(this,`_unmarshalFind`,e=>this._registeredMap.getByHandle(e)??this._map.getByHandle(e)),P(this,`_unmarshal`,e=>{let t=this._registeredMap.getByHandle(e);if(t!==void 0)return t;let[n]=this._wrapHandle(e);return or(n??e,{ctx:this.context,marshal:this._marshal,find:this._unmarshalFind,pre:this._preUnmarshal,custom:this._options?.customUnmarshaller})}),P(this,`_syncMode`,e=>{let t=this._unwrap(e);return this._sync.has(t)||this._temporalSync.has(t)?`both`:void 0}),P(this,`_unwrapIfNotSynced`,e=>{let t=this._unwrap(e);return t instanceof Promise||!this._sync.has(t)?t:e}),t!=null&&t.compat&&!(`runtime`in e)&&(e.runtime={hasPendingJob:()=>e.hasPendingJob(),executePendingJobs:t=>e.executePendingJobs(t)}),this.context=t!=null&&t.experimentalContextEx?Cn(e):e,this._options=t,this._symbolHandle=e.unwrapResult(e.evalCode(`Symbol()`)),this._map=new cr(e),this._registeredMap=new cr(e),this.registerAll(t?.registeredObjects??Tn)}dispose(){var e,t;this._map.dispose(),this._registeredMap.dispose(),this._symbolHandle.dispose(),(t=(e=this.context).disposeEx)==null||t.call(e)}evalCode(e){let t=this.context.evalCode(e);return this._unwrapResultAndUnmarshal(t)}evalModule(e,t=`module.js`){let n=this.context.evalCode(e,t,{type:`module`});this._unwrapResultAndUnmarshal(n)}executePendingJobs(e){let t=this.context.runtime.executePendingJobs(e);if(`value`in t)return t.value;throw this._unwrapIfNotSynced(t.error.consume(this._unmarshal))}setMemoryLimit(e){this.context.runtime.setMemoryLimit(e)}setMaxStackSize(e){this.context.runtime.setMaxStackSize(e)}getMemoryUsage(){let e=this.context.runtime.computeMemoryUsage();try{return this.context.dump(e)}finally{e.dispose()}}dumpMemoryUsage(){return this.context.runtime.dumpMemoryUsage()}expose(e){for(let[t,n]of Object.entries(e))jn(this._marshal(n),e=>{this.context.setProp(this.context.global,t,e)})}sync(e){let t=this._wrap(e);return t===void 0?e:(Vn(t,e=>{let t=this._unwrap(e);this._sync.add(t)}),t)}register(e,t){if(this._registeredMap.has(e))return;let n=typeof t==`string`?this._unwrapResult(this.context.evalCode(t)):t;Dn(this.context,n,this.context.undefined)||(typeof t==`string`&&this._registeredMapDispose.add(e),this._registeredMap.set(e,n))}registerAll(e){for(let[t,n]of e)this.register(t,n)}unregister(e,t){this._registeredMap.delete(e,this._registeredMapDispose.has(e)||t),this._registeredMapDispose.delete(e)}unregisterAll(e,t){for(let n of e)this.unregister(n,t)}startSync(e){if(!Bn(e))return;let t=this._unwrap(e);this._sync.add(t)}endSync(e){this._sync.delete(this._unwrap(e))}_unwrapResult(e){if(`value`in e)return e.value;throw this._unwrapIfNotSynced(e.error.consume(this._unmarshal))}_unwrapResultAndUnmarshal(e){if(e)return this._unwrapIfNotSynced(this._unwrapResult(e).consume(this._unmarshal))}_register(e,t,n=this._map,r){if(this._registeredMap.has(e)||this._registeredMap.hasHandle(t))return;let i=this._wrap(e),[a]=this._wrapHandle(t),o=e instanceof Promise;if(!a||!i&&!o)return;o&&(i=e);let s=this._unwrap(e),[c,l]=this._unwrapHandle(t);if(n.set(i,a,s,c))r&&this._sync.add(s);else throw l&&c.dispose(),Error(`already registered`);return[i,a]}_wrap(e){return lr(this.context,e,this._symbol,this._symbolHandle,this._marshal,this._syncMode,this._options?.isWrappable)}_unwrap(e){return dr(e,this._symbol)}_wrapHandle(e){return ur(this.context,e,this._symbol,this._symbolHandle,this._unmarshal,this._syncMode,this._options?.isHandleWrappable)}_unwrapHandle(e){return fr(this.context,e,this._symbolHandle)}},gr={param:(e,t,n=``)=>`<span class="param ${t||``}">${e||n}</span>`},_r={type:`sync`,importFFI:()=>o(()=>import(`./ffi-BCdwDTfq.js`).then(e=>e.QuickJSFFI),[]),importModuleLoader:()=>o(()=>import(`./emscripten-module-VHMWRAJ2-CzPuSaDz.js`).then(e=>e.default),__vite__mapDeps([2,3,4]))},vr=class extends Error{constructor(e,t){super(t),this.name=e,this.description=t,this.name=e}},yr=async e=>{let{logger:t}=gn(),n=await _n(e),r=()=>{let e=n.newContext(),r=new hr(e,{isMarshalable:!0});return{run:(e,n)=>{let i={fmt:gr,...n};r.expose(i);let a=`(() => {
94
94
  return ${e};
95
- })()`;try{return r.evalCode(a)}catch(e){throw t().error(`error`,e),t().error(`Final code was`,a),new ur(e.name,e.message)}},dispose:()=>{try{r.dispose()}catch(e){t().error(`Failed to dispose arena`,e)}try{e.dispose()}catch(e){t().error(`Failed to dispose VM`,e)}}}};return{run:(e,n)=>{let i=r();try{return i.run(e,n)}finally{try{i.dispose()}catch(e){t().error(`Failed to dispose context`,e)}}},createContext:r}},fr=()=>dr(lr),pr=async(e,t=e=>e,n)=>{let{logger:r}=cn(),i=n??await fr(),a={},o=`createContext`in i?i.createContext():null;for(let[n,s]of Object.entries(e.params))try{let r=(s.value??``).toString();try{a[n]=JSON.parse(r);continue}catch{}let c={steps:e.steps,params:{},variables:e.variables};a[n]=t(o?o.run(r,c):await i.run(r,c))}catch(e){r().error(`error`,e),a[n]=``}return o&&o.dispose(),a},mr=async(e,t)=>{let n={};for(let r of t){console.log(`variable.value`,r.value);let t=await e.run(r.value,{params:{}});n[r.id]=t}return n},hr=D({pluginId:k(),nodeId:k(),version:ot(O(k()),Ke(`Pinned version of the plugin for this block. Falls back to "latest" when absent.`))});E(`action`),O(T());var gr=A([E(`simple`),E(`editor`)]),_r=D({type:E(`action`),uid:k(),name:ot(O(k()),Ke(`A custom name provided by the user`)),disabled:O(T()),params:tt(k(),D({editor:gr,value:rt()})),origin:hr}),vr=D({type:E(`event`),uid:k(),origin:hr,params:tt(k(),Qe())});E(`comment`);var yr=D({blocks:w(it(`type`,[_r])),triggers:w(vr)}),br=$e(()=>!0);E(`1.0.0`),E(`2.0.0`),E(`3.0.0`);var xr=D({version:E(`4.0.0`),type:E(`default`),name:k(),description:k(),plugins:O(tt(k(),k())),canvas:yr,variables:w(br)}),Sr=D({version:E(`4.0.0`),type:E(`simple`),name:k(),description:k(),plugins:O(tt(k(),k())),source:D({type:A([E(`c3-html`),E(`c3-nwjs`),E(`godot`),E(`html`)]),path:k()}),packaging:D({enabled:T()}),publishing:D({steam:D({enabled:T(),appId:O(k())}),itch:D({enabled:T(),project:O(k())}),poki:D({enabled:T(),gameId:O(k())})})}),Cr=D({version:E(`5.0.0`),name:k(),description:k(),canvas:yr,variables:w(br)});E(`5.0.0`),E(`simple`),A([E(`c3-html`),E(`c3-nwjs`),E(`godot`),E(`html`)]),O(k()),O(k()),O(k()),A([xr,Sr]);var wr=Cr,Tr=wr;r([]);var Er=D({id:k(),project:k(),lastModified:k(),type:E(`internal`),configName:k()}),Dr=D({id:k(),project:k(),path:k(),lastModified:k(),type:E(`external`),summary:D({plugins:w(k()),name:k(),description:k()})}),Or=D({id:k(),project:k(),type:E(`pipelab-cloud`)}),kr=A([Dr,Er,Or]);function Ar(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function jr(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}var Mr=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Nr=class extends Error{constructor(e,t=`FunctionsError`,n){super(e),this.name=t,this.context=n}},Pr=class extends Nr{constructor(e){super(`Failed to send a request to the Edge Function`,`FunctionsFetchError`,e)}},Fr=class extends Nr{constructor(e){super(`Relay Error invoking the Edge Function`,`FunctionsRelayError`,e)}},Ir=class extends Nr{constructor(e){super(`Edge Function returned a non-2xx status code`,`FunctionsHttpError`,e)}},Lr;(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`})(Lr||={});var Rr=class{constructor(e,{headers:t={},customFetch:n,region:r=Lr.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=Mr(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return jr(this,arguments,void 0,function*(e,t={}){let n,r;try{let{headers:i,method:a,body:o,signal:s,timeout:c}=t,l={},{region:u}=t;u||=this.region;let d=new URL(`${this.url}/${e}`);u&&u!==`any`&&(l[`x-region`]=u,d.searchParams.set(`forceFunctionRegion`,u));let f;o&&(i&&!Object.prototype.hasOwnProperty.call(i,`Content-Type`)||!i)?typeof Blob<`u`&&o instanceof Blob||o instanceof ArrayBuffer?(l[`Content-Type`]=`application/octet-stream`,f=o):typeof o==`string`?(l[`Content-Type`]=`text/plain`,f=o):typeof FormData<`u`&&o instanceof FormData?f=o:(l[`Content-Type`]=`application/json`,f=JSON.stringify(o)):f=o&&typeof o!=`string`&&!(typeof Blob<`u`&&o instanceof Blob)&&!(o instanceof ArrayBuffer)&&!(typeof FormData<`u`&&o instanceof FormData)?JSON.stringify(o):o;let p=s;c&&(r=new AbortController,n=setTimeout(()=>r.abort(),c),s?(p=r.signal,s.addEventListener(`abort`,()=>r.abort())):p=r.signal);let m=yield this.fetch(d.toString(),{method:a||`POST`,headers:Object.assign(Object.assign(Object.assign({},l),this.headers),i),body:f,signal:p}).catch(e=>{throw new Pr(e)}),h=m.headers.get(`x-relay-error`);if(h&&h===`true`)throw new Fr(m);if(!m.ok)throw new Ir(m);let g=(m.headers.get(`Content-Type`)??`text/plain`).split(`;`)[0].trim(),_;return _=g===`application/json`?yield m.json():g===`application/octet-stream`||g===`application/pdf`?yield m.blob():g===`text/event-stream`?m:g===`multipart/form-data`?yield m.formData():yield m.text(),{data:_,error:null,response:m}}catch(e){return{data:null,error:e,response:e instanceof Ir||e instanceof Fr?e.context:void 0}}finally{n&&clearTimeout(n)}})}},zr=class extends Error{constructor(e){super(e.message),this.name=`PostgrestError`,this.details=e.details,this.hint=e.hint,this.code=e.code}},Br=class{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError??!1,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle??!1,this.urlLengthLimit=e.urlLengthLimit??8e3,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){var n=this;this.schema===void 0||([`GET`,`HEAD`].includes(this.method)?this.headers.set(`Accept-Profile`,this.schema):this.headers.set(`Content-Profile`,this.schema)),this.method!==`GET`&&this.method!==`HEAD`&&this.headers.set(`Content-Type`,`application/json`);let r=this.fetch,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{let t=null,r=null,i=null,a=e.status,o=e.statusText;if(e.ok){if(n.method!==`HEAD`){let t=await e.text();t===``||(r=n.headers.get(`Accept`)===`text/csv`||n.headers.get(`Accept`)&&n.headers.get(`Accept`)?.includes(`application/vnd.pgrst.plan+text`)?t:JSON.parse(t))}let s=n.headers.get(`Prefer`)?.match(/count=(exact|planned|estimated)/),c=e.headers.get(`content-range`)?.split(`/`);s&&c&&c.length>1&&(i=parseInt(c[1])),n.isMaybeSingle&&n.method===`GET`&&Array.isArray(r)&&(r.length>1?(t={code:`PGRST116`,details:`Results contain ${r.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:`JSON object requested, multiple (or no) rows returned`},r=null,i=null,a=406,o=`Not Acceptable`):r=r.length===1?r[0]:null)}else{var s;let i=await e.text();try{t=JSON.parse(i),Array.isArray(t)&&e.status===404&&(r=[],t=null,a=200,o=`OK`)}catch{e.status===404&&i===``?(a=204,o=`No Content`):t={message:i}}if(t&&n.isMaybeSingle&&!(t==null||(s=t.details)==null)&&s.includes(`0 rows`)&&(t=null,a=200,o=`OK`),t&&n.shouldThrowOnError)throw new zr(t)}return{error:t,data:r,count:i,status:a,statusText:o}});return this.shouldThrowOnError||(i=i.catch(e=>{let t=``,n=``,r=``,i=e?.cause;if(i){let n=i?.message??``,r=i?.code??``;t=`${e?.name??`FetchError`}: ${e?.message}`,t+=`\n\nCaused by: ${i?.name??`Error`}: ${n}`,r&&(t+=` (${r})`),i?.stack&&(t+=`\n${i.stack}`)}else t=e?.stack??``;let a=this.url.toString().length;return e?.name===`AbortError`||e?.code===`ABORT_ERR`?(r=``,n=`Request was aborted (timeout or manual cancellation)`,a>this.urlLengthLimit&&(n+=`. Note: Your request URL is ${a} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(i?.name===`HeadersOverflowError`||i?.code===`UND_ERR_HEADERS_OVERFLOW`)&&(r=``,n=`HTTP headers exceeded server limits (typically 16KB)`,a>this.urlLengthLimit&&(n+=`. Your request URL is ${a} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${e?.name??`FetchError`}: ${e?.message}`,details:t,hint:n,code:r},data:null,count:null,status:0,statusText:``}})),i.then(e,t)}returns(){return this}overrideTypes(){return this}},Vr=class extends Br{select(e){let t=!1,n=(e??`*`).split(``).map(e=>/\s/.test(e)&&!t?``:(e===`"`&&(t=!t),e)).join(``);return this.url.searchParams.set(`select`,n),this.headers.append(`Prefer`,`return=representation`),this}order(e,{ascending:t=!0,nullsFirst:n,foreignTable:r,referencedTable:i=r}={}){let a=i?`${i}.order`:`order`,o=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${o?`${o},`:``}${e}.${t?`asc`:`desc`}${n===void 0?``:n?`.nullsfirst`:`.nullslast`}`),this}limit(e,{foreignTable:t,referencedTable:n=t}={}){let r=n===void 0?`limit`:`${n}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:n,referencedTable:r=n}={}){let i=r===void 0?`offset`:`${r}.offset`,a=r===void 0?`limit`:`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(a,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set(`Accept`,`application/vnd.pgrst.object+json`),this}maybeSingle(){return this.method===`GET`?this.headers.set(`Accept`,`application/json`):this.headers.set(`Accept`,`application/vnd.pgrst.object+json`),this.isMaybeSingle=!0,this}csv(){return this.headers.set(`Accept`,`text/csv`),this}geojson(){return this.headers.set(`Accept`,`application/geo+json`),this}explain({analyze:e=!1,verbose:t=!1,settings:n=!1,buffers:r=!1,wal:i=!1,format:a=`text`}={}){let o=[e?`analyze`:null,t?`verbose`:null,n?`settings`:null,r?`buffers`:null,i?`wal`:null].filter(Boolean).join(`|`),s=this.headers.get(`Accept`)??`application/json`;return this.headers.set(`Accept`,`application/vnd.pgrst.plan+${a}; for="${s}"; options=${o};`),this}rollback(){return this.headers.append(`Prefer`,`tx=rollback`),this}returns(){return this}maxAffected(e){return this.headers.append(`Prefer`,`handling=strict`),this.headers.append(`Prefer`,`max-affected=${e}`),this}},Hr=RegExp(`[,()]`),Ur=class extends Vr{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(`,`)}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(`,`)}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(`,`)}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(`,`)}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){let n=Array.from(new Set(t)).map(e=>typeof e==`string`&&Hr.test(e)?`"${e}"`:`${e}`).join(`,`);return this.url.searchParams.append(e,`in.(${n})`),this}notIn(e,t){let n=Array.from(new Set(t)).map(e=>typeof e==`string`&&Hr.test(e)?`"${e}"`:`${e}`).join(`,`);return this.url.searchParams.append(e,`not.in.(${n})`),this}contains(e,t){return typeof t==`string`?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 typeof t==`string`?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(`,`)}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t==`string`?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(`,`)}}`),this}textSearch(e,t,{config:n,type:r}={}){let i=``;r===`plain`?i=`pl`:r===`phrase`?i=`ph`:r===`websearch`&&(i=`w`);let a=n===void 0?``:`(${n})`;return this.url.searchParams.append(e,`${i}fts${a}.${t}`),this}match(e){return Object.entries(e).filter(([e,t])=>t!==void 0).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,n){return this.url.searchParams.append(e,`not.${t}.${n}`),this}or(e,{foreignTable:t,referencedTable:n=t}={}){let r=n?`${n}.or`:`or`;return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,n){return this.url.searchParams.append(e,`${t}.${n}`),this}},Wr=class{constructor(e,{headers:t={},schema:n,fetch:r,urlLengthLimit:i=8e3}){this.url=e,this.headers=new Headers(t),this.schema=n,this.fetch=r,this.urlLengthLimit=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){let{head:n=!1,count:r}=t??{},i=n?`HEAD`:`GET`,a=!1,o=(e??`*`).split(``).map(e=>/\s/.test(e)&&!a?``:(e===`"`&&(a=!a),e)).join(``),{url:s,headers:c}=this.cloneRequestState();return s.searchParams.set(`select`,o),r&&c.append(`Prefer`,`count=${r}`),new Ur({method:i,url:s,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(e,{count:t,defaultToNull:n=!0}={}){let{url:r,headers:i}=this.cloneRequestState();if(t&&i.append(`Prefer`,`count=${t}`),n||i.append(`Prefer`,`missing=default`),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);r.searchParams.set(`columns`,e.join(`,`))}}return new Ur({method:`POST`,url:r,headers:i,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit})}upsert(e,{onConflict:t,ignoreDuplicates:n=!1,count:r,defaultToNull:i=!0}={}){let{url:a,headers:o}=this.cloneRequestState();if(o.append(`Prefer`,`resolution=${n?`ignore`:`merge`}-duplicates`),t!==void 0&&a.searchParams.set(`on_conflict`,t),r&&o.append(`Prefer`,`count=${r}`),i||o.append(`Prefer`,`missing=default`),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);a.searchParams.set(`columns`,e.join(`,`))}}return new Ur({method:`POST`,url:a,headers:o,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit})}update(e,{count:t}={}){let{url:n,headers:r}=this.cloneRequestState();return t&&r.append(`Prefer`,`count=${t}`),new Ur({method:`PATCH`,url:n,headers:r,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:e}={}){let{url:t,headers:n}=this.cloneRequestState();return e&&n.append(`Prefer`,`count=${e}`),new Ur({method:`DELETE`,url:t,headers:n,schema:this.schema,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit})}};function Gr(e){"@babel/helpers - typeof";return Gr=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},Gr(e)}function Kr(e,t){if(Gr(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(Gr(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function qr(e){var t=Kr(e,`string`);return Gr(t)==`symbol`?t:t+``}function Jr(e,t,n){return(t=qr(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Yr(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Xr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Yr(Object(n),!0).forEach(function(t){Jr(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Yr(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var Zr=class e{constructor(e,{headers:t={},schema:n,fetch:r,timeout:i,urlLengthLimit:a=8e3}={}){this.url=e,this.headers=new Headers(t),this.schemaName=n,this.urlLengthLimit=a;let o=r??globalThis.fetch;i!==void 0&&i>0?this.fetch=(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),i),a=t?.signal;if(a){if(a.aborted)return clearTimeout(r),o(e,t);let i=()=>{clearTimeout(r),n.abort()};return a.addEventListener(`abort`,i,{once:!0}),o(e,Xr(Xr({},t),{},{signal:n.signal})).finally(()=>{clearTimeout(r),a.removeEventListener(`abort`,i)})}return o(e,Xr(Xr({},t),{},{signal:n.signal})).finally(()=>clearTimeout(r))}:this.fetch=o}from(e){if(!e||typeof e!=`string`||e.trim()===``)throw Error(`Invalid relation name: relation must be a non-empty string.`);return new Wr(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,t={},{head:n=!1,get:r=!1,count:i}={}){let a,o=new URL(`${this.url}/rpc/${e}`),s,c=e=>typeof e==`object`&&!!e&&(!Array.isArray(e)||e.some(c)),l=n&&Object.values(t).some(c);l?(a=`POST`,s=t):n||r?(a=n?`HEAD`:`GET`,Object.entries(t).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(`,`)}}`:`${t}`]).forEach(([e,t])=>{o.searchParams.append(e,t)})):(a=`POST`,s=t);let u=new Headers(this.headers);return l?u.set(`Prefer`,i?`count=${i},return=minimal`:`return=minimal`):i&&u.set(`Prefer`,`count=${i}`),new Ur({method:a,url:o,headers:u,schema:this.schemaName,body:s,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit})}},Qr=class{constructor(){}static detectEnvironment(){if(typeof WebSocket<`u`)return{type:`native`,constructor:WebSocket};if(typeof globalThis<`u`&&globalThis.WebSocket!==void 0)return{type:`native`,constructor:globalThis.WebSocket};if(typeof global<`u`&&global.WebSocket!==void 0)return{type:`native`,constructor:global.WebSocket};if(typeof globalThis<`u`&&globalThis.WebSocketPair!==void 0&&globalThis.WebSocket===void 0)return{type:`cloudflare`,error:`Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.`,workaround:`Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime.`};if(typeof globalThis<`u`&&globalThis.EdgeRuntime||typeof navigator<`u`&&navigator.userAgent?.includes(`Vercel-Edge`))return{type:`unsupported`,error:`Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.`,workaround:`Use serverless functions or a different deployment target for WebSocket functionality.`};let e=globalThis.process;if(e){let t=e.versions;if(t&&t.node){let e=t.node,n=parseInt(e.replace(/^v/,``).split(`.`)[0]);return n>=22?globalThis.WebSocket===void 0?{type:`unsupported`,error:`Node.js ${n} detected but native WebSocket not found.`,workaround:`Provide a WebSocket implementation via the transport option.`}:{type:`native`,constructor:globalThis.WebSocket}:{type:`unsupported`,error:`Node.js ${n} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
95
+ })()`;try{return r.evalCode(a)}catch(e){throw t().error(`error`,e),t().error(`Final code was`,a),new vr(e.name,e.message)}},dispose:()=>{try{r.dispose()}catch(e){t().error(`Failed to dispose arena`,e)}try{e.dispose()}catch(e){t().error(`Failed to dispose VM`,e)}}}};return{run:(e,n)=>{let i=r();try{return i.run(e,n)}finally{try{i.dispose()}catch(e){t().error(`Failed to dispose context`,e)}}},createContext:r}},br=()=>yr(_r),xr=async(e,t=e=>e,n)=>{let{logger:r}=gn(),i=n??await br(),a={},o=`createContext`in i?i.createContext():null;for(let[n,s]of Object.entries(e.params))try{let r=(s.value??``).toString();try{a[n]=JSON.parse(r);continue}catch{}let c={steps:e.steps,params:{},variables:e.variables};a[n]=t(o?o.run(r,c):await i.run(r,c))}catch(e){r().error(`error`,e),a[n]=``}return o&&o.dispose(),a},Sr=async(e,t)=>{let n={};for(let r of t){console.log(`variable.value`,r.value);let t=await e.run(r.value,{params:{}});n[r.id]=t}return n},Cr=D({pluginId:k(),nodeId:k(),version:O(st(k(),Ke(`Pinned version of the plugin for this block. Falls back to "latest" when absent.`)))});E(`action`),O(T());var wr=A([E(`simple`),E(`editor`)]),Tr=D({type:E(`action`),uid:k(),name:O(st(k(),Ke(`A custom name provided by the user`))),disabled:O(T()),params:nt(k(),D({editor:wr,value:it()})),origin:Cr}),Er=D({type:E(`event`),uid:k(),origin:Cr,params:nt(k(),Qe())});E(`comment`);var Dr=D({blocks:w(at(`type`,[Tr])),triggers:w(Er)}),Or=$e(()=>!0);E(`1.0.0`),E(`2.0.0`),E(`3.0.0`);var kr=D({version:E(`4.0.0`),type:E(`default`),name:k(),description:k(),plugins:O(nt(k(),k())),canvas:Dr,variables:w(Or)}),Ar=D({version:E(`4.0.0`),type:E(`simple`),name:k(),description:k(),plugins:O(nt(k(),k())),source:D({type:A([E(`c3-html`),E(`c3-nwjs`),E(`godot`),E(`html`)]),path:k()}),packaging:D({enabled:T()}),publishing:D({steam:D({enabled:T(),appId:O(k())}),itch:D({enabled:T(),project:O(k())}),poki:D({enabled:T(),gameId:O(k())})})}),jr=D({version:E(`5.0.0`),name:k(),description:k(),canvas:Dr,variables:w(Or)});E(`5.0.0`),E(`simple`),A([E(`c3-html`),E(`c3-nwjs`),E(`godot`),E(`html`)]),O(k()),O(k()),O(k()),A([kr,Ar]);var Mr=jr,Nr=Mr;r([]);function Pr(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function Fr(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}var Ir=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Lr=class extends Error{constructor(e,t=`FunctionsError`,n){super(e),this.name=t,this.context=n}},Rr=class extends Lr{constructor(e){super(`Failed to send a request to the Edge Function`,`FunctionsFetchError`,e)}},zr=class extends Lr{constructor(e){super(`Relay Error invoking the Edge Function`,`FunctionsRelayError`,e)}},Br=class extends Lr{constructor(e){super(`Edge Function returned a non-2xx status code`,`FunctionsHttpError`,e)}},Vr;(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`})(Vr||={});var Hr=class{constructor(e,{headers:t={},customFetch:n,region:r=Vr.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=Ir(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Fr(this,arguments,void 0,function*(e,t={}){let n,r;try{let{headers:i,method:a,body:o,signal:s,timeout:c}=t,l={},{region:u}=t;u||=this.region;let d=new URL(`${this.url}/${e}`);u&&u!==`any`&&(l[`x-region`]=u,d.searchParams.set(`forceFunctionRegion`,u));let f;o&&(i&&!Object.prototype.hasOwnProperty.call(i,`Content-Type`)||!i)?typeof Blob<`u`&&o instanceof Blob||o instanceof ArrayBuffer?(l[`Content-Type`]=`application/octet-stream`,f=o):typeof o==`string`?(l[`Content-Type`]=`text/plain`,f=o):typeof FormData<`u`&&o instanceof FormData?f=o:(l[`Content-Type`]=`application/json`,f=JSON.stringify(o)):f=o&&typeof o!=`string`&&!(typeof Blob<`u`&&o instanceof Blob)&&!(o instanceof ArrayBuffer)&&!(typeof FormData<`u`&&o instanceof FormData)?JSON.stringify(o):o;let p=s;c&&(r=new AbortController,n=setTimeout(()=>r.abort(),c),s?(p=r.signal,s.addEventListener(`abort`,()=>r.abort())):p=r.signal);let m=yield this.fetch(d.toString(),{method:a||`POST`,headers:Object.assign(Object.assign(Object.assign({},l),this.headers),i),body:f,signal:p}).catch(e=>{throw new Rr(e)}),h=m.headers.get(`x-relay-error`);if(h&&h===`true`)throw new zr(m);if(!m.ok)throw new Br(m);let g=(m.headers.get(`Content-Type`)??`text/plain`).split(`;`)[0].trim(),_;return _=g===`application/json`?yield m.json():g===`application/octet-stream`||g===`application/pdf`?yield m.blob():g===`text/event-stream`?m:g===`multipart/form-data`?yield m.formData():yield m.text(),{data:_,error:null,response:m}}catch(e){return{data:null,error:e,response:e instanceof Br||e instanceof zr?e.context:void 0}}finally{n&&clearTimeout(n)}})}},Ur=class extends Error{constructor(e){super(e.message),this.name=`PostgrestError`,this.details=e.details,this.hint=e.hint,this.code=e.code}},Wr=class{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError??!1,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle??!1,this.urlLengthLimit=e.urlLengthLimit??8e3,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){var n=this;this.schema===void 0||([`GET`,`HEAD`].includes(this.method)?this.headers.set(`Accept-Profile`,this.schema):this.headers.set(`Content-Profile`,this.schema)),this.method!==`GET`&&this.method!==`HEAD`&&this.headers.set(`Content-Type`,`application/json`);let r=this.fetch,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{let t=null,r=null,i=null,a=e.status,o=e.statusText;if(e.ok){if(n.method!==`HEAD`){let t=await e.text();t===``||(r=n.headers.get(`Accept`)===`text/csv`||n.headers.get(`Accept`)&&n.headers.get(`Accept`)?.includes(`application/vnd.pgrst.plan+text`)?t:JSON.parse(t))}let s=n.headers.get(`Prefer`)?.match(/count=(exact|planned|estimated)/),c=e.headers.get(`content-range`)?.split(`/`);s&&c&&c.length>1&&(i=parseInt(c[1])),n.isMaybeSingle&&n.method===`GET`&&Array.isArray(r)&&(r.length>1?(t={code:`PGRST116`,details:`Results contain ${r.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:`JSON object requested, multiple (or no) rows returned`},r=null,i=null,a=406,o=`Not Acceptable`):r=r.length===1?r[0]:null)}else{var s;let i=await e.text();try{t=JSON.parse(i),Array.isArray(t)&&e.status===404&&(r=[],t=null,a=200,o=`OK`)}catch{e.status===404&&i===``?(a=204,o=`No Content`):t={message:i}}if(t&&n.isMaybeSingle&&!(t==null||(s=t.details)==null)&&s.includes(`0 rows`)&&(t=null,a=200,o=`OK`),t&&n.shouldThrowOnError)throw new Ur(t)}return{error:t,data:r,count:i,status:a,statusText:o}});return this.shouldThrowOnError||(i=i.catch(e=>{let t=``,n=``,r=``,i=e?.cause;if(i){let n=i?.message??``,r=i?.code??``;t=`${e?.name??`FetchError`}: ${e?.message}`,t+=`\n\nCaused by: ${i?.name??`Error`}: ${n}`,r&&(t+=` (${r})`),i?.stack&&(t+=`\n${i.stack}`)}else t=e?.stack??``;let a=this.url.toString().length;return e?.name===`AbortError`||e?.code===`ABORT_ERR`?(r=``,n=`Request was aborted (timeout or manual cancellation)`,a>this.urlLengthLimit&&(n+=`. Note: Your request URL is ${a} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(i?.name===`HeadersOverflowError`||i?.code===`UND_ERR_HEADERS_OVERFLOW`)&&(r=``,n=`HTTP headers exceeded server limits (typically 16KB)`,a>this.urlLengthLimit&&(n+=`. Your request URL is ${a} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${e?.name??`FetchError`}: ${e?.message}`,details:t,hint:n,code:r},data:null,count:null,status:0,statusText:``}})),i.then(e,t)}returns(){return this}overrideTypes(){return this}},Gr=class extends Wr{select(e){let t=!1,n=(e??`*`).split(``).map(e=>/\s/.test(e)&&!t?``:(e===`"`&&(t=!t),e)).join(``);return this.url.searchParams.set(`select`,n),this.headers.append(`Prefer`,`return=representation`),this}order(e,{ascending:t=!0,nullsFirst:n,foreignTable:r,referencedTable:i=r}={}){let a=i?`${i}.order`:`order`,o=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${o?`${o},`:``}${e}.${t?`asc`:`desc`}${n===void 0?``:n?`.nullsfirst`:`.nullslast`}`),this}limit(e,{foreignTable:t,referencedTable:n=t}={}){let r=n===void 0?`limit`:`${n}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:n,referencedTable:r=n}={}){let i=r===void 0?`offset`:`${r}.offset`,a=r===void 0?`limit`:`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(a,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set(`Accept`,`application/vnd.pgrst.object+json`),this}maybeSingle(){return this.method===`GET`?this.headers.set(`Accept`,`application/json`):this.headers.set(`Accept`,`application/vnd.pgrst.object+json`),this.isMaybeSingle=!0,this}csv(){return this.headers.set(`Accept`,`text/csv`),this}geojson(){return this.headers.set(`Accept`,`application/geo+json`),this}explain({analyze:e=!1,verbose:t=!1,settings:n=!1,buffers:r=!1,wal:i=!1,format:a=`text`}={}){let o=[e?`analyze`:null,t?`verbose`:null,n?`settings`:null,r?`buffers`:null,i?`wal`:null].filter(Boolean).join(`|`),s=this.headers.get(`Accept`)??`application/json`;return this.headers.set(`Accept`,`application/vnd.pgrst.plan+${a}; for="${s}"; options=${o};`),this}rollback(){return this.headers.append(`Prefer`,`tx=rollback`),this}returns(){return this}maxAffected(e){return this.headers.append(`Prefer`,`handling=strict`),this.headers.append(`Prefer`,`max-affected=${e}`),this}},Kr=RegExp(`[,()]`),qr=class extends Gr{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(`,`)}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(`,`)}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(`,`)}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(`,`)}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){let n=Array.from(new Set(t)).map(e=>typeof e==`string`&&Kr.test(e)?`"${e}"`:`${e}`).join(`,`);return this.url.searchParams.append(e,`in.(${n})`),this}notIn(e,t){let n=Array.from(new Set(t)).map(e=>typeof e==`string`&&Kr.test(e)?`"${e}"`:`${e}`).join(`,`);return this.url.searchParams.append(e,`not.in.(${n})`),this}contains(e,t){return typeof t==`string`?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 typeof t==`string`?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(`,`)}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t==`string`?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(`,`)}}`),this}textSearch(e,t,{config:n,type:r}={}){let i=``;r===`plain`?i=`pl`:r===`phrase`?i=`ph`:r===`websearch`&&(i=`w`);let a=n===void 0?``:`(${n})`;return this.url.searchParams.append(e,`${i}fts${a}.${t}`),this}match(e){return Object.entries(e).filter(([e,t])=>t!==void 0).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,n){return this.url.searchParams.append(e,`not.${t}.${n}`),this}or(e,{foreignTable:t,referencedTable:n=t}={}){let r=n?`${n}.or`:`or`;return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,n){return this.url.searchParams.append(e,`${t}.${n}`),this}},Jr=class{constructor(e,{headers:t={},schema:n,fetch:r,urlLengthLimit:i=8e3}){this.url=e,this.headers=new Headers(t),this.schema=n,this.fetch=r,this.urlLengthLimit=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){let{head:n=!1,count:r}=t??{},i=n?`HEAD`:`GET`,a=!1,o=(e??`*`).split(``).map(e=>/\s/.test(e)&&!a?``:(e===`"`&&(a=!a),e)).join(``),{url:s,headers:c}=this.cloneRequestState();return s.searchParams.set(`select`,o),r&&c.append(`Prefer`,`count=${r}`),new qr({method:i,url:s,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(e,{count:t,defaultToNull:n=!0}={}){let{url:r,headers:i}=this.cloneRequestState();if(t&&i.append(`Prefer`,`count=${t}`),n||i.append(`Prefer`,`missing=default`),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);r.searchParams.set(`columns`,e.join(`,`))}}return new qr({method:`POST`,url:r,headers:i,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit})}upsert(e,{onConflict:t,ignoreDuplicates:n=!1,count:r,defaultToNull:i=!0}={}){let{url:a,headers:o}=this.cloneRequestState();if(o.append(`Prefer`,`resolution=${n?`ignore`:`merge`}-duplicates`),t!==void 0&&a.searchParams.set(`on_conflict`,t),r&&o.append(`Prefer`,`count=${r}`),i||o.append(`Prefer`,`missing=default`),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);a.searchParams.set(`columns`,e.join(`,`))}}return new qr({method:`POST`,url:a,headers:o,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit})}update(e,{count:t}={}){let{url:n,headers:r}=this.cloneRequestState();return t&&r.append(`Prefer`,`count=${t}`),new qr({method:`PATCH`,url:n,headers:r,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:e}={}){let{url:t,headers:n}=this.cloneRequestState();return e&&n.append(`Prefer`,`count=${e}`),new qr({method:`DELETE`,url:t,headers:n,schema:this.schema,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit})}};function Yr(e){"@babel/helpers - typeof";return Yr=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},Yr(e)}function Xr(e,t){if(Yr(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(Yr(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Zr(e){var t=Xr(e,`string`);return Yr(t)==`symbol`?t:t+``}function Qr(e,t,n){return(t=Zr(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function $r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function ei(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?$r(Object(n),!0).forEach(function(t){Qr(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):$r(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var ti=class e{constructor(e,{headers:t={},schema:n,fetch:r,timeout:i,urlLengthLimit:a=8e3}={}){this.url=e,this.headers=new Headers(t),this.schemaName=n,this.urlLengthLimit=a;let o=r??globalThis.fetch;i!==void 0&&i>0?this.fetch=(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),i),a=t?.signal;if(a){if(a.aborted)return clearTimeout(r),o(e,t);let i=()=>{clearTimeout(r),n.abort()};return a.addEventListener(`abort`,i,{once:!0}),o(e,ei(ei({},t),{},{signal:n.signal})).finally(()=>{clearTimeout(r),a.removeEventListener(`abort`,i)})}return o(e,ei(ei({},t),{},{signal:n.signal})).finally(()=>clearTimeout(r))}:this.fetch=o}from(e){if(!e||typeof e!=`string`||e.trim()===``)throw Error(`Invalid relation name: relation must be a non-empty string.`);return new Jr(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,t={},{head:n=!1,get:r=!1,count:i}={}){let a,o=new URL(`${this.url}/rpc/${e}`),s,c=e=>typeof e==`object`&&!!e&&(!Array.isArray(e)||e.some(c)),l=n&&Object.values(t).some(c);l?(a=`POST`,s=t):n||r?(a=n?`HEAD`:`GET`,Object.entries(t).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(`,`)}}`:`${t}`]).forEach(([e,t])=>{o.searchParams.append(e,t)})):(a=`POST`,s=t);let u=new Headers(this.headers);return l?u.set(`Prefer`,i?`count=${i},return=minimal`:`return=minimal`):i&&u.set(`Prefer`,`count=${i}`),new qr({method:a,url:o,headers:u,schema:this.schemaName,body:s,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit})}},ni=class{constructor(){}static detectEnvironment(){if(typeof WebSocket<`u`)return{type:`native`,constructor:WebSocket};if(typeof globalThis<`u`&&globalThis.WebSocket!==void 0)return{type:`native`,constructor:globalThis.WebSocket};if(typeof global<`u`&&global.WebSocket!==void 0)return{type:`native`,constructor:global.WebSocket};if(typeof globalThis<`u`&&globalThis.WebSocketPair!==void 0&&globalThis.WebSocket===void 0)return{type:`cloudflare`,error:`Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.`,workaround:`Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime.`};if(typeof globalThis<`u`&&globalThis.EdgeRuntime||typeof navigator<`u`&&navigator.userAgent?.includes(`Vercel-Edge`))return{type:`unsupported`,error:`Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.`,workaround:`Use serverless functions or a different deployment target for WebSocket functionality.`};let e=globalThis.process;if(e){let t=e.versions;if(t&&t.node){let e=t.node,n=parseInt(e.replace(/^v/,``).split(`.`)[0]);return n>=22?globalThis.WebSocket===void 0?{type:`unsupported`,error:`Node.js ${n} detected but native WebSocket not found.`,workaround:`Provide a WebSocket implementation via the transport option.`}:{type:`native`,constructor:globalThis.WebSocket}:{type:`unsupported`,error:`Node.js ${n} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
96
96
  import ws from "ws"
97
- new RealtimeClient(url, { transport: ws })`}}}return{type:`unsupported`,error:`Unknown JavaScript runtime without WebSocket support.`,workaround:`Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation.`}}static getWebSocketConstructor(){let e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||`WebSocket not supported in this environment.`;throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),Error(t)}static createWebSocket(e,t){return new(this.getWebSocketConstructor())(e,t)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type===`native`||e.type===`ws`}catch{return!1}}},$r=`realtime-js/2.99.3`,ei=`1.0.0`,ti=`2.0.0`,ni=ti,ri=1e4,ii;(function(e){e[e.connecting=0]=`connecting`,e[e.open=1]=`open`,e[e.closing=2]=`closing`,e[e.closed=3]=`closed`})(ii||={});var I;(function(e){e.closed=`closed`,e.errored=`errored`,e.joined=`joined`,e.joining=`joining`,e.leaving=`leaving`})(I||={});var L;(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`})(L||={});var ai;(function(e){e.websocket=`websocket`})(ai||={});var oi;(function(e){e.Connecting=`connecting`,e.Open=`open`,e.Closing=`closing`,e.Closed=`closed`})(oi||={});var si=class{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT=`broadcast`,this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event==`string`)return t(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){return this._isArrayBuffer(e.payload?.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){let t=e.payload?.payload??new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,t)}_encodeJsonUserBroadcastPush(e){let t=e.payload?.payload??{},n=new TextEncoder().encode(JSON.stringify(t)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,n)}_encodeUserBroadcastPush(e,t,n){let r=e.topic,i=e.ref??``,a=e.join_ref??``,o=e.payload.event,s=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},c=Object.keys(s).length===0?``:JSON.stringify(s);if(a.length>255)throw Error(`joinRef length ${a.length} exceeds maximum of 255`);if(i.length>255)throw Error(`ref length ${i.length} exceeds maximum of 255`);if(r.length>255)throw Error(`topic length ${r.length} exceeds maximum of 255`);if(o.length>255)throw Error(`userEvent length ${o.length} exceeds maximum of 255`);if(c.length>255)throw Error(`metadata length ${c.length} exceeds maximum of 255`);let l=this.USER_BROADCAST_PUSH_META_LENGTH+a.length+i.length+r.length+o.length+c.length,u=new ArrayBuffer(this.HEADER_LENGTH+l),d=new DataView(u),f=0;d.setUint8(f++,this.KINDS.userBroadcastPush),d.setUint8(f++,a.length),d.setUint8(f++,i.length),d.setUint8(f++,r.length),d.setUint8(f++,o.length),d.setUint8(f++,c.length),d.setUint8(f++,t),Array.from(a,e=>d.setUint8(f++,e.charCodeAt(0))),Array.from(i,e=>d.setUint8(f++,e.charCodeAt(0))),Array.from(r,e=>d.setUint8(f++,e.charCodeAt(0))),Array.from(o,e=>d.setUint8(f++,e.charCodeAt(0))),Array.from(c,e=>d.setUint8(f++,e.charCodeAt(0)));var p=new Uint8Array(u.byteLength+n.byteLength);return p.set(new Uint8Array(u),0),p.set(new Uint8Array(n),u.byteLength),p.buffer}decode(e,t){if(this._isArrayBuffer(e))return t(this._binaryDecode(e));if(typeof e==`string`){let[n,r,i,a,o]=JSON.parse(e);return t({join_ref:n,ref:r,topic:i,event:a,payload:o})}return t({})}_binaryDecode(e){let t=new DataView(e),n=t.getUint8(0),r=new TextDecoder;switch(n){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,t,r)}}_decodeUserBroadcast(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=t.getUint8(3),o=t.getUint8(4),s=this.HEADER_LENGTH+4,c=n.decode(e.slice(s,s+r));s+=r;let l=n.decode(e.slice(s,s+i));s+=i;let u=n.decode(e.slice(s,s+a));s+=a;let d=e.slice(s,e.byteLength),f=o===this.JSON_ENCODING?JSON.parse(n.decode(d)):d,p={type:this.BROADCAST_EVENT,event:l,payload:f};return a>0&&(p.meta=JSON.parse(u)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){return e instanceof ArrayBuffer||e?.constructor?.name===`ArrayBuffer`}_pick(e,t){return!e||typeof e!=`object`?{}:Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e)))}},ci=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries+=1,this.callback()},this.timerCalc(this.tries+1))}},R;(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`})(R||={});var li=(e,t,n={})=>{let r=n.skipTypes??[];return t?Object.keys(t).reduce((n,i)=>(n[i]=ui(i,e,t,r),n),{}):{}},ui=(e,t,n,r)=>{let i=t.find(t=>t.name===e)?.type,a=n[e];return i&&!r.includes(i)?di(i,a):fi(a)},di=(e,t)=>{if(e.charAt(0)===`_`)return gi(t,e.slice(1,e.length));switch(e){case R.bool:return pi(t);case R.float4:case R.float8:case R.int2:case R.int4:case R.int8:case R.numeric:case R.oid:return mi(t);case R.json:case R.jsonb:return hi(t);case R.timestamp:return _i(t);case R.abstime:case R.date:case R.daterange:case R.int4range:case R.int8range:case R.money:case R.reltime:case R.text:case R.time:case R.timestamptz:case R.timetz:case R.tsrange:case R.tstzrange:return fi(t);default:return fi(t)}},fi=e=>e,pi=e=>{switch(e){case`t`:return!0;case`f`:return!1;default:return e}},mi=e=>{if(typeof e==`string`){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},hi=e=>{if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e},gi=(e,t)=>{if(typeof e!=`string`)return e;let n=e.length-1,r=e[n];if(e[0]===`{`&&r===`}`){let r,i=e.slice(1,n);try{r=JSON.parse(`[`+i+`]`)}catch{r=i?i.split(`,`):[]}return r.map(e=>di(t,e))}return e},_i=e=>typeof e==`string`?e.replace(` `,`T`):e,vi=e=>{let t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,`http`),t.pathname=t.pathname.replace(/\/+$/,``).replace(/\/socket\/websocket$/i,``).replace(/\/socket$/i,``).replace(/\/websocket$/i,``),t.pathname===``||t.pathname===`/`?t.pathname=`/api/broadcast`:t.pathname+=`/api/broadcast`,t.href},yi=class{constructor(e,t,n={},r=ri){this.channel=e,this.event=t,this.payload=n,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){return this._hasReceived(e)&&t(this.receivedResp?.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)}),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}},bi;(function(e){e.SYNC=`sync`,e.JOIN=`join`,e.LEAVE=`leave`})(bi||={});var xi=class e{constructor(t,n){this.channel=t,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let r=n?.events||{state:`presence_state`,diff:`presence_diff`};this.channel._on(r.state,{},t=>{let{onJoin:n,onLeave:r,onSync:i}=this.caller;this.joinRef=this.channel._joinRef(),this.state=e.syncState(this.state,t,n,r),this.pendingDiffs.forEach(t=>{this.state=e.syncDiff(this.state,t,n,r)}),this.pendingDiffs=[],i()}),this.channel._on(r.diff,{},t=>{let{onJoin:n,onLeave:r,onSync:i}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(t):(this.state=e.syncDiff(this.state,t,n,r),i())}),this.onJoin((e,t,n)=>{this.channel._trigger(`presence`,{event:`join`,key:e,currentPresences:t,newPresences:n})}),this.onLeave((e,t,n)=>{this.channel._trigger(`presence`,{event:`leave`,key:e,currentPresences:t,leftPresences:n})}),this.onSync(()=>{this.channel._trigger(`presence`,{event:`sync`})})}static syncState(e,t,n,r){let i=this.cloneDeep(e),a=this.transformState(t),o={},s={};return this.map(i,(e,t)=>{a[e]||(s[e]=t)}),this.map(a,(e,t)=>{let n=i[e];if(n){let r=t.map(e=>e.presence_ref),i=n.map(e=>e.presence_ref),a=t.filter(e=>i.indexOf(e.presence_ref)<0),c=n.filter(e=>r.indexOf(e.presence_ref)<0);a.length>0&&(o[e]=a),c.length>0&&(s[e]=c)}else o[e]=t}),this.syncDiff(i,{joins:o,leaves:s},n,r)}static syncDiff(e,t,n,r){let{joins:i,leaves:a}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return n||=()=>{},r||=()=>{},this.map(i,(t,r)=>{let i=e[t]??[];if(e[t]=this.cloneDeep(r),i.length>0){let n=e[t].map(e=>e.presence_ref),r=i.filter(e=>n.indexOf(e.presence_ref)<0);e[t].unshift(...r)}n(t,i,r)}),this.map(a,(t,n)=>{let i=e[t];if(!i)return;let a=n.map(e=>e.presence_ref);i=i.filter(e=>a.indexOf(e.presence_ref)<0),e[t]=i,r(t,i,n),i.length===0&&delete e[t]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(n=>t(n,e[n]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,n)=>{let r=e[n];return`metas`in r?t[n]=r.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):t[n]=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()}},Si;(function(e){e.ALL=`*`,e.INSERT=`INSERT`,e.UPDATE=`UPDATE`,e.DELETE=`DELETE`})(Si||={});var Ci;(function(e){e.BROADCAST=`broadcast`,e.PRESENCE=`presence`,e.POSTGRES_CHANGES=`postgres_changes`,e.SYSTEM=`system`})(Ci||={});var z;(function(e){e.SUBSCRIBED=`SUBSCRIBED`,e.TIMED_OUT=`TIMED_OUT`,e.CLOSED=`CLOSED`,e.CHANNEL_ERROR=`CHANNEL_ERROR`})(z||={});var wi=class e{constructor(e,t={config:{}},n){if(this.topic=e,this.params=t,this.socket=n,this.bindings={},this.state=I.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,``),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:``,enabled:!1},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new yi(this,L.join,this.params,this.timeout),this.rejoinTimer=new ci(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive(`ok`,()=>{this.state=I.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=I.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log(`channel`,`error ${this.topic}`,e),this.state=I.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive(`timeout`,()=>{this._isJoining()&&(this.socket.log(`channel`,`timeout ${this.topic}`,this.joinPush.timeout),this.state=I.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive(`error`,e=>{this._isLeaving()||this._isClosed()||(this.socket.log(`channel`,`error ${this.topic}`,e),this.state=I.errored,this.rejoinTimer.scheduleTimeout())}),this._on(L.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new xi(this),this.broadcastEndpointURL=vi(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&this.params.config?.broadcast?.replay)throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(t,n=this.timeout){if(this.socket.isConnected()||this.socket.connect(),this.state==I.closed){let{config:{broadcast:r,presence:i,private:a}}=this.params,o=this.bindings.postgres_changes?.map(e=>e.filter)??[],s=!!this.bindings[Ci.PRESENCE]&&this.bindings[Ci.PRESENCE].length>0||this.params.config.presence?.enabled===!0,c={},l={broadcast:r,presence:Object.assign(Object.assign({},i),{enabled:s}),postgres_changes:o,private:a};this.socket.accessTokenValue&&(c.access_token=this.socket.accessTokenValue),this._onError(e=>t?.(z.CHANNEL_ERROR,e)),this._onClose(()=>t?.(z.CLOSED)),this.updateJoinPayload(Object.assign({config:l},c)),this.joinedOnce=!0,this._rejoin(n),this.joinPush.receive(`ok`,async({postgres_changes:n})=>{if(this.socket._isManualToken()||this.socket.setAuth(),n===void 0){t?.(z.SUBSCRIBED);return}else{let r=this.bindings.postgres_changes,i=r?.length??0,a=[];for(let o=0;o<i;o++){let i=r[o],{filter:{event:s,schema:c,table:l,filter:u}}=i,d=n&&n[o];if(d&&d.event===s&&e.isFilterValueEqual(d.schema,c)&&e.isFilterValueEqual(d.table,l)&&e.isFilterValueEqual(d.filter,u))a.push(Object.assign(Object.assign({},i),{id:d.id}));else{this.unsubscribe(),this.state=I.errored,t?.(z.CHANNEL_ERROR,Error(`mismatch between server and client bindings for postgres changes`));return}}this.bindings.postgres_changes=a,t&&t(z.SUBSCRIBED);return}}).receive(`error`,e=>{this.state=I.errored,t?.(z.CHANNEL_ERROR,Error(JSON.stringify(Object.values(e).join(`, `)||`error`)))}).receive(`timeout`,()=>{t?.(z.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,n){return this.state===I.joined&&e===Ci.PRESENCE&&(this.socket.log(`channel`,`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,t,n)}async httpSend(e,t,n={}){if(t==null)return Promise.reject(`Payload is required for httpSend()`);let r={apikey:this.socket.apiKey?this.socket.apiKey:``,"Content-Type":`application/json`};this.socket.accessTokenValue&&(r.Authorization=`Bearer ${this.socket.accessTokenValue}`);let i={method:`POST`,headers:r,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,i,n.timeout??this.timeout);if(a.status===202)return{success:!0};let o=a.statusText;try{let e=await a.json();o=e.error||e.message||o}catch{}return Promise.reject(Error(o))}async send(e,t={}){if(!this._canPush()&&e.type===`broadcast`){console.warn(`Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.`);let{event:n,payload:r}=e,i={apikey:this.socket.apiKey?this.socket.apiKey:``,"Content-Type":`application/json`};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);let a={method:`POST`,headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:r,private:this.private}]})};try{let e=await this._fetchWithTimeout(this.broadcastEndpointURL,a,t.timeout??this.timeout);return await e.body?.cancel(),e.ok?`ok`:`error`}catch(e){return e.name===`AbortError`?`timed out`:`error`}}else return new Promise(n=>{let r=this._push(e.type,e,t.timeout||this.timeout);e.type===`broadcast`&&!this.params?.config?.broadcast?.ack&&n(`ok`),r.receive(`ok`,()=>n(`ok`)),r.receive(`error`,()=>n(`error`)),r.receive(`timeout`,()=>n(`timed out`))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=I.leaving;let t=()=>{this.socket.log(`channel`,`leave ${this.topic}`),this._trigger(L.close,`leave`,this._joinRef())};this.joinPush.destroy();let n=null;return new Promise(r=>{n=new yi(this,L.leave,{},e),n.receive(`ok`,()=>{t(),r(`ok`)}).receive(`timeout`,()=>{t(),r(`timed out`)}).receive(`error`,()=>{r(`error`)}),n.send(),this._canPush()||n.trigger(`ok`,{})}).finally(()=>{n?.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=I.closed,this.bindings={}}async _fetchWithTimeout(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),n),a=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(i),a}_push(e,t,n=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let r=new yi(this,e,t,n);return this._canPush()?r.send():this._addToPushBuffer(r),r}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>100){let e=this.pushBuffer.shift();e&&(e.destroy(),this.socket.log(`channel`,`discarded push due to buffer overflow: ${e.event}`,e.payload))}}_onMessage(e,t,n){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,n){var r,i;let a=e.toLocaleLowerCase(),{close:o,error:s,leave:c,join:l}=L;if(n&&[o,s,c,l].indexOf(a)>=0&&n!==this._joinRef())return;let u=this._onMessage(a,t,n);if(t&&!u)throw`channel onMessage callbacks must return the payload, modified or unmodified`;[`insert`,`update`,`delete`].includes(a)?(r=this.bindings.postgres_changes)==null||r.filter(e=>e.filter?.event===`*`||(e.filter?.event)?.toLocaleLowerCase()===a).map(e=>e.callback(u,n)):(i=this.bindings[a])==null||i.filter(e=>{if([`broadcast`,`presence`,`postgres_changes`].includes(a))if(`id`in e){let n=e.id,r=e.filter?.event;return n&&t.ids?.includes(n)&&(r===`*`||r?.toLocaleLowerCase()===t.data?.type.toLocaleLowerCase())}else{let n=(e?.filter?.event)?.toLocaleLowerCase();return n===`*`||n===(t?.event)?.toLocaleLowerCase()}else return e.type.toLocaleLowerCase()===a}).map(e=>{if(typeof u==`object`&&`ids`in u){let e=u.data,{schema:t,table:n,commit_timestamp:r,type:i,errors:a}=e;u=Object.assign(Object.assign({},{schema:t,table:n,commit_timestamp:r,eventType:i,new:{},old:{},errors:a}),this._getPayloadRecords(e))}e.callback(u,n)})}_isClosed(){return this.state===I.closed}_isJoined(){return this.state===I.joined}_isJoining(){return this.state===I.joining}_isLeaving(){return this.state===I.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,n){let r=e.toLocaleLowerCase(),i={type:r,filter:t,callback:n};return this.bindings[r]?this.bindings[r].push(i):this.bindings[r]=[i],this}_off(t,n){let r=t.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(t=>!(t.type?.toLocaleLowerCase()===r&&e.isEqual(t.filter,n)))),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}static isFilterValueEqual(e,t){return(e??void 0)===(t??void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(L.close,{},e)}_onError(e){this._on(L.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=I.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type===`INSERT`||e.type===`UPDATE`)&&(t.new=li(e.columns,e.record)),(e.type===`UPDATE`||e.type===`DELETE`)&&(t.old=li(e.columns,e.old_record)),t}},Ti=()=>{},Ei={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Di=[1e3,2e3,5e3,1e4],Oi=1e4,ki=`
97
+ new RealtimeClient(url, { transport: ws })`}}}return{type:`unsupported`,error:`Unknown JavaScript runtime without WebSocket support.`,workaround:`Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation.`}}static getWebSocketConstructor(){let e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||`WebSocket not supported in this environment.`;throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),Error(t)}static createWebSocket(e,t){return new(this.getWebSocketConstructor())(e,t)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type===`native`||e.type===`ws`}catch{return!1}}},ri=`realtime-js/2.99.3`,ii=`1.0.0`,ai=`2.0.0`,oi=ai,si=1e4,ci;(function(e){e[e.connecting=0]=`connecting`,e[e.open=1]=`open`,e[e.closing=2]=`closing`,e[e.closed=3]=`closed`})(ci||={});var I;(function(e){e.closed=`closed`,e.errored=`errored`,e.joined=`joined`,e.joining=`joining`,e.leaving=`leaving`})(I||={});var L;(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`})(L||={});var li;(function(e){e.websocket=`websocket`})(li||={});var ui;(function(e){e.Connecting=`connecting`,e.Open=`open`,e.Closing=`closing`,e.Closed=`closed`})(ui||={});var di=class{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT=`broadcast`,this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event==`string`)return t(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){return this._isArrayBuffer(e.payload?.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){let t=e.payload?.payload??new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,t)}_encodeJsonUserBroadcastPush(e){let t=e.payload?.payload??{},n=new TextEncoder().encode(JSON.stringify(t)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,n)}_encodeUserBroadcastPush(e,t,n){let r=e.topic,i=e.ref??``,a=e.join_ref??``,o=e.payload.event,s=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},c=Object.keys(s).length===0?``:JSON.stringify(s);if(a.length>255)throw Error(`joinRef length ${a.length} exceeds maximum of 255`);if(i.length>255)throw Error(`ref length ${i.length} exceeds maximum of 255`);if(r.length>255)throw Error(`topic length ${r.length} exceeds maximum of 255`);if(o.length>255)throw Error(`userEvent length ${o.length} exceeds maximum of 255`);if(c.length>255)throw Error(`metadata length ${c.length} exceeds maximum of 255`);let l=this.USER_BROADCAST_PUSH_META_LENGTH+a.length+i.length+r.length+o.length+c.length,u=new ArrayBuffer(this.HEADER_LENGTH+l),d=new DataView(u),f=0;d.setUint8(f++,this.KINDS.userBroadcastPush),d.setUint8(f++,a.length),d.setUint8(f++,i.length),d.setUint8(f++,r.length),d.setUint8(f++,o.length),d.setUint8(f++,c.length),d.setUint8(f++,t),Array.from(a,e=>d.setUint8(f++,e.charCodeAt(0))),Array.from(i,e=>d.setUint8(f++,e.charCodeAt(0))),Array.from(r,e=>d.setUint8(f++,e.charCodeAt(0))),Array.from(o,e=>d.setUint8(f++,e.charCodeAt(0))),Array.from(c,e=>d.setUint8(f++,e.charCodeAt(0)));var p=new Uint8Array(u.byteLength+n.byteLength);return p.set(new Uint8Array(u),0),p.set(new Uint8Array(n),u.byteLength),p.buffer}decode(e,t){if(this._isArrayBuffer(e))return t(this._binaryDecode(e));if(typeof e==`string`){let[n,r,i,a,o]=JSON.parse(e);return t({join_ref:n,ref:r,topic:i,event:a,payload:o})}return t({})}_binaryDecode(e){let t=new DataView(e),n=t.getUint8(0),r=new TextDecoder;switch(n){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,t,r)}}_decodeUserBroadcast(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=t.getUint8(3),o=t.getUint8(4),s=this.HEADER_LENGTH+4,c=n.decode(e.slice(s,s+r));s+=r;let l=n.decode(e.slice(s,s+i));s+=i;let u=n.decode(e.slice(s,s+a));s+=a;let d=e.slice(s,e.byteLength),f=o===this.JSON_ENCODING?JSON.parse(n.decode(d)):d,p={type:this.BROADCAST_EVENT,event:l,payload:f};return a>0&&(p.meta=JSON.parse(u)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){return e instanceof ArrayBuffer||e?.constructor?.name===`ArrayBuffer`}_pick(e,t){return!e||typeof e!=`object`?{}:Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e)))}},fi=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries+=1,this.callback()},this.timerCalc(this.tries+1))}},R;(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`})(R||={});var pi=(e,t,n={})=>{let r=n.skipTypes??[];return t?Object.keys(t).reduce((n,i)=>(n[i]=mi(i,e,t,r),n),{}):{}},mi=(e,t,n,r)=>{let i=t.find(t=>t.name===e)?.type,a=n[e];return i&&!r.includes(i)?hi(i,a):gi(a)},hi=(e,t)=>{if(e.charAt(0)===`_`)return bi(t,e.slice(1,e.length));switch(e){case R.bool:return _i(t);case R.float4:case R.float8:case R.int2:case R.int4:case R.int8:case R.numeric:case R.oid:return vi(t);case R.json:case R.jsonb:return yi(t);case R.timestamp:return xi(t);case R.abstime:case R.date:case R.daterange:case R.int4range:case R.int8range:case R.money:case R.reltime:case R.text:case R.time:case R.timestamptz:case R.timetz:case R.tsrange:case R.tstzrange:return gi(t);default:return gi(t)}},gi=e=>e,_i=e=>{switch(e){case`t`:return!0;case`f`:return!1;default:return e}},vi=e=>{if(typeof e==`string`){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},yi=e=>{if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e},bi=(e,t)=>{if(typeof e!=`string`)return e;let n=e.length-1,r=e[n];if(e[0]===`{`&&r===`}`){let r,i=e.slice(1,n);try{r=JSON.parse(`[`+i+`]`)}catch{r=i?i.split(`,`):[]}return r.map(e=>hi(t,e))}return e},xi=e=>typeof e==`string`?e.replace(` `,`T`):e,Si=e=>{let t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,`http`),t.pathname=t.pathname.replace(/\/+$/,``).replace(/\/socket\/websocket$/i,``).replace(/\/socket$/i,``).replace(/\/websocket$/i,``),t.pathname===``||t.pathname===`/`?t.pathname=`/api/broadcast`:t.pathname+=`/api/broadcast`,t.href},Ci=class{constructor(e,t,n={},r=si){this.channel=e,this.event=t,this.payload=n,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){return this._hasReceived(e)&&t(this.receivedResp?.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)}),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}},wi;(function(e){e.SYNC=`sync`,e.JOIN=`join`,e.LEAVE=`leave`})(wi||={});var Ti=class e{constructor(t,n){this.channel=t,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let r=n?.events||{state:`presence_state`,diff:`presence_diff`};this.channel._on(r.state,{},t=>{let{onJoin:n,onLeave:r,onSync:i}=this.caller;this.joinRef=this.channel._joinRef(),this.state=e.syncState(this.state,t,n,r),this.pendingDiffs.forEach(t=>{this.state=e.syncDiff(this.state,t,n,r)}),this.pendingDiffs=[],i()}),this.channel._on(r.diff,{},t=>{let{onJoin:n,onLeave:r,onSync:i}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(t):(this.state=e.syncDiff(this.state,t,n,r),i())}),this.onJoin((e,t,n)=>{this.channel._trigger(`presence`,{event:`join`,key:e,currentPresences:t,newPresences:n})}),this.onLeave((e,t,n)=>{this.channel._trigger(`presence`,{event:`leave`,key:e,currentPresences:t,leftPresences:n})}),this.onSync(()=>{this.channel._trigger(`presence`,{event:`sync`})})}static syncState(e,t,n,r){let i=this.cloneDeep(e),a=this.transformState(t),o={},s={};return this.map(i,(e,t)=>{a[e]||(s[e]=t)}),this.map(a,(e,t)=>{let n=i[e];if(n){let r=t.map(e=>e.presence_ref),i=n.map(e=>e.presence_ref),a=t.filter(e=>i.indexOf(e.presence_ref)<0),c=n.filter(e=>r.indexOf(e.presence_ref)<0);a.length>0&&(o[e]=a),c.length>0&&(s[e]=c)}else o[e]=t}),this.syncDiff(i,{joins:o,leaves:s},n,r)}static syncDiff(e,t,n,r){let{joins:i,leaves:a}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return n||=()=>{},r||=()=>{},this.map(i,(t,r)=>{let i=e[t]??[];if(e[t]=this.cloneDeep(r),i.length>0){let n=e[t].map(e=>e.presence_ref),r=i.filter(e=>n.indexOf(e.presence_ref)<0);e[t].unshift(...r)}n(t,i,r)}),this.map(a,(t,n)=>{let i=e[t];if(!i)return;let a=n.map(e=>e.presence_ref);i=i.filter(e=>a.indexOf(e.presence_ref)<0),e[t]=i,r(t,i,n),i.length===0&&delete e[t]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(n=>t(n,e[n]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,n)=>{let r=e[n];return`metas`in r?t[n]=r.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):t[n]=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()}},Ei;(function(e){e.ALL=`*`,e.INSERT=`INSERT`,e.UPDATE=`UPDATE`,e.DELETE=`DELETE`})(Ei||={});var Di;(function(e){e.BROADCAST=`broadcast`,e.PRESENCE=`presence`,e.POSTGRES_CHANGES=`postgres_changes`,e.SYSTEM=`system`})(Di||={});var z;(function(e){e.SUBSCRIBED=`SUBSCRIBED`,e.TIMED_OUT=`TIMED_OUT`,e.CLOSED=`CLOSED`,e.CHANNEL_ERROR=`CHANNEL_ERROR`})(z||={});var Oi=class e{constructor(e,t={config:{}},n){if(this.topic=e,this.params=t,this.socket=n,this.bindings={},this.state=I.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,``),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:``,enabled:!1},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new Ci(this,L.join,this.params,this.timeout),this.rejoinTimer=new fi(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive(`ok`,()=>{this.state=I.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=I.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log(`channel`,`error ${this.topic}`,e),this.state=I.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive(`timeout`,()=>{this._isJoining()&&(this.socket.log(`channel`,`timeout ${this.topic}`,this.joinPush.timeout),this.state=I.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive(`error`,e=>{this._isLeaving()||this._isClosed()||(this.socket.log(`channel`,`error ${this.topic}`,e),this.state=I.errored,this.rejoinTimer.scheduleTimeout())}),this._on(L.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new Ti(this),this.broadcastEndpointURL=Si(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&this.params.config?.broadcast?.replay)throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(t,n=this.timeout){if(this.socket.isConnected()||this.socket.connect(),this.state==I.closed){let{config:{broadcast:r,presence:i,private:a}}=this.params,o=this.bindings.postgres_changes?.map(e=>e.filter)??[],s=!!this.bindings[Di.PRESENCE]&&this.bindings[Di.PRESENCE].length>0||this.params.config.presence?.enabled===!0,c={},l={broadcast:r,presence:Object.assign(Object.assign({},i),{enabled:s}),postgres_changes:o,private:a};this.socket.accessTokenValue&&(c.access_token=this.socket.accessTokenValue),this._onError(e=>t?.(z.CHANNEL_ERROR,e)),this._onClose(()=>t?.(z.CLOSED)),this.updateJoinPayload(Object.assign({config:l},c)),this.joinedOnce=!0,this._rejoin(n),this.joinPush.receive(`ok`,async({postgres_changes:n})=>{if(this.socket._isManualToken()||this.socket.setAuth(),n===void 0){t?.(z.SUBSCRIBED);return}else{let r=this.bindings.postgres_changes,i=r?.length??0,a=[];for(let o=0;o<i;o++){let i=r[o],{filter:{event:s,schema:c,table:l,filter:u}}=i,d=n&&n[o];if(d&&d.event===s&&e.isFilterValueEqual(d.schema,c)&&e.isFilterValueEqual(d.table,l)&&e.isFilterValueEqual(d.filter,u))a.push(Object.assign(Object.assign({},i),{id:d.id}));else{this.unsubscribe(),this.state=I.errored,t?.(z.CHANNEL_ERROR,Error(`mismatch between server and client bindings for postgres changes`));return}}this.bindings.postgres_changes=a,t&&t(z.SUBSCRIBED);return}}).receive(`error`,e=>{this.state=I.errored,t?.(z.CHANNEL_ERROR,Error(JSON.stringify(Object.values(e).join(`, `)||`error`)))}).receive(`timeout`,()=>{t?.(z.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,n){return this.state===I.joined&&e===Di.PRESENCE&&(this.socket.log(`channel`,`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,t,n)}async httpSend(e,t,n={}){if(t==null)return Promise.reject(`Payload is required for httpSend()`);let r={apikey:this.socket.apiKey?this.socket.apiKey:``,"Content-Type":`application/json`};this.socket.accessTokenValue&&(r.Authorization=`Bearer ${this.socket.accessTokenValue}`);let i={method:`POST`,headers:r,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,i,n.timeout??this.timeout);if(a.status===202)return{success:!0};let o=a.statusText;try{let e=await a.json();o=e.error||e.message||o}catch{}return Promise.reject(Error(o))}async send(e,t={}){if(!this._canPush()&&e.type===`broadcast`){console.warn(`Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.`);let{event:n,payload:r}=e,i={apikey:this.socket.apiKey?this.socket.apiKey:``,"Content-Type":`application/json`};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);let a={method:`POST`,headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:r,private:this.private}]})};try{let e=await this._fetchWithTimeout(this.broadcastEndpointURL,a,t.timeout??this.timeout);return await e.body?.cancel(),e.ok?`ok`:`error`}catch(e){return e.name===`AbortError`?`timed out`:`error`}}else return new Promise(n=>{let r=this._push(e.type,e,t.timeout||this.timeout);e.type===`broadcast`&&!this.params?.config?.broadcast?.ack&&n(`ok`),r.receive(`ok`,()=>n(`ok`)),r.receive(`error`,()=>n(`error`)),r.receive(`timeout`,()=>n(`timed out`))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=I.leaving;let t=()=>{this.socket.log(`channel`,`leave ${this.topic}`),this._trigger(L.close,`leave`,this._joinRef())};this.joinPush.destroy();let n=null;return new Promise(r=>{n=new Ci(this,L.leave,{},e),n.receive(`ok`,()=>{t(),r(`ok`)}).receive(`timeout`,()=>{t(),r(`timed out`)}).receive(`error`,()=>{r(`error`)}),n.send(),this._canPush()||n.trigger(`ok`,{})}).finally(()=>{n?.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=I.closed,this.bindings={}}async _fetchWithTimeout(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),n),a=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(i),a}_push(e,t,n=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let r=new Ci(this,e,t,n);return this._canPush()?r.send():this._addToPushBuffer(r),r}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>100){let e=this.pushBuffer.shift();e&&(e.destroy(),this.socket.log(`channel`,`discarded push due to buffer overflow: ${e.event}`,e.payload))}}_onMessage(e,t,n){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,n){var r,i;let a=e.toLocaleLowerCase(),{close:o,error:s,leave:c,join:l}=L;if(n&&[o,s,c,l].indexOf(a)>=0&&n!==this._joinRef())return;let u=this._onMessage(a,t,n);if(t&&!u)throw`channel onMessage callbacks must return the payload, modified or unmodified`;[`insert`,`update`,`delete`].includes(a)?(r=this.bindings.postgres_changes)==null||r.filter(e=>e.filter?.event===`*`||(e.filter?.event)?.toLocaleLowerCase()===a).map(e=>e.callback(u,n)):(i=this.bindings[a])==null||i.filter(e=>{if([`broadcast`,`presence`,`postgres_changes`].includes(a))if(`id`in e){let n=e.id,r=e.filter?.event;return n&&t.ids?.includes(n)&&(r===`*`||r?.toLocaleLowerCase()===t.data?.type.toLocaleLowerCase())}else{let n=(e?.filter?.event)?.toLocaleLowerCase();return n===`*`||n===(t?.event)?.toLocaleLowerCase()}else return e.type.toLocaleLowerCase()===a}).map(e=>{if(typeof u==`object`&&`ids`in u){let e=u.data,{schema:t,table:n,commit_timestamp:r,type:i,errors:a}=e;u=Object.assign(Object.assign({},{schema:t,table:n,commit_timestamp:r,eventType:i,new:{},old:{},errors:a}),this._getPayloadRecords(e))}e.callback(u,n)})}_isClosed(){return this.state===I.closed}_isJoined(){return this.state===I.joined}_isJoining(){return this.state===I.joining}_isLeaving(){return this.state===I.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,n){let r=e.toLocaleLowerCase(),i={type:r,filter:t,callback:n};return this.bindings[r]?this.bindings[r].push(i):this.bindings[r]=[i],this}_off(t,n){let r=t.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(t=>!(t.type?.toLocaleLowerCase()===r&&e.isEqual(t.filter,n)))),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}static isFilterValueEqual(e,t){return(e??void 0)===(t??void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(L.close,{},e)}_onError(e){this._on(L.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=I.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type===`INSERT`||e.type===`UPDATE`)&&(t.new=pi(e.columns,e.record)),(e.type===`UPDATE`||e.type===`DELETE`)&&(t.old=pi(e.columns,e.old_record)),t}},ki=()=>{},Ai={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},ji=[1e3,2e3,5e3,1e4],Mi=1e4,Ni=`
98
98
  addEventListener("message", (e) => {
99
99
  if (e.data.event === "start") {
100
100
  setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
101
101
  }
102
- });`,Ai=class{constructor(e,t){if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=[],this.endPoint=``,this.httpEndpoint=``,this.headers={},this.params={},this.timeout=ri,this.transport=null,this.heartbeatIntervalMs=Ei.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Ti,this.ref=0,this.reconnectTimer=null,this.vsn=ni,this.logger=Ti,this.conn=null,this.sendBuffer=[],this.serializer=new si,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState=`disconnected`,this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!t?.params?.apikey)throw Error(`API key is required to connect to Realtime`);this.apiKey=t.params.apikey,this.endPoint=`${e}/${ai.websocket}`,this.httpEndpoint=vi(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState(`connecting`),this.accessToken&&!this._authPromise&&this._setAuthSafely(`connect`),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=Qr.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState(`disconnected`);let t=e.message;throw t.includes(`Node.js`)?Error(`${t}\n\nTo use Realtime in Node.js, you need to provide a WebSocket implementation:
102
+ });`,Pi=class{constructor(e,t){if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=[],this.endPoint=``,this.httpEndpoint=``,this.headers={},this.params={},this.timeout=si,this.transport=null,this.heartbeatIntervalMs=Ai.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=ki,this.ref=0,this.reconnectTimer=null,this.vsn=oi,this.logger=ki,this.conn=null,this.sendBuffer=[],this.serializer=new di,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState=`disconnected`,this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!t?.params?.apikey)throw Error(`API key is required to connect to Realtime`);this.apiKey=t.params.apikey,this.endPoint=`${e}/${li.websocket}`,this.httpEndpoint=Si(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState(`connecting`),this.accessToken&&!this._authPromise&&this._setAuthSafely(`connect`),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=ni.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState(`disconnected`);let t=e.message;throw t.includes(`Node.js`)?Error(`${t}\n\nTo use Realtime in Node.js, you need to provide a WebSocket implementation:
103
103
 
104
104
  Option 1: Use Node.js 22+ which has native WebSocket support
105
105
  Option 2: Install and provide the "ws" package:
@@ -110,8 +110,8 @@ Option 2: Install and provide the "ws" package:
110
110
  const client = new RealtimeClient(url, {
111
111
  ...options,
112
112
  transport: ws
113
- })`):Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState(`disconnecting`,!0),this.conn){let n=setTimeout(()=>{this._setConnectionState(`disconnected`)},100);this.conn.onclose=()=>{clearTimeout(n),this._setConnectionState(`disconnected`)},typeof this.conn.close==`function`&&(e?this.conn.close(e,t??``):this.conn.close()),this._teardownConnection()}else this._setConnectionState(`disconnected`)}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(e=>e.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,n){this.logger(e,t,n)}connectionState(){switch(this.conn&&this.conn.readyState){case ii.connecting:return oi.Connecting;case ii.open:return oi.Open;case ii.closing:return oi.Closing;default:return oi.Closed}}isConnected(){return this.connectionState()===oi.Open}isConnecting(){return this._connectionState===`connecting`}isDisconnecting(){return this._connectionState===`disconnecting`}channel(e,t={config:{}}){let n=`realtime:${e}`,r=this.getChannels().find(e=>e.topic===n);if(r)return r;{let n=new wi(`realtime:${e}`,t,this);return this.channels.push(n),n}}push(e){let{topic:t,event:n,payload:r,ref:i}=e,a=()=>{this.encode(e,e=>{var t;(t=this.conn)==null||t.send(e)})};this.log(`push`,`${t} ${n} (${i})`,r),this.isConnected()?a():this.sendBuffer.push(a)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback(`disconnected`)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log(`transport`,`heartbeat timeout. Attempting to re-establish connection`);try{this.heartbeatCallback(`timeout`)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}this._wasManualDisconnect=!1,(e=this.conn)==null||e.close(1e3,`heartbeat timeout`),setTimeout(()=>{var e;this.isConnected()||(e=this.reconnectTimer)==null||e.scheduleTimeout()},Ei.HEARTBEAT_TIMEOUT_FALLBACK);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:`phoenix`,event:`heartbeat`,payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback(`sent`)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}this._setAuthSafely(`heartbeat`)}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log(`transport`,`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,e=>{if(e.topic===`phoenix`&&e.event===`phx_reply`&&e.ref&&e.ref===this.pendingHeartbeatRef){let t=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback(e.payload.status===`ok`?`ok`:`error`,t)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}let{topic:t,event:n,payload:r,ref:i}=e,a=i?`(${i})`:``,o=r.status||``;this.log(`receive`,`${o} ${t} ${n} ${a}`.trim(),r),this.channels.filter(e=>e._isMember(t)).forEach(e=>e._trigger(n,r,i)),this._triggerStateCallbacks(`message`,e)})}_clearTimer(e){var t;e===`heartbeat`&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e===`reconnect`&&((t=this.reconnectTimer)==null||t.reset())}_clearAllTimers(){this._clearTimer(`heartbeat`),this._clearTimer(`reconnect`)}_setupConnectionHandlers(){this.conn&&(`binaryType`in this.conn&&(this.conn.binaryType=`arraybuffer`),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e),this.conn.readyState===ii.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===ii.open||this.conn.readyState===ii.connecting)try{this.conn.close()}catch(e){this.log(`error`,`Error closing connection`,e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState(`connected`),this.log(`transport`,`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.accessTokenValue&&(this.channels.forEach(e=>{e.updateJoinPayload({access_token:this.accessTokenValue})}),this.sendBuffer=[],this.channels.forEach(e=>{e._isJoining()&&(e.joinPush.sent=!1,e.joinPush.send())})),this.flushSendBuffer()}).catch(e=>{this.log(`error`,`error waiting for auth on connect`,e),this.flushSendBuffer()}),this._clearTimer(`reconnect`),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks(`open`)}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log(`worker`,`starting worker for from ${this.workerUrl}`):this.log(`worker`,`starting default worker`);let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log(`worker`,`worker error`,e.message),this._terminateWorker()},this.workerRef.onmessage=e=>{e.data.event===`keepAlive`&&this.sendHeartbeat()},this.workerRef.postMessage({event:`start`,interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&=(this.log(`worker`,`terminating worker`),this.workerRef.terminate(),void 0)}_onConnClose(e){var t;this._setConnectionState(`disconnected`),this.log(`transport`,`close`,e),this._triggerChanError(),this._clearTimer(`heartbeat`),this._wasManualDisconnect||(t=this.reconnectTimer)==null||t.scheduleTimeout(),this._triggerStateCallbacks(`close`,e)}_onConnError(e){this._setConnectionState(`disconnected`),this.log(`transport`,`${e}`),this._triggerChanError(),this._triggerStateCallbacks(`error`,e);try{this.heartbeatCallback(`error`)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}}_triggerChanError(){this.channels.forEach(e=>e._trigger(L.error))}_appendParams(e,t){return Object.keys(t).length===0?e:`${e}${e.match(/\?/)?`&`:`?`}${new URLSearchParams(t)}`}_workerObjectUrl(e){let t;if(e)t=e;else{let e=new Blob([ki],{type:`application/javascript`});t=URL.createObjectURL(e)}return t}_setConnectionState(e,t=!1){this._connectionState=e,e===`connecting`?this._wasManualDisconnect=!1:e===`disconnecting`&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t,n=!1;if(e)t=e,n=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(e){this.log(`error`,`Error fetching access token from callback`,e),t=this.accessTokenValue}else t=this.accessTokenValue;n?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{let n={access_token:t,version:$r};t&&e.updateJoinPayload(n),e.joinedOnce&&e._isJoined()&&e._push(L.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e=`general`){this._isManualToken()||this.setAuth().catch(t=>{this.log(`error`,`Error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(n=>{try{n(t)}catch(t){this.log(`error`,`error in ${e} callback`,t)}})}catch(t){this.log(`error`,`error triggering ${e} callbacks`,t)}}_setupReconnectionTimer(){this.reconnectTimer=new ci(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},Ei.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){switch(this.transport=e?.transport??null,this.timeout=e?.timeout??ri,this.heartbeatIntervalMs=e?.heartbeatIntervalMs??Ei.HEARTBEAT_INTERVAL,this.worker=e?.worker??!1,this.accessToken=e?.accessToken??null,this.heartbeatCallback=e?.heartbeatCallback??Ti,this.vsn=e?.vsn??ni,e?.params&&(this.params=e.params),e?.logger&&(this.logger=e.logger),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=e?.reconnectAfterMs??(e=>Di[e-1]||Oi),this.vsn){case ei:this.encode=e?.encode??((e,t)=>t(JSON.stringify(e))),this.decode=e?.decode??((e,t)=>t(JSON.parse(e)));break;case ti:this.encode=e?.encode??this.serializer.encode.bind(this.serializer),this.decode=e?.decode??this.serializer.decode.bind(this.serializer);break;default:throw Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<`u`&&!window.Worker)throw Error(`Web Worker is not supported`);this.workerUrl=e?.workerUrl}}},ji=class extends Error{constructor(e,t){super(e),this.name=`IcebergError`,this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown=t.icebergType===`CommitStateUnknownException`||[500,502,504].includes(t.status)&&t.icebergType?.includes(`CommitState`)===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function Mi(e,t,n){let r=new URL(t,e);if(n)for(let[e,t]of Object.entries(n))t!==void 0&&r.searchParams.set(e,t);return r.toString()}async function Ni(e){return!e||e.type===`none`?{}:e.type===`bearer`?{Authorization:`Bearer ${e.token}`}:e.type===`header`?{[e.name]:e.value}:e.type===`custom`?await e.getHeaders():{}}function Pi(e){let t=e.fetchImpl??globalThis.fetch;return{async request({method:n,path:r,query:i,body:a,headers:o}){let s=Mi(e.baseUrl,r,i),c=await Ni(e.auth),l=await t(s,{method:n,headers:{...a?{"Content-Type":`application/json`}:{},...c,...o},body:a?JSON.stringify(a):void 0}),u=await l.text(),d=(l.headers.get(`content-type`)||``).includes(`application/json`),f=d&&u?JSON.parse(u):u;if(!l.ok){let e=d?f:void 0,t=e?.error;throw new ji(t?.message??`Request failed with status ${l.status}`,{status:l.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:l.status,headers:l.headers,data:f}}}}function Fi(e){return e.join(``)}var Ii=class{constructor(e,t=``){this.client=e,this.prefix=t}async listNamespaces(e){let t=e?{parent:Fi(e.namespace)}:void 0;return(await this.client.request({method:`GET`,path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(e=>({namespace:e}))}async createNamespace(e,t){let n={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:`POST`,path:`${this.prefix}/namespaces`,body:n})).data}async dropNamespace(e){await this.client.request({method:`DELETE`,path:`${this.prefix}/namespaces/${Fi(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:`GET`,path:`${this.prefix}/namespaces/${Fi(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:`HEAD`,path:`${this.prefix}/namespaces/${Fi(e.namespace)}`}),!0}catch(e){if(e instanceof ji&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof ji&&e.status===409)return;throw e}}};function Li(e){return e.join(``)}var Ri=class{constructor(e,t=``,n){this.client=e,this.prefix=t,this.accessDelegation=n}async listTables(e){return(await this.client.request({method:`GET`,path:`${this.prefix}/namespaces/${Li(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){let n={};return this.accessDelegation&&(n[`X-Iceberg-Access-Delegation`]=this.accessDelegation),(await this.client.request({method:`POST`,path:`${this.prefix}/namespaces/${Li(e.namespace)}/tables`,body:t,headers:n})).data.metadata}async updateTable(e,t){let n=await this.client.request({method:`POST`,path:`${this.prefix}/namespaces/${Li(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":n.data[`metadata-location`],metadata:n.data.metadata}}async dropTable(e,t){await this.client.request({method:`DELETE`,path:`${this.prefix}/namespaces/${Li(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){let t={};return this.accessDelegation&&(t[`X-Iceberg-Access-Delegation`]=this.accessDelegation),(await this.client.request({method:`GET`,path:`${this.prefix}/namespaces/${Li(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){let t={};this.accessDelegation&&(t[`X-Iceberg-Access-Delegation`]=this.accessDelegation);try{return await this.client.request({method:`HEAD`,path:`${this.prefix}/namespaces/${Li(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof ji&&e.status===404)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(n){if(n instanceof ji&&n.status===409)return await this.loadTable({namespace:e.namespace,name:t.name});throw n}}},zi=class{constructor(e){let t=`v1`;e.catalogName&&(t+=`/${e.catalogName}`),this.client=Pi({baseUrl:e.baseUrl.endsWith(`/`)?e.baseUrl:`${e.baseUrl}/`,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(`,`),this.namespaceOps=new Ii(this.client,t),this.tableOps=new Ri(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}},Bi=class extends Error{constructor(e,t=`storage`,n,r){super(e),this.__isStorageError=!0,this.namespace=t,this.name=t===`vectors`?`StorageVectorsError`:`StorageError`,this.status=n,this.statusCode=r}};function Vi(e){return typeof e==`object`&&!!e&&`__isStorageError`in e}var Hi=class extends Bi{constructor(e,t,n,r=`storage`){super(e,r,t,n),this.name=r===`vectors`?`StorageVectorsApiError`:`StorageApiError`,this.status=t,this.statusCode=n}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},Ui=class extends Bi{constructor(e,t,n=`storage`){super(e,n),this.name=n===`vectors`?`StorageVectorsUnknownError`:`StorageUnknownError`,this.originalError=t}},Wi=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Gi=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},Ki=e=>{if(Array.isArray(e))return e.map(e=>Ki(e));if(typeof e==`function`||e!==Object(e))return e;let t={};return Object.entries(e).forEach(([e,n])=>{let r=e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,``));t[r]=Ki(n)}),t},qi=e=>!e||typeof e!=`string`||e.length===0||e.length>100||e.trim()!==e||e.includes(`/`)||e.includes(`\\`)?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(e);function Ji(e){"@babel/helpers - typeof";return Ji=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},Ji(e)}function Yi(e,t){if(Ji(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(Ji(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Xi(e){var t=Yi(e,`string`);return Ji(t)==`symbol`?t:t+``}function Zi(e,t,n){return(t=Xi(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Qi(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function B(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Qi(Object(n),!0).forEach(function(t){Zi(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Qi(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var $i=e=>e.msg||e.message||e.error_description||(typeof e.error==`string`?e.error:e.error?.message)||JSON.stringify(e),ea=async(e,t,n,r)=>{if(typeof e==`object`&&e&&typeof e.json==`function`){let n=e,i=parseInt(n.status,10);Number.isFinite(i)||(i=500),n.json().then(e=>{let n=e?.statusCode||e?.code||i+``;t(new Hi($i(e),i,n,r))}).catch(()=>{let e=i+``;t(new Hi(n.statusText||`HTTP ${i} error`,i,e,r))})}else t(new Ui($i(e),e,r))},ta=(e,t,n,r)=>{let i={method:e,headers:t?.headers||{}};return e===`GET`||e===`HEAD`||!r?B(B({},i),n):(Gi(r)?(i.headers=B({"Content-Type":`application/json`},t?.headers),i.body=JSON.stringify(r)):i.body=r,t?.duplex&&(i.duplex=t.duplex),B(B({},i),n))};async function na(e,t,n,r,i,a,o){return new Promise((s,c)=>{e(n,ta(t,r,i,a)).then(e=>{if(!e.ok)throw e;if(r?.noResolveJson)return e;if(o===`vectors`){let t=e.headers.get(`content-type`);if(e.headers.get(`content-length`)===`0`||e.status===204||!t||!t.includes(`application/json`))return{}}return e.json()}).then(e=>s(e)).catch(e=>ea(e,c,r,o))})}function ra(e=`storage`){return{get:async(t,n,r,i)=>na(t,`GET`,n,r,i,void 0,e),post:async(t,n,r,i,a)=>na(t,`POST`,n,i,a,r,e),put:async(t,n,r,i,a)=>na(t,`PUT`,n,i,a,r,e),head:async(t,n,r,i)=>na(t,`HEAD`,n,B(B({},r),{},{noResolveJson:!0}),i,void 0,e),remove:async(t,n,r,i,a)=>na(t,`DELETE`,n,i,a,r,e)}}var{get:ia,post:V,put:aa,head:oa,remove:sa}=ra(`storage`),H=ra(`vectors`),ca=class{constructor(e,t={},n,r=`storage`){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.fetch=Wi(n),this.namespace=r}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=B(B({},this.headers),{},{[e]:t}),this}async handleOperation(e){var t=this;try{return{data:await e(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Vi(e))return{data:null,error:e};throw e}}},la=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}async execute(){var e=this;try{return{data:(await e.downloadFn()).body,error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Vi(t))return{data:null,error:t};throw t}}},ua=Symbol.toStringTag,da=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[ua]=`BlobDownloadBuilder`,this.promise=null}asStream(){return new la(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||=this.execute(),this.promise}async execute(){var e=this;try{return{data:await(await e.downloadFn()).blob(),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Vi(t))return{data:null,error:t};throw t}}},fa={limit:100,offset:0,sortBy:{column:`name`,order:`asc`}},pa={cacheControl:`3600`,contentType:`text/plain;charset=UTF-8`,upsert:!1},ma=class extends ca{constructor(e,t={},n,r){super(e,t,r,`storage`),this.bucketId=n}async uploadOrUpdate(e,t,n,r){var i=this;return i.handleOperation(async()=>{let a,o=B(B({},pa),r),s=B(B({},i.headers),e===`POST`&&{"x-upsert":String(o.upsert)}),c=o.metadata;typeof Blob<`u`&&n instanceof Blob?(a=new FormData,a.append(`cacheControl`,o.cacheControl),c&&a.append(`metadata`,i.encodeMetadata(c)),a.append(``,n)):typeof FormData<`u`&&n instanceof FormData?(a=n,a.has(`cacheControl`)||a.append(`cacheControl`,o.cacheControl),c&&!a.has(`metadata`)&&a.append(`metadata`,i.encodeMetadata(c))):(a=n,s[`cache-control`]=`max-age=${o.cacheControl}`,s[`content-type`]=o.contentType,c&&(s[`x-metadata`]=i.toBase64(i.encodeMetadata(c))),(typeof ReadableStream<`u`&&a instanceof ReadableStream||a&&typeof a==`object`&&`pipe`in a&&typeof a.pipe==`function`)&&!o.duplex&&(o.duplex=`half`)),r?.headers&&(s=B(B({},s),r.headers));let l=i._removeEmptyFolders(t),u=i._getFinalPath(l),d=await(e==`PUT`?aa:V)(i.fetch,`${i.url}/object/${u}`,a,B({headers:s},o?.duplex?{duplex:o.duplex}:{}));return{path:l,id:d.Id,fullPath:d.Key}})}async upload(e,t,n){return this.uploadOrUpdate(`POST`,e,t,n)}async uploadToSignedUrl(e,t,n,r){var i=this;let a=i._removeEmptyFolders(e),o=i._getFinalPath(a),s=new URL(i.url+`/object/upload/sign/${o}`);return s.searchParams.set(`token`,t),i.handleOperation(async()=>{let e,t=B({upsert:pa.upsert},r),o=B(B({},i.headers),{"x-upsert":String(t.upsert)});return typeof Blob<`u`&&n instanceof Blob?(e=new FormData,e.append(`cacheControl`,t.cacheControl),e.append(``,n)):typeof FormData<`u`&&n instanceof FormData?(e=n,e.append(`cacheControl`,t.cacheControl)):(e=n,o[`cache-control`]=`max-age=${t.cacheControl}`,o[`content-type`]=t.contentType),{path:a,fullPath:(await aa(i.fetch,s.toString(),e,{headers:o})).Key}})}async createSignedUploadUrl(e,t){var n=this;return n.handleOperation(async()=>{let r=n._getFinalPath(e),i=B({},n.headers);t?.upsert&&(i[`x-upsert`]=`true`);let a=await V(n.fetch,`${n.url}/object/upload/sign/${r}`,{},{headers:i}),o=new URL(n.url+a.url),s=o.searchParams.get(`token`);if(!s)throw new Bi(`No token returned by API`);return{signedUrl:o.toString(),path:e,token:s}})}async update(e,t,n){return this.uploadOrUpdate(`PUT`,e,t,n)}async move(e,t,n){var r=this;return r.handleOperation(async()=>await V(r.fetch,`${r.url}/object/move`,{bucketId:r.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n?.destinationBucket},{headers:r.headers}))}async copy(e,t,n){var r=this;return r.handleOperation(async()=>({path:(await V(r.fetch,`${r.url}/object/copy`,{bucketId:r.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n?.destinationBucket},{headers:r.headers})).Key}))}async createSignedUrl(e,t,n){var r=this;return r.handleOperation(async()=>{let i=r._getFinalPath(e),a=typeof n?.transform==`object`&&n.transform!==null&&Object.keys(n.transform).length>0,o=await V(r.fetch,`${r.url}/object/sign/${i}`,B({expiresIn:t},a?{transform:n.transform}:{}),{headers:r.headers}),s=n?.download?`&download=${n.download===!0?``:n.download}`:``,c=a&&o.signedURL.includes(`/object/sign/`)?o.signedURL.replace(`/object/sign/`,`/render/image/sign/`):o.signedURL;return{signedUrl:encodeURI(`${r.url}${c}${s}`)}})}async createSignedUrls(e,t,n){var r=this;return r.handleOperation(async()=>{let i=await V(r.fetch,`${r.url}/object/sign/${r.bucketId}`,{expiresIn:t,paths:e},{headers:r.headers}),a=n?.download?`&download=${n.download===!0?``:n.download}`:``;return i.map(e=>B(B({},e),{},{signedUrl:e.signedURL?encodeURI(`${r.url}${e.signedURL}${a}`):null}))})}download(e,t,n){let r=t?.transform===void 0?`object`:`render/image/authenticated`,i=this.transformOptsToQueryString(t?.transform||{}),a=i?`?${i}`:``,o=this._getFinalPath(e);return new da(()=>ia(this.fetch,`${this.url}/${r}/${o}${a}`,{headers:this.headers,noResolveJson:!0},n),this.shouldThrowOnError)}async info(e){var t=this;let n=t._getFinalPath(e);return t.handleOperation(async()=>Ki(await ia(t.fetch,`${t.url}/object/info/${n}`,{headers:t.headers})))}async exists(e){var t=this;let n=t._getFinalPath(e);try{return await oa(t.fetch,`${t.url}/object/${n}`,{headers:t.headers}),{data:!0,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Vi(e)){let t=e instanceof Hi?e.status:e instanceof Ui?e.originalError?.status:void 0;if(t!==void 0&&[400,404].includes(t))return{data:!1,error:e}}throw e}}getPublicUrl(e,t){let n=this._getFinalPath(e),r=[],i=t?.download?`download=${t.download===!0?``:t.download}`:``;i!==``&&r.push(i);let a=t?.transform===void 0?`object`:`render/image`,o=this.transformOptsToQueryString(t?.transform||{});o!==``&&r.push(o);let s=r.join(`&`);return s!==``&&(s=`?${s}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${n}${s}`)}}}async remove(e){var t=this;return t.handleOperation(async()=>await sa(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}))}async list(e,t,n){var r=this;return r.handleOperation(async()=>{let i=B(B(B({},fa),t),{},{prefix:e||``});return await V(r.fetch,`${r.url}/object/list/${r.bucketId}`,i,{headers:r.headers},n)})}async listV2(e,t){var n=this;return n.handleOperation(async()=>{let r=B({},e);return await V(n.fetch,`${n.url}/object/list-v2/${n.bucketId}`,r,{headers:n.headers},t)})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<`u`?Buffer.from(e).toString(`base64`):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,``)}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,``).replace(/\/+/g,`/`)}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join(`&`)}},ha={"X-Client-Info":`storage-js/2.99.3`},ga=class extends ca{constructor(e,t={},n,r){let i=new URL(e);r?.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes(`storage.supabase.`)&&(i.hostname=i.hostname.replace(`supabase.`,`storage.supabase.`));let a=i.href.replace(/\/$/,``),o=B(B({},ha),t);super(a,o,n,`storage`)}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let n=t.listBucketOptionsToQueryString(e);return await ia(t.fetch,`${t.url}/bucket${n}`,{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await ia(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}))}async createBucket(e,t={public:!1}){var n=this;return n.handleOperation(async()=>await V(n.fetch,`${n.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:n.headers}))}async updateBucket(e,t){var n=this;return n.handleOperation(async()=>await aa(n.fetch,`${n.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:n.headers}))}async emptyBucket(e){var t=this;return t.handleOperation(async()=>await V(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await sa(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}listBucketOptionsToQueryString(e){let t={};return e&&(`limit`in e&&(t.limit=String(e.limit)),`offset`in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?`?`+new URLSearchParams(t).toString():``}},_a=class extends ca{constructor(e,t={},n){let r=e.replace(/\/$/,``),i=B(B({},ha),t);super(r,i,n,`storage`)}async createBucket(e){var t=this;return t.handleOperation(async()=>await V(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}))}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let n=new URLSearchParams;e?.limit!==void 0&&n.set(`limit`,e.limit.toString()),e?.offset!==void 0&&n.set(`offset`,e.offset.toString()),e?.sortColumn&&n.set(`sortColumn`,e.sortColumn),e?.sortOrder&&n.set(`sortOrder`,e.sortOrder),e?.search&&n.set(`search`,e.search);let r=n.toString(),i=r?`${t.url}/bucket?${r}`:`${t.url}/bucket`;return await ia(t.fetch,i,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await sa(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}from(e){var t=this;if(!qi(e))throw new Bi(`Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.`);let n=new zi({baseUrl:this.url,catalogName:e,auth:{type:`custom`,getHeaders:async()=>t.headers},fetch:this.fetch}),r=this.shouldThrowOnError;return new Proxy(n,{get(e,t){let n=e[t];return typeof n==`function`?async(...t)=>{try{return{data:await n.apply(e,t),error:null}}catch(e){if(r)throw e;return{data:null,error:e}}}:n}})}},va=class extends ca{constructor(e,t={},n){let r=e.replace(/\/$/,``),i=B(B({},ha),{},{"Content-Type":`application/json`},t);super(r,i,n,`vectors`)}async createIndex(e){var t=this;return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{})}async getIndex(e,t){var n=this;return n.handleOperation(async()=>await H.post(n.fetch,`${n.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:n.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}))}async deleteIndex(e,t){var n=this;return n.handleOperation(async()=>await H.post(n.fetch,`${n.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:n.headers})||{})}},ya=class extends ca{constructor(e,t={},n){let r=e.replace(/\/$/,``),i=B(B({},ha),{},{"Content-Type":`application/json`},t);super(r,i,n,`vectors`)}async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw Error(`Vector batch size must be between 1 and 500 items`);return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}))}async listVectors(e){var t=this;if(e.segmentCount!==void 0){if(e.segmentCount<1||e.segmentCount>16)throw Error(`segmentCount must be between 1 and 16`);if(e.segmentIndex!==void 0&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw Error(`Keys batch size must be between 1 and 500 items`);return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{})}},ba=class extends ca{constructor(e,t={},n){let r=e.replace(/\/$/,``),i=B(B({},ha),{},{"Content-Type":`application/json`},t);super(r,i,n,`vectors`)}async createBucket(e){var t=this;return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}))}async listBuckets(e={}){var t=this;return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}},xa=class extends ba{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new Sa(this.url,this.headers,e,this.fetch)}async createBucket(e){var t=()=>super.createBucket,n=this;return t().call(n,e)}async getBucket(e){var t=()=>super.getBucket,n=this;return t().call(n,e)}async listBuckets(e={}){var t=()=>super.listBuckets,n=this;return t().call(n,e)}async deleteBucket(e){var t=()=>super.deleteBucket,n=this;return t().call(n,e)}},Sa=class extends va{constructor(e,t,n,r){super(e,t,r),this.vectorBucketName=n}async createIndex(e){var t=()=>super.createIndex,n=this;return t().call(n,B(B({},e),{},{vectorBucketName:n.vectorBucketName}))}async listIndexes(e={}){var t=()=>super.listIndexes,n=this;return t().call(n,B(B({},e),{},{vectorBucketName:n.vectorBucketName}))}async getIndex(e){var t=()=>super.getIndex,n=this;return t().call(n,n.vectorBucketName,e)}async deleteIndex(e){var t=()=>super.deleteIndex,n=this;return t().call(n,n.vectorBucketName,e)}index(e){return new Ca(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},Ca=class extends ya{constructor(e,t,n,r,i){super(e,t,i),this.vectorBucketName=n,this.indexName=r}async putVectors(e){var t=()=>super.putVectors,n=this;return t().call(n,B(B({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async getVectors(e){var t=()=>super.getVectors,n=this;return t().call(n,B(B({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async listVectors(e={}){var t=()=>super.listVectors,n=this;return t().call(n,B(B({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async queryVectors(e){var t=()=>super.queryVectors,n=this;return t().call(n,B(B({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async deleteVectors(e){var t=()=>super.deleteVectors,n=this;return t().call(n,B(B({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}},wa=class extends ga{constructor(e,t={},n,r){super(e,t,n,r)}from(e){return new ma(this.url,this.headers,e,this.fetch)}get vectors(){return new xa(this.url+`/vector`,{headers:this.headers,fetch:this.fetch})}get analytics(){return new _a(this.url+`/iceberg`,this.headers,this.fetch)}},Ta=`2.99.3`,Ea=30*1e3,Da=3*Ea,Oa=`http://localhost:9999`,ka=`supabase.auth.token`,Aa={"X-Client-Info":`gotrue-js/${Ta}`},ja=`X-Supabase-Api-Version`,Ma={"2024-01-01":{timestamp:Date.parse(`2024-01-01T00:00:00.0Z`),name:`2024-01-01`}},Na=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Pa=class extends Error{constructor(e,t,n){super(e),this.__isAuthError=!0,this.name=`AuthError`,this.status=t,this.code=n}};function U(e){return typeof e==`object`&&!!e&&`__isAuthError`in e}var Fa=class extends Pa{constructor(e,t,n){super(e,t,n),this.name=`AuthApiError`,this.status=t,this.code=n}};function Ia(e){return U(e)&&e.name===`AuthApiError`}var La=class extends Pa{constructor(e,t){super(e),this.name=`AuthUnknownError`,this.originalError=t}},W=class extends Pa{constructor(e,t,n,r){super(e,n,r),this.name=t,this.status=n}},G=class extends W{constructor(){super(`Auth session missing!`,`AuthSessionMissingError`,400,void 0)}};function Ra(e){return U(e)&&e.name===`AuthSessionMissingError`}var za=class extends W{constructor(){super(`Auth session or user missing`,`AuthInvalidTokenResponseError`,500,void 0)}},Ba=class extends W{constructor(e){super(e,`AuthInvalidCredentialsError`,400,void 0)}},Va=class extends W{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 Ha(e){return U(e)&&e.name===`AuthImplicitGrantRedirectError`}var Ua=class extends W{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}}},Wa=class extends W{constructor(){super(`PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.`,`AuthPKCECodeVerifierMissingError`,400,`pkce_code_verifier_not_found`)}},Ga=class extends W{constructor(e,t){super(e,`AuthRetryableFetchError`,t,void 0)}};function Ka(e){return U(e)&&e.name===`AuthRetryableFetchError`}var qa=class extends W{constructor(e,t,n){super(e,`AuthWeakPasswordError`,t,`weak_password`),this.reasons=n}},Ja=class extends W{constructor(e){super(e,`AuthInvalidJwtError`,400,`invalid_jwt`)}},Ya=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`.split(``),Xa=`
114
- \r=`.split(``),Za=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<Xa.length;t+=1)e[Xa[t].charCodeAt(0)]=-2;for(let t=0;t<Ya.length;t+=1)e[Ya[t].charCodeAt(0)]=t;return e})();function Qa(e,t,n){if(e!==null)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;)n(Ya[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6;else if(t.queuedBits>0)for(t.queue<<=6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;)n(Ya[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6}function $a(e,t,n){let r=Za[e];if(r>-1)for(t.queue=t.queue<<6|r,t.queuedBits+=6;t.queuedBits>=8;)n(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else if(r===-2)return;else throw Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}function eo(e){let t=[],n=e=>{t.push(String.fromCodePoint(e))},r={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},a=e=>{ro(e,r,n)};for(let t=0;t<e.length;t+=1)$a(e.charCodeAt(t),i,a);return t.join(``)}function to(e,t){if(e<=127){t(e);return}else if(e<=2047){t(192|e>>6),t(128|e&63);return}else if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|e&63);return}else if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|e&63);return}throw Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}function no(e,t){for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);if(r>55295&&r<=56319){let t=(r-55296)*1024&65535;r=(e.charCodeAt(n+1)-56320&65535|t)+65536,n+=1}to(r,t)}}function ro(e,t,n){if(t.utf8seq===0){if(e<=127){n(e);return}for(let n=1;n<6;n+=1)if(!(e>>7-n&1)){t.utf8seq=n;break}if(t.utf8seq===2)t.codepoint=e&31;else if(t.utf8seq===3)t.codepoint=e&15;else if(t.utf8seq===4)t.codepoint=e&7;else throw Error(`Invalid UTF-8 sequence`);--t.utf8seq}else if(t.utf8seq>0){if(e<=127)throw Error(`Invalid UTF-8 sequence`);t.codepoint=t.codepoint<<6|e&63,--t.utf8seq,t.utf8seq===0&&n(t.codepoint)}}function io(e){let t=[],n={queue:0,queuedBits:0},r=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)$a(e.charCodeAt(t),n,r);return new Uint8Array(t)}function ao(e){let t=[];return no(e,e=>t.push(e)),new Uint8Array(t)}function oo(e){let t=[],n={queue:0,queuedBits:0},r=e=>{t.push(e)};return e.forEach(e=>Qa(e,n,r)),Qa(null,n,r),t.join(``)}function so(e){return Math.round(Date.now()/1e3)+e}function co(){return Symbol(`auth-callback`)}var K=()=>typeof window<`u`&&typeof document<`u`,lo={tested:!1,writable:!1},uo=()=>{if(!K())return!1;try{if(typeof globalThis.localStorage!=`object`)return!1}catch{return!1}if(lo.tested)return lo.writable;let e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),lo.tested=!0,lo.writable=!0}catch{lo.tested=!0,lo.writable=!1}return lo.writable};function fo(e){let t={},n=new URL(e);if(n.hash&&n.hash[0]===`#`)try{new URLSearchParams(n.hash.substring(1)).forEach((e,n)=>{t[n]=e})}catch{}return n.searchParams.forEach((e,n)=>{t[n]=e}),t}var po=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),mo=e=>typeof e==`object`&&!!e&&`status`in e&&`ok`in e&&`json`in e&&typeof e.json==`function`,ho=async(e,t,n)=>{await e.setItem(t,JSON.stringify(n))},go=async(e,t)=>{let n=await e.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},q=async(e,t)=>{await e.removeItem(t)},_o=class e{constructor(){this.promise=new e.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};_o.promiseConstructor=Promise;function vo(e){let t=e.split(`.`);if(t.length!==3)throw new Ja(`Invalid JWT structure`);for(let e=0;e<t.length;e++)if(!Na.test(t[e]))throw new Ja(`JWT not in base64url format`);return{header:JSON.parse(eo(t[0])),payload:JSON.parse(eo(t[1])),signature:io(t[2]),raw:{header:t[0],payload:t[1]}}}async function yo(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function bo(e,t){return new Promise((n,r)=>{(async()=>{for(let i=0;i<1/0;i++)try{let r=await e(i);if(!t(i,null,r)){n(r);return}}catch(e){if(!t(i,e)){r(e);return}}})()})}function xo(e){return(`0`+e.toString(16)).substr(-2)}function So(){let e=new Uint32Array(56);if(typeof crypto>`u`){let e=``;for(let t=0;t<56;t++)e+=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~`.charAt(Math.floor(Math.random()*66));return e}return crypto.getRandomValues(e),Array.from(e,xo).join(``)}async function Co(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t),r=new Uint8Array(n);return Array.from(r).map(e=>String.fromCharCode(e)).join(``)}async function wo(e){if(!(typeof crypto<`u`&&crypto.subtle!==void 0&&typeof TextEncoder<`u`))return console.warn(`WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.`),e;let t=await Co(e);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}async function To(e,t,n=!1){let r=So(),i=r;n&&(i+=`/PASSWORD_RECOVERY`),await ho(e,`${t}-code-verifier`,i);let a=await wo(r);return[a,r===a?`plain`:`s256`]}var Eo=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Do(e){let t=e.headers.get(ja);if(!t||!t.match(Eo))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function Oo(e){if(!e)throw Error(`Missing exp claim`);if(e<=Math.floor(Date.now()/1e3))throw Error(`JWT has expired`)}function ko(e){switch(e){case`RS256`:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-256`}};case`ES256`:return{name:`ECDSA`,namedCurve:`P-256`,hash:{name:`SHA-256`}};default:throw Error(`Invalid alg claim`)}}var Ao=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function jo(e){if(!Ao.test(e))throw Error(`@supabase/auth-js: Expected parameter to be UUID but is not`)}function Mo(){return new Proxy({},{get:(e,t)=>{if(t===`__isUserNotAvailableProxy`)return!0;if(typeof t==`symbol`){let e=t.toString();if(e===`Symbol(Symbol.toPrimitive)`||e===`Symbol(Symbol.toStringTag)`||e===`Symbol(util.inspect.custom)`)return}throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function No(e,t){return new Proxy(e,{get:(e,n,r)=>{if(n===`__isInsecureUserWarningProxy`)return!0;if(typeof n==`symbol`){let t=n.toString();if(t===`Symbol(Symbol.toPrimitive)`||t===`Symbol(Symbol.toStringTag)`||t===`Symbol(util.inspect.custom)`||t===`Symbol(nodejs.util.inspect.custom)`)return Reflect.get(e,n,r)}return!t.value&&typeof n==`string`&&(console.warn(`Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.`),t.value=!0),Reflect.get(e,n,r)}})}function Po(e){return JSON.parse(JSON.stringify(e))}var Fo=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Io=[502,503,504];async function Lo(e){if(!mo(e))throw new Ga(Fo(e),0);if(Io.includes(e.status))throw new Ga(Fo(e),e.status);let t;try{t=await e.json()}catch(e){throw new La(Fo(e),e)}let n,r=Do(e);if(r&&r.getTime()>=Ma[`2024-01-01`].timestamp&&typeof t==`object`&&t&&typeof t.code==`string`?n=t.code:typeof t==`object`&&t&&typeof t.error_code==`string`&&(n=t.error_code),!n){if(typeof t==`object`&&t&&typeof t.weak_password==`object`&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((e,t)=>e&&typeof t==`string`,!0))throw new qa(Fo(t),e.status,t.weak_password.reasons)}else if(n===`weak_password`)throw new qa(Fo(t),e.status,t.weak_password?.reasons||[]);else if(n===`session_not_found`)throw new G;throw new Fa(Fo(t),e.status||500,n)}var Ro=(e,t,n,r)=>{let i={method:e,headers:t?.headers||{}};return e===`GET`?i:(i.headers=Object.assign({"Content-Type":`application/json;charset=UTF-8`},t?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),n))};async function J(e,t,n,r){let i=Object.assign({},r?.headers);i[`X-Supabase-Api-Version`]||(i[ja]=Ma[`2024-01-01`].name),r?.jwt&&(i.Authorization=`Bearer ${r.jwt}`);let a=r?.query??{};r?.redirectTo&&(a.redirect_to=r.redirectTo);let o=await zo(e,t,n+(Object.keys(a).length?`?`+new URLSearchParams(a).toString():``),{headers:i,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(o):{data:Object.assign({},o),error:null}}async function zo(e,t,n,r,i,a){let o=Ro(t,r,i,a),s;try{s=await e(n,Object.assign({},o))}catch(e){throw console.error(e),new Ga(Fo(e),0)}if(s.ok||await Lo(s),r?.noResolveJson)return s;try{return await s.json()}catch(e){await Lo(e)}}function Y(e){let t=null;Wo(e)&&(t=Object.assign({},e),e.expires_at||(t.expires_at=so(e.expires_in)));let n=e.user??e;return{data:{session:t,user:n},error:null}}function Bo(e){let t=Y(e);return!t.error&&e.weak_password&&typeof e.weak_password==`object`&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message==`string`&&e.weak_password.reasons.reduce((e,t)=>e&&typeof t==`string`,!0)&&(t.data.weak_password=e.weak_password),t}function X(e){return{data:{user:e.user??e},error:null}}function Vo(e){return{data:e,error:null}}function Ho(e){let{action_link:t,email_otp:n,hashed_token:r,redirect_to:i,verification_type:a}=e,o=Ar(e,[`action_link`,`email_otp`,`hashed_token`,`redirect_to`,`verification_type`]);return{data:{properties:{action_link:t,email_otp:n,hashed_token:r,redirect_to:i,verification_type:a},user:Object.assign({},o)},error:null}}function Uo(e){return e}function Wo(e){return e.access_token&&e.refresh_token&&e.expires_in}var Go=[`global`,`local`,`others`],Ko=class{constructor({url:e=``,headers:t={},fetch:n}){this.url=e,this.headers=t,this.fetch=po(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)}}async signOut(e,t=Go[0]){if(Go.indexOf(t)<0)throw Error(`@supabase/auth-js: Parameter scope must be one of ${Go.join(`, `)}`);try{return await J(this.fetch,`POST`,`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(U(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await J(this.fetch,`POST`,`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:X})}catch(e){if(U(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{let{options:t}=e,n=Ar(e,[`options`]),r=Object.assign(Object.assign({},n),t);return`newEmail`in n&&(r.new_email=n?.newEmail,delete r.newEmail),await J(this.fetch,`POST`,`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:Ho,redirectTo:t?.redirectTo})}catch(e){if(U(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await J(this.fetch,`POST`,`${this.url}/admin/users`,{body:e,headers:this.headers,xform:X})}catch(e){if(U(e))return{data:{user:null},error:e};throw e}}async listUsers(e){try{let t={nextPage:null,lastPage:0,total:0},n=await J(this.fetch,`GET`,`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(e?.page)?.toString()??``,per_page:(e?.perPage)?.toString()??``},xform:Uo});if(n.error)throw n.error;let r=await n.json(),i=n.headers.get(`x-total-count`)??0,a=n.headers.get(`link`)?.split(`,`)??[];return a.length>0&&(a.forEach(e=>{let n=parseInt(e.split(`;`)[0].split(`=`)[1].substring(0,1)),r=JSON.parse(e.split(`;`)[1].split(`=`)[1]);t[`${r}Page`]=n}),t.total=parseInt(i)),{data:Object.assign(Object.assign({},r),t),error:null}}catch(e){if(U(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){jo(e);try{return await J(this.fetch,`GET`,`${this.url}/admin/users/${e}`,{headers:this.headers,xform:X})}catch(e){if(U(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){jo(e);try{return await J(this.fetch,`PUT`,`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:X})}catch(e){if(U(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){jo(e);try{return await J(this.fetch,`DELETE`,`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:X})}catch(e){if(U(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){jo(e.userId);try{let{data:t,error:n}=await J(this.fetch,`GET`,`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:n}}catch(e){if(U(e))return{data:null,error:e};throw e}}async _deleteFactor(e){jo(e.userId),jo(e.id);try{return{data:await J(this.fetch,`DELETE`,`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(U(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){try{let t={nextPage:null,lastPage:0,total:0},n=await J(this.fetch,`GET`,`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(e?.page)?.toString()??``,per_page:(e?.perPage)?.toString()??``},xform:Uo});if(n.error)throw n.error;let r=await n.json(),i=n.headers.get(`x-total-count`)??0,a=n.headers.get(`link`)?.split(`,`)??[];return a.length>0&&(a.forEach(e=>{let n=parseInt(e.split(`;`)[0].split(`=`)[1].substring(0,1)),r=JSON.parse(e.split(`;`)[1].split(`=`)[1]);t[`${r}Page`]=n}),t.total=parseInt(i)),{data:Object.assign(Object.assign({},r),t),error:null}}catch(e){if(U(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await J(this.fetch,`POST`,`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(U(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await J(this.fetch,`GET`,`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(U(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await J(this.fetch,`PUT`,`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(U(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await J(this.fetch,`DELETE`,`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(U(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await J(this.fetch,`POST`,`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(U(e))return{data:null,error:e};throw e}}async _listCustomProviders(e){try{let t={};return e?.type&&(t.type=e.type),await J(this.fetch,`GET`,`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:e=>({data:{providers:e?.providers??[]},error:null})})}catch(e){if(U(e))return{data:{providers:[]},error:e};throw e}}async _createCustomProvider(e){try{return await J(this.fetch,`POST`,`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(U(e))return{data:null,error:e};throw e}}async _getCustomProvider(e){try{return await J(this.fetch,`GET`,`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(U(e))return{data:null,error:e};throw e}}async _updateCustomProvider(e,t){try{return await J(this.fetch,`PUT`,`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(U(e))return{data:null,error:e};throw e}}async _deleteCustomProvider(e){try{return await J(this.fetch,`DELETE`,`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(U(e))return{data:null,error:e};throw e}}};function qo(e={}){return{getItem:t=>e[t]||null,setItem:(t,n)=>{e[t]=n},removeItem:t=>{delete e[t]}}}var Z={debug:!!(globalThis&&uo()&&globalThis.localStorage&&globalThis.localStorage.getItem(`supabase.gotrue-js.locks.debug`)===`true`)},Jo=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Yo=class extends Jo{};async function Xo(e,t,n){Z.debug&&console.log(`@supabase/gotrue-js: navigatorLock: acquire lock`,e,t);let r=new globalThis.AbortController,i;t>0&&(i=setTimeout(()=>{r.abort(),Z.debug&&console.log(`@supabase/gotrue-js: navigatorLock acquire timed out`,e)},t)),await Promise.resolve();try{return await globalThis.navigator.locks.request(e,t===0?{mode:`exclusive`,ifAvailable:!0}:{mode:`exclusive`,signal:r.signal},async r=>{if(r){clearTimeout(i),Z.debug&&console.log(`@supabase/gotrue-js: navigatorLock: acquired`,e,r.name);try{return await n()}finally{Z.debug&&console.log(`@supabase/gotrue-js: navigatorLock: released`,e,r.name)}}else if(t===0)throw Z.debug&&console.log(`@supabase/gotrue-js: navigatorLock: not immediately available`,e),new Yo(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);else{if(Z.debug)try{let e=await globalThis.navigator.locks.query();console.log(`@supabase/gotrue-js: Navigator LockManager state`,JSON.stringify(e,null,` `))}catch(e){console.warn(`@supabase/gotrue-js: Error when querying Navigator LockManager state`,e)}return console.warn(`@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request`),clearTimeout(i),await n()}})}catch(a){if(t>0&&clearTimeout(i),a?.name===`AbortError`&&t>0){if(r.signal.aborted)return Z.debug&&console.log(`@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock`,e),console.warn(`@supabase/gotrue-js: Lock "${e}" was not released within ${t}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,{mode:`exclusive`,steal:!0},async t=>{if(t){Z.debug&&console.log(`@supabase/gotrue-js: navigatorLock: recovered (stolen)`,e,t.name);try{return await n()}finally{Z.debug&&console.log(`@supabase/gotrue-js: navigatorLock: released (stolen)`,e,t.name)}}else return console.warn(`@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true`),await n()}));throw Z.debug&&console.log(`@supabase/gotrue-js: navigatorLock: lock was stolen by another request`,e),new Yo(`Lock "${e}" was released because another request stole it`)}throw a}}function Zo(){if(typeof globalThis!=`object`)try{Object.defineProperty(Object.prototype,`__magic__`,{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<`u`&&(self.globalThis=self)}}function Qo(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function $o(e){return parseInt(e,16)}function es(e){let t=new TextEncoder().encode(e);return`0x`+Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}function ts(e){let{chainId:t,domain:n,expirationTime:r,issuedAt:i=new Date,nonce:a,notBefore:o,requestId:s,resources:c,scheme:l,uri:u,version:d}=e;if(!Number.isInteger(t))throw Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!n)throw Error(`@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.`);if(a&&a.length<8)throw Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!u)throw Error(`@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.`);if(d!==`1`)throw Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(e.statement?.includes(`
115
- `))throw Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);let f=Qo(e.address),p=`${l?`${l}://${n}`:n} wants you to sign in with your Ethereum account:\n${f}\n\n${e.statement?`${e.statement}\n`:``}`,m=`URI: ${u}\nVersion: ${d}\nChain ID: ${t}${a?`\nNonce: ${a}`:``}\nIssued At: ${i.toISOString()}`;if(r&&(m+=`\nExpiration Time: ${r.toISOString()}`),o&&(m+=`\nNot Before: ${o.toISOString()}`),s&&(m+=`\nRequest ID: ${s}`),c){let e=`
116
- Resources:`;for(let t of c){if(!t||typeof t!=`string`)throw Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`\n- ${t}`}m+=e}return`${p}\n${m}`}var Q=class extends Error{constructor({message:e,code:t,cause:n,name:r}){super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=r??(n instanceof Error?n.name:void 0)??`Unknown Error`,this.code=t}},ns=class extends Q{constructor(e,t){super({code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:t,message:e}),this.name=`WebAuthnUnknownError`,this.originalError=t}};function rs({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new Q({message:`Registration ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`ConstraintError`){if(n.authenticatorSelection?.requireResidentKey===!0)return new Q({message:`Discoverable credentials were required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT`,cause:e});if(t.mediation===`conditional`&&n.authenticatorSelection?.userVerification===`required`)return new Q({message:`User verification was required during automatic registration but it could not be performed`,code:`ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE`,cause:e});if(n.authenticatorSelection?.userVerification===`required`)return new Q({message:`User verification was required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT`,cause:e})}else if(e.name===`InvalidStateError`)return new Q({message:`The authenticator was previously registered`,code:`ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED`,cause:e});else if(e.name===`NotAllowedError`)return new Q({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`NotSupportedError`)return n.pubKeyCredParams.filter(e=>e.type===`public-key`).length===0?new Q({message:`No entry in pubKeyCredParams was of type "public-key"`,code:`ERROR_MALFORMED_PUBKEYCREDPARAMS`,cause:e}):new Q({message:`No available authenticator supported any of the specified pubKeyCredParams algorithms`,code:`ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG`,cause:e});else if(e.name===`SecurityError`){let t=window.location.hostname;if(!us(t))return new Q({message:`${window.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rp.id!==t)return new Q({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`TypeError`){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new Q({message:`User ID was not between 1 and 64 characters`,code:`ERROR_INVALID_USER_ID_LENGTH`,cause:e})}else if(e.name===`UnknownError`)return new Q({message:`The authenticator was unable to process the specified options, or could not create a new credential`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return new Q({message:`a Non-Webauthn related error has occurred`,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e})}function is({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new Q({message:`Authentication ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`NotAllowedError`)return new Q({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`SecurityError`){let t=window.location.hostname;if(!us(t))return new Q({message:`${window.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rpId!==t)return new Q({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`UnknownError`)return new Q({message:`The authenticator was unable to process the specified options, or could not create a new assertion signature`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return new Q({message:`a Non-Webauthn related error has occurred`,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e})}var as=new class{createNewAbortSignal(){if(this.controller){let e=Error(`Cancelling existing WebAuthn API call for new one`);e.name=`AbortError`,this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error(`Manually cancelling existing WebAuthn API call`);e.name=`AbortError`,this.controller.abort(e),this.controller=void 0}}};function os(e){if(!e)throw Error(`Credential creation options are required`);if(typeof PublicKeyCredential<`u`&&`parseCreationOptionsFromJSON`in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON==`function`)return PublicKeyCredential.parseCreationOptionsFromJSON(e);let{challenge:t,user:n,excludeCredentials:r}=e,i=Ar(e,[`challenge`,`user`,`excludeCredentials`]),a=io(t).buffer,o=Object.assign(Object.assign({},n),{id:io(n.id).buffer}),s=Object.assign(Object.assign({},i),{challenge:a,user:o});if(r&&r.length>0){s.excludeCredentials=Array(r.length);for(let e=0;e<r.length;e++){let t=r[e];s.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:io(t.id).buffer,type:t.type||`public-key`,transports:t.transports})}}return s}function ss(e){if(!e)throw Error(`Credential request options are required`);if(typeof PublicKeyCredential<`u`&&`parseRequestOptionsFromJSON`in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON==`function`)return PublicKeyCredential.parseRequestOptionsFromJSON(e);let{challenge:t,allowCredentials:n}=e,r=Ar(e,[`challenge`,`allowCredentials`]),i=io(t).buffer,a=Object.assign(Object.assign({},r),{challenge:i});if(n&&n.length>0){a.allowCredentials=Array(n.length);for(let e=0;e<n.length;e++){let t=n[e];a.allowCredentials[e]=Object.assign(Object.assign({},t),{id:io(t.id).buffer,type:t.type||`public-key`,transports:t.transports})}}return a}function cs(e){if(`toJSON`in e&&typeof e.toJSON==`function`)return e.toJSON();let t=e;return{id:e.id,rawId:e.id,response:{attestationObject:oo(new Uint8Array(e.response.attestationObject)),clientDataJSON:oo(new Uint8Array(e.response.clientDataJSON))},type:`public-key`,clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:t.authenticatorAttachment??void 0}}function ls(e){if(`toJSON`in e&&typeof e.toJSON==`function`)return e.toJSON();let t=e,n=e.getClientExtensionResults(),r=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:oo(new Uint8Array(r.authenticatorData)),clientDataJSON:oo(new Uint8Array(r.clientDataJSON)),signature:oo(new Uint8Array(r.signature)),userHandle:r.userHandle?oo(new Uint8Array(r.userHandle)):void 0},type:`public-key`,clientExtensionResults:n,authenticatorAttachment:t.authenticatorAttachment??void 0}}function us(e){return e===`localhost`||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function ds(){return!!(K()&&`PublicKeyCredential`in window&&window.PublicKeyCredential&&`credentials`in navigator&&typeof(navigator==null?void 0:navigator.credentials)?.create==`function`&&typeof(navigator==null?void 0:navigator.credentials)?.get==`function`)}async function fs(e){try{let t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new ns(`Browser returned unexpected credential type`,t)}:{data:null,error:new ns(`Empty credential response`,t)}}catch(t){return{data:null,error:rs({error:t,options:e})}}}async function ps(e){try{let t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new ns(`Browser returned unexpected credential type`,t)}:{data:null,error:new ns(`Empty credential response`,t)}}catch(t){return{data:null,error:is({error:t,options:e})}}}var ms={hints:[`security-key`],authenticatorSelection:{authenticatorAttachment:`cross-platform`,requireResidentKey:!1,userVerification:`preferred`,residentKey:`discouraged`},attestation:`direct`},hs={userVerification:`preferred`,hints:[`security-key`],attestation:`direct`};function gs(...e){let t=e=>typeof e==`object`&&!!e&&!Array.isArray(e),n=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),r={};for(let i of e)if(i)for(let e in i){let a=i[e];if(a!==void 0)if(Array.isArray(a))r[e]=a;else if(n(a))r[e]=a;else if(t(a)){let n=r[e];t(n)?r[e]=gs(n,a):r[e]=gs(a)}else r[e]=a}return r}function _s(e,t){return gs(ms,e,t||{})}function vs(e,t){return gs(hs,e,t||{})}var ys=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:`webauthn`}))}async _challenge({factorId:e,webauthn:t,friendlyName:n,signal:r},i){try{let{data:a,error:o}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!a)return{data:null,error:o};let s=r??as.createNewAbortSignal();if(a.webauthn.type===`create`){let{user:e}=a.webauthn.credential_options.publicKey;if(!e.name){let t=n;if(t)e.name=`${e.id}:${t}`;else{let t=(await this.client.getUser()).data.user,n=t?.user_metadata?.name||t?.email||t?.id||`User`;e.name=`${e.id}:${n}`}}e.displayName||=e.name}switch(a.webauthn.type){case`create`:{let{data:t,error:n}=await fs({publicKey:_s(a.webauthn.credential_options.publicKey,i?.create),signal:s});return t?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:t}},error:null}:{data:null,error:n}}case`request`:{let t=vs(a.webauthn.credential_options.publicKey,i?.request),{data:n,error:r}=await ps(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:t,signal:s}));return n?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:n}},error:null}:{data:null,error:r}}}}catch(e){return U(e)?{data:null,error:e}:{data:null,error:new La(`Unexpected error in challenge`,e)}}}async _verify({challengeId:e,factorId:t,webauthn:n}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<`u`?window.location.hostname:void 0,rpOrigins:n=typeof window<`u`?[window.location.origin]:void 0,signal:r}={}},i){if(!t)return{data:null,error:new Pa(`rpId is required for WebAuthn authentication`)};try{if(!ds())return{data:null,error:new La(`Browser does not support WebAuthn`,null)};let{data:a,error:o}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:n},signal:r},{request:i});if(!a)return{data:null,error:o};let{webauthn:s}=a;return this._verify({factorId:e,challengeId:a.challengeId,webauthn:{type:s.type,rpId:t,rpOrigins:n,credential_response:s.credential_response}})}catch(e){return U(e)?{data:null,error:e}:{data:null,error:new La(`Unexpected error in authenticate`,e)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<`u`?window.location.hostname:void 0,rpOrigins:n=typeof window<`u`?[window.location.origin]:void 0,signal:r}={}},i){if(!t)return{data:null,error:new Pa(`rpId is required for WebAuthn registration`)};try{if(!ds())return{data:null,error:new La(`Browser does not support WebAuthn`,null)};let{data:a,error:o}=await this._enroll({friendlyName:e});if(!a)return await this.client.mfa.listFactors().then(t=>t.data?.all.find(t=>t.factor_type===`webauthn`&&t.friendly_name===e&&t.status!==`unverified`)).then(e=>e?this.client.mfa.unenroll({factorId:e?.id}):void 0),{data:null,error:o};let{data:s,error:c}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:t,rpOrigins:n},signal:r},{create:i});return s?this._verify({factorId:a.id,challengeId:s.challengeId,webauthn:{rpId:t,rpOrigins:n,type:s.webauthn.type,credential_response:s.webauthn.credential_response}}):{data:null,error:c}}catch(e){return U(e)?{data:null,error:e}:{data:null,error:new La(`Unexpected error in register`,e)}}}};Zo();var bs={url:Oa,storageKey:ka,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Aa,flowType:`implicit`,debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function xs(e,t,n){return await n()}var Ss={},Cs=class e{get jwks(){return Ss[this.storageKey]?.jwks??{keys:[]}}set jwks(e){Ss[this.storageKey]=Object.assign(Object.assign({},Ss[this.storageKey]),{jwks:e})}get jwks_cached_at(){return Ss[this.storageKey]?.cachedAt??-(2**53-1)}set jwks_cached_at(e){Ss[this.storageKey]=Object.assign(Object.assign({},Ss[this.storageKey]),{cachedAt:e})}constructor(t){var n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let r=Object.assign(Object.assign({},bs),t);if(this.storageKey=r.storageKey,this.instanceID=e.nextInstanceID[this.storageKey]??0,e.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!r.debug,typeof r.debug==`function`&&(this.logger=r.debug),this.instanceID>0&&K()){let e=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=r.persistSession,this.autoRefreshToken=r.autoRefreshToken,this.admin=new Ko({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=po(r.fetch),this.lock=r.lock||xs,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,this.throwOnError=r.throwOnError,this.lockAcquireTimeout=r.lockAcquireTimeout,r.lock?this.lock=r.lock:this.persistSession&&K()&&(globalThis==null?void 0:globalThis.navigator)?.locks?this.lock=Xo:this.lock=xs,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=-(2**53-1)),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new ys(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(r.storage?this.storage=r.storage:uo()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=qo(this.memoryStorage)),r.userStorage&&(this.userStorage=r.userStorage)):(this.memoryStorage={},this.storage=qo(this.memoryStorage)),K()&&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)}(n=this.broadcastChannel)==null||n.addEventListener(`message`,async e=>{this._debug(`received broadcast notification from other tab or client`,e);try{await this._notifyAllSubscribers(e.data.event,e.data.session,!1)}catch(e){this._debug(`#broadcastChannel`,`error`,e)}})}r.skipAutoInitialize||this.initialize().catch(e=>{this._debug(`#initialize()`,`error`,e)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Ta}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise||=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise}async _initialize(){try{let e={},t=`none`;if(K()&&(e=fo(window.location.href),this._isImplicitGrantCallback(e)?t=`implicit`:await this._isPKCECallback(e)&&(t=`pkce`)),K()&&this.detectSessionInUrl&&t!==`none`){let{data:n,error:r}=await this._getSessionFromURL(e,t);if(r){if(this._debug(`#_initialize()`,`error detecting session from URL`,r),Ha(r)){let e=r.details?.code;if(e===`identity_already_exists`||e===`identity_not_found`||e===`single_identity_not_deletable`)return{error:r}}return{error:r}}let{session:i,redirectType:a}=n;return this._debug(`#_initialize()`,`detected session in URL`,i,`redirect type`,a),await this._saveSession(i),setTimeout(async()=>{a===`recovery`?await this._notifyAllSubscribers(`PASSWORD_RECOVERY`,i):await this._notifyAllSubscribers(`SIGNED_IN`,i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return U(e)?this._returnResult({error:e}):this._returnResult({error:new La(`Unexpected error during initialization`,e)})}finally{await this._handleVisibilityChange(),this._debug(`#_initialize()`,`end`)}}async signInAnonymously(e){try{let{data:t,error:n}=await J(this.fetch,`POST`,`${this.url}/signup`,{headers:this.headers,body:{data:e?.options?.data??{},gotrue_meta_security:{captcha_token:e?.options?.captchaToken}},xform:Y});if(n||!t)return this._returnResult({data:{user:null,session:null},error:n});let r=t.session,i=t.user;return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers(`SIGNED_IN`,r)),this._returnResult({data:{user:i,session:r},error:null})}catch(e){if(U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){try{let t;if(`email`in e){let{email:n,password:r,options:i}=e,a=null,o=null;this.flowType===`pkce`&&([a,o]=await To(this.storage,this.storageKey)),t=await J(this.fetch,`POST`,`${this.url}/signup`,{headers:this.headers,redirectTo:i?.emailRedirectTo,body:{email:n,password:r,data:i?.data??{},gotrue_meta_security:{captcha_token:i?.captchaToken},code_challenge:a,code_challenge_method:o},xform:Y})}else if(`phone`in e){let{phone:n,password:r,options:i}=e;t=await J(this.fetch,`POST`,`${this.url}/signup`,{headers:this.headers,body:{phone:n,password:r,data:i?.data??{},channel:i?.channel??`sms`,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Y})}else throw new Ba(`You must provide either an email or phone number and a password`);let{data:n,error:r}=t;if(r||!n)return await q(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:r});let i=n.session,a=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers(`SIGNED_IN`,i)),this._returnResult({data:{user:a,session:i},error:null})}catch(e){if(await q(this.storage,`${this.storageKey}-code-verifier`),U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if(`email`in e){let{email:n,password:r,options:i}=e;t=await J(this.fetch,`POST`,`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:r,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Bo})}else if(`phone`in e){let{phone:n,password:r,options:i}=e;t=await J(this.fetch,`POST`,`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:r,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Bo})}else throw new Ba(`You must provide either an email or phone number and a password`);let{data:n,error:r}=t;if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!n||!n.session||!n.user){let e=new za;return this._returnResult({data:{user:null,session:null},error:e})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers(`SIGNED_IN`,n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:r})}catch(e){if(U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){return await this._handleProviderSignIn(e.provider,{redirectTo:e.options?.redirectTo,scopes:e.options?.scopes,queryParams:e.options?.queryParams,skipBrowserRedirect:e.options?.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:t}=e;switch(t){case`ethereum`:return await this.signInWithEthereum(e);case`solana`:return await this.signInWithSolana(e);default:throw Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){let t,n;if(`message`in e)t=e.message,n=e.signature;else{let{chain:r,wallet:i,statement:a,options:o}=e,s;if(!K()){if(typeof i!=`object`||!o?.url)throw Error(`@supabase/auth-js: Both wallet and url must be specified in non-browser environments.`);s=i}else if(typeof i==`object`)s=i;else{let e=window;if(`ethereum`in e&&typeof e.ethereum==`object`&&`request`in e.ethereum&&typeof e.ethereum.request==`function`)s=e.ethereum;else throw Error(`@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.`)}let c=new URL(o?.url??window.location.href),l=await s.request({method:`eth_requestAccounts`}).then(e=>e).catch(()=>{throw Error(`@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid`)});if(!l||l.length===0)throw Error(`@supabase/auth-js: No accounts available. Please ensure the wallet is connected.`);let u=Qo(l[0]),d=o?.signInWithEthereum?.chainId;d||=$o(await s.request({method:`eth_chainId`})),t=ts({domain:c.host,address:u,statement:a,uri:c.href,version:`1`,chainId:d,nonce:o?.signInWithEthereum?.nonce,issuedAt:o?.signInWithEthereum?.issuedAt??new Date,expirationTime:o?.signInWithEthereum?.expirationTime,notBefore:o?.signInWithEthereum?.notBefore,requestId:o?.signInWithEthereum?.requestId,resources:o?.signInWithEthereum?.resources}),n=await s.request({method:`personal_sign`,params:[es(t),u]})}try{let{data:r,error:i}=await J(this.fetch,`POST`,`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:`ethereum`,message:t,signature:n},e.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options?.captchaToken}}:null),xform:Y});if(i)throw i;if(!r||!r.session||!r.user){let e=new za;return this._returnResult({data:{user:null,session:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers(`SIGNED_IN`,r.session)),this._returnResult({data:Object.assign({},r),error:i})}catch(e){if(U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){let t,n;if(`message`in e)t=e.message,n=e.signature;else{let{chain:r,wallet:i,statement:a,options:o}=e,s;if(!K()){if(typeof i!=`object`||!o?.url)throw Error(`@supabase/auth-js: Both wallet and url must be specified in non-browser environments.`);s=i}else if(typeof i==`object`)s=i;else{let e=window;if(`solana`in e&&typeof e.solana==`object`&&(`signIn`in e.solana&&typeof e.solana.signIn==`function`||`signMessage`in e.solana&&typeof e.solana.signMessage==`function`))s=e.solana;else throw Error(`@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.`)}let c=new URL(o?.url??window.location.href);if(`signIn`in s&&s.signIn){let e=await s.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},o?.signInWithSolana),{version:`1`,domain:c.host,uri:c.href}),a?{statement:a}:null)),r;if(Array.isArray(e)&&e[0]&&typeof e[0]==`object`)r=e[0];else if(e&&typeof e==`object`&&`signedMessage`in e&&`signature`in e)r=e;else throw Error(`@supabase/auth-js: Wallet method signIn() returned unrecognized value`);if(`signedMessage`in r&&`signature`in r&&(typeof r.signedMessage==`string`||r.signedMessage instanceof Uint8Array)&&r.signature instanceof Uint8Array)t=typeof r.signedMessage==`string`?r.signedMessage:new TextDecoder().decode(r.signedMessage),n=r.signature;else throw Error(`@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields`)}else{if(!(`signMessage`in s)||typeof s.signMessage!=`function`||!(`publicKey`in s)||typeof s!=`object`||!s.publicKey||!(`toBase58`in s.publicKey)||typeof s.publicKey.toBase58!=`function`)throw Error(`@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API`);t=[`${c.host} wants you to sign in with your Solana account:`,s.publicKey.toBase58(),...a?[``,a,``]:[``],`Version: 1`,`URI: ${c.href}`,`Issued At: ${o?.signInWithSolana?.issuedAt??new Date().toISOString()}`,...o?.signInWithSolana?.notBefore?[`Not Before: ${o.signInWithSolana.notBefore}`]:[],...o?.signInWithSolana?.expirationTime?[`Expiration Time: ${o.signInWithSolana.expirationTime}`]:[],...o?.signInWithSolana?.chainId?[`Chain ID: ${o.signInWithSolana.chainId}`]:[],...o?.signInWithSolana?.nonce?[`Nonce: ${o.signInWithSolana.nonce}`]:[],...o?.signInWithSolana?.requestId?[`Request ID: ${o.signInWithSolana.requestId}`]:[],...o?.signInWithSolana?.resources?.length?[`Resources`,...o.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join(`
117
- `);let e=await s.signMessage(new TextEncoder().encode(t),`utf8`);if(!e||!(e instanceof Uint8Array))throw Error(`@supabase/auth-js: Wallet signMessage() API returned an recognized value`);n=e}}try{let{data:r,error:i}=await J(this.fetch,`POST`,`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:`solana`,message:t,signature:oo(n)},e.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options?.captchaToken}}:null),xform:Y});if(i)throw i;if(!r||!r.session||!r.user){let e=new za;return this._returnResult({data:{user:null,session:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers(`SIGNED_IN`,r.session)),this._returnResult({data:Object.assign({},r),error:i})}catch(e){if(U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){let[t,n]=(await go(this.storage,`${this.storageKey}-code-verifier`)??``).split(`/`);try{if(!t&&this.flowType===`pkce`)throw new Wa;let{data:r,error:i}=await J(this.fetch,`POST`,`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:t},xform:Y});if(await q(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!r||!r.session||!r.user){let e=new za;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers(`SIGNED_IN`,r.session)),this._returnResult({data:Object.assign(Object.assign({},r),{redirectType:n??null}),error:i})}catch(e){if(await q(this.storage,`${this.storageKey}-code-verifier`),U(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{let{options:t,provider:n,token:r,access_token:i,nonce:a}=e,{data:o,error:s}=await J(this.fetch,`POST`,`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:r,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:Y});if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!o||!o.session||!o.user){let e=new za;return this._returnResult({data:{user:null,session:null},error:e})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers(`SIGNED_IN`,o.session)),this._returnResult({data:o,error:s})}catch(e){if(U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){try{if(`email`in e){let{email:t,options:n}=e,r=null,i=null;this.flowType===`pkce`&&([r,i]=await To(this.storage,this.storageKey));let{error:a}=await J(this.fetch,`POST`,`${this.url}/otp`,{headers:this.headers,body:{email:t,data:n?.data??{},create_user:n?.shouldCreateUser??!0,gotrue_meta_security:{captcha_token:n?.captchaToken},code_challenge:r,code_challenge_method:i},redirectTo:n?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}if(`phone`in e){let{phone:t,options:n}=e,{data:r,error:i}=await J(this.fetch,`POST`,`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:n?.data??{},create_user:n?.shouldCreateUser??!0,gotrue_meta_security:{captcha_token:n?.captchaToken},channel:n?.channel??`sms`}});return this._returnResult({data:{user:null,session:null,messageId:r?.message_id},error:i})}throw new Ba(`You must provide either an email or phone number.`)}catch(e){if(await q(this.storage,`${this.storageKey}-code-verifier`),U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){try{let t,n;`options`in e&&(t=e.options?.redirectTo,n=e.options?.captchaToken);let{data:r,error:i}=await J(this.fetch,`POST`,`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:t,xform:Y});if(i)throw i;if(!r)throw Error(`An error occurred on token verification.`);let a=r.session,o=r.user;return a?.access_token&&(await this._saveSession(a),await this._notifyAllSubscribers(e.type==`recovery`?`PASSWORD_RECOVERY`:`SIGNED_IN`,a)),this._returnResult({data:{user:o,session:a},error:null})}catch(e){if(U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){try{let t=null,n=null;this.flowType===`pkce`&&([t,n]=await To(this.storage,this.storageKey));let r=await J(this.fetch,`POST`,`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},`providerId`in e?{provider_id:e.providerId}:null),`domain`in e?{domain:e.domain}:null),{redirect_to:e.options?.redirectTo??void 0}),e?.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:t,code_challenge_method:n}),headers:this.headers,xform:Vo});return r.data?.url&&K()&&!e.options?.skipBrowserRedirect&&window.location.assign(r.data.url),this._returnResult(r)}catch(e){if(await q(this.storage,`${this.storageKey}-code-verifier`),U(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;if(n)throw n;if(!t)throw new G;let{error:r}=await J(this.fetch,`GET`,`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:r})})}catch(e){if(U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let t=`${this.url}/resend`;if(`email`in e){let{email:n,type:r,options:i}=e,{error:a}=await J(this.fetch,`POST`,t,{headers:this.headers,body:{email:n,type:r,gotrue_meta_security:{captcha_token:i?.captchaToken}},redirectTo:i?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}else if(`phone`in e){let{phone:n,type:r,options:i}=e,{data:a,error:o}=await J(this.fetch,`POST`,t,{headers:this.headers,body:{phone:n,type:r,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a?.message_id},error:o})}throw new Ba(`You must provide either an email or phone number and a type`)}catch(e){if(U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug(`#_acquireLock`,`begin`,e);try{if(this.lockAcquired){let e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug(`#_acquireLock`,`lock acquired for storage key`,this.storageKey);try{this.lockAcquired=!0;let e=t();for(this.pendingInLock.push((async()=>{try{await e}catch{}})()),await e;this.pendingInLock.length;){let e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug(`#_acquireLock`,`lock released for storage key`,this.storageKey),this.lockAcquired=!1}})}finally{this._debug(`#_acquireLock`,`end`)}}async _useSession(e){this._debug(`#_useSession`,`begin`);try{return await e(await this.__loadSession())}finally{this._debug(`#_useSession`,`end`)}}async __loadSession(){this._debug(`#__loadSession()`,`begin`),this.lockAcquired||this._debug(`#__loadSession()`,`used outside of an acquired lock!`,Error().stack);try{let e=null,t=await go(this.storage,this.storageKey);if(this._debug(`#getSession()`,`session from storage`,t),t!==null&&(this._isValidSession(t)?e=t:(this._debug(`#getSession()`,`session from storage is not valid`),await this._removeSession())),!e)return{data:{session:null},error:null};let n=e.expires_at?e.expires_at*1e3-Date.now()<Da:!1;if(this._debug(`#__loadSession()`,`session has${n?``:` not`} expired`,`expires_at`,e.expires_at),!n){if(this.userStorage){let t=await go(this.userStorage,this.storageKey+`-user`);t?.user?e.user=t.user:e.user=Mo()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let t={value:this.suppressGetSessionWarning};e.user=No(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:r,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:r},error:null})}finally{this._debug(`#__loadSession()`,`end`)}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await J(this.fetch,`GET`,`${this.url}/user`,{headers:this.headers,jwt:e,xform:X}):await this._useSession(async e=>{let{data:t,error:n}=e;if(n)throw n;return!t.session?.access_token&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new G}:await J(this.fetch,`GET`,`${this.url}/user`,{headers:this.headers,jwt:t.session?.access_token??void 0,xform:X})})}catch(e){if(U(e))return Ra(e)&&(await this._removeSession(),await q(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async n=>{let{data:r,error:i}=n;if(i)throw i;if(!r.session)throw new G;let a=r.session,o=null,s=null;this.flowType===`pkce`&&e.email!=null&&([o,s]=await To(this.storage,this.storageKey));let{data:c,error:l}=await J(this.fetch,`PUT`,`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:s}),jwt:a.access_token,xform:X});if(l)throw l;return a.user=c.user,await this._saveSession(a),await this._notifyAllSubscribers(`USER_UPDATED`,a),this._returnResult({data:{user:a.user},error:null})})}catch(e){if(await q(this.storage,`${this.storageKey}-code-verifier`),U(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new G;let t=Date.now()/1e3,n=t,r=!0,i=null,{payload:a}=vo(e.access_token);if(a.exp&&(n=a.exp,r=n<=t),r){let{data:t,error:n}=await this._callRefreshToken(e.refresh_token);if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!t)return{data:{user:null,session:null},error:null};i=t}else{let{data:r,error:a}=await this._getUser(e.access_token);if(a)return this._returnResult({data:{user:null,session:null},error:a});i={access_token:e.access_token,refresh_token:e.refresh_token,user:r.user,token_type:`bearer`,expires_in:n-t,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers(`SIGNED_IN`,i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(e){if(U(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{if(!e){let{data:n,error:r}=t;if(r)throw r;e=n.session??void 0}if(!e?.refresh_token)throw new G;let{data:n,error:r}=await this._callRefreshToken(e.refresh_token);return r?this._returnResult({data:{user:null,session:null},error:r}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(e){if(U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!K())throw new Va(`No browser detected.`);if(e.error||e.error_description||e.error_code)throw new Va(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(this.flowType===`pkce`)throw new Ua(`Not a valid PKCE flow url.`);break;case`pkce`:if(this.flowType===`implicit`)throw new Va(`Not a valid implicit grant flow url.`);break;default:}if(t===`pkce`){if(this._debug(`#_initialize()`,`begin`,`is PKCE flow`,!0),!e.code)throw new Ua(`No code detected.`);let{data:t,error:n}=await this._exchangeCodeForSession(e.code);if(n)throw n;let 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}}let{provider_token:n,provider_refresh_token:r,access_token:i,refresh_token:a,expires_in:o,expires_at:s,token_type:c}=e;if(!i||!o||!a||!c)throw new Va(`No session defined in URL`);let l=Math.round(Date.now()/1e3),u=parseInt(o),d=l+u;s&&(d=parseInt(s));let f=d-l;f*1e3<=3e4&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);let p=d-u;l-p>=120?console.warn(`@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale`,p,d,l):l-p<0&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew`,p,d,l);let{data:m,error:h}=await this._getUser(i);if(h)throw h;let g={provider_token:n,provider_refresh_token:r,access_token:i,expires_in:u,expires_at:d,refresh_token:a,token_type:c,user:m.user};return window.location.hash=``,this._debug(`#_getSessionFromURL()`,`clearing window.location.hash`),this._returnResult({data:{session:g,redirectType:e.type},error:null})}catch(e){if(U(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl==`function`?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await go(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:`global`}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:`global`}){return await this._useSession(async t=>{let{data:n,error:r}=t;if(r&&!Ra(r))return this._returnResult({error:r});let i=n.session?.access_token;if(i){let{error:t}=await this.admin.signOut(i,e);if(t&&!(Ia(t)&&(t.status===404||t.status===401||t.status===403)||Ra(t)))return this._returnResult({error:t})}return e!==`others`&&(await this._removeSession(),await q(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let t=co(),n={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,n),(async()=>{await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async t=>{try{let{data:{session:n},error:r}=t;if(r)throw r;await this.stateChangeEmitters.get(e)?.callback(`INITIAL_SESSION`,n),this._debug(`INITIAL_SESSION`,`callback id`,e,`session`,n)}catch(t){await this.stateChangeEmitters.get(e)?.callback(`INITIAL_SESSION`,null),this._debug(`INITIAL_SESSION`,`callback id`,e,`error`,t),console.error(t)}})}async resetPasswordForEmail(e,t={}){let n=null,r=null;this.flowType===`pkce`&&([n,r]=await To(this.storage,this.storageKey,!0));try{return await J(this.fetch,`POST`,`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:r,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(await q(this.storage,`${this.storageKey}-code-verifier`),U(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){try{let{data:e,error:t}=await this.getUser();if(t)throw t;return this._returnResult({data:{identities:e.user.identities??[]},error:null})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return`token`in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){try{let{data:t,error:n}=await this._useSession(async t=>{let{data:n,error:r}=t;if(r)throw r;let i=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:e.options?.redirectTo,scopes:e.options?.scopes,queryParams:e.options?.queryParams,skipBrowserRedirect:!0});return await J(this.fetch,`GET`,i,{headers:this.headers,jwt:n.session?.access_token??void 0})});if(n)throw n;return K()&&!e.options?.skipBrowserRedirect&&window.location.assign(t?.url),this._returnResult({data:{provider:e.provider,url:t?.url},error:null})}catch(t){if(U(t))return this._returnResult({data:{provider:e.provider,url:null},error:t});throw t}}async linkIdentityIdToken(e){return await this._useSession(async t=>{try{let{error:n,data:{session:r}}=t;if(n)throw n;let{options:i,provider:a,token:o,access_token:s,nonce:c}=e,{data:l,error:u}=await J(this.fetch,`POST`,`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:r?.access_token??void 0,body:{provider:a,id_token:o,access_token:s,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Y});return u?this._returnResult({data:{user:null,session:null},error:u}):!l||!l.session||!l.user?this._returnResult({data:{user:null,session:null},error:new za}):(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers(`USER_UPDATED`,l.session)),this._returnResult({data:l,error:u}))}catch(e){if(await q(this.storage,`${this.storageKey}-code-verifier`),U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)throw r;return await J(this.fetch,`DELETE`,`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:n.session?.access_token??void 0})})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,`begin`);try{let n=Date.now();return await bo(async n=>(n>0&&await yo(200*2**(n-1)),this._debug(t,`refreshing attempt`,n),await J(this.fetch,`POST`,`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Y})),(e,t)=>{let r=200*2**e;return t&&Ka(t)&&Date.now()+r-n<3e4})}catch(e){if(this._debug(t,`error`,e),U(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}finally{this._debug(t,`end`)}}_isValidSession(e){return typeof e==`object`&&!!e&&`access_token`in e&&`refresh_token`in e&&`expires_at`in e}async _handleProviderSignIn(e,t){let n=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`,n),K()&&!t.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){let e=`#_recoverAndRefresh()`;this._debug(e,`begin`);try{let t=await go(this.storage,this.storageKey);if(t&&this.userStorage){let e=await go(this.userStorage,this.storageKey+`-user`);!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!e&&(e={user:t.user},await ho(this.userStorage,this.storageKey+`-user`,e)),t.user=e?.user??Mo()}else if(t&&!t.user&&!t.user){let e=await go(this.storage,this.storageKey+`-user`);e&&e?.user?(t.user=e.user,await q(this.storage,this.storageKey+`-user`),await ho(this.storage,this.storageKey,t)):t.user=Mo()}if(this._debug(e,`session from storage`,t),!this._isValidSession(t)){this._debug(e,`session is not valid`),t!==null&&await this._removeSession();return}let n=(t.expires_at??1/0)*1e3-Date.now()<Da;if(this._debug(e,`session has${n?``:` not`} expired with margin of ${Da}s`),n){if(this.autoRefreshToken&&t.refresh_token){let{error:n}=await this._callRefreshToken(t.refresh_token);n&&(console.error(n),Ka(n)||(this._debug(e,`refresh failed with a non-retryable error, removing the session`,n),await this._removeSession()))}}else if(t.user&&t.user.__isUserNotAvailableProxy===!0)try{let{data:n,error:r}=await this._getUser(t.access_token);!r&&n?.user?(t.user=n.user,await this._saveSession(t),await this._notifyAllSubscribers(`SIGNED_IN`,t)):this._debug(e,`could not get user data, skipping SIGNED_IN notification`)}catch(t){console.error(`Error getting user data:`,t),this._debug(e,`error getting user data, skipping SIGNED_IN notification`,t)}else await this._notifyAllSubscribers(`SIGNED_IN`,t)}catch(t){this._debug(e,`error`,t),console.error(t);return}finally{this._debug(e,`end`)}}async _callRefreshToken(e){var t,n;if(!e)throw new G;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,`begin`);try{this.refreshingDeferred=new _o;let{data:t,error:n}=await this._refreshAccessToken(e);if(n)throw n;if(!t.session)throw new G;await this._saveSession(t.session),await this._notifyAllSubscribers(`TOKEN_REFRESHED`,t.session);let r={data:t.session,error:null};return this.refreshingDeferred.resolve(r),r}catch(e){if(this._debug(r,`error`,e),U(e)){let n={data:null,error:e};return Ka(e)||await this._removeSession(),(t=this.refreshingDeferred)==null||t.resolve(n),n}throw(n=this.refreshingDeferred)==null||n.reject(e),e}finally{this.refreshingDeferred=null,this._debug(r,`end`)}}async _notifyAllSubscribers(e,t,n=!0){let r=`#_notifyAllSubscribers(${e})`;this._debug(r,`begin`,t,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:t});let r=[],i=Array.from(this.stateChangeEmitters.values()).map(async n=>{try{await n.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 q(this.storage,`${this.storageKey}-code-verifier`);let t=Object.assign({},e),n=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!n&&t.user&&await ho(this.userStorage,this.storageKey+`-user`,{user:t.user});let e=Object.assign({},t);delete e.user;let r=Po(e);await ho(this.storage,this.storageKey,r)}else{let e=Po(t);await ho(this.storage,this.storageKey,e)}}async _removeSession(){this._debug(`#_removeSession()`),this.suppressGetSessionWarning=!1,await q(this.storage,this.storageKey),await q(this.storage,this.storageKey+`-code-verifier`),await q(this.storage,this.storageKey+`-user`),this.userStorage&&await q(this.userStorage,this.storageKey+`-user`),await this._notifyAllSubscribers(`SIGNED_OUT`,null)}_removeVisibilityChangedCallback(){this._debug(`#_removeVisibilityChangedCallback()`);let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&K()&&window!=null&&window.removeEventListener&&window.removeEventListener(`visibilitychange`,e)}catch(e){console.error(`removing visibilitychange callback failed`,e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug(`#_startAutoRefresh()`);let e=setInterval(()=>this._autoRefreshTokenTick(),Ea);this.autoRefreshTicker=e,e&&typeof e==`object`&&typeof e.unref==`function`?e.unref():typeof Deno<`u`&&typeof Deno.unrefTimer==`function`&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&typeof t==`object`&&typeof t.unref==`function`?t.unref():typeof Deno<`u`&&typeof Deno.unrefTimer==`function`&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug(`#_stopAutoRefresh()`);let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug(`#_autoRefreshTokenTick()`,`begin`);try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:n}}=t;if(!n||!n.refresh_token||!n.expires_at){this._debug(`#_autoRefreshTokenTick()`,`no session`);return}let r=Math.floor((n.expires_at*1e3-e)/Ea);this._debug(`#_autoRefreshTokenTick()`,`access token expires in ${r} ticks, a tick lasts ${Ea}ms, refresh threshold is 3 ticks`),r<=3&&await this._callRefreshToken(n.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 Jo)this._debug(`auto refresh token tick lock not available`);else throw e}}async _handleVisibilityChange(){if(this._debug(`#_handleVisibilityChange()`),!K()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug(`#visibilityChangedCallback`,`error`,e)}},window==null||window.addEventListener(`visibilitychange`,this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error(`_handleVisibilityChange`,e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,`visibilityState`,document.visibilityState),document.visibilityState===`visible`?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!==`visible`){this._debug(t,`acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting`);return}await this._recoverAndRefresh()}))):document.visibilityState===`hidden`&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,n){let r=[`provider=${encodeURIComponent(t)}`];if(n?.redirectTo&&r.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n?.scopes&&r.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType===`pkce`){let[e,t]=await To(this.storage,this.storageKey),n=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});r.push(n.toString())}if(n?.queryParams){let e=new URLSearchParams(n.queryParams);r.push(e.toString())}return n?.skipBrowserRedirect&&r.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${r.join(`&`)}`}async _unenroll(e){try{return await this._useSession(async t=>{let{data:n,error:r}=t;return r?this._returnResult({data:null,error:r}):await J(this.fetch,`DELETE`,`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:n?.session?.access_token})})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)return this._returnResult({data:null,error:r});let i=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType===`phone`?{phone:e.phone}:e.factorType===`totp`?{issuer:e.issuer}:{}),{data:a,error:o}=await J(this.fetch,`POST`,`${this.url}/factors`,{body:i,headers:this.headers,jwt:n?.session?.access_token});return o?this._returnResult({data:null,error:o}):(e.factorType===`totp`&&a.type===`totp`&&a?.totp?.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),this._returnResult({data:a,error:null}))})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)return this._returnResult({data:null,error:r});let i=Object.assign({challenge_id:e.challengeId},`webauthn`in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type===`create`?cs(e.webauthn.credential_response):ls(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:o}=await J(this.fetch,`POST`,`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:n?.session?.access_token});return o?this._returnResult({data:null,error:o}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers(`MFA_CHALLENGE_VERIFIED`,a),this._returnResult({data:a,error:o}))})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)return this._returnResult({data:null,error:r});let i=await J(this.fetch,`POST`,`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:n?.session?.access_token});if(i.error)return i;let{data:a}=i;if(a.type!==`webauthn`)return{data:a,error:null};switch(a.webauthn.type){case`create`:return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:os(a.webauthn.credential_options.publicKey)})})}),error:null};case`request`:return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:ss(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}})}async _challengeAndVerify(e){let{data:t,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let n={all:[],phone:[],totp:[],webauthn:[]};for(let t of e?.factors??[])n.all.push(t),t.status===`verified`&&n[t.factor_type].push(t);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){if(e)try{let{payload:t}=vo(e),n=null;t.aal&&(n=t.aal);let r=n,{data:{user:i},error:a}=await this.getUser(e);if(a)return this._returnResult({data:null,error:a});((i?.factors)?.filter(e=>e.status===`verified`)??[]).length>0&&(r=`aal2`);let o=t.amr||[];return{data:{currentLevel:n,nextLevel:r,currentAuthenticationMethods:o},error:null}}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}let{data:{session:t},error:n}=await this.getSession();if(n)return this._returnResult({data:null,error:n});if(!t)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:r}=vo(t.access_token),i=null;r.aal&&(i=r.aal);let a=i;(t.user.factors?.filter(e=>e.status===`verified`)??[]).length>0&&(a=`aal2`);let o=r.amr||[];return{data:{currentLevel:i,nextLevel:a,currentAuthenticationMethods:o},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:n},error:r}=t;return r?this._returnResult({data:null,error:r}):n?await J(this.fetch,`GET`,`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new G})})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession(async n=>{let{data:{session:r},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!r)return this._returnResult({data:null,error:new G});let a=await J(this.fetch,`POST`,`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:r.access_token,body:{action:`approve`},xform:e=>({data:e,error:null})});return a.data&&a.data.redirect_url&&K()&&!t?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession(async n=>{let{data:{session:r},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!r)return this._returnResult({data:null,error:new G});let a=await J(this.fetch,`POST`,`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:r.access_token,body:{action:`deny`},xform:e=>({data:e,error:null})});return a.data&&a.data.redirect_url&&K()&&!t?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;return n?this._returnResult({data:null,error:n}):t?await J(this.fetch,`GET`,`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new G})})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:n},error:r}=t;return r?this._returnResult({data:null,error:r}):n?(await J(this.fetch,`DELETE`,`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new G})})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e,t={keys:[]}){let n=t.keys.find(t=>t.kid===e);if(n)return n;let r=Date.now();if(n=this.jwks.keys.find(t=>t.kid===e),n&&this.jwks_cached_at+6e5>r)return n;let{data:i,error:a}=await J(this.fetch,`GET`,`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=r,n=i.keys.find(t=>t.kid===e),!n)?null:n}async getClaims(e,t={}){try{let n=e;if(!n){let{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});n=e.session.access_token}let{header:r,payload:i,signature:a,raw:{header:o,payload:s}}=vo(n);t?.allowExpired||Oo(i.exp);let c=!r.alg||r.alg.startsWith(`HS`)||!r.kid||!(`crypto`in globalThis&&`subtle`in globalThis.crypto)?null:await this.fetchJwk(r.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!c){let{error:e}=await this.getUser(n);if(e)throw e;return{data:{claims:i,header:r,signature:a},error:null}}let l=ko(r.alg),u=await crypto.subtle.importKey(`jwk`,c,l,!0,[`verify`]);if(!await crypto.subtle.verify(l,u,a,ao(`${o}.${s}`)))throw new Ja(`Invalid JWT signature`);return{data:{claims:i,header:r,signature:a},error:null}}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}};Cs.nextInstanceID={};var ws=Cs,Ts=`2.99.3`,Es=``;Es=typeof Deno<`u`?`deno`:typeof document<`u`?`web`:typeof navigator<`u`&&navigator.product===`ReactNative`?`react-native`:`node`;var Ds={headers:{"X-Client-Info":`supabase-js-${Es}/${Ts}`}},Os={schema:`public`},ks={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:`implicit`},As={};function js(e){"@babel/helpers - typeof";return js=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},js(e)}function Ms(e,t){if(js(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(js(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Ns(e){var t=Ms(e,`string`);return js(t)==`symbol`?t:t+``}function Ps(e,t,n){return(t=Ns(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Fs(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function $(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Fs(Object(n),!0).forEach(function(t){Ps(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Fs(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var Is=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Ls=()=>Headers,Rs=(e,t,n)=>{let r=Is(n),i=Ls();return async(n,a)=>{let o=await t()??e,s=new i(a?.headers);return s.has(`apikey`)||s.set(`apikey`,e),s.has(`Authorization`)||s.set(`Authorization`,`Bearer ${o}`),r(n,$($({},a),{},{headers:s}))}};function zs(e){return e.endsWith(`/`)?e:e+`/`}function Bs(e,t){let{db:n,auth:r,realtime:i,global:a}=e,{db:o,auth:s,realtime:c,global:l}=t,u={db:$($({},o),n),auth:$($({},s),r),realtime:$($({},c),i),storage:{},global:$($($({},l),a),{},{headers:$($({},l?.headers??{}),a?.headers??{})}),accessToken:async()=>``};return e.accessToken?u.accessToken=e.accessToken:delete u.accessToken,u}function Vs(e){let t=e?.trim();if(!t)throw Error(`supabaseUrl is required.`);if(!t.match(/^https?:\/\//i))throw Error(`Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.`);try{return new URL(zs(t))}catch{throw Error(`Invalid supabaseUrl: Provided URL is malformed.`)}}var Hs=class extends ws{constructor(e){super(e)}},Us=class{constructor(e,t,n){this.supabaseUrl=e,this.supabaseKey=t;let r=Vs(e);if(!t)throw Error(`supabaseKey is required.`);this.realtimeUrl=new URL(`realtime/v1`,r),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace(`http`,`ws`),this.authUrl=new URL(`auth/v1`,r),this.storageUrl=new URL(`storage/v1`,r),this.functionsUrl=new URL(`functions/v1`,r);let i=`sb-${r.hostname.split(`.`)[0]}-auth-token`,a={db:Os,realtime:As,auth:$($({},ks),{},{storageKey:i}),global:Ds},o=Bs(n??{},a);this.storageKey=o.auth.storageKey??``,this.headers=o.global.headers??{},o.accessToken?(this.accessToken=o.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(o.auth??{},this.headers,o.global.fetch),this.fetch=Rs(t,this._getAccessToken.bind(this),o.global.fetch),this.realtime=this._initRealtimeClient($({headers:this.headers,accessToken:this._getAccessToken.bind(this)},o.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(e=>this.realtime.setAuth(e)).catch(e=>console.warn(`Failed to set initial Realtime auth token:`,e)),this.rest=new Zr(new URL(`rest/v1`,r).href,{headers:this.headers,schema:o.db.schema,fetch:this.fetch,timeout:o.db.timeout,urlLengthLimit:o.db.urlLengthLimit}),this.storage=new wa(this.storageUrl.href,this.headers,this.fetch,n?.storage),o.accessToken||this._listenForAuthEvents()}get functions(){return new Rr(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},n={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,n)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e=this;if(e.accessToken)return await e.accessToken();let{data:t}=await e.auth.getSession();return t.session?.access_token??e.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:i,storageKey:a,flowType:o,lock:s,debug:c,throwOnError:l},u,d){let f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Hs({url:this.authUrl.href,headers:$($({},f),u),storageKey:a,autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:i,flowType:o,lock:s,debug:c,throwOnError:l,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>e.toLowerCase()===`authorization`)})}_initRealtimeClient(e){return new Ai(this.realtimeUrl.href,$($({},e),{},{params:$($({},{apikey:this.supabaseKey}),e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,`CLIENT`,t?.access_token)})}_handleTokenChanged(e,t,n){(e===`TOKEN_REFRESHED`||e===`SIGNED_IN`)&&this.changedAccessToken!==n?(this.changedAccessToken=n,this.realtime.setAuth(n)):e===`SIGNED_OUT`&&(this.realtime.setAuth(),t==`STORAGE`&&this.auth.signOut(),this.changedAccessToken=void 0)}},Ws=(e,t,n)=>new Us(e,t,n);function Gs(){if(typeof window<`u`)return!1;let e=globalThis.process;if(!e)return!1;let t=e.version;if(t==null)return!1;let n=t.match(/^v(\d+)\./);return n?parseInt(n[1],10)<=18:!1}Gs()&&console.warn(`⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217`);var Ks=()=>({url:`https://uehmyyeqheqnxmzhctcd.supabase.co`,anonKey:`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InVlaG15eWVxaGVxbnhtemhjdGNkIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTg2MjA3NDMsImV4cCI6MjAzNDE5Njc0M30.a6tyestJTPSQ6ZdpjRGrataTSn_8_REHJC0SnoCaY2Y`}),qs=()=>{let{url:e,anonKey:t}=Ks();return!!(e&&t)},Js=e=>{let{url:t,anonKey:n}=Ks();return!t||!n?(console.warn(`Supabase environment variables are not configured. Supabase will not be available.`),null):Ws(t,n,e)},Ys=e=>{if(e&&typeof e==`string`){let t=()=>typeof window<`u`?window.location.port===`5173`?`http://${window.location.hostname}:33753`:`${window.location.protocol}//${window.location.host}`:`http://localhost:33753`;if(e.startsWith(`file://`)){let n=e.substring(7);return`${t()}/media-file/${encodeURIComponent(n)}`}if(e.startsWith(`media://`)){let n=e.replace(/^media:\/\/+/,`/`);return`${t()}/media-file/${encodeURIComponent(n)}`}}return e||``},Xs=e=>e.required===!0,Zs=class extends Error{constructor(e,t,n){super(e),this.code=t,this.requestId=n,this.name=`WebSocketError`}},Qs=class extends Zs{constructor(e,t){super(e),this.url=t,this.name=`WebSocketConnectionError`}},$s=e=>e&&typeof e.channel==`string`&&e.requestId,ec=e=>e&&e.type===`response`&&e.requestId&&e.events,tc=e=>e&&e.type===`error`&&e.requestId&&e.error;E(`1.0.0`),O(tt(k(),kr),{}),E(`2.0.0`),O(w(kr),[]),E(`1.0.0`),O(tt(k(),kr),{}),E(`2.0.0`),O(w(kr),[]);var nc=e({EditorParamValidatorV3:()=>gr,OriginValidator:()=>hr,SaveLocationExternalValidator:()=>Dr,SaveLocationInternalValidator:()=>Er,SaveLocationPipelabCloudValidator:()=>Or,SaveLocationValidator:()=>kr,SavedFileDefaultValidatorV4:()=>xr,SavedFileDefaultValidatorV5:()=>Cr,SavedFileSimpleValidatorV4:()=>Sr,SavedFileValidator:()=>Tr,SavedFileValidatorV5:()=>wr,ShellChannels:()=>vt,VariableValidatorV1:()=>br,WebSocketConnectionError:()=>Qs,WebSocketError:()=>Zs,createQuickJs:()=>fr,createQuickJsFromVariant:()=>dr,defaultFileRepo:()=>rc,fmt:()=>cr,foo:()=>`bar`,isRequired:()=>Xs,isSupabaseAvailable:()=>qs,isWebSocketErrorMessage:()=>tc,isWebSocketRequestMessage:()=>$s,isWebSocketResponseMessage:()=>ec,makeResolvedParams:()=>pr,supabase:()=>Js,transformUrl:()=>Ys,useLogger:()=>cn,variableToFormattedVariable:()=>mr}),rc=pt;export{D as C,k as D,Xe as E,S as O,Ye as S,ot as T,dn as _,tc as a,qe as b,Xs as c,Js as d,Tr as f,dr as g,fr as h,Zs as i,Ys as l,pr as m,nc as n,$s as o,mr as p,Qs as r,ec as s,rc as t,qs as u,cn as v,at as w,Je as x,vt as y};
113
+ })`):Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState(`disconnecting`,!0),this.conn){let n=setTimeout(()=>{this._setConnectionState(`disconnected`)},100);this.conn.onclose=()=>{clearTimeout(n),this._setConnectionState(`disconnected`)},typeof this.conn.close==`function`&&(e?this.conn.close(e,t??``):this.conn.close()),this._teardownConnection()}else this._setConnectionState(`disconnected`)}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(e=>e.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,n){this.logger(e,t,n)}connectionState(){switch(this.conn&&this.conn.readyState){case ci.connecting:return ui.Connecting;case ci.open:return ui.Open;case ci.closing:return ui.Closing;default:return ui.Closed}}isConnected(){return this.connectionState()===ui.Open}isConnecting(){return this._connectionState===`connecting`}isDisconnecting(){return this._connectionState===`disconnecting`}channel(e,t={config:{}}){let n=`realtime:${e}`,r=this.getChannels().find(e=>e.topic===n);if(r)return r;{let n=new Oi(`realtime:${e}`,t,this);return this.channels.push(n),n}}push(e){let{topic:t,event:n,payload:r,ref:i}=e,a=()=>{this.encode(e,e=>{var t;(t=this.conn)==null||t.send(e)})};this.log(`push`,`${t} ${n} (${i})`,r),this.isConnected()?a():this.sendBuffer.push(a)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback(`disconnected`)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log(`transport`,`heartbeat timeout. Attempting to re-establish connection`);try{this.heartbeatCallback(`timeout`)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}this._wasManualDisconnect=!1,(e=this.conn)==null||e.close(1e3,`heartbeat timeout`),setTimeout(()=>{var e;this.isConnected()||(e=this.reconnectTimer)==null||e.scheduleTimeout()},Ai.HEARTBEAT_TIMEOUT_FALLBACK);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:`phoenix`,event:`heartbeat`,payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback(`sent`)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}this._setAuthSafely(`heartbeat`)}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log(`transport`,`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,e=>{if(e.topic===`phoenix`&&e.event===`phx_reply`&&e.ref&&e.ref===this.pendingHeartbeatRef){let t=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback(e.payload.status===`ok`?`ok`:`error`,t)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}let{topic:t,event:n,payload:r,ref:i}=e,a=i?`(${i})`:``,o=r.status||``;this.log(`receive`,`${o} ${t} ${n} ${a}`.trim(),r),this.channels.filter(e=>e._isMember(t)).forEach(e=>e._trigger(n,r,i)),this._triggerStateCallbacks(`message`,e)})}_clearTimer(e){var t;e===`heartbeat`&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e===`reconnect`&&((t=this.reconnectTimer)==null||t.reset())}_clearAllTimers(){this._clearTimer(`heartbeat`),this._clearTimer(`reconnect`)}_setupConnectionHandlers(){this.conn&&(`binaryType`in this.conn&&(this.conn.binaryType=`arraybuffer`),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e),this.conn.readyState===ci.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===ci.open||this.conn.readyState===ci.connecting)try{this.conn.close()}catch(e){this.log(`error`,`Error closing connection`,e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState(`connected`),this.log(`transport`,`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.accessTokenValue&&(this.channels.forEach(e=>{e.updateJoinPayload({access_token:this.accessTokenValue})}),this.sendBuffer=[],this.channels.forEach(e=>{e._isJoining()&&(e.joinPush.sent=!1,e.joinPush.send())})),this.flushSendBuffer()}).catch(e=>{this.log(`error`,`error waiting for auth on connect`,e),this.flushSendBuffer()}),this._clearTimer(`reconnect`),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks(`open`)}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log(`worker`,`starting worker for from ${this.workerUrl}`):this.log(`worker`,`starting default worker`);let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log(`worker`,`worker error`,e.message),this._terminateWorker()},this.workerRef.onmessage=e=>{e.data.event===`keepAlive`&&this.sendHeartbeat()},this.workerRef.postMessage({event:`start`,interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&=(this.log(`worker`,`terminating worker`),this.workerRef.terminate(),void 0)}_onConnClose(e){var t;this._setConnectionState(`disconnected`),this.log(`transport`,`close`,e),this._triggerChanError(),this._clearTimer(`heartbeat`),this._wasManualDisconnect||(t=this.reconnectTimer)==null||t.scheduleTimeout(),this._triggerStateCallbacks(`close`,e)}_onConnError(e){this._setConnectionState(`disconnected`),this.log(`transport`,`${e}`),this._triggerChanError(),this._triggerStateCallbacks(`error`,e);try{this.heartbeatCallback(`error`)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}}_triggerChanError(){this.channels.forEach(e=>e._trigger(L.error))}_appendParams(e,t){return Object.keys(t).length===0?e:`${e}${e.match(/\?/)?`&`:`?`}${new URLSearchParams(t)}`}_workerObjectUrl(e){let t;if(e)t=e;else{let e=new Blob([Ni],{type:`application/javascript`});t=URL.createObjectURL(e)}return t}_setConnectionState(e,t=!1){this._connectionState=e,e===`connecting`?this._wasManualDisconnect=!1:e===`disconnecting`&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t,n=!1;if(e)t=e,n=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(e){this.log(`error`,`Error fetching access token from callback`,e),t=this.accessTokenValue}else t=this.accessTokenValue;n?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{let n={access_token:t,version:ri};t&&e.updateJoinPayload(n),e.joinedOnce&&e._isJoined()&&e._push(L.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e=`general`){this._isManualToken()||this.setAuth().catch(t=>{this.log(`error`,`Error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(n=>{try{n(t)}catch(t){this.log(`error`,`error in ${e} callback`,t)}})}catch(t){this.log(`error`,`error triggering ${e} callbacks`,t)}}_setupReconnectionTimer(){this.reconnectTimer=new fi(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},Ai.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){switch(this.transport=e?.transport??null,this.timeout=e?.timeout??si,this.heartbeatIntervalMs=e?.heartbeatIntervalMs??Ai.HEARTBEAT_INTERVAL,this.worker=e?.worker??!1,this.accessToken=e?.accessToken??null,this.heartbeatCallback=e?.heartbeatCallback??ki,this.vsn=e?.vsn??oi,e?.params&&(this.params=e.params),e?.logger&&(this.logger=e.logger),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=e?.reconnectAfterMs??(e=>ji[e-1]||Mi),this.vsn){case ii:this.encode=e?.encode??((e,t)=>t(JSON.stringify(e))),this.decode=e?.decode??((e,t)=>t(JSON.parse(e)));break;case ai:this.encode=e?.encode??this.serializer.encode.bind(this.serializer),this.decode=e?.decode??this.serializer.decode.bind(this.serializer);break;default:throw Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<`u`&&!window.Worker)throw Error(`Web Worker is not supported`);this.workerUrl=e?.workerUrl}}},Fi=class extends Error{constructor(e,t){super(e),this.name=`IcebergError`,this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown=t.icebergType===`CommitStateUnknownException`||[500,502,504].includes(t.status)&&t.icebergType?.includes(`CommitState`)===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function Ii(e,t,n){let r=new URL(t,e);if(n)for(let[e,t]of Object.entries(n))t!==void 0&&r.searchParams.set(e,t);return r.toString()}async function Li(e){return!e||e.type===`none`?{}:e.type===`bearer`?{Authorization:`Bearer ${e.token}`}:e.type===`header`?{[e.name]:e.value}:e.type===`custom`?await e.getHeaders():{}}function Ri(e){let t=e.fetchImpl??globalThis.fetch;return{async request({method:n,path:r,query:i,body:a,headers:o}){let s=Ii(e.baseUrl,r,i),c=await Li(e.auth),l=await t(s,{method:n,headers:{...a?{"Content-Type":`application/json`}:{},...c,...o},body:a?JSON.stringify(a):void 0}),u=await l.text(),d=(l.headers.get(`content-type`)||``).includes(`application/json`),f=d&&u?JSON.parse(u):u;if(!l.ok){let e=d?f:void 0,t=e?.error;throw new Fi(t?.message??`Request failed with status ${l.status}`,{status:l.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:l.status,headers:l.headers,data:f}}}}function zi(e){return e.join(``)}var Bi=class{constructor(e,t=``){this.client=e,this.prefix=t}async listNamespaces(e){let t=e?{parent:zi(e.namespace)}:void 0;return(await this.client.request({method:`GET`,path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(e=>({namespace:e}))}async createNamespace(e,t){let n={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:`POST`,path:`${this.prefix}/namespaces`,body:n})).data}async dropNamespace(e){await this.client.request({method:`DELETE`,path:`${this.prefix}/namespaces/${zi(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:`GET`,path:`${this.prefix}/namespaces/${zi(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:`HEAD`,path:`${this.prefix}/namespaces/${zi(e.namespace)}`}),!0}catch(e){if(e instanceof Fi&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof Fi&&e.status===409)return;throw e}}};function Vi(e){return e.join(``)}var Hi=class{constructor(e,t=``,n){this.client=e,this.prefix=t,this.accessDelegation=n}async listTables(e){return(await this.client.request({method:`GET`,path:`${this.prefix}/namespaces/${Vi(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){let n={};return this.accessDelegation&&(n[`X-Iceberg-Access-Delegation`]=this.accessDelegation),(await this.client.request({method:`POST`,path:`${this.prefix}/namespaces/${Vi(e.namespace)}/tables`,body:t,headers:n})).data.metadata}async updateTable(e,t){let n=await this.client.request({method:`POST`,path:`${this.prefix}/namespaces/${Vi(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":n.data[`metadata-location`],metadata:n.data.metadata}}async dropTable(e,t){await this.client.request({method:`DELETE`,path:`${this.prefix}/namespaces/${Vi(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){let t={};return this.accessDelegation&&(t[`X-Iceberg-Access-Delegation`]=this.accessDelegation),(await this.client.request({method:`GET`,path:`${this.prefix}/namespaces/${Vi(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){let t={};this.accessDelegation&&(t[`X-Iceberg-Access-Delegation`]=this.accessDelegation);try{return await this.client.request({method:`HEAD`,path:`${this.prefix}/namespaces/${Vi(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof Fi&&e.status===404)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(n){if(n instanceof Fi&&n.status===409)return await this.loadTable({namespace:e.namespace,name:t.name});throw n}}},Ui=class{constructor(e){let t=`v1`;e.catalogName&&(t+=`/${e.catalogName}`),this.client=Ri({baseUrl:e.baseUrl.endsWith(`/`)?e.baseUrl:`${e.baseUrl}/`,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(`,`),this.namespaceOps=new Bi(this.client,t),this.tableOps=new Hi(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}},Wi=class extends Error{constructor(e,t=`storage`,n,r){super(e),this.__isStorageError=!0,this.namespace=t,this.name=t===`vectors`?`StorageVectorsError`:`StorageError`,this.status=n,this.statusCode=r}};function Gi(e){return typeof e==`object`&&!!e&&`__isStorageError`in e}var Ki=class extends Wi{constructor(e,t,n,r=`storage`){super(e,r,t,n),this.name=r===`vectors`?`StorageVectorsApiError`:`StorageApiError`,this.status=t,this.statusCode=n}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},qi=class extends Wi{constructor(e,t,n=`storage`){super(e,n),this.name=n===`vectors`?`StorageVectorsUnknownError`:`StorageUnknownError`,this.originalError=t}},Ji=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Yi=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},Xi=e=>{if(Array.isArray(e))return e.map(e=>Xi(e));if(typeof e==`function`||e!==Object(e))return e;let t={};return Object.entries(e).forEach(([e,n])=>{let r=e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,``));t[r]=Xi(n)}),t},Zi=e=>!e||typeof e!=`string`||e.length===0||e.length>100||e.trim()!==e||e.includes(`/`)||e.includes(`\\`)?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(e);function Qi(e){"@babel/helpers - typeof";return Qi=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},Qi(e)}function $i(e,t){if(Qi(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(Qi(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function ea(e){var t=$i(e,`string`);return Qi(t)==`symbol`?t:t+``}function ta(e,t,n){return(t=ea(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function na(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function B(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?na(Object(n),!0).forEach(function(t){ta(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):na(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var ra=e=>e.msg||e.message||e.error_description||(typeof e.error==`string`?e.error:e.error?.message)||JSON.stringify(e),ia=async(e,t,n,r)=>{if(typeof e==`object`&&e&&typeof e.json==`function`){let n=e,i=parseInt(n.status,10);Number.isFinite(i)||(i=500),n.json().then(e=>{let n=e?.statusCode||e?.code||i+``;t(new Ki(ra(e),i,n,r))}).catch(()=>{let e=i+``;t(new Ki(n.statusText||`HTTP ${i} error`,i,e,r))})}else t(new qi(ra(e),e,r))},aa=(e,t,n,r)=>{let i={method:e,headers:t?.headers||{}};return e===`GET`||e===`HEAD`||!r?B(B({},i),n):(Yi(r)?(i.headers=B({"Content-Type":`application/json`},t?.headers),i.body=JSON.stringify(r)):i.body=r,t?.duplex&&(i.duplex=t.duplex),B(B({},i),n))};async function oa(e,t,n,r,i,a,o){return new Promise((s,c)=>{e(n,aa(t,r,i,a)).then(e=>{if(!e.ok)throw e;if(r?.noResolveJson)return e;if(o===`vectors`){let t=e.headers.get(`content-type`);if(e.headers.get(`content-length`)===`0`||e.status===204||!t||!t.includes(`application/json`))return{}}return e.json()}).then(e=>s(e)).catch(e=>ia(e,c,r,o))})}function sa(e=`storage`){return{get:async(t,n,r,i)=>oa(t,`GET`,n,r,i,void 0,e),post:async(t,n,r,i,a)=>oa(t,`POST`,n,i,a,r,e),put:async(t,n,r,i,a)=>oa(t,`PUT`,n,i,a,r,e),head:async(t,n,r,i)=>oa(t,`HEAD`,n,B(B({},r),{},{noResolveJson:!0}),i,void 0,e),remove:async(t,n,r,i,a)=>oa(t,`DELETE`,n,i,a,r,e)}}var{get:ca,post:V,put:la,head:ua,remove:da}=sa(`storage`),H=sa(`vectors`),fa=class{constructor(e,t={},n,r=`storage`){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.fetch=Ji(n),this.namespace=r}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=B(B({},this.headers),{},{[e]:t}),this}async handleOperation(e){var t=this;try{return{data:await e(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Gi(e))return{data:null,error:e};throw e}}},pa=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}async execute(){var e=this;try{return{data:(await e.downloadFn()).body,error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Gi(t))return{data:null,error:t};throw t}}},ma=Symbol.toStringTag,ha=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[ma]=`BlobDownloadBuilder`,this.promise=null}asStream(){return new pa(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||=this.execute(),this.promise}async execute(){var e=this;try{return{data:await(await e.downloadFn()).blob(),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Gi(t))return{data:null,error:t};throw t}}},ga={limit:100,offset:0,sortBy:{column:`name`,order:`asc`}},_a={cacheControl:`3600`,contentType:`text/plain;charset=UTF-8`,upsert:!1},va=class extends fa{constructor(e,t={},n,r){super(e,t,r,`storage`),this.bucketId=n}async uploadOrUpdate(e,t,n,r){var i=this;return i.handleOperation(async()=>{let a,o=B(B({},_a),r),s=B(B({},i.headers),e===`POST`&&{"x-upsert":String(o.upsert)}),c=o.metadata;typeof Blob<`u`&&n instanceof Blob?(a=new FormData,a.append(`cacheControl`,o.cacheControl),c&&a.append(`metadata`,i.encodeMetadata(c)),a.append(``,n)):typeof FormData<`u`&&n instanceof FormData?(a=n,a.has(`cacheControl`)||a.append(`cacheControl`,o.cacheControl),c&&!a.has(`metadata`)&&a.append(`metadata`,i.encodeMetadata(c))):(a=n,s[`cache-control`]=`max-age=${o.cacheControl}`,s[`content-type`]=o.contentType,c&&(s[`x-metadata`]=i.toBase64(i.encodeMetadata(c))),(typeof ReadableStream<`u`&&a instanceof ReadableStream||a&&typeof a==`object`&&`pipe`in a&&typeof a.pipe==`function`)&&!o.duplex&&(o.duplex=`half`)),r?.headers&&(s=B(B({},s),r.headers));let l=i._removeEmptyFolders(t),u=i._getFinalPath(l),d=await(e==`PUT`?la:V)(i.fetch,`${i.url}/object/${u}`,a,B({headers:s},o?.duplex?{duplex:o.duplex}:{}));return{path:l,id:d.Id,fullPath:d.Key}})}async upload(e,t,n){return this.uploadOrUpdate(`POST`,e,t,n)}async uploadToSignedUrl(e,t,n,r){var i=this;let a=i._removeEmptyFolders(e),o=i._getFinalPath(a),s=new URL(i.url+`/object/upload/sign/${o}`);return s.searchParams.set(`token`,t),i.handleOperation(async()=>{let e,t=B({upsert:_a.upsert},r),o=B(B({},i.headers),{"x-upsert":String(t.upsert)});return typeof Blob<`u`&&n instanceof Blob?(e=new FormData,e.append(`cacheControl`,t.cacheControl),e.append(``,n)):typeof FormData<`u`&&n instanceof FormData?(e=n,e.append(`cacheControl`,t.cacheControl)):(e=n,o[`cache-control`]=`max-age=${t.cacheControl}`,o[`content-type`]=t.contentType),{path:a,fullPath:(await la(i.fetch,s.toString(),e,{headers:o})).Key}})}async createSignedUploadUrl(e,t){var n=this;return n.handleOperation(async()=>{let r=n._getFinalPath(e),i=B({},n.headers);t?.upsert&&(i[`x-upsert`]=`true`);let a=await V(n.fetch,`${n.url}/object/upload/sign/${r}`,{},{headers:i}),o=new URL(n.url+a.url),s=o.searchParams.get(`token`);if(!s)throw new Wi(`No token returned by API`);return{signedUrl:o.toString(),path:e,token:s}})}async update(e,t,n){return this.uploadOrUpdate(`PUT`,e,t,n)}async move(e,t,n){var r=this;return r.handleOperation(async()=>await V(r.fetch,`${r.url}/object/move`,{bucketId:r.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n?.destinationBucket},{headers:r.headers}))}async copy(e,t,n){var r=this;return r.handleOperation(async()=>({path:(await V(r.fetch,`${r.url}/object/copy`,{bucketId:r.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n?.destinationBucket},{headers:r.headers})).Key}))}async createSignedUrl(e,t,n){var r=this;return r.handleOperation(async()=>{let i=r._getFinalPath(e),a=typeof n?.transform==`object`&&n.transform!==null&&Object.keys(n.transform).length>0,o=await V(r.fetch,`${r.url}/object/sign/${i}`,B({expiresIn:t},a?{transform:n.transform}:{}),{headers:r.headers}),s=n?.download?`&download=${n.download===!0?``:n.download}`:``,c=a&&o.signedURL.includes(`/object/sign/`)?o.signedURL.replace(`/object/sign/`,`/render/image/sign/`):o.signedURL;return{signedUrl:encodeURI(`${r.url}${c}${s}`)}})}async createSignedUrls(e,t,n){var r=this;return r.handleOperation(async()=>{let i=await V(r.fetch,`${r.url}/object/sign/${r.bucketId}`,{expiresIn:t,paths:e},{headers:r.headers}),a=n?.download?`&download=${n.download===!0?``:n.download}`:``;return i.map(e=>B(B({},e),{},{signedUrl:e.signedURL?encodeURI(`${r.url}${e.signedURL}${a}`):null}))})}download(e,t,n){let r=t?.transform===void 0?`object`:`render/image/authenticated`,i=this.transformOptsToQueryString(t?.transform||{}),a=i?`?${i}`:``,o=this._getFinalPath(e);return new ha(()=>ca(this.fetch,`${this.url}/${r}/${o}${a}`,{headers:this.headers,noResolveJson:!0},n),this.shouldThrowOnError)}async info(e){var t=this;let n=t._getFinalPath(e);return t.handleOperation(async()=>Xi(await ca(t.fetch,`${t.url}/object/info/${n}`,{headers:t.headers})))}async exists(e){var t=this;let n=t._getFinalPath(e);try{return await ua(t.fetch,`${t.url}/object/${n}`,{headers:t.headers}),{data:!0,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Gi(e)){let t=e instanceof Ki?e.status:e instanceof qi?e.originalError?.status:void 0;if(t!==void 0&&[400,404].includes(t))return{data:!1,error:e}}throw e}}getPublicUrl(e,t){let n=this._getFinalPath(e),r=[],i=t?.download?`download=${t.download===!0?``:t.download}`:``;i!==``&&r.push(i);let a=t?.transform===void 0?`object`:`render/image`,o=this.transformOptsToQueryString(t?.transform||{});o!==``&&r.push(o);let s=r.join(`&`);return s!==``&&(s=`?${s}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${n}${s}`)}}}async remove(e){var t=this;return t.handleOperation(async()=>await da(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}))}async list(e,t,n){var r=this;return r.handleOperation(async()=>{let i=B(B(B({},ga),t),{},{prefix:e||``});return await V(r.fetch,`${r.url}/object/list/${r.bucketId}`,i,{headers:r.headers},n)})}async listV2(e,t){var n=this;return n.handleOperation(async()=>{let r=B({},e);return await V(n.fetch,`${n.url}/object/list-v2/${n.bucketId}`,r,{headers:n.headers},t)})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<`u`?Buffer.from(e).toString(`base64`):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,``)}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,``).replace(/\/+/g,`/`)}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join(`&`)}},ya={"X-Client-Info":`storage-js/2.99.3`},ba=class extends fa{constructor(e,t={},n,r){let i=new URL(e);r?.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes(`storage.supabase.`)&&(i.hostname=i.hostname.replace(`supabase.`,`storage.supabase.`));let a=i.href.replace(/\/$/,``),o=B(B({},ya),t);super(a,o,n,`storage`)}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let n=t.listBucketOptionsToQueryString(e);return await ca(t.fetch,`${t.url}/bucket${n}`,{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await ca(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}))}async createBucket(e,t={public:!1}){var n=this;return n.handleOperation(async()=>await V(n.fetch,`${n.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:n.headers}))}async updateBucket(e,t){var n=this;return n.handleOperation(async()=>await la(n.fetch,`${n.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:n.headers}))}async emptyBucket(e){var t=this;return t.handleOperation(async()=>await V(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await da(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}listBucketOptionsToQueryString(e){let t={};return e&&(`limit`in e&&(t.limit=String(e.limit)),`offset`in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?`?`+new URLSearchParams(t).toString():``}},xa=class extends fa{constructor(e,t={},n){let r=e.replace(/\/$/,``),i=B(B({},ya),t);super(r,i,n,`storage`)}async createBucket(e){var t=this;return t.handleOperation(async()=>await V(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}))}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let n=new URLSearchParams;e?.limit!==void 0&&n.set(`limit`,e.limit.toString()),e?.offset!==void 0&&n.set(`offset`,e.offset.toString()),e?.sortColumn&&n.set(`sortColumn`,e.sortColumn),e?.sortOrder&&n.set(`sortOrder`,e.sortOrder),e?.search&&n.set(`search`,e.search);let r=n.toString(),i=r?`${t.url}/bucket?${r}`:`${t.url}/bucket`;return await ca(t.fetch,i,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await da(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}from(e){var t=this;if(!Zi(e))throw new Wi(`Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.`);let n=new Ui({baseUrl:this.url,catalogName:e,auth:{type:`custom`,getHeaders:async()=>t.headers},fetch:this.fetch}),r=this.shouldThrowOnError;return new Proxy(n,{get(e,t){let n=e[t];return typeof n==`function`?async(...t)=>{try{return{data:await n.apply(e,t),error:null}}catch(e){if(r)throw e;return{data:null,error:e}}}:n}})}},Sa=class extends fa{constructor(e,t={},n){let r=e.replace(/\/$/,``),i=B(B({},ya),{},{"Content-Type":`application/json`},t);super(r,i,n,`vectors`)}async createIndex(e){var t=this;return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{})}async getIndex(e,t){var n=this;return n.handleOperation(async()=>await H.post(n.fetch,`${n.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:n.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}))}async deleteIndex(e,t){var n=this;return n.handleOperation(async()=>await H.post(n.fetch,`${n.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:n.headers})||{})}},Ca=class extends fa{constructor(e,t={},n){let r=e.replace(/\/$/,``),i=B(B({},ya),{},{"Content-Type":`application/json`},t);super(r,i,n,`vectors`)}async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw Error(`Vector batch size must be between 1 and 500 items`);return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}))}async listVectors(e){var t=this;if(e.segmentCount!==void 0){if(e.segmentCount<1||e.segmentCount>16)throw Error(`segmentCount must be between 1 and 16`);if(e.segmentIndex!==void 0&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw Error(`Keys batch size must be between 1 and 500 items`);return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{})}},wa=class extends fa{constructor(e,t={},n){let r=e.replace(/\/$/,``),i=B(B({},ya),{},{"Content-Type":`application/json`},t);super(r,i,n,`vectors`)}async createBucket(e){var t=this;return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}))}async listBuckets(e={}){var t=this;return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await H.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}},Ta=class extends wa{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new Ea(this.url,this.headers,e,this.fetch)}async createBucket(e){var t=()=>super.createBucket,n=this;return t().call(n,e)}async getBucket(e){var t=()=>super.getBucket,n=this;return t().call(n,e)}async listBuckets(e={}){var t=()=>super.listBuckets,n=this;return t().call(n,e)}async deleteBucket(e){var t=()=>super.deleteBucket,n=this;return t().call(n,e)}},Ea=class extends Sa{constructor(e,t,n,r){super(e,t,r),this.vectorBucketName=n}async createIndex(e){var t=()=>super.createIndex,n=this;return t().call(n,B(B({},e),{},{vectorBucketName:n.vectorBucketName}))}async listIndexes(e={}){var t=()=>super.listIndexes,n=this;return t().call(n,B(B({},e),{},{vectorBucketName:n.vectorBucketName}))}async getIndex(e){var t=()=>super.getIndex,n=this;return t().call(n,n.vectorBucketName,e)}async deleteIndex(e){var t=()=>super.deleteIndex,n=this;return t().call(n,n.vectorBucketName,e)}index(e){return new Da(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},Da=class extends Ca{constructor(e,t,n,r,i){super(e,t,i),this.vectorBucketName=n,this.indexName=r}async putVectors(e){var t=()=>super.putVectors,n=this;return t().call(n,B(B({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async getVectors(e){var t=()=>super.getVectors,n=this;return t().call(n,B(B({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async listVectors(e={}){var t=()=>super.listVectors,n=this;return t().call(n,B(B({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async queryVectors(e){var t=()=>super.queryVectors,n=this;return t().call(n,B(B({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async deleteVectors(e){var t=()=>super.deleteVectors,n=this;return t().call(n,B(B({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}},Oa=class extends ba{constructor(e,t={},n,r){super(e,t,n,r)}from(e){return new va(this.url,this.headers,e,this.fetch)}get vectors(){return new Ta(this.url+`/vector`,{headers:this.headers,fetch:this.fetch})}get analytics(){return new xa(this.url+`/iceberg`,this.headers,this.fetch)}},ka=`2.99.3`,Aa=30*1e3,ja=3*Aa,Ma=`http://localhost:9999`,Na=`supabase.auth.token`,Pa={"X-Client-Info":`gotrue-js/${ka}`},Fa=`X-Supabase-Api-Version`,Ia={"2024-01-01":{timestamp:Date.parse(`2024-01-01T00:00:00.0Z`),name:`2024-01-01`}},La=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Ra=class extends Error{constructor(e,t,n){super(e),this.__isAuthError=!0,this.name=`AuthError`,this.status=t,this.code=n}};function U(e){return typeof e==`object`&&!!e&&`__isAuthError`in e}var za=class extends Ra{constructor(e,t,n){super(e,t,n),this.name=`AuthApiError`,this.status=t,this.code=n}};function Ba(e){return U(e)&&e.name===`AuthApiError`}var Va=class extends Ra{constructor(e,t){super(e),this.name=`AuthUnknownError`,this.originalError=t}},W=class extends Ra{constructor(e,t,n,r){super(e,n,r),this.name=t,this.status=n}},G=class extends W{constructor(){super(`Auth session missing!`,`AuthSessionMissingError`,400,void 0)}};function Ha(e){return U(e)&&e.name===`AuthSessionMissingError`}var Ua=class extends W{constructor(){super(`Auth session or user missing`,`AuthInvalidTokenResponseError`,500,void 0)}},Wa=class extends W{constructor(e){super(e,`AuthInvalidCredentialsError`,400,void 0)}},Ga=class extends W{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 Ka(e){return U(e)&&e.name===`AuthImplicitGrantRedirectError`}var qa=class extends W{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}}},Ja=class extends W{constructor(){super(`PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.`,`AuthPKCECodeVerifierMissingError`,400,`pkce_code_verifier_not_found`)}},Ya=class extends W{constructor(e,t){super(e,`AuthRetryableFetchError`,t,void 0)}};function Xa(e){return U(e)&&e.name===`AuthRetryableFetchError`}var Za=class extends W{constructor(e,t,n){super(e,`AuthWeakPasswordError`,t,`weak_password`),this.reasons=n}},Qa=class extends W{constructor(e){super(e,`AuthInvalidJwtError`,400,`invalid_jwt`)}},$a=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`.split(``),eo=`
114
+ \r=`.split(``),to=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<eo.length;t+=1)e[eo[t].charCodeAt(0)]=-2;for(let t=0;t<$a.length;t+=1)e[$a[t].charCodeAt(0)]=t;return e})();function no(e,t,n){if(e!==null)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;)n($a[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6;else if(t.queuedBits>0)for(t.queue<<=6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;)n($a[t.queue>>t.queuedBits-6&63]),t.queuedBits-=6}function ro(e,t,n){let r=to[e];if(r>-1)for(t.queue=t.queue<<6|r,t.queuedBits+=6;t.queuedBits>=8;)n(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else if(r===-2)return;else throw Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}function io(e){let t=[],n=e=>{t.push(String.fromCodePoint(e))},r={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},a=e=>{so(e,r,n)};for(let t=0;t<e.length;t+=1)ro(e.charCodeAt(t),i,a);return t.join(``)}function ao(e,t){if(e<=127){t(e);return}else if(e<=2047){t(192|e>>6),t(128|e&63);return}else if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|e&63);return}else if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|e&63);return}throw Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}function oo(e,t){for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);if(r>55295&&r<=56319){let t=(r-55296)*1024&65535;r=(e.charCodeAt(n+1)-56320&65535|t)+65536,n+=1}ao(r,t)}}function so(e,t,n){if(t.utf8seq===0){if(e<=127){n(e);return}for(let n=1;n<6;n+=1)if(!(e>>7-n&1)){t.utf8seq=n;break}if(t.utf8seq===2)t.codepoint=e&31;else if(t.utf8seq===3)t.codepoint=e&15;else if(t.utf8seq===4)t.codepoint=e&7;else throw Error(`Invalid UTF-8 sequence`);--t.utf8seq}else if(t.utf8seq>0){if(e<=127)throw Error(`Invalid UTF-8 sequence`);t.codepoint=t.codepoint<<6|e&63,--t.utf8seq,t.utf8seq===0&&n(t.codepoint)}}function co(e){let t=[],n={queue:0,queuedBits:0},r=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)ro(e.charCodeAt(t),n,r);return new Uint8Array(t)}function lo(e){let t=[];return oo(e,e=>t.push(e)),new Uint8Array(t)}function uo(e){let t=[],n={queue:0,queuedBits:0},r=e=>{t.push(e)};return e.forEach(e=>no(e,n,r)),no(null,n,r),t.join(``)}function fo(e){return Math.round(Date.now()/1e3)+e}function po(){return Symbol(`auth-callback`)}var K=()=>typeof window<`u`&&typeof document<`u`,mo={tested:!1,writable:!1},ho=()=>{if(!K())return!1;try{if(typeof globalThis.localStorage!=`object`)return!1}catch{return!1}if(mo.tested)return mo.writable;let e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),mo.tested=!0,mo.writable=!0}catch{mo.tested=!0,mo.writable=!1}return mo.writable};function go(e){let t={},n=new URL(e);if(n.hash&&n.hash[0]===`#`)try{new URLSearchParams(n.hash.substring(1)).forEach((e,n)=>{t[n]=e})}catch{}return n.searchParams.forEach((e,n)=>{t[n]=e}),t}var _o=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),vo=e=>typeof e==`object`&&!!e&&`status`in e&&`ok`in e&&`json`in e&&typeof e.json==`function`,yo=async(e,t,n)=>{await e.setItem(t,JSON.stringify(n))},bo=async(e,t)=>{let n=await e.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},q=async(e,t)=>{await e.removeItem(t)},xo=class e{constructor(){this.promise=new e.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};xo.promiseConstructor=Promise;function So(e){let t=e.split(`.`);if(t.length!==3)throw new Qa(`Invalid JWT structure`);for(let e=0;e<t.length;e++)if(!La.test(t[e]))throw new Qa(`JWT not in base64url format`);return{header:JSON.parse(io(t[0])),payload:JSON.parse(io(t[1])),signature:co(t[2]),raw:{header:t[0],payload:t[1]}}}async function Co(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function wo(e,t){return new Promise((n,r)=>{(async()=>{for(let i=0;i<1/0;i++)try{let r=await e(i);if(!t(i,null,r)){n(r);return}}catch(e){if(!t(i,e)){r(e);return}}})()})}function To(e){return(`0`+e.toString(16)).substr(-2)}function Eo(){let e=new Uint32Array(56);if(typeof crypto>`u`){let e=``;for(let t=0;t<56;t++)e+=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~`.charAt(Math.floor(Math.random()*66));return e}return crypto.getRandomValues(e),Array.from(e,To).join(``)}async function Do(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t),r=new Uint8Array(n);return Array.from(r).map(e=>String.fromCharCode(e)).join(``)}async function Oo(e){if(!(typeof crypto<`u`&&crypto.subtle!==void 0&&typeof TextEncoder<`u`))return console.warn(`WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.`),e;let t=await Do(e);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}async function ko(e,t,n=!1){let r=Eo(),i=r;n&&(i+=`/PASSWORD_RECOVERY`),await yo(e,`${t}-code-verifier`,i);let a=await Oo(r);return[a,r===a?`plain`:`s256`]}var Ao=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function jo(e){let t=e.headers.get(Fa);if(!t||!t.match(Ao))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function Mo(e){if(!e)throw Error(`Missing exp claim`);if(e<=Math.floor(Date.now()/1e3))throw Error(`JWT has expired`)}function No(e){switch(e){case`RS256`:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-256`}};case`ES256`:return{name:`ECDSA`,namedCurve:`P-256`,hash:{name:`SHA-256`}};default:throw Error(`Invalid alg claim`)}}var Po=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Fo(e){if(!Po.test(e))throw Error(`@supabase/auth-js: Expected parameter to be UUID but is not`)}function Io(){return new Proxy({},{get:(e,t)=>{if(t===`__isUserNotAvailableProxy`)return!0;if(typeof t==`symbol`){let e=t.toString();if(e===`Symbol(Symbol.toPrimitive)`||e===`Symbol(Symbol.toStringTag)`||e===`Symbol(util.inspect.custom)`)return}throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Lo(e,t){return new Proxy(e,{get:(e,n,r)=>{if(n===`__isInsecureUserWarningProxy`)return!0;if(typeof n==`symbol`){let t=n.toString();if(t===`Symbol(Symbol.toPrimitive)`||t===`Symbol(Symbol.toStringTag)`||t===`Symbol(util.inspect.custom)`||t===`Symbol(nodejs.util.inspect.custom)`)return Reflect.get(e,n,r)}return!t.value&&typeof n==`string`&&(console.warn(`Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.`),t.value=!0),Reflect.get(e,n,r)}})}function Ro(e){return JSON.parse(JSON.stringify(e))}var zo=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Bo=[502,503,504];async function Vo(e){if(!vo(e))throw new Ya(zo(e),0);if(Bo.includes(e.status))throw new Ya(zo(e),e.status);let t;try{t=await e.json()}catch(e){throw new Va(zo(e),e)}let n,r=jo(e);if(r&&r.getTime()>=Ia[`2024-01-01`].timestamp&&typeof t==`object`&&t&&typeof t.code==`string`?n=t.code:typeof t==`object`&&t&&typeof t.error_code==`string`&&(n=t.error_code),!n){if(typeof t==`object`&&t&&typeof t.weak_password==`object`&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((e,t)=>e&&typeof t==`string`,!0))throw new Za(zo(t),e.status,t.weak_password.reasons)}else if(n===`weak_password`)throw new Za(zo(t),e.status,t.weak_password?.reasons||[]);else if(n===`session_not_found`)throw new G;throw new za(zo(t),e.status||500,n)}var Ho=(e,t,n,r)=>{let i={method:e,headers:t?.headers||{}};return e===`GET`?i:(i.headers=Object.assign({"Content-Type":`application/json;charset=UTF-8`},t?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),n))};async function J(e,t,n,r){let i=Object.assign({},r?.headers);i[`X-Supabase-Api-Version`]||(i[Fa]=Ia[`2024-01-01`].name),r?.jwt&&(i.Authorization=`Bearer ${r.jwt}`);let a=r?.query??{};r?.redirectTo&&(a.redirect_to=r.redirectTo);let o=await Uo(e,t,n+(Object.keys(a).length?`?`+new URLSearchParams(a).toString():``),{headers:i,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(o):{data:Object.assign({},o),error:null}}async function Uo(e,t,n,r,i,a){let o=Ho(t,r,i,a),s;try{s=await e(n,Object.assign({},o))}catch(e){throw console.error(e),new Ya(zo(e),0)}if(s.ok||await Vo(s),r?.noResolveJson)return s;try{return await s.json()}catch(e){await Vo(e)}}function Y(e){let t=null;Jo(e)&&(t=Object.assign({},e),e.expires_at||(t.expires_at=fo(e.expires_in)));let n=e.user??e;return{data:{session:t,user:n},error:null}}function Wo(e){let t=Y(e);return!t.error&&e.weak_password&&typeof e.weak_password==`object`&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message==`string`&&e.weak_password.reasons.reduce((e,t)=>e&&typeof t==`string`,!0)&&(t.data.weak_password=e.weak_password),t}function X(e){return{data:{user:e.user??e},error:null}}function Go(e){return{data:e,error:null}}function Ko(e){let{action_link:t,email_otp:n,hashed_token:r,redirect_to:i,verification_type:a}=e,o=Pr(e,[`action_link`,`email_otp`,`hashed_token`,`redirect_to`,`verification_type`]);return{data:{properties:{action_link:t,email_otp:n,hashed_token:r,redirect_to:i,verification_type:a},user:Object.assign({},o)},error:null}}function qo(e){return e}function Jo(e){return e.access_token&&e.refresh_token&&e.expires_in}var Yo=[`global`,`local`,`others`],Xo=class{constructor({url:e=``,headers:t={},fetch:n}){this.url=e,this.headers=t,this.fetch=_o(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)}}async signOut(e,t=Yo[0]){if(Yo.indexOf(t)<0)throw Error(`@supabase/auth-js: Parameter scope must be one of ${Yo.join(`, `)}`);try{return await J(this.fetch,`POST`,`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(U(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await J(this.fetch,`POST`,`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:X})}catch(e){if(U(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{let{options:t}=e,n=Pr(e,[`options`]),r=Object.assign(Object.assign({},n),t);return`newEmail`in n&&(r.new_email=n?.newEmail,delete r.newEmail),await J(this.fetch,`POST`,`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:Ko,redirectTo:t?.redirectTo})}catch(e){if(U(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await J(this.fetch,`POST`,`${this.url}/admin/users`,{body:e,headers:this.headers,xform:X})}catch(e){if(U(e))return{data:{user:null},error:e};throw e}}async listUsers(e){try{let t={nextPage:null,lastPage:0,total:0},n=await J(this.fetch,`GET`,`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(e?.page)?.toString()??``,per_page:(e?.perPage)?.toString()??``},xform:qo});if(n.error)throw n.error;let r=await n.json(),i=n.headers.get(`x-total-count`)??0,a=n.headers.get(`link`)?.split(`,`)??[];return a.length>0&&(a.forEach(e=>{let n=parseInt(e.split(`;`)[0].split(`=`)[1].substring(0,1)),r=JSON.parse(e.split(`;`)[1].split(`=`)[1]);t[`${r}Page`]=n}),t.total=parseInt(i)),{data:Object.assign(Object.assign({},r),t),error:null}}catch(e){if(U(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){Fo(e);try{return await J(this.fetch,`GET`,`${this.url}/admin/users/${e}`,{headers:this.headers,xform:X})}catch(e){if(U(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){Fo(e);try{return await J(this.fetch,`PUT`,`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:X})}catch(e){if(U(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){Fo(e);try{return await J(this.fetch,`DELETE`,`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:X})}catch(e){if(U(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){Fo(e.userId);try{let{data:t,error:n}=await J(this.fetch,`GET`,`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:n}}catch(e){if(U(e))return{data:null,error:e};throw e}}async _deleteFactor(e){Fo(e.userId),Fo(e.id);try{return{data:await J(this.fetch,`DELETE`,`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(U(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){try{let t={nextPage:null,lastPage:0,total:0},n=await J(this.fetch,`GET`,`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(e?.page)?.toString()??``,per_page:(e?.perPage)?.toString()??``},xform:qo});if(n.error)throw n.error;let r=await n.json(),i=n.headers.get(`x-total-count`)??0,a=n.headers.get(`link`)?.split(`,`)??[];return a.length>0&&(a.forEach(e=>{let n=parseInt(e.split(`;`)[0].split(`=`)[1].substring(0,1)),r=JSON.parse(e.split(`;`)[1].split(`=`)[1]);t[`${r}Page`]=n}),t.total=parseInt(i)),{data:Object.assign(Object.assign({},r),t),error:null}}catch(e){if(U(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await J(this.fetch,`POST`,`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(U(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await J(this.fetch,`GET`,`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(U(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await J(this.fetch,`PUT`,`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(U(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await J(this.fetch,`DELETE`,`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(U(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await J(this.fetch,`POST`,`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(U(e))return{data:null,error:e};throw e}}async _listCustomProviders(e){try{let t={};return e?.type&&(t.type=e.type),await J(this.fetch,`GET`,`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:e=>({data:{providers:e?.providers??[]},error:null})})}catch(e){if(U(e))return{data:{providers:[]},error:e};throw e}}async _createCustomProvider(e){try{return await J(this.fetch,`POST`,`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(U(e))return{data:null,error:e};throw e}}async _getCustomProvider(e){try{return await J(this.fetch,`GET`,`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(U(e))return{data:null,error:e};throw e}}async _updateCustomProvider(e,t){try{return await J(this.fetch,`PUT`,`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(U(e))return{data:null,error:e};throw e}}async _deleteCustomProvider(e){try{return await J(this.fetch,`DELETE`,`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(U(e))return{data:null,error:e};throw e}}};function Zo(e={}){return{getItem:t=>e[t]||null,setItem:(t,n)=>{e[t]=n},removeItem:t=>{delete e[t]}}}var Z={debug:!!(globalThis&&ho()&&globalThis.localStorage&&globalThis.localStorage.getItem(`supabase.gotrue-js.locks.debug`)===`true`)},Qo=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},$o=class extends Qo{};async function es(e,t,n){Z.debug&&console.log(`@supabase/gotrue-js: navigatorLock: acquire lock`,e,t);let r=new globalThis.AbortController,i;t>0&&(i=setTimeout(()=>{r.abort(),Z.debug&&console.log(`@supabase/gotrue-js: navigatorLock acquire timed out`,e)},t)),await Promise.resolve();try{return await globalThis.navigator.locks.request(e,t===0?{mode:`exclusive`,ifAvailable:!0}:{mode:`exclusive`,signal:r.signal},async r=>{if(r){clearTimeout(i),Z.debug&&console.log(`@supabase/gotrue-js: navigatorLock: acquired`,e,r.name);try{return await n()}finally{Z.debug&&console.log(`@supabase/gotrue-js: navigatorLock: released`,e,r.name)}}else if(t===0)throw Z.debug&&console.log(`@supabase/gotrue-js: navigatorLock: not immediately available`,e),new $o(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);else{if(Z.debug)try{let e=await globalThis.navigator.locks.query();console.log(`@supabase/gotrue-js: Navigator LockManager state`,JSON.stringify(e,null,` `))}catch(e){console.warn(`@supabase/gotrue-js: Error when querying Navigator LockManager state`,e)}return console.warn(`@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request`),clearTimeout(i),await n()}})}catch(a){if(t>0&&clearTimeout(i),a?.name===`AbortError`&&t>0){if(r.signal.aborted)return Z.debug&&console.log(`@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock`,e),console.warn(`@supabase/gotrue-js: Lock "${e}" was not released within ${t}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,{mode:`exclusive`,steal:!0},async t=>{if(t){Z.debug&&console.log(`@supabase/gotrue-js: navigatorLock: recovered (stolen)`,e,t.name);try{return await n()}finally{Z.debug&&console.log(`@supabase/gotrue-js: navigatorLock: released (stolen)`,e,t.name)}}else return console.warn(`@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true`),await n()}));throw Z.debug&&console.log(`@supabase/gotrue-js: navigatorLock: lock was stolen by another request`,e),new $o(`Lock "${e}" was released because another request stole it`)}throw a}}function ts(){if(typeof globalThis!=`object`)try{Object.defineProperty(Object.prototype,`__magic__`,{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<`u`&&(self.globalThis=self)}}function ns(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function rs(e){return parseInt(e,16)}function is(e){let t=new TextEncoder().encode(e);return`0x`+Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}function as(e){let{chainId:t,domain:n,expirationTime:r,issuedAt:i=new Date,nonce:a,notBefore:o,requestId:s,resources:c,scheme:l,uri:u,version:d}=e;if(!Number.isInteger(t))throw Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!n)throw Error(`@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.`);if(a&&a.length<8)throw Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!u)throw Error(`@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.`);if(d!==`1`)throw Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(e.statement?.includes(`
115
+ `))throw Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);let f=ns(e.address),p=`${l?`${l}://${n}`:n} wants you to sign in with your Ethereum account:\n${f}\n\n${e.statement?`${e.statement}\n`:``}`,m=`URI: ${u}\nVersion: ${d}\nChain ID: ${t}${a?`\nNonce: ${a}`:``}\nIssued At: ${i.toISOString()}`;if(r&&(m+=`\nExpiration Time: ${r.toISOString()}`),o&&(m+=`\nNot Before: ${o.toISOString()}`),s&&(m+=`\nRequest ID: ${s}`),c){let e=`
116
+ Resources:`;for(let t of c){if(!t||typeof t!=`string`)throw Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`\n- ${t}`}m+=e}return`${p}\n${m}`}var Q=class extends Error{constructor({message:e,code:t,cause:n,name:r}){super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=r??(n instanceof Error?n.name:void 0)??`Unknown Error`,this.code=t}},os=class extends Q{constructor(e,t){super({code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:t,message:e}),this.name=`WebAuthnUnknownError`,this.originalError=t}};function ss({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new Q({message:`Registration ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`ConstraintError`){if(n.authenticatorSelection?.requireResidentKey===!0)return new Q({message:`Discoverable credentials were required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT`,cause:e});if(t.mediation===`conditional`&&n.authenticatorSelection?.userVerification===`required`)return new Q({message:`User verification was required during automatic registration but it could not be performed`,code:`ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE`,cause:e});if(n.authenticatorSelection?.userVerification===`required`)return new Q({message:`User verification was required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT`,cause:e})}else if(e.name===`InvalidStateError`)return new Q({message:`The authenticator was previously registered`,code:`ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED`,cause:e});else if(e.name===`NotAllowedError`)return new Q({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`NotSupportedError`)return n.pubKeyCredParams.filter(e=>e.type===`public-key`).length===0?new Q({message:`No entry in pubKeyCredParams was of type "public-key"`,code:`ERROR_MALFORMED_PUBKEYCREDPARAMS`,cause:e}):new Q({message:`No available authenticator supported any of the specified pubKeyCredParams algorithms`,code:`ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG`,cause:e});else if(e.name===`SecurityError`){let t=window.location.hostname;if(!ms(t))return new Q({message:`${window.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rp.id!==t)return new Q({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`TypeError`){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new Q({message:`User ID was not between 1 and 64 characters`,code:`ERROR_INVALID_USER_ID_LENGTH`,cause:e})}else if(e.name===`UnknownError`)return new Q({message:`The authenticator was unable to process the specified options, or could not create a new credential`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return new Q({message:`a Non-Webauthn related error has occurred`,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e})}function cs({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new Q({message:`Authentication ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`NotAllowedError`)return new Q({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`SecurityError`){let t=window.location.hostname;if(!ms(t))return new Q({message:`${window.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rpId!==t)return new Q({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`UnknownError`)return new Q({message:`The authenticator was unable to process the specified options, or could not create a new assertion signature`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return new Q({message:`a Non-Webauthn related error has occurred`,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e})}var ls=new class{createNewAbortSignal(){if(this.controller){let e=Error(`Cancelling existing WebAuthn API call for new one`);e.name=`AbortError`,this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error(`Manually cancelling existing WebAuthn API call`);e.name=`AbortError`,this.controller.abort(e),this.controller=void 0}}};function us(e){if(!e)throw Error(`Credential creation options are required`);if(typeof PublicKeyCredential<`u`&&`parseCreationOptionsFromJSON`in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON==`function`)return PublicKeyCredential.parseCreationOptionsFromJSON(e);let{challenge:t,user:n,excludeCredentials:r}=e,i=Pr(e,[`challenge`,`user`,`excludeCredentials`]),a=co(t).buffer,o=Object.assign(Object.assign({},n),{id:co(n.id).buffer}),s=Object.assign(Object.assign({},i),{challenge:a,user:o});if(r&&r.length>0){s.excludeCredentials=Array(r.length);for(let e=0;e<r.length;e++){let t=r[e];s.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:co(t.id).buffer,type:t.type||`public-key`,transports:t.transports})}}return s}function ds(e){if(!e)throw Error(`Credential request options are required`);if(typeof PublicKeyCredential<`u`&&`parseRequestOptionsFromJSON`in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON==`function`)return PublicKeyCredential.parseRequestOptionsFromJSON(e);let{challenge:t,allowCredentials:n}=e,r=Pr(e,[`challenge`,`allowCredentials`]),i=co(t).buffer,a=Object.assign(Object.assign({},r),{challenge:i});if(n&&n.length>0){a.allowCredentials=Array(n.length);for(let e=0;e<n.length;e++){let t=n[e];a.allowCredentials[e]=Object.assign(Object.assign({},t),{id:co(t.id).buffer,type:t.type||`public-key`,transports:t.transports})}}return a}function fs(e){if(`toJSON`in e&&typeof e.toJSON==`function`)return e.toJSON();let t=e;return{id:e.id,rawId:e.id,response:{attestationObject:uo(new Uint8Array(e.response.attestationObject)),clientDataJSON:uo(new Uint8Array(e.response.clientDataJSON))},type:`public-key`,clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:t.authenticatorAttachment??void 0}}function ps(e){if(`toJSON`in e&&typeof e.toJSON==`function`)return e.toJSON();let t=e,n=e.getClientExtensionResults(),r=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:uo(new Uint8Array(r.authenticatorData)),clientDataJSON:uo(new Uint8Array(r.clientDataJSON)),signature:uo(new Uint8Array(r.signature)),userHandle:r.userHandle?uo(new Uint8Array(r.userHandle)):void 0},type:`public-key`,clientExtensionResults:n,authenticatorAttachment:t.authenticatorAttachment??void 0}}function ms(e){return e===`localhost`||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function hs(){return!!(K()&&`PublicKeyCredential`in window&&window.PublicKeyCredential&&`credentials`in navigator&&typeof(navigator==null?void 0:navigator.credentials)?.create==`function`&&typeof(navigator==null?void 0:navigator.credentials)?.get==`function`)}async function gs(e){try{let t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new os(`Browser returned unexpected credential type`,t)}:{data:null,error:new os(`Empty credential response`,t)}}catch(t){return{data:null,error:ss({error:t,options:e})}}}async function _s(e){try{let t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new os(`Browser returned unexpected credential type`,t)}:{data:null,error:new os(`Empty credential response`,t)}}catch(t){return{data:null,error:cs({error:t,options:e})}}}var vs={hints:[`security-key`],authenticatorSelection:{authenticatorAttachment:`cross-platform`,requireResidentKey:!1,userVerification:`preferred`,residentKey:`discouraged`},attestation:`direct`},ys={userVerification:`preferred`,hints:[`security-key`],attestation:`direct`};function bs(...e){let t=e=>typeof e==`object`&&!!e&&!Array.isArray(e),n=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),r={};for(let i of e)if(i)for(let e in i){let a=i[e];if(a!==void 0)if(Array.isArray(a))r[e]=a;else if(n(a))r[e]=a;else if(t(a)){let n=r[e];t(n)?r[e]=bs(n,a):r[e]=bs(a)}else r[e]=a}return r}function xs(e,t){return bs(vs,e,t||{})}function Ss(e,t){return bs(ys,e,t||{})}var Cs=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:`webauthn`}))}async _challenge({factorId:e,webauthn:t,friendlyName:n,signal:r},i){try{let{data:a,error:o}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!a)return{data:null,error:o};let s=r??ls.createNewAbortSignal();if(a.webauthn.type===`create`){let{user:e}=a.webauthn.credential_options.publicKey;if(!e.name){let t=n;if(t)e.name=`${e.id}:${t}`;else{let t=(await this.client.getUser()).data.user,n=t?.user_metadata?.name||t?.email||t?.id||`User`;e.name=`${e.id}:${n}`}}e.displayName||=e.name}switch(a.webauthn.type){case`create`:{let{data:t,error:n}=await gs({publicKey:xs(a.webauthn.credential_options.publicKey,i?.create),signal:s});return t?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:t}},error:null}:{data:null,error:n}}case`request`:{let t=Ss(a.webauthn.credential_options.publicKey,i?.request),{data:n,error:r}=await _s(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:t,signal:s}));return n?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:n}},error:null}:{data:null,error:r}}}}catch(e){return U(e)?{data:null,error:e}:{data:null,error:new Va(`Unexpected error in challenge`,e)}}}async _verify({challengeId:e,factorId:t,webauthn:n}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<`u`?window.location.hostname:void 0,rpOrigins:n=typeof window<`u`?[window.location.origin]:void 0,signal:r}={}},i){if(!t)return{data:null,error:new Ra(`rpId is required for WebAuthn authentication`)};try{if(!hs())return{data:null,error:new Va(`Browser does not support WebAuthn`,null)};let{data:a,error:o}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:n},signal:r},{request:i});if(!a)return{data:null,error:o};let{webauthn:s}=a;return this._verify({factorId:e,challengeId:a.challengeId,webauthn:{type:s.type,rpId:t,rpOrigins:n,credential_response:s.credential_response}})}catch(e){return U(e)?{data:null,error:e}:{data:null,error:new Va(`Unexpected error in authenticate`,e)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<`u`?window.location.hostname:void 0,rpOrigins:n=typeof window<`u`?[window.location.origin]:void 0,signal:r}={}},i){if(!t)return{data:null,error:new Ra(`rpId is required for WebAuthn registration`)};try{if(!hs())return{data:null,error:new Va(`Browser does not support WebAuthn`,null)};let{data:a,error:o}=await this._enroll({friendlyName:e});if(!a)return await this.client.mfa.listFactors().then(t=>t.data?.all.find(t=>t.factor_type===`webauthn`&&t.friendly_name===e&&t.status!==`unverified`)).then(e=>e?this.client.mfa.unenroll({factorId:e?.id}):void 0),{data:null,error:o};let{data:s,error:c}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:t,rpOrigins:n},signal:r},{create:i});return s?this._verify({factorId:a.id,challengeId:s.challengeId,webauthn:{rpId:t,rpOrigins:n,type:s.webauthn.type,credential_response:s.webauthn.credential_response}}):{data:null,error:c}}catch(e){return U(e)?{data:null,error:e}:{data:null,error:new Va(`Unexpected error in register`,e)}}}};ts();var ws={url:Ma,storageKey:Na,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Pa,flowType:`implicit`,debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function Ts(e,t,n){return await n()}var Es={},Ds=class e{get jwks(){return Es[this.storageKey]?.jwks??{keys:[]}}set jwks(e){Es[this.storageKey]=Object.assign(Object.assign({},Es[this.storageKey]),{jwks:e})}get jwks_cached_at(){return Es[this.storageKey]?.cachedAt??-(2**53-1)}set jwks_cached_at(e){Es[this.storageKey]=Object.assign(Object.assign({},Es[this.storageKey]),{cachedAt:e})}constructor(t){var n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let r=Object.assign(Object.assign({},ws),t);if(this.storageKey=r.storageKey,this.instanceID=e.nextInstanceID[this.storageKey]??0,e.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!r.debug,typeof r.debug==`function`&&(this.logger=r.debug),this.instanceID>0&&K()){let e=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=r.persistSession,this.autoRefreshToken=r.autoRefreshToken,this.admin=new Xo({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=_o(r.fetch),this.lock=r.lock||Ts,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.hasCustomAuthorizationHeader=r.hasCustomAuthorizationHeader,this.throwOnError=r.throwOnError,this.lockAcquireTimeout=r.lockAcquireTimeout,r.lock?this.lock=r.lock:this.persistSession&&K()&&(globalThis==null?void 0:globalThis.navigator)?.locks?this.lock=es:this.lock=Ts,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=-(2**53-1)),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new Cs(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(r.storage?this.storage=r.storage:ho()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Zo(this.memoryStorage)),r.userStorage&&(this.userStorage=r.userStorage)):(this.memoryStorage={},this.storage=Zo(this.memoryStorage)),K()&&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)}(n=this.broadcastChannel)==null||n.addEventListener(`message`,async e=>{this._debug(`received broadcast notification from other tab or client`,e);try{await this._notifyAllSubscribers(e.data.event,e.data.session,!1)}catch(e){this._debug(`#broadcastChannel`,`error`,e)}})}r.skipAutoInitialize||this.initialize().catch(e=>{this._debug(`#initialize()`,`error`,e)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${ka}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise||=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise}async _initialize(){try{let e={},t=`none`;if(K()&&(e=go(window.location.href),this._isImplicitGrantCallback(e)?t=`implicit`:await this._isPKCECallback(e)&&(t=`pkce`)),K()&&this.detectSessionInUrl&&t!==`none`){let{data:n,error:r}=await this._getSessionFromURL(e,t);if(r){if(this._debug(`#_initialize()`,`error detecting session from URL`,r),Ka(r)){let e=r.details?.code;if(e===`identity_already_exists`||e===`identity_not_found`||e===`single_identity_not_deletable`)return{error:r}}return{error:r}}let{session:i,redirectType:a}=n;return this._debug(`#_initialize()`,`detected session in URL`,i,`redirect type`,a),await this._saveSession(i),setTimeout(async()=>{a===`recovery`?await this._notifyAllSubscribers(`PASSWORD_RECOVERY`,i):await this._notifyAllSubscribers(`SIGNED_IN`,i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return U(e)?this._returnResult({error:e}):this._returnResult({error:new Va(`Unexpected error during initialization`,e)})}finally{await this._handleVisibilityChange(),this._debug(`#_initialize()`,`end`)}}async signInAnonymously(e){try{let{data:t,error:n}=await J(this.fetch,`POST`,`${this.url}/signup`,{headers:this.headers,body:{data:e?.options?.data??{},gotrue_meta_security:{captcha_token:e?.options?.captchaToken}},xform:Y});if(n||!t)return this._returnResult({data:{user:null,session:null},error:n});let r=t.session,i=t.user;return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers(`SIGNED_IN`,r)),this._returnResult({data:{user:i,session:r},error:null})}catch(e){if(U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){try{let t;if(`email`in e){let{email:n,password:r,options:i}=e,a=null,o=null;this.flowType===`pkce`&&([a,o]=await ko(this.storage,this.storageKey)),t=await J(this.fetch,`POST`,`${this.url}/signup`,{headers:this.headers,redirectTo:i?.emailRedirectTo,body:{email:n,password:r,data:i?.data??{},gotrue_meta_security:{captcha_token:i?.captchaToken},code_challenge:a,code_challenge_method:o},xform:Y})}else if(`phone`in e){let{phone:n,password:r,options:i}=e;t=await J(this.fetch,`POST`,`${this.url}/signup`,{headers:this.headers,body:{phone:n,password:r,data:i?.data??{},channel:i?.channel??`sms`,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Y})}else throw new Wa(`You must provide either an email or phone number and a password`);let{data:n,error:r}=t;if(r||!n)return await q(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:r});let i=n.session,a=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers(`SIGNED_IN`,i)),this._returnResult({data:{user:a,session:i},error:null})}catch(e){if(await q(this.storage,`${this.storageKey}-code-verifier`),U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if(`email`in e){let{email:n,password:r,options:i}=e;t=await J(this.fetch,`POST`,`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:r,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Wo})}else if(`phone`in e){let{phone:n,password:r,options:i}=e;t=await J(this.fetch,`POST`,`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:r,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Wo})}else throw new Wa(`You must provide either an email or phone number and a password`);let{data:n,error:r}=t;if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!n||!n.session||!n.user){let e=new Ua;return this._returnResult({data:{user:null,session:null},error:e})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers(`SIGNED_IN`,n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:r})}catch(e){if(U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){return await this._handleProviderSignIn(e.provider,{redirectTo:e.options?.redirectTo,scopes:e.options?.scopes,queryParams:e.options?.queryParams,skipBrowserRedirect:e.options?.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:t}=e;switch(t){case`ethereum`:return await this.signInWithEthereum(e);case`solana`:return await this.signInWithSolana(e);default:throw Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){let t,n;if(`message`in e)t=e.message,n=e.signature;else{let{chain:r,wallet:i,statement:a,options:o}=e,s;if(!K()){if(typeof i!=`object`||!o?.url)throw Error(`@supabase/auth-js: Both wallet and url must be specified in non-browser environments.`);s=i}else if(typeof i==`object`)s=i;else{let e=window;if(`ethereum`in e&&typeof e.ethereum==`object`&&`request`in e.ethereum&&typeof e.ethereum.request==`function`)s=e.ethereum;else throw Error(`@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.`)}let c=new URL(o?.url??window.location.href),l=await s.request({method:`eth_requestAccounts`}).then(e=>e).catch(()=>{throw Error(`@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid`)});if(!l||l.length===0)throw Error(`@supabase/auth-js: No accounts available. Please ensure the wallet is connected.`);let u=ns(l[0]),d=o?.signInWithEthereum?.chainId;d||=rs(await s.request({method:`eth_chainId`})),t=as({domain:c.host,address:u,statement:a,uri:c.href,version:`1`,chainId:d,nonce:o?.signInWithEthereum?.nonce,issuedAt:o?.signInWithEthereum?.issuedAt??new Date,expirationTime:o?.signInWithEthereum?.expirationTime,notBefore:o?.signInWithEthereum?.notBefore,requestId:o?.signInWithEthereum?.requestId,resources:o?.signInWithEthereum?.resources}),n=await s.request({method:`personal_sign`,params:[is(t),u]})}try{let{data:r,error:i}=await J(this.fetch,`POST`,`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:`ethereum`,message:t,signature:n},e.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options?.captchaToken}}:null),xform:Y});if(i)throw i;if(!r||!r.session||!r.user){let e=new Ua;return this._returnResult({data:{user:null,session:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers(`SIGNED_IN`,r.session)),this._returnResult({data:Object.assign({},r),error:i})}catch(e){if(U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){let t,n;if(`message`in e)t=e.message,n=e.signature;else{let{chain:r,wallet:i,statement:a,options:o}=e,s;if(!K()){if(typeof i!=`object`||!o?.url)throw Error(`@supabase/auth-js: Both wallet and url must be specified in non-browser environments.`);s=i}else if(typeof i==`object`)s=i;else{let e=window;if(`solana`in e&&typeof e.solana==`object`&&(`signIn`in e.solana&&typeof e.solana.signIn==`function`||`signMessage`in e.solana&&typeof e.solana.signMessage==`function`))s=e.solana;else throw Error(`@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.`)}let c=new URL(o?.url??window.location.href);if(`signIn`in s&&s.signIn){let e=await s.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},o?.signInWithSolana),{version:`1`,domain:c.host,uri:c.href}),a?{statement:a}:null)),r;if(Array.isArray(e)&&e[0]&&typeof e[0]==`object`)r=e[0];else if(e&&typeof e==`object`&&`signedMessage`in e&&`signature`in e)r=e;else throw Error(`@supabase/auth-js: Wallet method signIn() returned unrecognized value`);if(`signedMessage`in r&&`signature`in r&&(typeof r.signedMessage==`string`||r.signedMessage instanceof Uint8Array)&&r.signature instanceof Uint8Array)t=typeof r.signedMessage==`string`?r.signedMessage:new TextDecoder().decode(r.signedMessage),n=r.signature;else throw Error(`@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields`)}else{if(!(`signMessage`in s)||typeof s.signMessage!=`function`||!(`publicKey`in s)||typeof s!=`object`||!s.publicKey||!(`toBase58`in s.publicKey)||typeof s.publicKey.toBase58!=`function`)throw Error(`@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API`);t=[`${c.host} wants you to sign in with your Solana account:`,s.publicKey.toBase58(),...a?[``,a,``]:[``],`Version: 1`,`URI: ${c.href}`,`Issued At: ${o?.signInWithSolana?.issuedAt??new Date().toISOString()}`,...o?.signInWithSolana?.notBefore?[`Not Before: ${o.signInWithSolana.notBefore}`]:[],...o?.signInWithSolana?.expirationTime?[`Expiration Time: ${o.signInWithSolana.expirationTime}`]:[],...o?.signInWithSolana?.chainId?[`Chain ID: ${o.signInWithSolana.chainId}`]:[],...o?.signInWithSolana?.nonce?[`Nonce: ${o.signInWithSolana.nonce}`]:[],...o?.signInWithSolana?.requestId?[`Request ID: ${o.signInWithSolana.requestId}`]:[],...o?.signInWithSolana?.resources?.length?[`Resources`,...o.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join(`
117
+ `);let e=await s.signMessage(new TextEncoder().encode(t),`utf8`);if(!e||!(e instanceof Uint8Array))throw Error(`@supabase/auth-js: Wallet signMessage() API returned an recognized value`);n=e}}try{let{data:r,error:i}=await J(this.fetch,`POST`,`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:`solana`,message:t,signature:uo(n)},e.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options?.captchaToken}}:null),xform:Y});if(i)throw i;if(!r||!r.session||!r.user){let e=new Ua;return this._returnResult({data:{user:null,session:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers(`SIGNED_IN`,r.session)),this._returnResult({data:Object.assign({},r),error:i})}catch(e){if(U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){let[t,n]=(await bo(this.storage,`${this.storageKey}-code-verifier`)??``).split(`/`);try{if(!t&&this.flowType===`pkce`)throw new Ja;let{data:r,error:i}=await J(this.fetch,`POST`,`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:t},xform:Y});if(await q(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!r||!r.session||!r.user){let e=new Ua;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers(`SIGNED_IN`,r.session)),this._returnResult({data:Object.assign(Object.assign({},r),{redirectType:n??null}),error:i})}catch(e){if(await q(this.storage,`${this.storageKey}-code-verifier`),U(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{let{options:t,provider:n,token:r,access_token:i,nonce:a}=e,{data:o,error:s}=await J(this.fetch,`POST`,`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:r,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:Y});if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!o||!o.session||!o.user){let e=new Ua;return this._returnResult({data:{user:null,session:null},error:e})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers(`SIGNED_IN`,o.session)),this._returnResult({data:o,error:s})}catch(e){if(U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){try{if(`email`in e){let{email:t,options:n}=e,r=null,i=null;this.flowType===`pkce`&&([r,i]=await ko(this.storage,this.storageKey));let{error:a}=await J(this.fetch,`POST`,`${this.url}/otp`,{headers:this.headers,body:{email:t,data:n?.data??{},create_user:n?.shouldCreateUser??!0,gotrue_meta_security:{captcha_token:n?.captchaToken},code_challenge:r,code_challenge_method:i},redirectTo:n?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}if(`phone`in e){let{phone:t,options:n}=e,{data:r,error:i}=await J(this.fetch,`POST`,`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:n?.data??{},create_user:n?.shouldCreateUser??!0,gotrue_meta_security:{captcha_token:n?.captchaToken},channel:n?.channel??`sms`}});return this._returnResult({data:{user:null,session:null,messageId:r?.message_id},error:i})}throw new Wa(`You must provide either an email or phone number.`)}catch(e){if(await q(this.storage,`${this.storageKey}-code-verifier`),U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){try{let t,n;`options`in e&&(t=e.options?.redirectTo,n=e.options?.captchaToken);let{data:r,error:i}=await J(this.fetch,`POST`,`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:t,xform:Y});if(i)throw i;if(!r)throw Error(`An error occurred on token verification.`);let a=r.session,o=r.user;return a?.access_token&&(await this._saveSession(a),await this._notifyAllSubscribers(e.type==`recovery`?`PASSWORD_RECOVERY`:`SIGNED_IN`,a)),this._returnResult({data:{user:o,session:a},error:null})}catch(e){if(U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){try{let t=null,n=null;this.flowType===`pkce`&&([t,n]=await ko(this.storage,this.storageKey));let r=await J(this.fetch,`POST`,`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},`providerId`in e?{provider_id:e.providerId}:null),`domain`in e?{domain:e.domain}:null),{redirect_to:e.options?.redirectTo??void 0}),e?.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:t,code_challenge_method:n}),headers:this.headers,xform:Go});return r.data?.url&&K()&&!e.options?.skipBrowserRedirect&&window.location.assign(r.data.url),this._returnResult(r)}catch(e){if(await q(this.storage,`${this.storageKey}-code-verifier`),U(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;if(n)throw n;if(!t)throw new G;let{error:r}=await J(this.fetch,`GET`,`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:r})})}catch(e){if(U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let t=`${this.url}/resend`;if(`email`in e){let{email:n,type:r,options:i}=e,{error:a}=await J(this.fetch,`POST`,t,{headers:this.headers,body:{email:n,type:r,gotrue_meta_security:{captcha_token:i?.captchaToken}},redirectTo:i?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}else if(`phone`in e){let{phone:n,type:r,options:i}=e,{data:a,error:o}=await J(this.fetch,`POST`,t,{headers:this.headers,body:{phone:n,type:r,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a?.message_id},error:o})}throw new Wa(`You must provide either an email or phone number and a type`)}catch(e){if(U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug(`#_acquireLock`,`begin`,e);try{if(this.lockAcquired){let e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug(`#_acquireLock`,`lock acquired for storage key`,this.storageKey);try{this.lockAcquired=!0;let e=t();for(this.pendingInLock.push((async()=>{try{await e}catch{}})()),await e;this.pendingInLock.length;){let e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug(`#_acquireLock`,`lock released for storage key`,this.storageKey),this.lockAcquired=!1}})}finally{this._debug(`#_acquireLock`,`end`)}}async _useSession(e){this._debug(`#_useSession`,`begin`);try{return await e(await this.__loadSession())}finally{this._debug(`#_useSession`,`end`)}}async __loadSession(){this._debug(`#__loadSession()`,`begin`),this.lockAcquired||this._debug(`#__loadSession()`,`used outside of an acquired lock!`,Error().stack);try{let e=null,t=await bo(this.storage,this.storageKey);if(this._debug(`#getSession()`,`session from storage`,t),t!==null&&(this._isValidSession(t)?e=t:(this._debug(`#getSession()`,`session from storage is not valid`),await this._removeSession())),!e)return{data:{session:null},error:null};let n=e.expires_at?e.expires_at*1e3-Date.now()<ja:!1;if(this._debug(`#__loadSession()`,`session has${n?``:` not`} expired`,`expires_at`,e.expires_at),!n){if(this.userStorage){let t=await bo(this.userStorage,this.storageKey+`-user`);t?.user?e.user=t.user:e.user=Io()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let t={value:this.suppressGetSessionWarning};e.user=Lo(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:r,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:r},error:null})}finally{this._debug(`#__loadSession()`,`end`)}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await J(this.fetch,`GET`,`${this.url}/user`,{headers:this.headers,jwt:e,xform:X}):await this._useSession(async e=>{let{data:t,error:n}=e;if(n)throw n;return!t.session?.access_token&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new G}:await J(this.fetch,`GET`,`${this.url}/user`,{headers:this.headers,jwt:t.session?.access_token??void 0,xform:X})})}catch(e){if(U(e))return Ha(e)&&(await this._removeSession(),await q(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async n=>{let{data:r,error:i}=n;if(i)throw i;if(!r.session)throw new G;let a=r.session,o=null,s=null;this.flowType===`pkce`&&e.email!=null&&([o,s]=await ko(this.storage,this.storageKey));let{data:c,error:l}=await J(this.fetch,`PUT`,`${this.url}/user`,{headers:this.headers,redirectTo:t?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:s}),jwt:a.access_token,xform:X});if(l)throw l;return a.user=c.user,await this._saveSession(a),await this._notifyAllSubscribers(`USER_UPDATED`,a),this._returnResult({data:{user:a.user},error:null})})}catch(e){if(await q(this.storage,`${this.storageKey}-code-verifier`),U(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new G;let t=Date.now()/1e3,n=t,r=!0,i=null,{payload:a}=So(e.access_token);if(a.exp&&(n=a.exp,r=n<=t),r){let{data:t,error:n}=await this._callRefreshToken(e.refresh_token);if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!t)return{data:{user:null,session:null},error:null};i=t}else{let{data:r,error:a}=await this._getUser(e.access_token);if(a)return this._returnResult({data:{user:null,session:null},error:a});i={access_token:e.access_token,refresh_token:e.refresh_token,user:r.user,token_type:`bearer`,expires_in:n-t,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers(`SIGNED_IN`,i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(e){if(U(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{if(!e){let{data:n,error:r}=t;if(r)throw r;e=n.session??void 0}if(!e?.refresh_token)throw new G;let{data:n,error:r}=await this._callRefreshToken(e.refresh_token);return r?this._returnResult({data:{user:null,session:null},error:r}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(e){if(U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!K())throw new Ga(`No browser detected.`);if(e.error||e.error_description||e.error_code)throw new Ga(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(this.flowType===`pkce`)throw new qa(`Not a valid PKCE flow url.`);break;case`pkce`:if(this.flowType===`implicit`)throw new Ga(`Not a valid implicit grant flow url.`);break;default:}if(t===`pkce`){if(this._debug(`#_initialize()`,`begin`,`is PKCE flow`,!0),!e.code)throw new qa(`No code detected.`);let{data:t,error:n}=await this._exchangeCodeForSession(e.code);if(n)throw n;let 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}}let{provider_token:n,provider_refresh_token:r,access_token:i,refresh_token:a,expires_in:o,expires_at:s,token_type:c}=e;if(!i||!o||!a||!c)throw new Ga(`No session defined in URL`);let l=Math.round(Date.now()/1e3),u=parseInt(o),d=l+u;s&&(d=parseInt(s));let f=d-l;f*1e3<=3e4&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${u}s`);let p=d-u;l-p>=120?console.warn(`@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale`,p,d,l):l-p<0&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew`,p,d,l);let{data:m,error:h}=await this._getUser(i);if(h)throw h;let g={provider_token:n,provider_refresh_token:r,access_token:i,expires_in:u,expires_at:d,refresh_token:a,token_type:c,user:m.user};return window.location.hash=``,this._debug(`#_getSessionFromURL()`,`clearing window.location.hash`),this._returnResult({data:{session:g,redirectType:e.type},error:null})}catch(e){if(U(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl==`function`?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await bo(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:`global`}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:`global`}){return await this._useSession(async t=>{let{data:n,error:r}=t;if(r&&!Ha(r))return this._returnResult({error:r});let i=n.session?.access_token;if(i){let{error:t}=await this.admin.signOut(i,e);if(t&&!(Ba(t)&&(t.status===404||t.status===401||t.status===403)||Ha(t)))return this._returnResult({error:t})}return e!==`others`&&(await this._removeSession(),await q(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let t=po(),n={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,n),(async()=>{await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async t=>{try{let{data:{session:n},error:r}=t;if(r)throw r;await this.stateChangeEmitters.get(e)?.callback(`INITIAL_SESSION`,n),this._debug(`INITIAL_SESSION`,`callback id`,e,`session`,n)}catch(t){await this.stateChangeEmitters.get(e)?.callback(`INITIAL_SESSION`,null),this._debug(`INITIAL_SESSION`,`callback id`,e,`error`,t),console.error(t)}})}async resetPasswordForEmail(e,t={}){let n=null,r=null;this.flowType===`pkce`&&([n,r]=await ko(this.storage,this.storageKey,!0));try{return await J(this.fetch,`POST`,`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:r,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(await q(this.storage,`${this.storageKey}-code-verifier`),U(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){try{let{data:e,error:t}=await this.getUser();if(t)throw t;return this._returnResult({data:{identities:e.user.identities??[]},error:null})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return`token`in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){try{let{data:t,error:n}=await this._useSession(async t=>{let{data:n,error:r}=t;if(r)throw r;let i=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:e.options?.redirectTo,scopes:e.options?.scopes,queryParams:e.options?.queryParams,skipBrowserRedirect:!0});return await J(this.fetch,`GET`,i,{headers:this.headers,jwt:n.session?.access_token??void 0})});if(n)throw n;return K()&&!e.options?.skipBrowserRedirect&&window.location.assign(t?.url),this._returnResult({data:{provider:e.provider,url:t?.url},error:null})}catch(t){if(U(t))return this._returnResult({data:{provider:e.provider,url:null},error:t});throw t}}async linkIdentityIdToken(e){return await this._useSession(async t=>{try{let{error:n,data:{session:r}}=t;if(n)throw n;let{options:i,provider:a,token:o,access_token:s,nonce:c}=e,{data:l,error:u}=await J(this.fetch,`POST`,`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:r?.access_token??void 0,body:{provider:a,id_token:o,access_token:s,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Y});return u?this._returnResult({data:{user:null,session:null},error:u}):!l||!l.session||!l.user?this._returnResult({data:{user:null,session:null},error:new Ua}):(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers(`USER_UPDATED`,l.session)),this._returnResult({data:l,error:u}))}catch(e){if(await q(this.storage,`${this.storageKey}-code-verifier`),U(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)throw r;return await J(this.fetch,`DELETE`,`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:n.session?.access_token??void 0})})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,`begin`);try{let n=Date.now();return await wo(async n=>(n>0&&await Co(200*2**(n-1)),this._debug(t,`refreshing attempt`,n),await J(this.fetch,`POST`,`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Y})),(e,t)=>{let r=200*2**e;return t&&Xa(t)&&Date.now()+r-n<3e4})}catch(e){if(this._debug(t,`error`,e),U(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}finally{this._debug(t,`end`)}}_isValidSession(e){return typeof e==`object`&&!!e&&`access_token`in e&&`refresh_token`in e&&`expires_at`in e}async _handleProviderSignIn(e,t){let n=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`,n),K()&&!t.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){let e=`#_recoverAndRefresh()`;this._debug(e,`begin`);try{let t=await bo(this.storage,this.storageKey);if(t&&this.userStorage){let e=await bo(this.userStorage,this.storageKey+`-user`);!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!e&&(e={user:t.user},await yo(this.userStorage,this.storageKey+`-user`,e)),t.user=e?.user??Io()}else if(t&&!t.user&&!t.user){let e=await bo(this.storage,this.storageKey+`-user`);e&&e?.user?(t.user=e.user,await q(this.storage,this.storageKey+`-user`),await yo(this.storage,this.storageKey,t)):t.user=Io()}if(this._debug(e,`session from storage`,t),!this._isValidSession(t)){this._debug(e,`session is not valid`),t!==null&&await this._removeSession();return}let n=(t.expires_at??1/0)*1e3-Date.now()<ja;if(this._debug(e,`session has${n?``:` not`} expired with margin of ${ja}s`),n){if(this.autoRefreshToken&&t.refresh_token){let{error:n}=await this._callRefreshToken(t.refresh_token);n&&(console.error(n),Xa(n)||(this._debug(e,`refresh failed with a non-retryable error, removing the session`,n),await this._removeSession()))}}else if(t.user&&t.user.__isUserNotAvailableProxy===!0)try{let{data:n,error:r}=await this._getUser(t.access_token);!r&&n?.user?(t.user=n.user,await this._saveSession(t),await this._notifyAllSubscribers(`SIGNED_IN`,t)):this._debug(e,`could not get user data, skipping SIGNED_IN notification`)}catch(t){console.error(`Error getting user data:`,t),this._debug(e,`error getting user data, skipping SIGNED_IN notification`,t)}else await this._notifyAllSubscribers(`SIGNED_IN`,t)}catch(t){this._debug(e,`error`,t),console.error(t);return}finally{this._debug(e,`end`)}}async _callRefreshToken(e){var t,n;if(!e)throw new G;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,`begin`);try{this.refreshingDeferred=new xo;let{data:t,error:n}=await this._refreshAccessToken(e);if(n)throw n;if(!t.session)throw new G;await this._saveSession(t.session),await this._notifyAllSubscribers(`TOKEN_REFRESHED`,t.session);let r={data:t.session,error:null};return this.refreshingDeferred.resolve(r),r}catch(e){if(this._debug(r,`error`,e),U(e)){let n={data:null,error:e};return Xa(e)||await this._removeSession(),(t=this.refreshingDeferred)==null||t.resolve(n),n}throw(n=this.refreshingDeferred)==null||n.reject(e),e}finally{this.refreshingDeferred=null,this._debug(r,`end`)}}async _notifyAllSubscribers(e,t,n=!0){let r=`#_notifyAllSubscribers(${e})`;this._debug(r,`begin`,t,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:t});let r=[],i=Array.from(this.stateChangeEmitters.values()).map(async n=>{try{await n.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 q(this.storage,`${this.storageKey}-code-verifier`);let t=Object.assign({},e),n=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!n&&t.user&&await yo(this.userStorage,this.storageKey+`-user`,{user:t.user});let e=Object.assign({},t);delete e.user;let r=Ro(e);await yo(this.storage,this.storageKey,r)}else{let e=Ro(t);await yo(this.storage,this.storageKey,e)}}async _removeSession(){this._debug(`#_removeSession()`),this.suppressGetSessionWarning=!1,await q(this.storage,this.storageKey),await q(this.storage,this.storageKey+`-code-verifier`),await q(this.storage,this.storageKey+`-user`),this.userStorage&&await q(this.userStorage,this.storageKey+`-user`),await this._notifyAllSubscribers(`SIGNED_OUT`,null)}_removeVisibilityChangedCallback(){this._debug(`#_removeVisibilityChangedCallback()`);let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&K()&&window!=null&&window.removeEventListener&&window.removeEventListener(`visibilitychange`,e)}catch(e){console.error(`removing visibilitychange callback failed`,e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug(`#_startAutoRefresh()`);let e=setInterval(()=>this._autoRefreshTokenTick(),Aa);this.autoRefreshTicker=e,e&&typeof e==`object`&&typeof e.unref==`function`?e.unref():typeof Deno<`u`&&typeof Deno.unrefTimer==`function`&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&typeof t==`object`&&typeof t.unref==`function`?t.unref():typeof Deno<`u`&&typeof Deno.unrefTimer==`function`&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug(`#_stopAutoRefresh()`);let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug(`#_autoRefreshTokenTick()`,`begin`);try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:n}}=t;if(!n||!n.refresh_token||!n.expires_at){this._debug(`#_autoRefreshTokenTick()`,`no session`);return}let r=Math.floor((n.expires_at*1e3-e)/Aa);this._debug(`#_autoRefreshTokenTick()`,`access token expires in ${r} ticks, a tick lasts ${Aa}ms, refresh threshold is 3 ticks`),r<=3&&await this._callRefreshToken(n.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 Qo)this._debug(`auto refresh token tick lock not available`);else throw e}}async _handleVisibilityChange(){if(this._debug(`#_handleVisibilityChange()`),!K()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug(`#visibilityChangedCallback`,`error`,e)}},window==null||window.addEventListener(`visibilitychange`,this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error(`_handleVisibilityChange`,e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,`visibilityState`,document.visibilityState),document.visibilityState===`visible`?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!==`visible`){this._debug(t,`acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting`);return}await this._recoverAndRefresh()}))):document.visibilityState===`hidden`&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,n){let r=[`provider=${encodeURIComponent(t)}`];if(n?.redirectTo&&r.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n?.scopes&&r.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType===`pkce`){let[e,t]=await ko(this.storage,this.storageKey),n=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});r.push(n.toString())}if(n?.queryParams){let e=new URLSearchParams(n.queryParams);r.push(e.toString())}return n?.skipBrowserRedirect&&r.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${r.join(`&`)}`}async _unenroll(e){try{return await this._useSession(async t=>{let{data:n,error:r}=t;return r?this._returnResult({data:null,error:r}):await J(this.fetch,`DELETE`,`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:n?.session?.access_token})})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)return this._returnResult({data:null,error:r});let i=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType===`phone`?{phone:e.phone}:e.factorType===`totp`?{issuer:e.issuer}:{}),{data:a,error:o}=await J(this.fetch,`POST`,`${this.url}/factors`,{body:i,headers:this.headers,jwt:n?.session?.access_token});return o?this._returnResult({data:null,error:o}):(e.factorType===`totp`&&a.type===`totp`&&a?.totp?.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),this._returnResult({data:a,error:null}))})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)return this._returnResult({data:null,error:r});let i=Object.assign({challenge_id:e.challengeId},`webauthn`in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type===`create`?fs(e.webauthn.credential_response):ps(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:o}=await J(this.fetch,`POST`,`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:n?.session?.access_token});return o?this._returnResult({data:null,error:o}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers(`MFA_CHALLENGE_VERIFIED`,a),this._returnResult({data:a,error:o}))})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)return this._returnResult({data:null,error:r});let i=await J(this.fetch,`POST`,`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:n?.session?.access_token});if(i.error)return i;let{data:a}=i;if(a.type!==`webauthn`)return{data:a,error:null};switch(a.webauthn.type){case`create`:return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:us(a.webauthn.credential_options.publicKey)})})}),error:null};case`request`:return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:ds(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}})}async _challengeAndVerify(e){let{data:t,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let n={all:[],phone:[],totp:[],webauthn:[]};for(let t of e?.factors??[])n.all.push(t),t.status===`verified`&&n[t.factor_type].push(t);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){if(e)try{let{payload:t}=So(e),n=null;t.aal&&(n=t.aal);let r=n,{data:{user:i},error:a}=await this.getUser(e);if(a)return this._returnResult({data:null,error:a});((i?.factors)?.filter(e=>e.status===`verified`)??[]).length>0&&(r=`aal2`);let o=t.amr||[];return{data:{currentLevel:n,nextLevel:r,currentAuthenticationMethods:o},error:null}}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}let{data:{session:t},error:n}=await this.getSession();if(n)return this._returnResult({data:null,error:n});if(!t)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:r}=So(t.access_token),i=null;r.aal&&(i=r.aal);let a=i;(t.user.factors?.filter(e=>e.status===`verified`)??[]).length>0&&(a=`aal2`);let o=r.amr||[];return{data:{currentLevel:i,nextLevel:a,currentAuthenticationMethods:o},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:n},error:r}=t;return r?this._returnResult({data:null,error:r}):n?await J(this.fetch,`GET`,`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new G})})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession(async n=>{let{data:{session:r},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!r)return this._returnResult({data:null,error:new G});let a=await J(this.fetch,`POST`,`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:r.access_token,body:{action:`approve`},xform:e=>({data:e,error:null})});return a.data&&a.data.redirect_url&&K()&&!t?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession(async n=>{let{data:{session:r},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!r)return this._returnResult({data:null,error:new G});let a=await J(this.fetch,`POST`,`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:r.access_token,body:{action:`deny`},xform:e=>({data:e,error:null})});return a.data&&a.data.redirect_url&&K()&&!t?.skipBrowserRedirect&&window.location.assign(a.data.redirect_url),a})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;return n?this._returnResult({data:null,error:n}):t?await J(this.fetch,`GET`,`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new G})})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:n},error:r}=t;return r?this._returnResult({data:null,error:r}):n?(await J(this.fetch,`DELETE`,`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new G})})}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e,t={keys:[]}){let n=t.keys.find(t=>t.kid===e);if(n)return n;let r=Date.now();if(n=this.jwks.keys.find(t=>t.kid===e),n&&this.jwks_cached_at+6e5>r)return n;let{data:i,error:a}=await J(this.fetch,`GET`,`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(a)throw a;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=r,n=i.keys.find(t=>t.kid===e),!n)?null:n}async getClaims(e,t={}){try{let n=e;if(!n){let{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});n=e.session.access_token}let{header:r,payload:i,signature:a,raw:{header:o,payload:s}}=So(n);t?.allowExpired||Mo(i.exp);let c=!r.alg||r.alg.startsWith(`HS`)||!r.kid||!(`crypto`in globalThis&&`subtle`in globalThis.crypto)?null:await this.fetchJwk(r.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!c){let{error:e}=await this.getUser(n);if(e)throw e;return{data:{claims:i,header:r,signature:a},error:null}}let l=No(r.alg),u=await crypto.subtle.importKey(`jwk`,c,l,!0,[`verify`]);if(!await crypto.subtle.verify(l,u,a,lo(`${o}.${s}`)))throw new Qa(`Invalid JWT signature`);return{data:{claims:i,header:r,signature:a},error:null}}catch(e){if(U(e))return this._returnResult({data:null,error:e});throw e}}};Ds.nextInstanceID={};var Os=Ds,ks=`2.99.3`,As=``;As=typeof Deno<`u`?`deno`:typeof document<`u`?`web`:typeof navigator<`u`&&navigator.product===`ReactNative`?`react-native`:`node`;var js={headers:{"X-Client-Info":`supabase-js-${As}/${ks}`}},Ms={schema:`public`},Ns={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:`implicit`},Ps={};function Fs(e){"@babel/helpers - typeof";return Fs=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},Fs(e)}function Is(e,t){if(Fs(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(Fs(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Ls(e){var t=Is(e,`string`);return Fs(t)==`symbol`?t:t+``}function Rs(e,t,n){return(t=Ls(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function zs(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function $(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?zs(Object(n),!0).forEach(function(t){Rs(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):zs(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var Bs=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Vs=()=>Headers,Hs=(e,t,n)=>{let r=Bs(n),i=Vs();return async(n,a)=>{let o=await t()??e,s=new i(a?.headers);return s.has(`apikey`)||s.set(`apikey`,e),s.has(`Authorization`)||s.set(`Authorization`,`Bearer ${o}`),r(n,$($({},a),{},{headers:s}))}};function Us(e){return e.endsWith(`/`)?e:e+`/`}function Ws(e,t){let{db:n,auth:r,realtime:i,global:a}=e,{db:o,auth:s,realtime:c,global:l}=t,u={db:$($({},o),n),auth:$($({},s),r),realtime:$($({},c),i),storage:{},global:$($($({},l),a),{},{headers:$($({},l?.headers??{}),a?.headers??{})}),accessToken:async()=>``};return e.accessToken?u.accessToken=e.accessToken:delete u.accessToken,u}function Gs(e){let t=e?.trim();if(!t)throw Error(`supabaseUrl is required.`);if(!t.match(/^https?:\/\//i))throw Error(`Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.`);try{return new URL(Us(t))}catch{throw Error(`Invalid supabaseUrl: Provided URL is malformed.`)}}var Ks=class extends Os{constructor(e){super(e)}},qs=class{constructor(e,t,n){this.supabaseUrl=e,this.supabaseKey=t;let r=Gs(e);if(!t)throw Error(`supabaseKey is required.`);this.realtimeUrl=new URL(`realtime/v1`,r),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace(`http`,`ws`),this.authUrl=new URL(`auth/v1`,r),this.storageUrl=new URL(`storage/v1`,r),this.functionsUrl=new URL(`functions/v1`,r);let i=`sb-${r.hostname.split(`.`)[0]}-auth-token`,a={db:Ms,realtime:Ps,auth:$($({},Ns),{},{storageKey:i}),global:js},o=Ws(n??{},a);this.storageKey=o.auth.storageKey??``,this.headers=o.global.headers??{},o.accessToken?(this.accessToken=o.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(o.auth??{},this.headers,o.global.fetch),this.fetch=Hs(t,this._getAccessToken.bind(this),o.global.fetch),this.realtime=this._initRealtimeClient($({headers:this.headers,accessToken:this._getAccessToken.bind(this)},o.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(e=>this.realtime.setAuth(e)).catch(e=>console.warn(`Failed to set initial Realtime auth token:`,e)),this.rest=new ti(new URL(`rest/v1`,r).href,{headers:this.headers,schema:o.db.schema,fetch:this.fetch,timeout:o.db.timeout,urlLengthLimit:o.db.urlLengthLimit}),this.storage=new Oa(this.storageUrl.href,this.headers,this.fetch,n?.storage),o.accessToken||this._listenForAuthEvents()}get functions(){return new Hr(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},n={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,n)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e=this;if(e.accessToken)return await e.accessToken();let{data:t}=await e.auth.getSession();return t.session?.access_token??e.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:i,storageKey:a,flowType:o,lock:s,debug:c,throwOnError:l},u,d){let f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Ks({url:this.authUrl.href,headers:$($({},f),u),storageKey:a,autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:i,flowType:o,lock:s,debug:c,throwOnError:l,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>e.toLowerCase()===`authorization`)})}_initRealtimeClient(e){return new Pi(this.realtimeUrl.href,$($({},e),{},{params:$($({},{apikey:this.supabaseKey}),e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,`CLIENT`,t?.access_token)})}_handleTokenChanged(e,t,n){(e===`TOKEN_REFRESHED`||e===`SIGNED_IN`)&&this.changedAccessToken!==n?(this.changedAccessToken=n,this.realtime.setAuth(n)):e===`SIGNED_OUT`&&(this.realtime.setAuth(),t==`STORAGE`&&this.auth.signOut(),this.changedAccessToken=void 0)}},Js=(e,t,n)=>new qs(e,t,n);function Ys(){if(typeof window<`u`)return!1;let e=globalThis.process;if(!e)return!1;let t=e.version;if(t==null)return!1;let n=t.match(/^v(\d+)\./);return n?parseInt(n[1],10)<=18:!1}Ys()&&console.warn(`⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217`);var Xs=()=>({url:`https://uehmyyeqheqnxmzhctcd.supabase.co`,anonKey:`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InVlaG15eWVxaGVxbnhtemhjdGNkIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTg2MjA3NDMsImV4cCI6MjAzNDE5Njc0M30.a6tyestJTPSQ6ZdpjRGrataTSn_8_REHJC0SnoCaY2Y`}),Zs=()=>{let{url:e,anonKey:t}=Xs();return!!(e&&t)},Qs=e=>{let{url:t,anonKey:n}=Xs();return!t||!n?(console.warn(`Supabase environment variables are not configured. Supabase will not be available.`),null):Js(t,n,e)},$s=e=>{if(e&&typeof e==`string`){let t=()=>typeof window<`u`?window.location.port===`5173`?`http://${window.location.hostname}:33753`:`${window.location.protocol}//${window.location.host}`:`http://localhost:33753`;if(e.startsWith(`file://`)){let n=e.substring(7);return`${t()}/media-file/${encodeURIComponent(n)}`}if(e.startsWith(`media://`)){let n=e.replace(/^media:\/\/+/,`/`);return`${t()}/media-file/${encodeURIComponent(n)}`}}return e||``},ec=e=>e.required===!0,tc=class extends Error{constructor(e,t,n){super(e),this.code=t,this.requestId=n,this.name=`WebSocketError`}},nc=class extends tc{constructor(e,t){super(e),this.url=t,this.name=`WebSocketConnectionError`}},rc=e=>e&&typeof e.channel==`string`&&e.requestId,ic=e=>e&&e.type===`response`&&e.requestId&&e.events,ac=e=>e&&e.type===`error`&&e.requestId&&e.error;E(`1.0.0`),O(nt(k(),wt),{}),E(`2.0.0`),O(w(wt),[]);var oc=e({ConnectionValidator:()=>Et,EditorParamValidatorV3:()=>wr,OriginValidator:()=>Cr,SaveLocationExternalValidator:()=>St,SaveLocationInternalValidator:()=>xt,SaveLocationPipelabCloudValidator:()=>Ct,SaveLocationValidator:()=>wt,SavedFileDefaultValidatorV4:()=>kr,SavedFileDefaultValidatorV5:()=>jr,SavedFileSimpleValidatorV4:()=>Ar,SavedFileValidator:()=>Nr,SavedFileValidatorV5:()=>Mr,ShellChannels:()=>Tt,VariableValidatorV1:()=>Or,WebSocketConnectionError:()=>nc,WebSocketError:()=>tc,createQuickJs:()=>br,createQuickJsFromVariant:()=>yr,defaultAppSettings:()=>sc,defaultConnections:()=>lc,defaultFileRepo:()=>cc,fmt:()=>gr,foo:()=>`bar`,isRequired:()=>ec,isSupabaseAvailable:()=>Zs,isWebSocketErrorMessage:()=>ac,isWebSocketRequestMessage:()=>rc,isWebSocketResponseMessage:()=>ic,makeResolvedParams:()=>xr,supabase:()=>Qs,transformUrl:()=>$s,useLogger:()=>gn,variableToFormattedVariable:()=>Sr}),sc=ft,cc=gt,lc=mt;export{S as A,Je as C,st as D,ot as E,Xe as O,qe as S,D as T,br as _,nc as a,gn as b,rc as c,$s as d,Zs as f,xr as g,Sr as h,oc as i,k,ic as l,Nr as m,lc as n,tc as o,Qs as p,cc as r,ac as s,sc as t,ec as u,yr as v,Ye as w,Tt as x,yn as y};