@zorgo/next 2.0.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/cli.mjs.map +1 -1
- package/dist/images.js.map +1 -1
- package/dist/images.mjs.map +1 -1
- package/dist/index.d.mts +5 -2
- package/dist/index.d.ts +5 -2
- package/dist/index.js +25 -25
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +23 -23
- package/dist/index.mjs.map +1 -1
- package/dist/item-page.js.map +1 -1
- package/dist/item-page.mjs.map +1 -1
- package/dist/server.js.map +1 -1
- package/dist/server.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use strict";var _b=Object.create;var zs=Object.defineProperty;var wb=Object.getOwnPropertyDescriptor;var vb=Object.getOwnPropertyNames;var Sb=Object.getPrototypeOf,xb=Object.prototype.hasOwnProperty;var Gs=(t,e)=>()=>(t&&(e=t(t=0)),e);var it=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ud=(t,e)=>{for(var r in e)zs(t,r,{get:e[r],enumerable:!0})},Fd=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of vb(e))!xb.call(t,n)&&n!==r&&zs(t,n,{get:()=>e[n],enumerable:!(o=wb(e,n))||o.enumerable});return t};var Le=(t,e,r)=>(r=t!=null?_b(Sb(t)):{},Fd(e||!t||!t.__esModule?zs(r,"default",{value:t,enumerable:!0}):r,t)),Ol=t=>Fd(zs({},"__esModule",{value:!0}),t);var Pu=it(Eu=>{"use strict";Eu.parse=Kv;Eu.serialize=Jv;var qv=Object.prototype.toString,Vv=Object.prototype.hasOwnProperty,Wv=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Hv=/^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/,zv=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Gv=/^[\u0020-\u003A\u003D-\u007E]*$/;function Kv(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");var r={},o=t.length;if(o<2)return r;var n=e&&e.decode||Yv,s=0,i=0,a=0;do{if(i=t.indexOf("=",s),i===-1)break;if(a=t.indexOf(";",s),a===-1)a=o;else if(i>a){s=t.lastIndexOf(";",i-1)+1;continue}var l=Zm(t,s,i),u=eh(t,i,l),c=t.slice(l,u);if(!Vv.call(r,c)){var d=Zm(t,i+1,a),f=eh(t,a,d);t.charCodeAt(d)===34&&t.charCodeAt(f-1)===34&&(d++,f--);var m=t.slice(d,f);r[c]=Qv(m,n)}s=a+1}while(s<o);return r}function Zm(t,e,r){do{var o=t.charCodeAt(e);if(o!==32&&o!==9)return e}while(++e<r);return r}function eh(t,e,r){for(;e>r;){var o=t.charCodeAt(--e);if(o!==32&&o!==9)return e+1}return r}function Jv(t,e,r){var o=r&&r.encode||encodeURIComponent;if(typeof o!="function")throw new TypeError("option encode is invalid");if(!Wv.test(t))throw new TypeError("argument name is invalid");var n=o(e);if(!Hv.test(n))throw new TypeError("argument val is invalid");var s=t+"="+n;if(!r)return s;if(r.maxAge!=null){var i=Math.floor(r.maxAge);if(!isFinite(i))throw new TypeError("option maxAge is invalid");s+="; Max-Age="+i}if(r.domain){if(!zv.test(r.domain))throw new TypeError("option domain is invalid");s+="; Domain="+r.domain}if(r.path){if(!Gv.test(r.path))throw new TypeError("option path is invalid");s+="; Path="+r.path}if(r.expires){var a=r.expires;if(!Xv(a)||isNaN(a.valueOf()))throw new TypeError("option expires is invalid");s+="; Expires="+a.toUTCString()}if(r.httpOnly&&(s+="; HttpOnly"),r.secure&&(s+="; Secure"),r.partitioned&&(s+="; Partitioned"),r.priority){var l=typeof r.priority=="string"?r.priority.toLowerCase():r.priority;switch(l){case"low":s+="; Priority=Low";break;case"medium":s+="; Priority=Medium";break;case"high":s+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}}if(r.sameSite){var u=typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite;switch(u){case!0:s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"strict":s+="; SameSite=Strict";break;case"none":s+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return s}function Yv(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}function Xv(t){return qv.call(t)==="[object Date]"}function Qv(t,e){try{return e(t)}catch{return t}}});var ah=it((JR,ih)=>{"use strict";ih.exports=t=>{if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}});var mh=it((dh,fh)=>{"use strict";var Gi=ah(),{hasOwnProperty:uh}=Object.prototype,{propertyIsEnumerable:n0}=Object,Go=(t,e,r)=>Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0}),s0=dh,lh={concatArrays:!1,ignoreUndefined:!1},Ki=t=>{let e=[];for(let r in t)uh.call(t,r)&&e.push(r);if(Object.getOwnPropertySymbols){let r=Object.getOwnPropertySymbols(t);for(let o of r)n0.call(t,o)&&e.push(o)}return e};function Ko(t){return Array.isArray(t)?i0(t):Gi(t)?a0(t):t}function i0(t){let e=t.slice(0,0);return Ki(t).forEach(r=>{Go(e,r,Ko(t[r]))}),e}function a0(t){let e=Object.getPrototypeOf(t)===null?Object.create(null):{};return Ki(t).forEach(r=>{Go(e,r,Ko(t[r]))}),e}var ch=(t,e,r,o)=>(r.forEach(n=>{typeof e[n]>"u"&&o.ignoreUndefined||(n in t&&t[n]!==Object.getPrototypeOf(t)?Go(t,n,Uu(t[n],e[n],o)):Go(t,n,Ko(e[n])))}),t),l0=(t,e,r)=>{let o=t.slice(0,0),n=0;return[t,e].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)uh.call(s,a)&&(i.push(String(a)),s===t?Go(o,n++,s[a]):Go(o,n++,Ko(s[a])));o=ch(o,s,Ki(s).filter(a=>!i.includes(a)),r)}),o};function Uu(t,e,r){return r.concatArrays&&Array.isArray(t)&&Array.isArray(e)?l0(t,e,r):!Gi(e)||!Gi(t)?Ko(e):ch(t,e,Ki(e),r)}fh.exports=function(...t){let e=Uu(Ko(lh),this!==s0&&this||{},lh),r={_:{}};for(let o of t)if(o!==void 0){if(!Gi(o))throw new TypeError("`"+o+"` is not an Option Object");r=Uu(r,{_:o},e)}return r._}});var hh,ph,gh=Gs(()=>{"use strict";hh=Le(mh(),1),ph=hh.default});function c0(t,e){let r=window.localStorage.getItem(t);if(r){let o=JSON.parse(r),n=JSON.parse(e),s=JSON.stringify(u0(o,n));window.localStorage.setItem(t,s)}else window.localStorage.setItem(t,e)}function Jo(t,e){return new Promise((r,o)=>{try{let n=t();e?.(null,n),r(n)}catch(n){e?.(n),o(n)}})}function Ji(t,e,r){return Promise.all(t).then(o=>{let n=r?.(o)??null;return e?.(null,n),Promise.resolve(n)},o=>(e?.(o),Promise.reject(o)))}var u0,_s,so,Fu=Gs(()=>{"use strict";gh();u0=ph.bind({concatArrays:!0,ignoreUndefined:!0});_s={getItem:(t,e)=>Jo(()=>window.localStorage.getItem(t),e),setItem:(t,e,r)=>Jo(()=>window.localStorage.setItem(t,e),r),removeItem:(t,e)=>Jo(()=>window.localStorage.removeItem(t),e),mergeItem:(t,e,r)=>Jo(()=>c0(t,e),r),clear:t=>Jo(()=>window.localStorage.clear(),t),getAllKeys:t=>Jo(()=>{let e=window.localStorage.length,r=[];for(let o=0;o<e;o+=1){let n=window.localStorage.key(o)||"";r.push(n)}return r},t),flushGetRequests:()=>{},multiGet:(t,e)=>{let r=t.map(n=>_s.getItem(n));return Ji(r,e,n=>n.map((s,i)=>[t[i],s]))},multiSet:(t,e)=>{let r=t.map(o=>_s.setItem(o[0],o[1]));return Ji(r,e)},multiRemove:(t,e)=>{let r=t.map(o=>_s.removeItem(o));return Ji(r,e)},multiMerge:(t,e)=>{let r=t.map(o=>_s.mergeItem(o[0],o[1]));return Ji(r,e)}},so=_s});function yh(t){return{getItem:(...e)=>so.getItem(t,...e),setItem:(...e)=>so.setItem(t,...e),mergeItem:(...e)=>so.mergeItem(t,...e),removeItem:(...e)=>so.removeItem(t,...e)}}var bh=Gs(()=>{"use strict";Fu()});var $u={};Ud($u,{default:()=>d0,useAsyncStorage:()=>yh});var d0,Bu=Gs(()=>{"use strict";Fu();bh();d0=so});var eg=it((qM,Zp)=>{"use strict";Zp.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var o,n,s;if(Array.isArray(e)){if(o=e.length,o!=r.length)return!1;for(n=o;n--!==0;)if(!t(e[n],r[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),o=s.length,o!==Object.keys(r).length)return!1;for(n=o;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=o;n--!==0;){var i=s[n];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var xc=it((IF,Ng)=>{"use strict";Ng.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}});var Mg=it((DF,jg)=>{"use strict";jg.exports=function(e){return!e||typeof e=="string"?!1:e instanceof Array||Array.isArray(e)||e.length>=0&&(e.splice instanceof Function||Object.getOwnPropertyDescriptor(e,e.length-1)&&e.constructor.name!=="String")}});var $g=it((LF,Fg)=>{"use strict";var Zx=Mg(),ek=Array.prototype.concat,tk=Array.prototype.slice,Ug=Fg.exports=function(e){for(var r=[],o=0,n=e.length;o<n;o++){var s=e[o];Zx(s)?r=ek.call(r,tk.call(s)):r.push(s)}return r};Ug.wrap=function(t){return function(){return t(Ug(arguments))}}});var Wg=it((NF,Vg)=>{"use strict";var Ds=xc(),Ls=$g(),Bg=Object.hasOwnProperty,qg=Object.create(null);for(ul in Ds)Bg.call(Ds,ul)&&(qg[Ds[ul]]=ul);var ul,et=Vg.exports={to:{},get:{}};et.get=function(t){var e=t.substring(0,3).toLowerCase(),r,o;switch(e){case"hsl":r=et.get.hsl(t),o="hsl";break;case"hwb":r=et.get.hwb(t),o="hwb";break;default:r=et.get.rgb(t),o="rgb";break}return r?{model:o,value:r}:null};et.get.rgb=function(t){if(!t)return null;var e=/^#([a-f0-9]{3,4})$/i,r=/^#([a-f0-9]{6})([a-f0-9]{2})?$/i,o=/^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/,n=/^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/,s=/^(\w+)$/,i=[0,0,0,1],a,l,u;if(a=t.match(r)){for(u=a[2],a=a[1],l=0;l<3;l++){var c=l*2;i[l]=parseInt(a.slice(c,c+2),16)}u&&(i[3]=parseInt(u,16)/255)}else if(a=t.match(e)){for(a=a[1],u=a[3],l=0;l<3;l++)i[l]=parseInt(a[l]+a[l],16);u&&(i[3]=parseInt(u+u,16)/255)}else if(a=t.match(o)){for(l=0;l<3;l++)i[l]=parseInt(a[l+1],0);a[4]&&(a[5]?i[3]=parseFloat(a[4])*.01:i[3]=parseFloat(a[4]))}else if(a=t.match(n)){for(l=0;l<3;l++)i[l]=Math.round(parseFloat(a[l+1])*2.55);a[4]&&(a[5]?i[3]=parseFloat(a[4])*.01:i[3]=parseFloat(a[4]))}else return(a=t.match(s))?a[1]==="transparent"?[0,0,0,0]:Bg.call(Ds,a[1])?(i=Ds[a[1]],i[3]=1,i):null:null;for(l=0;l<3;l++)i[l]=Ar(i[l],0,255);return i[3]=Ar(i[3],0,1),i};et.get.hsl=function(t){if(!t)return null;var e=/^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/,r=t.match(e);if(r){var o=parseFloat(r[4]),n=(parseFloat(r[1])%360+360)%360,s=Ar(parseFloat(r[2]),0,100),i=Ar(parseFloat(r[3]),0,100),a=Ar(isNaN(o)?1:o,0,1);return[n,s,i,a]}return null};et.get.hwb=function(t){if(!t)return null;var e=/^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/,r=t.match(e);if(r){var o=parseFloat(r[4]),n=(parseFloat(r[1])%360+360)%360,s=Ar(parseFloat(r[2]),0,100),i=Ar(parseFloat(r[3]),0,100),a=Ar(isNaN(o)?1:o,0,1);return[n,s,i,a]}return null};et.to.hex=function(){var t=Ls(arguments);return"#"+cl(t[0])+cl(t[1])+cl(t[2])+(t[3]<1?cl(Math.round(t[3]*255)):"")};et.to.rgb=function(){var t=Ls(arguments);return t.length<4||t[3]===1?"rgb("+Math.round(t[0])+", "+Math.round(t[1])+", "+Math.round(t[2])+")":"rgba("+Math.round(t[0])+", "+Math.round(t[1])+", "+Math.round(t[2])+", "+t[3]+")"};et.to.rgb.percent=function(){var t=Ls(arguments),e=Math.round(t[0]/255*100),r=Math.round(t[1]/255*100),o=Math.round(t[2]/255*100);return t.length<4||t[3]===1?"rgb("+e+"%, "+r+"%, "+o+"%)":"rgba("+e+"%, "+r+"%, "+o+"%, "+t[3]+")"};et.to.hsl=function(){var t=Ls(arguments);return t.length<4||t[3]===1?"hsl("+t[0]+", "+t[1]+"%, "+t[2]+"%)":"hsla("+t[0]+", "+t[1]+"%, "+t[2]+"%, "+t[3]+")"};et.to.hwb=function(){var t=Ls(arguments),e="";return t.length>=4&&t[3]!==1&&(e=", "+t[3]),"hwb("+t[0]+", "+t[1]+"%, "+t[2]+"%"+e+")"};et.to.keyword=function(t){return qg[t.slice(0,3)]};function Ar(t,e,r){return Math.min(Math.max(e,t),r)}function cl(t){var e=Math.round(t).toString(16).toUpperCase();return e.length<2?"0"+e:e}});var kc=it((jF,zg)=>{"use strict";var Ns=xc(),Hg={};for(let t of Object.keys(Ns))Hg[Ns[t]]=t;var E={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};zg.exports=E;for(let t of Object.keys(E)){if(!("channels"in E[t]))throw new Error("missing channels property: "+t);if(!("labels"in E[t]))throw new Error("missing channel labels property: "+t);if(E[t].labels.length!==E[t].channels)throw new Error("channel and label counts mismatch: "+t);let{channels:e,labels:r}=E[t];delete E[t].channels,delete E[t].labels,Object.defineProperty(E[t],"channels",{value:e}),Object.defineProperty(E[t],"labels",{value:r})}E.rgb.hsl=function(t){let e=t[0]/255,r=t[1]/255,o=t[2]/255,n=Math.min(e,r,o),s=Math.max(e,r,o),i=s-n,a,l;s===n?a=0:e===s?a=(r-o)/i:r===s?a=2+(o-e)/i:o===s&&(a=4+(e-r)/i),a=Math.min(a*60,360),a<0&&(a+=360);let u=(n+s)/2;return s===n?l=0:u<=.5?l=i/(s+n):l=i/(2-s-n),[a,l*100,u*100]};E.rgb.hsv=function(t){let e,r,o,n,s,i=t[0]/255,a=t[1]/255,l=t[2]/255,u=Math.max(i,a,l),c=u-Math.min(i,a,l),d=function(f){return(u-f)/6/c+1/2};return c===0?(n=0,s=0):(s=c/u,e=d(i),r=d(a),o=d(l),i===u?n=o-r:a===u?n=1/3+e-o:l===u&&(n=2/3+r-e),n<0?n+=1:n>1&&(n-=1)),[n*360,s*100,u*100]};E.rgb.hwb=function(t){let e=t[0],r=t[1],o=t[2],n=E.rgb.hsl(t)[0],s=1/255*Math.min(e,Math.min(r,o));return o=1-1/255*Math.max(e,Math.max(r,o)),[n,s*100,o*100]};E.rgb.cmyk=function(t){let e=t[0]/255,r=t[1]/255,o=t[2]/255,n=Math.min(1-e,1-r,1-o),s=(1-e-n)/(1-n)||0,i=(1-r-n)/(1-n)||0,a=(1-o-n)/(1-n)||0;return[s*100,i*100,a*100,n*100]};function rk(t,e){return(t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2}E.rgb.keyword=function(t){let e=Hg[t];if(e)return e;let r=1/0,o;for(let n of Object.keys(Ns)){let s=Ns[n],i=rk(t,s);i<r&&(r=i,o=n)}return o};E.keyword.rgb=function(t){return Ns[t]};E.rgb.xyz=function(t){let e=t[0]/255,r=t[1]/255,o=t[2]/255;e=e>.04045?((e+.055)/1.055)**2.4:e/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92,o=o>.04045?((o+.055)/1.055)**2.4:o/12.92;let n=e*.4124+r*.3576+o*.1805,s=e*.2126+r*.7152+o*.0722,i=e*.0193+r*.1192+o*.9505;return[n*100,s*100,i*100]};E.rgb.lab=function(t){let e=E.rgb.xyz(t),r=e[0],o=e[1],n=e[2];r/=95.047,o/=100,n/=108.883,r=r>.008856?r**(1/3):7.787*r+16/116,o=o>.008856?o**(1/3):7.787*o+16/116,n=n>.008856?n**(1/3):7.787*n+16/116;let s=116*o-16,i=500*(r-o),a=200*(o-n);return[s,i,a]};E.hsl.rgb=function(t){let e=t[0]/360,r=t[1]/100,o=t[2]/100,n,s,i;if(r===0)return i=o*255,[i,i,i];o<.5?n=o*(1+r):n=o+r-o*r;let a=2*o-n,l=[0,0,0];for(let u=0;u<3;u++)s=e+1/3*-(u-1),s<0&&s++,s>1&&s--,6*s<1?i=a+(n-a)*6*s:2*s<1?i=n:3*s<2?i=a+(n-a)*(2/3-s)*6:i=a,l[u]=i*255;return l};E.hsl.hsv=function(t){let e=t[0],r=t[1]/100,o=t[2]/100,n=r,s=Math.max(o,.01);o*=2,r*=o<=1?o:2-o,n*=s<=1?s:2-s;let i=(o+r)/2,a=o===0?2*n/(s+n):2*r/(o+r);return[e,a*100,i*100]};E.hsv.rgb=function(t){let e=t[0]/60,r=t[1]/100,o=t[2]/100,n=Math.floor(e)%6,s=e-Math.floor(e),i=255*o*(1-r),a=255*o*(1-r*s),l=255*o*(1-r*(1-s));switch(o*=255,n){case 0:return[o,l,i];case 1:return[a,o,i];case 2:return[i,o,l];case 3:return[i,a,o];case 4:return[l,i,o];case 5:return[o,i,a]}};E.hsv.hsl=function(t){let e=t[0],r=t[1]/100,o=t[2]/100,n=Math.max(o,.01),s,i;i=(2-r)*o;let a=(2-r)*n;return s=r*n,s/=a<=1?a:2-a,s=s||0,i/=2,[e,s*100,i*100]};E.hwb.rgb=function(t){let e=t[0]/360,r=t[1]/100,o=t[2]/100,n=r+o,s;n>1&&(r/=n,o/=n);let i=Math.floor(6*e),a=1-o;s=6*e-i,(i&1)!==0&&(s=1-s);let l=r+s*(a-r),u,c,d;switch(i){default:case 6:case 0:u=a,c=l,d=r;break;case 1:u=l,c=a,d=r;break;case 2:u=r,c=a,d=l;break;case 3:u=r,c=l,d=a;break;case 4:u=l,c=r,d=a;break;case 5:u=a,c=r,d=l;break}return[u*255,c*255,d*255]};E.cmyk.rgb=function(t){let e=t[0]/100,r=t[1]/100,o=t[2]/100,n=t[3]/100,s=1-Math.min(1,e*(1-n)+n),i=1-Math.min(1,r*(1-n)+n),a=1-Math.min(1,o*(1-n)+n);return[s*255,i*255,a*255]};E.xyz.rgb=function(t){let e=t[0]/100,r=t[1]/100,o=t[2]/100,n,s,i;return n=e*3.2406+r*-1.5372+o*-.4986,s=e*-.9689+r*1.8758+o*.0415,i=e*.0557+r*-.204+o*1.057,n=n>.0031308?1.055*n**(1/2.4)-.055:n*12.92,s=s>.0031308?1.055*s**(1/2.4)-.055:s*12.92,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,n=Math.min(Math.max(0,n),1),s=Math.min(Math.max(0,s),1),i=Math.min(Math.max(0,i),1),[n*255,s*255,i*255]};E.xyz.lab=function(t){let e=t[0],r=t[1],o=t[2];e/=95.047,r/=100,o/=108.883,e=e>.008856?e**(1/3):7.787*e+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,o=o>.008856?o**(1/3):7.787*o+16/116;let n=116*r-16,s=500*(e-r),i=200*(r-o);return[n,s,i]};E.lab.xyz=function(t){let e=t[0],r=t[1],o=t[2],n,s,i;s=(e+16)/116,n=r/500+s,i=s-o/200;let a=s**3,l=n**3,u=i**3;return s=a>.008856?a:(s-16/116)/7.787,n=l>.008856?l:(n-16/116)/7.787,i=u>.008856?u:(i-16/116)/7.787,n*=95.047,s*=100,i*=108.883,[n,s,i]};E.lab.lch=function(t){let e=t[0],r=t[1],o=t[2],n;n=Math.atan2(o,r)*360/2/Math.PI,n<0&&(n+=360);let i=Math.sqrt(r*r+o*o);return[e,i,n]};E.lch.lab=function(t){let e=t[0],r=t[1],n=t[2]/360*2*Math.PI,s=r*Math.cos(n),i=r*Math.sin(n);return[e,s,i]};E.rgb.ansi16=function(t,e=null){let[r,o,n]=t,s=e===null?E.rgb.hsv(t)[2]:e;if(s=Math.round(s/50),s===0)return 30;let i=30+(Math.round(n/255)<<2|Math.round(o/255)<<1|Math.round(r/255));return s===2&&(i+=60),i};E.hsv.ansi16=function(t){return E.rgb.ansi16(E.hsv.rgb(t),t[2])};E.rgb.ansi256=function(t){let e=t[0],r=t[1],o=t[2];return e===r&&r===o?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(r/255*5)+Math.round(o/255*5)};E.ansi16.rgb=function(t){let e=t%10;if(e===0||e===7)return t>50&&(e+=3.5),e=e/10.5*255,[e,e,e];let r=(~~(t>50)+1)*.5,o=(e&1)*r*255,n=(e>>1&1)*r*255,s=(e>>2&1)*r*255;return[o,n,s]};E.ansi256.rgb=function(t){if(t>=232){let s=(t-232)*10+8;return[s,s,s]}t-=16;let e,r=Math.floor(t/36)/5*255,o=Math.floor((e=t%36)/6)/5*255,n=e%6/5*255;return[r,o,n]};E.rgb.hex=function(t){let r=(((Math.round(t[0])&255)<<16)+((Math.round(t[1])&255)<<8)+(Math.round(t[2])&255)).toString(16).toUpperCase();return"000000".substring(r.length)+r};E.hex.rgb=function(t){let e=t.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!e)return[0,0,0];let r=e[0];e[0].length===3&&(r=r.split("").map(a=>a+a).join(""));let o=parseInt(r,16),n=o>>16&255,s=o>>8&255,i=o&255;return[n,s,i]};E.rgb.hcg=function(t){let e=t[0]/255,r=t[1]/255,o=t[2]/255,n=Math.max(Math.max(e,r),o),s=Math.min(Math.min(e,r),o),i=n-s,a,l;return i<1?a=s/(1-i):a=0,i<=0?l=0:n===e?l=(r-o)/i%6:n===r?l=2+(o-e)/i:l=4+(e-r)/i,l/=6,l%=1,[l*360,i*100,a*100]};E.hsl.hcg=function(t){let e=t[1]/100,r=t[2]/100,o=r<.5?2*e*r:2*e*(1-r),n=0;return o<1&&(n=(r-.5*o)/(1-o)),[t[0],o*100,n*100]};E.hsv.hcg=function(t){let e=t[1]/100,r=t[2]/100,o=e*r,n=0;return o<1&&(n=(r-o)/(1-o)),[t[0],o*100,n*100]};E.hcg.rgb=function(t){let e=t[0]/360,r=t[1]/100,o=t[2]/100;if(r===0)return[o*255,o*255,o*255];let n=[0,0,0],s=e%1*6,i=s%1,a=1-i,l=0;switch(Math.floor(s)){case 0:n[0]=1,n[1]=i,n[2]=0;break;case 1:n[0]=a,n[1]=1,n[2]=0;break;case 2:n[0]=0,n[1]=1,n[2]=i;break;case 3:n[0]=0,n[1]=a,n[2]=1;break;case 4:n[0]=i,n[1]=0,n[2]=1;break;default:n[0]=1,n[1]=0,n[2]=a}return l=(1-r)*o,[(r*n[0]+l)*255,(r*n[1]+l)*255,(r*n[2]+l)*255]};E.hcg.hsv=function(t){let e=t[1]/100,r=t[2]/100,o=e+r*(1-e),n=0;return o>0&&(n=e/o),[t[0],n*100,o*100]};E.hcg.hsl=function(t){let e=t[1]/100,o=t[2]/100*(1-e)+.5*e,n=0;return o>0&&o<.5?n=e/(2*o):o>=.5&&o<1&&(n=e/(2*(1-o))),[t[0],n*100,o*100]};E.hcg.hwb=function(t){let e=t[1]/100,r=t[2]/100,o=e+r*(1-e);return[t[0],(o-e)*100,(1-o)*100]};E.hwb.hcg=function(t){let e=t[1]/100,o=1-t[2]/100,n=o-e,s=0;return n<1&&(s=(o-n)/(1-n)),[t[0],n*100,s*100]};E.apple.rgb=function(t){return[t[0]/65535*255,t[1]/65535*255,t[2]/65535*255]};E.rgb.apple=function(t){return[t[0]/255*65535,t[1]/255*65535,t[2]/255*65535]};E.gray.rgb=function(t){return[t[0]/100*255,t[0]/100*255,t[0]/100*255]};E.gray.hsl=function(t){return[0,0,t[0]]};E.gray.hsv=E.gray.hsl;E.gray.hwb=function(t){return[0,100,t[0]]};E.gray.cmyk=function(t){return[0,0,0,t[0]]};E.gray.lab=function(t){return[t[0],0,0]};E.gray.hex=function(t){let e=Math.round(t[0]/100*255)&255,o=((e<<16)+(e<<8)+e).toString(16).toUpperCase();return"000000".substring(o.length)+o};E.rgb.gray=function(t){return[(t[0]+t[1]+t[2])/3/255*100]}});var Kg=it((MF,Gg)=>{"use strict";var dl=kc();function ok(){let t={},e=Object.keys(dl);for(let r=e.length,o=0;o<r;o++)t[e[o]]={distance:-1,parent:null};return t}function nk(t){let e=ok(),r=[t];for(e[t].distance=0;r.length;){let o=r.pop(),n=Object.keys(dl[o]);for(let s=n.length,i=0;i<s;i++){let a=n[i],l=e[a];l.distance===-1&&(l.distance=e[o].distance+1,l.parent=o,r.unshift(a))}}return e}function sk(t,e){return function(r){return e(t(r))}}function ik(t,e){let r=[e[t].parent,t],o=dl[e[t].parent][t],n=e[t].parent;for(;e[n].parent;)r.unshift(e[n].parent),o=sk(dl[e[n].parent][n],o),n=e[n].parent;return o.conversion=r,o}Gg.exports=function(t){let e=nk(t),r={},o=Object.keys(e);for(let n=o.length,s=0;s<n;s++){let i=o[s];e[i].parent!==null&&(r[i]=ik(i,e))}return r}});var Yg=it((UF,Jg)=>{"use strict";var Tc=kc(),ak=Kg(),fn={},lk=Object.keys(Tc);function uk(t){let e=function(...r){let o=r[0];return o==null?o:(o.length>1&&(r=o),t(r))};return"conversion"in t&&(e.conversion=t.conversion),e}function ck(t){let e=function(...r){let o=r[0];if(o==null)return o;o.length>1&&(r=o);let n=t(r);if(typeof n=="object")for(let s=n.length,i=0;i<s;i++)n[i]=Math.round(n[i]);return n};return"conversion"in t&&(e.conversion=t.conversion),e}lk.forEach(t=>{fn[t]={},Object.defineProperty(fn[t],"channels",{value:Tc[t].channels}),Object.defineProperty(fn[t],"labels",{value:Tc[t].labels});let e=ak(t);Object.keys(e).forEach(o=>{let n=e[o];fn[t][o]=ck(n),fn[t][o].raw=uk(n)})});Jg.exports=fn});var Zg=it((FF,Qg)=>{"use strict";var mn=Wg(),tt=Yg(),Xg=["keyword","gray","hex"],Cc={};for(let t of Object.keys(tt))Cc[[...tt[t].labels].sort().join("")]=t;var fl={};function Ie(t,e){if(!(this instanceof Ie))return new Ie(t,e);if(e&&e in Xg&&(e=null),e&&!(e in tt))throw new Error("Unknown model: "+e);let r,o;if(t==null)this.model="rgb",this.color=[0,0,0],this.valpha=1;else if(t instanceof Ie)this.model=t.model,this.color=[...t.color],this.valpha=t.valpha;else if(typeof t=="string"){let n=mn.get(t);if(n===null)throw new Error("Unable to parse color from string: "+t);this.model=n.model,o=tt[this.model].channels,this.color=n.value.slice(0,o),this.valpha=typeof n.value[o]=="number"?n.value[o]:1}else if(t.length>0){this.model=e||"rgb",o=tt[this.model].channels;let n=Array.prototype.slice.call(t,0,o);this.color=Ec(n,o),this.valpha=typeof t[o]=="number"?t[o]:1}else if(typeof t=="number")this.model="rgb",this.color=[t>>16&255,t>>8&255,t&255],this.valpha=1;else{this.valpha=1;let n=Object.keys(t);"alpha"in t&&(n.splice(n.indexOf("alpha"),1),this.valpha=typeof t.alpha=="number"?t.alpha:0);let s=n.sort().join("");if(!(s in Cc))throw new Error("Unable to parse color from object: "+JSON.stringify(t));this.model=Cc[s];let{labels:i}=tt[this.model],a=[];for(r=0;r<i.length;r++)a.push(t[i[r]]);this.color=Ec(a)}if(fl[this.model])for(o=tt[this.model].channels,r=0;r<o;r++){let n=fl[this.model][r];n&&(this.color[r]=n(this.color[r]))}this.valpha=Math.max(0,Math.min(1,this.valpha)),Object.freeze&&Object.freeze(this)}Ie.prototype={toString(){return this.string()},toJSON(){return this[this.model]()},string(t){let e=this.model in mn.to?this:this.rgb();e=e.round(typeof t=="number"?t:1);let r=e.valpha===1?e.color:[...e.color,this.valpha];return mn.to[e.model](r)},percentString(t){let e=this.rgb().round(typeof t=="number"?t:1),r=e.valpha===1?e.color:[...e.color,this.valpha];return mn.to.rgb.percent(r)},array(){return this.valpha===1?[...this.color]:[...this.color,this.valpha]},object(){let t={},{channels:e}=tt[this.model],{labels:r}=tt[this.model];for(let o=0;o<e;o++)t[r[o]]=this.color[o];return this.valpha!==1&&(t.alpha=this.valpha),t},unitArray(){let t=this.rgb().color;return t[0]/=255,t[1]/=255,t[2]/=255,this.valpha!==1&&t.push(this.valpha),t},unitObject(){let t=this.rgb().object();return t.r/=255,t.g/=255,t.b/=255,this.valpha!==1&&(t.alpha=this.valpha),t},round(t){return t=Math.max(t||0,0),new Ie([...this.color.map(fk(t)),this.valpha],this.model)},alpha(t){return t!==void 0?new Ie([...this.color,Math.max(0,Math.min(1,t))],this.model):this.valpha},red:he("rgb",0,Ee(255)),green:he("rgb",1,Ee(255)),blue:he("rgb",2,Ee(255)),hue:he(["hsl","hsv","hsl","hwb","hcg"],0,t=>(t%360+360)%360),saturationl:he("hsl",1,Ee(100)),lightness:he("hsl",2,Ee(100)),saturationv:he("hsv",1,Ee(100)),value:he("hsv",2,Ee(100)),chroma:he("hcg",1,Ee(100)),gray:he("hcg",2,Ee(100)),white:he("hwb",1,Ee(100)),wblack:he("hwb",2,Ee(100)),cyan:he("cmyk",0,Ee(100)),magenta:he("cmyk",1,Ee(100)),yellow:he("cmyk",2,Ee(100)),black:he("cmyk",3,Ee(100)),x:he("xyz",0,Ee(95.047)),y:he("xyz",1,Ee(100)),z:he("xyz",2,Ee(108.833)),l:he("lab",0,Ee(100)),a:he("lab",1),b:he("lab",2),keyword(t){return t!==void 0?new Ie(t):tt[this.model].keyword(this.color)},hex(t){return t!==void 0?new Ie(t):mn.to.hex(this.rgb().round().color)},hexa(t){if(t!==void 0)return new Ie(t);let e=this.rgb().round().color,r=Math.round(this.valpha*255).toString(16).toUpperCase();return r.length===1&&(r="0"+r),mn.to.hex(e)+r},rgbNumber(){let t=this.rgb().color;return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255},luminosity(){let t=this.rgb().color,e=[];for(let[r,o]of t.entries()){let n=o/255;e[r]=n<=.04045?n/12.92:((n+.055)/1.055)**2.4}return .2126*e[0]+.7152*e[1]+.0722*e[2]},contrast(t){let e=this.luminosity(),r=t.luminosity();return e>r?(e+.05)/(r+.05):(r+.05)/(e+.05)},level(t){let e=this.contrast(t);return e>=7?"AAA":e>=4.5?"AA":""},isDark(){let t=this.rgb().color;return(t[0]*2126+t[1]*7152+t[2]*722)/1e4<128},isLight(){return!this.isDark()},negate(){let t=this.rgb();for(let e=0;e<3;e++)t.color[e]=255-t.color[e];return t},lighten(t){let e=this.hsl();return e.color[2]+=e.color[2]*t,e},darken(t){let e=this.hsl();return e.color[2]-=e.color[2]*t,e},saturate(t){let e=this.hsl();return e.color[1]+=e.color[1]*t,e},desaturate(t){let e=this.hsl();return e.color[1]-=e.color[1]*t,e},whiten(t){let e=this.hwb();return e.color[1]+=e.color[1]*t,e},blacken(t){let e=this.hwb();return e.color[2]+=e.color[2]*t,e},grayscale(){let t=this.rgb().color,e=t[0]*.3+t[1]*.59+t[2]*.11;return Ie.rgb(e,e,e)},fade(t){return this.alpha(this.valpha-this.valpha*t)},opaquer(t){return this.alpha(this.valpha+this.valpha*t)},rotate(t){let e=this.hsl(),r=e.color[0];return r=(r+t)%360,r=r<0?360+r:r,e.color[0]=r,e},mix(t,e){if(!t||!t.rgb)throw new Error('Argument to "mix" was not a Color instance, but rather an instance of '+typeof t);let r=t.rgb(),o=this.rgb(),n=e===void 0?.5:e,s=2*n-1,i=r.alpha()-o.alpha(),a=((s*i===-1?s:(s+i)/(1+s*i))+1)/2,l=1-a;return Ie.rgb(a*r.red()+l*o.red(),a*r.green()+l*o.green(),a*r.blue()+l*o.blue(),r.alpha()*n+o.alpha()*(1-n))}};for(let t of Object.keys(tt)){if(Xg.includes(t))continue;let{channels:e}=tt[t];Ie.prototype[t]=function(...r){return this.model===t?new Ie(this):r.length>0?new Ie(r,t):new Ie([...mk(tt[this.model][t].raw(this.color)),this.valpha],t)},Ie[t]=function(...r){let o=r[0];return typeof o=="number"&&(o=Ec(r,e)),new Ie(o,t)}}function dk(t,e){return Number(t.toFixed(e))}function fk(t){return function(e){return dk(e,t)}}function he(t,e,r){t=Array.isArray(t)?t:[t];for(let o of t)(fl[o]||(fl[o]=[]))[e]=r;return t=t[0],function(o){let n;return o!==void 0?(r&&(o=r(o)),n=this[t](),n.color[e]=o,n):(n=this[t]().color[e],r&&(n=r(n)),n)}}function Ee(t){return function(e){return Math.max(0,Math.min(t,e))}}function mk(t){return Array.isArray(t)?t:[t]}function Ec(t,e){for(let r=0;r<e;r++)typeof t[r]!="number"&&(t[r]=0);return t}Qg.exports=Ie});var sC={};Ud(sC,{CheckboxField:()=>sd,ClickableField:()=>Yc,ConditionalRenderer:()=>Gc,DateField:()=>go,DateTime:()=>ud,DateTimeRange:()=>cd,DisclaimerText:()=>zc,DiscreteNumberField:()=>rd,DynamicFormShell:()=>Mc,EmailField:()=>Jc,FieldError:()=>_e,FieldLabel:()=>rt,GuestCountField:()=>dd,Header:()=>$c,IncrementField:()=>ad,LOCATION_ORDERING_TIMEZONE:()=>Ps,LocationField:()=>ed,NameFields:()=>ld,ORDER_ITEMIZED_DEFAULT_ITEM_CLASSES:()=>Ld,ORDER_STATUS_DEFAULT_ITEM_CLASSES:()=>Id,OrderItemized:()=>gb,OrderStatus:()=>pb,PhoneField:()=>Kc,Platforms:()=>Ga,PricePreview:()=>Wc,SectionLabel:()=>Hc,SliderField:()=>od,SubmitButton:()=>Uc,TextField:()=>De,TimeField:()=>Rr,deriveApproval:()=>Od,deriveOrderStatus:()=>Ad,divisionsFor:()=>US,formatAddOnPrice:()=>Md,formatCateringLineLabel:()=>jd,groupItemPortions:()=>VS,isConfirmable:()=>Rd,isLocationClosedByWeeklySchedule:()=>tl,itemizeOrder:()=>sn,locationWindowOn:()=>dc,mergeOrderItemizedItemClasses:()=>Nd,mergeOrderStatusItemClasses:()=>Dd,parsePortion:()=>Vt,parsePortionKey:()=>ht,portionGlyph:()=>hp,portionKey:()=>uo,portionLabel:()=>$S,portionRows:()=>Xu,portionWeight:()=>Ts,radialSectionPath:()=>WS,remapPortion:()=>Zu,resolveEventDisplay:()=>Pd,sectionLabel:()=>mp,selectionWeight:()=>Ya,setZorgoBoot:()=>Ic,setZorgoPathnameHook:()=>Dc,splitUpcharge:()=>MS,useCart:()=>_k,useCateringConfig:()=>Tk,useCustomer:()=>Pk,useField:()=>ie,useFormStatus:()=>js,useFormValidity:()=>Ms,useFormValues:()=>Ve,useHydrateMenu:()=>vk,useHydrateStore:()=>hy,useItemCustomization:()=>Sk,useLocation:()=>wk,useMenu:()=>my,useModal:()=>bk,usePayment:()=>kk,usePromotions:()=>xk,useRecommendations:()=>Ck,useRegisterField:()=>ot,weightedUpcharges:()=>Qu});module.exports=Ol(sC);var yb=require("next/navigation");var L=require("react");var tg=require("zustand");function We(t,e){var r={};for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(r[o]=t[o]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,o=Object.getOwnPropertySymbols(t);n<o.length;n++)e.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(t,o[n])&&(r[o[n]]=t[o[n]]);return r}function Ks(t,e,r,o){function n(s){return s instanceof r?s:new r(function(i){i(s)})}return new(r||(r=Promise))(function(s,i){function a(c){try{u(o.next(c))}catch(d){i(d)}}function l(c){try{u(o.throw(c))}catch(d){i(d)}}function u(c){c.done?s(c.value):n(c.value).then(a,l)}u((o=o.apply(t,e||[])).next())})}var $d=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);var wo=class extends Error{constructor(e,r="FunctionsError",o){super(e),this.name=r,this.context=o}},Tn=class extends wo{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},vo=class extends wo{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},So=class extends wo{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Cn;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(Cn||(Cn={}));var En=class{constructor(e,{headers:r={},customFetch:o,region:n=Cn.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=$d(o)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Ks(this,arguments,void 0,function*(r,o={}){var n;let s,i;try{let{headers:a,method:l,body:u,signal:c,timeout:d}=o,f={},{region:m}=o;m||(m=this.region);let h=new URL(`${this.url}/${r}`);m&&m!=="any"&&(f["x-region"]=m,h.searchParams.set("forceFunctionRegion",m));let g;u&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(f["Content-Type"]="application/octet-stream",g=u):typeof u=="string"?(f["Content-Type"]="text/plain",g=u):typeof FormData<"u"&&u instanceof FormData?g=u:(f["Content-Type"]="application/json",g=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?g=JSON.stringify(u):g=u;let y=c;d&&(i=new AbortController,s=setTimeout(()=>i.abort(),d),c?(y=i.signal,c.addEventListener("abort",()=>i.abort())):y=i.signal);let p=yield this.fetch(h.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},f),this.headers),a),body:g,signal:y}).catch(N=>{throw new Tn(N)}),b=p.headers.get("x-relay-error");if(b&&b==="true")throw new vo(p);if(!p.ok)throw new So(p);let _=((n=p.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),v;return _==="application/json"?v=yield p.json():_==="application/octet-stream"||_==="application/pdf"?v=yield p.blob():_==="text/event-stream"?v=p:_==="multipart/form-data"?v=yield p.formData():v=yield p.text(),{data:v,error:null,response:p}}catch(a){return{data:null,error:a,response:a instanceof So||a instanceof vo?a.context:void 0}}finally{s&&clearTimeout(s)}})}};var Vd=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},kb=class{constructor(t){var e,r,o;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(o=t.urlLengthLimit)!==null&&o!==void 0?o:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}then(t,e){var r=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 o=this.fetch,n=o(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{let i=null,a=null,l=null,u=s.status,c=s.statusText;if(s.ok){var d,f;if(r.method!=="HEAD"){var m;let y=await s.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((m=r.headers.get("Accept"))===null||m===void 0)&&m.includes("application/vnd.pgrst.plan+text"))?a=y:a=JSON.parse(y))}let h=(d=r.headers.get("Prefer"))===null||d===void 0?void 0:d.match(/count=(exact|planned|estimated)/),g=(f=s.headers.get("content-range"))===null||f===void 0?void 0:f.split("/");h&&g&&g.length>1&&(l=parseInt(g[1])),r.isMaybeSingle&&Array.isArray(a)&&(a.length>1?(i={code:"PGRST116",details:`Results contain ${a.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},a=null,l=null,u=406,c="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{let h=await s.text();try{i=JSON.parse(h),Array.isArray(i)&&s.status===404&&(a=[],i=null,u=200,c="OK")}catch{s.status===404&&h===""?(u=204,c="No Content"):i={message:h}}if(i&&r.shouldThrowOnError)throw new Vd(i)}return{error:i,data:a,count:l,status:u,statusText:c}});return this.shouldThrowOnError||(n=n.catch(s=>{var i;let a="",l="",u="",c=s?.cause;if(c){var d,f,m,h;let p=(d=c?.message)!==null&&d!==void 0?d:"",b=(f=c?.code)!==null&&f!==void 0?f:"";a=`${(m=s?.name)!==null&&m!==void 0?m:"FetchError"}: ${s?.message}`,a+=`
|
|
2
|
+
"use strict";var _b=Object.create;var Ks=Object.defineProperty;var wb=Object.getOwnPropertyDescriptor;var vb=Object.getOwnPropertyNames;var Sb=Object.getPrototypeOf,xb=Object.prototype.hasOwnProperty;var Js=(t,e)=>()=>(t&&(e=t(t=0)),e);var it=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ud=(t,e)=>{for(var r in e)Ks(t,r,{get:e[r],enumerable:!0})},Fd=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of vb(e))!xb.call(t,n)&&n!==r&&Ks(t,n,{get:()=>e[n],enumerable:!(o=wb(e,n))||o.enumerable});return t};var Le=(t,e,r)=>(r=t!=null?_b(Sb(t)):{},Fd(e||!t||!t.__esModule?Ks(r,"default",{value:t,enumerable:!0}):r,t)),Rl=t=>Fd(Ks({},"__esModule",{value:!0}),t);var Au=it(Ou=>{"use strict";Ou.parse=Kv;Ou.serialize=Jv;var qv=Object.prototype.toString,Vv=Object.prototype.hasOwnProperty,Wv=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Hv=/^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/,zv=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Gv=/^[\u0020-\u003A\u003D-\u007E]*$/;function Kv(t,e){if(typeof t!="string")throw new TypeError("argument str must be a string");var r={},o=t.length;if(o<2)return r;var n=e&&e.decode||Yv,s=0,i=0,a=0;do{if(i=t.indexOf("=",s),i===-1)break;if(a=t.indexOf(";",s),a===-1)a=o;else if(i>a){s=t.lastIndexOf(";",i-1)+1;continue}var l=Zm(t,s,i),u=eh(t,i,l),c=t.slice(l,u);if(!Vv.call(r,c)){var d=Zm(t,i+1,a),f=eh(t,a,d);t.charCodeAt(d)===34&&t.charCodeAt(f-1)===34&&(d++,f--);var m=t.slice(d,f);r[c]=Qv(m,n)}s=a+1}while(s<o);return r}function Zm(t,e,r){do{var o=t.charCodeAt(e);if(o!==32&&o!==9)return e}while(++e<r);return r}function eh(t,e,r){for(;e>r;){var o=t.charCodeAt(--e);if(o!==32&&o!==9)return e+1}return r}function Jv(t,e,r){var o=r&&r.encode||encodeURIComponent;if(typeof o!="function")throw new TypeError("option encode is invalid");if(!Wv.test(t))throw new TypeError("argument name is invalid");var n=o(e);if(!Hv.test(n))throw new TypeError("argument val is invalid");var s=t+"="+n;if(!r)return s;if(r.maxAge!=null){var i=Math.floor(r.maxAge);if(!isFinite(i))throw new TypeError("option maxAge is invalid");s+="; Max-Age="+i}if(r.domain){if(!zv.test(r.domain))throw new TypeError("option domain is invalid");s+="; Domain="+r.domain}if(r.path){if(!Gv.test(r.path))throw new TypeError("option path is invalid");s+="; Path="+r.path}if(r.expires){var a=r.expires;if(!Xv(a)||isNaN(a.valueOf()))throw new TypeError("option expires is invalid");s+="; Expires="+a.toUTCString()}if(r.httpOnly&&(s+="; HttpOnly"),r.secure&&(s+="; Secure"),r.partitioned&&(s+="; Partitioned"),r.priority){var l=typeof r.priority=="string"?r.priority.toLowerCase():r.priority;switch(l){case"low":s+="; Priority=Low";break;case"medium":s+="; Priority=Medium";break;case"high":s+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}}if(r.sameSite){var u=typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite;switch(u){case!0:s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"strict":s+="; SameSite=Strict";break;case"none":s+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return s}function Yv(t){return t.indexOf("%")!==-1?decodeURIComponent(t):t}function Xv(t){return qv.call(t)==="[object Date]"}function Qv(t,e){try{return e(t)}catch{return t}}});var ah=it((JR,ih)=>{"use strict";ih.exports=t=>{if(Object.prototype.toString.call(t)!=="[object Object]")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype}});var mh=it((dh,fh)=>{"use strict";var Ji=ah(),{hasOwnProperty:uh}=Object.prototype,{propertyIsEnumerable:n0}=Object,Go=(t,e,r)=>Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0}),s0=dh,lh={concatArrays:!1,ignoreUndefined:!1},Yi=t=>{let e=[];for(let r in t)uh.call(t,r)&&e.push(r);if(Object.getOwnPropertySymbols){let r=Object.getOwnPropertySymbols(t);for(let o of r)n0.call(t,o)&&e.push(o)}return e};function Ko(t){return Array.isArray(t)?i0(t):Ji(t)?a0(t):t}function i0(t){let e=t.slice(0,0);return Yi(t).forEach(r=>{Go(e,r,Ko(t[r]))}),e}function a0(t){let e=Object.getPrototypeOf(t)===null?Object.create(null):{};return Yi(t).forEach(r=>{Go(e,r,Ko(t[r]))}),e}var ch=(t,e,r,o)=>(r.forEach(n=>{typeof e[n]>"u"&&o.ignoreUndefined||(n in t&&t[n]!==Object.getPrototypeOf(t)?Go(t,n,$u(t[n],e[n],o)):Go(t,n,Ko(e[n])))}),t),l0=(t,e,r)=>{let o=t.slice(0,0),n=0;return[t,e].forEach(s=>{let i=[];for(let a=0;a<s.length;a++)uh.call(s,a)&&(i.push(String(a)),s===t?Go(o,n++,s[a]):Go(o,n++,Ko(s[a])));o=ch(o,s,Yi(s).filter(a=>!i.includes(a)),r)}),o};function $u(t,e,r){return r.concatArrays&&Array.isArray(t)&&Array.isArray(e)?l0(t,e,r):!Ji(e)||!Ji(t)?Ko(e):ch(t,e,Yi(e),r)}fh.exports=function(...t){let e=$u(Ko(lh),this!==s0&&this||{},lh),r={_:{}};for(let o of t)if(o!==void 0){if(!Ji(o))throw new TypeError("`"+o+"` is not an Option Object");r=$u(r,{_:o},e)}return r._}});var hh,ph,gh=Js(()=>{"use strict";hh=Le(mh(),1),ph=hh.default});function c0(t,e){let r=window.localStorage.getItem(t);if(r){let o=JSON.parse(r),n=JSON.parse(e),s=JSON.stringify(u0(o,n));window.localStorage.setItem(t,s)}else window.localStorage.setItem(t,e)}function Jo(t,e){return new Promise((r,o)=>{try{let n=t();e?.(null,n),r(n)}catch(n){e?.(n),o(n)}})}function Xi(t,e,r){return Promise.all(t).then(o=>{let n=r?.(o)??null;return e?.(null,n),Promise.resolve(n)},o=>(e?.(o),Promise.reject(o)))}var u0,_s,so,Bu=Js(()=>{"use strict";gh();u0=ph.bind({concatArrays:!0,ignoreUndefined:!0});_s={getItem:(t,e)=>Jo(()=>window.localStorage.getItem(t),e),setItem:(t,e,r)=>Jo(()=>window.localStorage.setItem(t,e),r),removeItem:(t,e)=>Jo(()=>window.localStorage.removeItem(t),e),mergeItem:(t,e,r)=>Jo(()=>c0(t,e),r),clear:t=>Jo(()=>window.localStorage.clear(),t),getAllKeys:t=>Jo(()=>{let e=window.localStorage.length,r=[];for(let o=0;o<e;o+=1){let n=window.localStorage.key(o)||"";r.push(n)}return r},t),flushGetRequests:()=>{},multiGet:(t,e)=>{let r=t.map(n=>_s.getItem(n));return Xi(r,e,n=>n.map((s,i)=>[t[i],s]))},multiSet:(t,e)=>{let r=t.map(o=>_s.setItem(o[0],o[1]));return Xi(r,e)},multiRemove:(t,e)=>{let r=t.map(o=>_s.removeItem(o));return Xi(r,e)},multiMerge:(t,e)=>{let r=t.map(o=>_s.mergeItem(o[0],o[1]));return Xi(r,e)}},so=_s});function yh(t){return{getItem:(...e)=>so.getItem(t,...e),setItem:(...e)=>so.setItem(t,...e),mergeItem:(...e)=>so.mergeItem(t,...e),removeItem:(...e)=>so.removeItem(t,...e)}}var bh=Js(()=>{"use strict";Bu()});var qu={};Ud(qu,{default:()=>d0,useAsyncStorage:()=>yh});var d0,Vu=Js(()=>{"use strict";Bu();bh();d0=so});var eg=it((qM,Zp)=>{"use strict";Zp.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var o,n,s;if(Array.isArray(e)){if(o=e.length,o!=r.length)return!1;for(n=o;n--!==0;)if(!t(e[n],r[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),o=s.length,o!==Object.keys(r).length)return!1;for(n=o;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[n]))return!1;for(n=o;n--!==0;){var i=s[n];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Tc=it((IF,Ng)=>{"use strict";Ng.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}});var Mg=it((DF,jg)=>{"use strict";jg.exports=function(e){return!e||typeof e=="string"?!1:e instanceof Array||Array.isArray(e)||e.length>=0&&(e.splice instanceof Function||Object.getOwnPropertyDescriptor(e,e.length-1)&&e.constructor.name!=="String")}});var $g=it((LF,Fg)=>{"use strict";var Zx=Mg(),ek=Array.prototype.concat,tk=Array.prototype.slice,Ug=Fg.exports=function(e){for(var r=[],o=0,n=e.length;o<n;o++){var s=e[o];Zx(s)?r=ek.call(r,tk.call(s)):r.push(s)}return r};Ug.wrap=function(t){return function(){return t(Ug(arguments))}}});var Wg=it((NF,Vg)=>{"use strict";var Ns=Tc(),js=$g(),Bg=Object.hasOwnProperty,qg=Object.create(null);for(dl in Ns)Bg.call(Ns,dl)&&(qg[Ns[dl]]=dl);var dl,et=Vg.exports={to:{},get:{}};et.get=function(t){var e=t.substring(0,3).toLowerCase(),r,o;switch(e){case"hsl":r=et.get.hsl(t),o="hsl";break;case"hwb":r=et.get.hwb(t),o="hwb";break;default:r=et.get.rgb(t),o="rgb";break}return r?{model:o,value:r}:null};et.get.rgb=function(t){if(!t)return null;var e=/^#([a-f0-9]{3,4})$/i,r=/^#([a-f0-9]{6})([a-f0-9]{2})?$/i,o=/^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/,n=/^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/,s=/^(\w+)$/,i=[0,0,0,1],a,l,u;if(a=t.match(r)){for(u=a[2],a=a[1],l=0;l<3;l++){var c=l*2;i[l]=parseInt(a.slice(c,c+2),16)}u&&(i[3]=parseInt(u,16)/255)}else if(a=t.match(e)){for(a=a[1],u=a[3],l=0;l<3;l++)i[l]=parseInt(a[l]+a[l],16);u&&(i[3]=parseInt(u+u,16)/255)}else if(a=t.match(o)){for(l=0;l<3;l++)i[l]=parseInt(a[l+1],0);a[4]&&(a[5]?i[3]=parseFloat(a[4])*.01:i[3]=parseFloat(a[4]))}else if(a=t.match(n)){for(l=0;l<3;l++)i[l]=Math.round(parseFloat(a[l+1])*2.55);a[4]&&(a[5]?i[3]=parseFloat(a[4])*.01:i[3]=parseFloat(a[4]))}else return(a=t.match(s))?a[1]==="transparent"?[0,0,0,0]:Bg.call(Ns,a[1])?(i=Ns[a[1]],i[3]=1,i):null:null;for(l=0;l<3;l++)i[l]=Ar(i[l],0,255);return i[3]=Ar(i[3],0,1),i};et.get.hsl=function(t){if(!t)return null;var e=/^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/,r=t.match(e);if(r){var o=parseFloat(r[4]),n=(parseFloat(r[1])%360+360)%360,s=Ar(parseFloat(r[2]),0,100),i=Ar(parseFloat(r[3]),0,100),a=Ar(isNaN(o)?1:o,0,1);return[n,s,i,a]}return null};et.get.hwb=function(t){if(!t)return null;var e=/^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/,r=t.match(e);if(r){var o=parseFloat(r[4]),n=(parseFloat(r[1])%360+360)%360,s=Ar(parseFloat(r[2]),0,100),i=Ar(parseFloat(r[3]),0,100),a=Ar(isNaN(o)?1:o,0,1);return[n,s,i,a]}return null};et.to.hex=function(){var t=js(arguments);return"#"+fl(t[0])+fl(t[1])+fl(t[2])+(t[3]<1?fl(Math.round(t[3]*255)):"")};et.to.rgb=function(){var t=js(arguments);return t.length<4||t[3]===1?"rgb("+Math.round(t[0])+", "+Math.round(t[1])+", "+Math.round(t[2])+")":"rgba("+Math.round(t[0])+", "+Math.round(t[1])+", "+Math.round(t[2])+", "+t[3]+")"};et.to.rgb.percent=function(){var t=js(arguments),e=Math.round(t[0]/255*100),r=Math.round(t[1]/255*100),o=Math.round(t[2]/255*100);return t.length<4||t[3]===1?"rgb("+e+"%, "+r+"%, "+o+"%)":"rgba("+e+"%, "+r+"%, "+o+"%, "+t[3]+")"};et.to.hsl=function(){var t=js(arguments);return t.length<4||t[3]===1?"hsl("+t[0]+", "+t[1]+"%, "+t[2]+"%)":"hsla("+t[0]+", "+t[1]+"%, "+t[2]+"%, "+t[3]+")"};et.to.hwb=function(){var t=js(arguments),e="";return t.length>=4&&t[3]!==1&&(e=", "+t[3]),"hwb("+t[0]+", "+t[1]+"%, "+t[2]+"%"+e+")"};et.to.keyword=function(t){return qg[t.slice(0,3)]};function Ar(t,e,r){return Math.min(Math.max(e,t),r)}function fl(t){var e=Math.round(t).toString(16).toUpperCase();return e.length<2?"0"+e:e}});var Cc=it((jF,zg)=>{"use strict";var Ms=Tc(),Hg={};for(let t of Object.keys(Ms))Hg[Ms[t]]=t;var E={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};zg.exports=E;for(let t of Object.keys(E)){if(!("channels"in E[t]))throw new Error("missing channels property: "+t);if(!("labels"in E[t]))throw new Error("missing channel labels property: "+t);if(E[t].labels.length!==E[t].channels)throw new Error("channel and label counts mismatch: "+t);let{channels:e,labels:r}=E[t];delete E[t].channels,delete E[t].labels,Object.defineProperty(E[t],"channels",{value:e}),Object.defineProperty(E[t],"labels",{value:r})}E.rgb.hsl=function(t){let e=t[0]/255,r=t[1]/255,o=t[2]/255,n=Math.min(e,r,o),s=Math.max(e,r,o),i=s-n,a,l;s===n?a=0:e===s?a=(r-o)/i:r===s?a=2+(o-e)/i:o===s&&(a=4+(e-r)/i),a=Math.min(a*60,360),a<0&&(a+=360);let u=(n+s)/2;return s===n?l=0:u<=.5?l=i/(s+n):l=i/(2-s-n),[a,l*100,u*100]};E.rgb.hsv=function(t){let e,r,o,n,s,i=t[0]/255,a=t[1]/255,l=t[2]/255,u=Math.max(i,a,l),c=u-Math.min(i,a,l),d=function(f){return(u-f)/6/c+1/2};return c===0?(n=0,s=0):(s=c/u,e=d(i),r=d(a),o=d(l),i===u?n=o-r:a===u?n=1/3+e-o:l===u&&(n=2/3+r-e),n<0?n+=1:n>1&&(n-=1)),[n*360,s*100,u*100]};E.rgb.hwb=function(t){let e=t[0],r=t[1],o=t[2],n=E.rgb.hsl(t)[0],s=1/255*Math.min(e,Math.min(r,o));return o=1-1/255*Math.max(e,Math.max(r,o)),[n,s*100,o*100]};E.rgb.cmyk=function(t){let e=t[0]/255,r=t[1]/255,o=t[2]/255,n=Math.min(1-e,1-r,1-o),s=(1-e-n)/(1-n)||0,i=(1-r-n)/(1-n)||0,a=(1-o-n)/(1-n)||0;return[s*100,i*100,a*100,n*100]};function rk(t,e){return(t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2}E.rgb.keyword=function(t){let e=Hg[t];if(e)return e;let r=1/0,o;for(let n of Object.keys(Ms)){let s=Ms[n],i=rk(t,s);i<r&&(r=i,o=n)}return o};E.keyword.rgb=function(t){return Ms[t]};E.rgb.xyz=function(t){let e=t[0]/255,r=t[1]/255,o=t[2]/255;e=e>.04045?((e+.055)/1.055)**2.4:e/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92,o=o>.04045?((o+.055)/1.055)**2.4:o/12.92;let n=e*.4124+r*.3576+o*.1805,s=e*.2126+r*.7152+o*.0722,i=e*.0193+r*.1192+o*.9505;return[n*100,s*100,i*100]};E.rgb.lab=function(t){let e=E.rgb.xyz(t),r=e[0],o=e[1],n=e[2];r/=95.047,o/=100,n/=108.883,r=r>.008856?r**(1/3):7.787*r+16/116,o=o>.008856?o**(1/3):7.787*o+16/116,n=n>.008856?n**(1/3):7.787*n+16/116;let s=116*o-16,i=500*(r-o),a=200*(o-n);return[s,i,a]};E.hsl.rgb=function(t){let e=t[0]/360,r=t[1]/100,o=t[2]/100,n,s,i;if(r===0)return i=o*255,[i,i,i];o<.5?n=o*(1+r):n=o+r-o*r;let a=2*o-n,l=[0,0,0];for(let u=0;u<3;u++)s=e+1/3*-(u-1),s<0&&s++,s>1&&s--,6*s<1?i=a+(n-a)*6*s:2*s<1?i=n:3*s<2?i=a+(n-a)*(2/3-s)*6:i=a,l[u]=i*255;return l};E.hsl.hsv=function(t){let e=t[0],r=t[1]/100,o=t[2]/100,n=r,s=Math.max(o,.01);o*=2,r*=o<=1?o:2-o,n*=s<=1?s:2-s;let i=(o+r)/2,a=o===0?2*n/(s+n):2*r/(o+r);return[e,a*100,i*100]};E.hsv.rgb=function(t){let e=t[0]/60,r=t[1]/100,o=t[2]/100,n=Math.floor(e)%6,s=e-Math.floor(e),i=255*o*(1-r),a=255*o*(1-r*s),l=255*o*(1-r*(1-s));switch(o*=255,n){case 0:return[o,l,i];case 1:return[a,o,i];case 2:return[i,o,l];case 3:return[i,a,o];case 4:return[l,i,o];case 5:return[o,i,a]}};E.hsv.hsl=function(t){let e=t[0],r=t[1]/100,o=t[2]/100,n=Math.max(o,.01),s,i;i=(2-r)*o;let a=(2-r)*n;return s=r*n,s/=a<=1?a:2-a,s=s||0,i/=2,[e,s*100,i*100]};E.hwb.rgb=function(t){let e=t[0]/360,r=t[1]/100,o=t[2]/100,n=r+o,s;n>1&&(r/=n,o/=n);let i=Math.floor(6*e),a=1-o;s=6*e-i,(i&1)!==0&&(s=1-s);let l=r+s*(a-r),u,c,d;switch(i){default:case 6:case 0:u=a,c=l,d=r;break;case 1:u=l,c=a,d=r;break;case 2:u=r,c=a,d=l;break;case 3:u=r,c=l,d=a;break;case 4:u=l,c=r,d=a;break;case 5:u=a,c=r,d=l;break}return[u*255,c*255,d*255]};E.cmyk.rgb=function(t){let e=t[0]/100,r=t[1]/100,o=t[2]/100,n=t[3]/100,s=1-Math.min(1,e*(1-n)+n),i=1-Math.min(1,r*(1-n)+n),a=1-Math.min(1,o*(1-n)+n);return[s*255,i*255,a*255]};E.xyz.rgb=function(t){let e=t[0]/100,r=t[1]/100,o=t[2]/100,n,s,i;return n=e*3.2406+r*-1.5372+o*-.4986,s=e*-.9689+r*1.8758+o*.0415,i=e*.0557+r*-.204+o*1.057,n=n>.0031308?1.055*n**(1/2.4)-.055:n*12.92,s=s>.0031308?1.055*s**(1/2.4)-.055:s*12.92,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,n=Math.min(Math.max(0,n),1),s=Math.min(Math.max(0,s),1),i=Math.min(Math.max(0,i),1),[n*255,s*255,i*255]};E.xyz.lab=function(t){let e=t[0],r=t[1],o=t[2];e/=95.047,r/=100,o/=108.883,e=e>.008856?e**(1/3):7.787*e+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,o=o>.008856?o**(1/3):7.787*o+16/116;let n=116*r-16,s=500*(e-r),i=200*(r-o);return[n,s,i]};E.lab.xyz=function(t){let e=t[0],r=t[1],o=t[2],n,s,i;s=(e+16)/116,n=r/500+s,i=s-o/200;let a=s**3,l=n**3,u=i**3;return s=a>.008856?a:(s-16/116)/7.787,n=l>.008856?l:(n-16/116)/7.787,i=u>.008856?u:(i-16/116)/7.787,n*=95.047,s*=100,i*=108.883,[n,s,i]};E.lab.lch=function(t){let e=t[0],r=t[1],o=t[2],n;n=Math.atan2(o,r)*360/2/Math.PI,n<0&&(n+=360);let i=Math.sqrt(r*r+o*o);return[e,i,n]};E.lch.lab=function(t){let e=t[0],r=t[1],n=t[2]/360*2*Math.PI,s=r*Math.cos(n),i=r*Math.sin(n);return[e,s,i]};E.rgb.ansi16=function(t,e=null){let[r,o,n]=t,s=e===null?E.rgb.hsv(t)[2]:e;if(s=Math.round(s/50),s===0)return 30;let i=30+(Math.round(n/255)<<2|Math.round(o/255)<<1|Math.round(r/255));return s===2&&(i+=60),i};E.hsv.ansi16=function(t){return E.rgb.ansi16(E.hsv.rgb(t),t[2])};E.rgb.ansi256=function(t){let e=t[0],r=t[1],o=t[2];return e===r&&r===o?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(r/255*5)+Math.round(o/255*5)};E.ansi16.rgb=function(t){let e=t%10;if(e===0||e===7)return t>50&&(e+=3.5),e=e/10.5*255,[e,e,e];let r=(~~(t>50)+1)*.5,o=(e&1)*r*255,n=(e>>1&1)*r*255,s=(e>>2&1)*r*255;return[o,n,s]};E.ansi256.rgb=function(t){if(t>=232){let s=(t-232)*10+8;return[s,s,s]}t-=16;let e,r=Math.floor(t/36)/5*255,o=Math.floor((e=t%36)/6)/5*255,n=e%6/5*255;return[r,o,n]};E.rgb.hex=function(t){let r=(((Math.round(t[0])&255)<<16)+((Math.round(t[1])&255)<<8)+(Math.round(t[2])&255)).toString(16).toUpperCase();return"000000".substring(r.length)+r};E.hex.rgb=function(t){let e=t.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!e)return[0,0,0];let r=e[0];e[0].length===3&&(r=r.split("").map(a=>a+a).join(""));let o=parseInt(r,16),n=o>>16&255,s=o>>8&255,i=o&255;return[n,s,i]};E.rgb.hcg=function(t){let e=t[0]/255,r=t[1]/255,o=t[2]/255,n=Math.max(Math.max(e,r),o),s=Math.min(Math.min(e,r),o),i=n-s,a,l;return i<1?a=s/(1-i):a=0,i<=0?l=0:n===e?l=(r-o)/i%6:n===r?l=2+(o-e)/i:l=4+(e-r)/i,l/=6,l%=1,[l*360,i*100,a*100]};E.hsl.hcg=function(t){let e=t[1]/100,r=t[2]/100,o=r<.5?2*e*r:2*e*(1-r),n=0;return o<1&&(n=(r-.5*o)/(1-o)),[t[0],o*100,n*100]};E.hsv.hcg=function(t){let e=t[1]/100,r=t[2]/100,o=e*r,n=0;return o<1&&(n=(r-o)/(1-o)),[t[0],o*100,n*100]};E.hcg.rgb=function(t){let e=t[0]/360,r=t[1]/100,o=t[2]/100;if(r===0)return[o*255,o*255,o*255];let n=[0,0,0],s=e%1*6,i=s%1,a=1-i,l=0;switch(Math.floor(s)){case 0:n[0]=1,n[1]=i,n[2]=0;break;case 1:n[0]=a,n[1]=1,n[2]=0;break;case 2:n[0]=0,n[1]=1,n[2]=i;break;case 3:n[0]=0,n[1]=a,n[2]=1;break;case 4:n[0]=i,n[1]=0,n[2]=1;break;default:n[0]=1,n[1]=0,n[2]=a}return l=(1-r)*o,[(r*n[0]+l)*255,(r*n[1]+l)*255,(r*n[2]+l)*255]};E.hcg.hsv=function(t){let e=t[1]/100,r=t[2]/100,o=e+r*(1-e),n=0;return o>0&&(n=e/o),[t[0],n*100,o*100]};E.hcg.hsl=function(t){let e=t[1]/100,o=t[2]/100*(1-e)+.5*e,n=0;return o>0&&o<.5?n=e/(2*o):o>=.5&&o<1&&(n=e/(2*(1-o))),[t[0],n*100,o*100]};E.hcg.hwb=function(t){let e=t[1]/100,r=t[2]/100,o=e+r*(1-e);return[t[0],(o-e)*100,(1-o)*100]};E.hwb.hcg=function(t){let e=t[1]/100,o=1-t[2]/100,n=o-e,s=0;return n<1&&(s=(o-n)/(1-n)),[t[0],n*100,s*100]};E.apple.rgb=function(t){return[t[0]/65535*255,t[1]/65535*255,t[2]/65535*255]};E.rgb.apple=function(t){return[t[0]/255*65535,t[1]/255*65535,t[2]/255*65535]};E.gray.rgb=function(t){return[t[0]/100*255,t[0]/100*255,t[0]/100*255]};E.gray.hsl=function(t){return[0,0,t[0]]};E.gray.hsv=E.gray.hsl;E.gray.hwb=function(t){return[0,100,t[0]]};E.gray.cmyk=function(t){return[0,0,0,t[0]]};E.gray.lab=function(t){return[t[0],0,0]};E.gray.hex=function(t){let e=Math.round(t[0]/100*255)&255,o=((e<<16)+(e<<8)+e).toString(16).toUpperCase();return"000000".substring(o.length)+o};E.rgb.gray=function(t){return[(t[0]+t[1]+t[2])/3/255*100]}});var Kg=it((MF,Gg)=>{"use strict";var ml=Cc();function ok(){let t={},e=Object.keys(ml);for(let r=e.length,o=0;o<r;o++)t[e[o]]={distance:-1,parent:null};return t}function nk(t){let e=ok(),r=[t];for(e[t].distance=0;r.length;){let o=r.pop(),n=Object.keys(ml[o]);for(let s=n.length,i=0;i<s;i++){let a=n[i],l=e[a];l.distance===-1&&(l.distance=e[o].distance+1,l.parent=o,r.unshift(a))}}return e}function sk(t,e){return function(r){return e(t(r))}}function ik(t,e){let r=[e[t].parent,t],o=ml[e[t].parent][t],n=e[t].parent;for(;e[n].parent;)r.unshift(e[n].parent),o=sk(ml[e[n].parent][n],o),n=e[n].parent;return o.conversion=r,o}Gg.exports=function(t){let e=nk(t),r={},o=Object.keys(e);for(let n=o.length,s=0;s<n;s++){let i=o[s];e[i].parent!==null&&(r[i]=ik(i,e))}return r}});var Yg=it((UF,Jg)=>{"use strict";var Ec=Cc(),ak=Kg(),fn={},lk=Object.keys(Ec);function uk(t){let e=function(...r){let o=r[0];return o==null?o:(o.length>1&&(r=o),t(r))};return"conversion"in t&&(e.conversion=t.conversion),e}function ck(t){let e=function(...r){let o=r[0];if(o==null)return o;o.length>1&&(r=o);let n=t(r);if(typeof n=="object")for(let s=n.length,i=0;i<s;i++)n[i]=Math.round(n[i]);return n};return"conversion"in t&&(e.conversion=t.conversion),e}lk.forEach(t=>{fn[t]={},Object.defineProperty(fn[t],"channels",{value:Ec[t].channels}),Object.defineProperty(fn[t],"labels",{value:Ec[t].labels});let e=ak(t);Object.keys(e).forEach(o=>{let n=e[o];fn[t][o]=ck(n),fn[t][o].raw=uk(n)})});Jg.exports=fn});var Zg=it((FF,Qg)=>{"use strict";var mn=Wg(),tt=Yg(),Xg=["keyword","gray","hex"],Pc={};for(let t of Object.keys(tt))Pc[[...tt[t].labels].sort().join("")]=t;var hl={};function Ie(t,e){if(!(this instanceof Ie))return new Ie(t,e);if(e&&e in Xg&&(e=null),e&&!(e in tt))throw new Error("Unknown model: "+e);let r,o;if(t==null)this.model="rgb",this.color=[0,0,0],this.valpha=1;else if(t instanceof Ie)this.model=t.model,this.color=[...t.color],this.valpha=t.valpha;else if(typeof t=="string"){let n=mn.get(t);if(n===null)throw new Error("Unable to parse color from string: "+t);this.model=n.model,o=tt[this.model].channels,this.color=n.value.slice(0,o),this.valpha=typeof n.value[o]=="number"?n.value[o]:1}else if(t.length>0){this.model=e||"rgb",o=tt[this.model].channels;let n=Array.prototype.slice.call(t,0,o);this.color=Oc(n,o),this.valpha=typeof t[o]=="number"?t[o]:1}else if(typeof t=="number")this.model="rgb",this.color=[t>>16&255,t>>8&255,t&255],this.valpha=1;else{this.valpha=1;let n=Object.keys(t);"alpha"in t&&(n.splice(n.indexOf("alpha"),1),this.valpha=typeof t.alpha=="number"?t.alpha:0);let s=n.sort().join("");if(!(s in Pc))throw new Error("Unable to parse color from object: "+JSON.stringify(t));this.model=Pc[s];let{labels:i}=tt[this.model],a=[];for(r=0;r<i.length;r++)a.push(t[i[r]]);this.color=Oc(a)}if(hl[this.model])for(o=tt[this.model].channels,r=0;r<o;r++){let n=hl[this.model][r];n&&(this.color[r]=n(this.color[r]))}this.valpha=Math.max(0,Math.min(1,this.valpha)),Object.freeze&&Object.freeze(this)}Ie.prototype={toString(){return this.string()},toJSON(){return this[this.model]()},string(t){let e=this.model in mn.to?this:this.rgb();e=e.round(typeof t=="number"?t:1);let r=e.valpha===1?e.color:[...e.color,this.valpha];return mn.to[e.model](r)},percentString(t){let e=this.rgb().round(typeof t=="number"?t:1),r=e.valpha===1?e.color:[...e.color,this.valpha];return mn.to.rgb.percent(r)},array(){return this.valpha===1?[...this.color]:[...this.color,this.valpha]},object(){let t={},{channels:e}=tt[this.model],{labels:r}=tt[this.model];for(let o=0;o<e;o++)t[r[o]]=this.color[o];return this.valpha!==1&&(t.alpha=this.valpha),t},unitArray(){let t=this.rgb().color;return t[0]/=255,t[1]/=255,t[2]/=255,this.valpha!==1&&t.push(this.valpha),t},unitObject(){let t=this.rgb().object();return t.r/=255,t.g/=255,t.b/=255,this.valpha!==1&&(t.alpha=this.valpha),t},round(t){return t=Math.max(t||0,0),new Ie([...this.color.map(fk(t)),this.valpha],this.model)},alpha(t){return t!==void 0?new Ie([...this.color,Math.max(0,Math.min(1,t))],this.model):this.valpha},red:he("rgb",0,Ee(255)),green:he("rgb",1,Ee(255)),blue:he("rgb",2,Ee(255)),hue:he(["hsl","hsv","hsl","hwb","hcg"],0,t=>(t%360+360)%360),saturationl:he("hsl",1,Ee(100)),lightness:he("hsl",2,Ee(100)),saturationv:he("hsv",1,Ee(100)),value:he("hsv",2,Ee(100)),chroma:he("hcg",1,Ee(100)),gray:he("hcg",2,Ee(100)),white:he("hwb",1,Ee(100)),wblack:he("hwb",2,Ee(100)),cyan:he("cmyk",0,Ee(100)),magenta:he("cmyk",1,Ee(100)),yellow:he("cmyk",2,Ee(100)),black:he("cmyk",3,Ee(100)),x:he("xyz",0,Ee(95.047)),y:he("xyz",1,Ee(100)),z:he("xyz",2,Ee(108.833)),l:he("lab",0,Ee(100)),a:he("lab",1),b:he("lab",2),keyword(t){return t!==void 0?new Ie(t):tt[this.model].keyword(this.color)},hex(t){return t!==void 0?new Ie(t):mn.to.hex(this.rgb().round().color)},hexa(t){if(t!==void 0)return new Ie(t);let e=this.rgb().round().color,r=Math.round(this.valpha*255).toString(16).toUpperCase();return r.length===1&&(r="0"+r),mn.to.hex(e)+r},rgbNumber(){let t=this.rgb().color;return(t[0]&255)<<16|(t[1]&255)<<8|t[2]&255},luminosity(){let t=this.rgb().color,e=[];for(let[r,o]of t.entries()){let n=o/255;e[r]=n<=.04045?n/12.92:((n+.055)/1.055)**2.4}return .2126*e[0]+.7152*e[1]+.0722*e[2]},contrast(t){let e=this.luminosity(),r=t.luminosity();return e>r?(e+.05)/(r+.05):(r+.05)/(e+.05)},level(t){let e=this.contrast(t);return e>=7?"AAA":e>=4.5?"AA":""},isDark(){let t=this.rgb().color;return(t[0]*2126+t[1]*7152+t[2]*722)/1e4<128},isLight(){return!this.isDark()},negate(){let t=this.rgb();for(let e=0;e<3;e++)t.color[e]=255-t.color[e];return t},lighten(t){let e=this.hsl();return e.color[2]+=e.color[2]*t,e},darken(t){let e=this.hsl();return e.color[2]-=e.color[2]*t,e},saturate(t){let e=this.hsl();return e.color[1]+=e.color[1]*t,e},desaturate(t){let e=this.hsl();return e.color[1]-=e.color[1]*t,e},whiten(t){let e=this.hwb();return e.color[1]+=e.color[1]*t,e},blacken(t){let e=this.hwb();return e.color[2]+=e.color[2]*t,e},grayscale(){let t=this.rgb().color,e=t[0]*.3+t[1]*.59+t[2]*.11;return Ie.rgb(e,e,e)},fade(t){return this.alpha(this.valpha-this.valpha*t)},opaquer(t){return this.alpha(this.valpha+this.valpha*t)},rotate(t){let e=this.hsl(),r=e.color[0];return r=(r+t)%360,r=r<0?360+r:r,e.color[0]=r,e},mix(t,e){if(!t||!t.rgb)throw new Error('Argument to "mix" was not a Color instance, but rather an instance of '+typeof t);let r=t.rgb(),o=this.rgb(),n=e===void 0?.5:e,s=2*n-1,i=r.alpha()-o.alpha(),a=((s*i===-1?s:(s+i)/(1+s*i))+1)/2,l=1-a;return Ie.rgb(a*r.red()+l*o.red(),a*r.green()+l*o.green(),a*r.blue()+l*o.blue(),r.alpha()*n+o.alpha()*(1-n))}};for(let t of Object.keys(tt)){if(Xg.includes(t))continue;let{channels:e}=tt[t];Ie.prototype[t]=function(...r){return this.model===t?new Ie(this):r.length>0?new Ie(r,t):new Ie([...mk(tt[this.model][t].raw(this.color)),this.valpha],t)},Ie[t]=function(...r){let o=r[0];return typeof o=="number"&&(o=Oc(r,e)),new Ie(o,t)}}function dk(t,e){return Number(t.toFixed(e))}function fk(t){return function(e){return dk(e,t)}}function he(t,e,r){t=Array.isArray(t)?t:[t];for(let o of t)(hl[o]||(hl[o]=[]))[e]=r;return t=t[0],function(o){let n;return o!==void 0?(r&&(o=r(o)),n=this[t](),n.color[e]=o,n):(n=this[t]().color[e],r&&(n=r(n)),n)}}function Ee(t){return function(e){return Math.max(0,Math.min(t,e))}}function mk(t){return Array.isArray(t)?t:[t]}function Oc(t,e){for(let r=0;r<e;r++)typeof t[r]!="number"&&(t[r]=0);return t}Qg.exports=Ie});var sC={};Ud(sC,{CheckboxField:()=>ad,ClickableField:()=>Qc,ConditionalRenderer:()=>Jc,DateField:()=>go,DateTime:()=>dd,DateTimeRange:()=>fd,DisclaimerText:()=>Kc,DiscreteNumberField:()=>nd,DynamicFormShell:()=>Fc,EmailField:()=>Xc,FieldError:()=>_e,FieldLabel:()=>rt,GuestCountField:()=>md,Header:()=>qc,IncrementField:()=>ud,LOCATION_ORDERING_TIMEZONE:()=>Ps,LocationField:()=>rd,NameFields:()=>cd,ORDER_ITEMIZED_DEFAULT_ITEM_CLASSES:()=>jd,ORDER_STATUS_DEFAULT_ITEM_CLASSES:()=>Ld,OrderItemized:()=>gb,OrderStatus:()=>pb,PhoneField:()=>Yc,Platforms:()=>Ja,PricePreview:()=>zc,SectionLabel:()=>Gc,SliderField:()=>sd,SubmitButton:()=>$c,TextField:()=>De,TimeField:()=>Rr,deriveApproval:()=>Rd,deriveOrderStatus:()=>Id,divisionsFor:()=>US,formatAddOnPrice:()=>Rs,formatCateringLineLabel:()=>As,groupItemPortions:()=>VS,isConfirmable:()=>Dd,isLocationClosedByWeeklySchedule:()=>ol,itemizeOrder:()=>sn,locationWindowOn:()=>mc,mergeOrderItemizedItemClasses:()=>Md,mergeOrderStatusItemClasses:()=>Nd,parsePortion:()=>Vt,parsePortionKey:()=>ht,portionGlyph:()=>hp,portionKey:()=>uo,portionLabel:()=>$S,portionRows:()=>Zu,portionWeight:()=>Ts,radialSectionPath:()=>WS,remapPortion:()=>tc,resolveEventDisplay:()=>Ad,sectionLabel:()=>mp,selectionWeight:()=>Qa,setZorgoBoot:()=>Lc,setZorgoPathnameHook:()=>Nc,splitUpcharge:()=>MS,useCart:()=>_k,useCateringConfig:()=>Tk,useCustomer:()=>Pk,useField:()=>ie,useFormStatus:()=>Us,useFormValidity:()=>Fs,useFormValues:()=>Ve,useHydrateMenu:()=>vk,useHydrateStore:()=>hy,useItemCustomization:()=>Sk,useLocation:()=>wk,useMenu:()=>my,useModal:()=>bk,usePayment:()=>kk,usePromotions:()=>xk,useRecommendations:()=>Ck,useRegisterField:()=>ot,weightedUpcharges:()=>ec});module.exports=Rl(sC);var yb=require("next/navigation");var L=require("react");var tg=require("zustand");function We(t,e){var r={};for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(r[o]=t[o]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,o=Object.getOwnPropertySymbols(t);n<o.length;n++)e.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(t,o[n])&&(r[o[n]]=t[o[n]]);return r}function Ys(t,e,r,o){function n(s){return s instanceof r?s:new r(function(i){i(s)})}return new(r||(r=Promise))(function(s,i){function a(c){try{u(o.next(c))}catch(d){i(d)}}function l(c){try{u(o.throw(c))}catch(d){i(d)}}function u(c){c.done?s(c.value):n(c.value).then(a,l)}u((o=o.apply(t,e||[])).next())})}var $d=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);var wo=class extends Error{constructor(e,r="FunctionsError",o){super(e),this.name=r,this.context=o}},Tn=class extends wo{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},vo=class extends wo{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},So=class extends wo{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Cn;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(Cn||(Cn={}));var En=class{constructor(e,{headers:r={},customFetch:o,region:n=Cn.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=$d(o)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Ys(this,arguments,void 0,function*(r,o={}){var n;let s,i;try{let{headers:a,method:l,body:u,signal:c,timeout:d}=o,f={},{region:m}=o;m||(m=this.region);let h=new URL(`${this.url}/${r}`);m&&m!=="any"&&(f["x-region"]=m,h.searchParams.set("forceFunctionRegion",m));let g;u&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(f["Content-Type"]="application/octet-stream",g=u):typeof u=="string"?(f["Content-Type"]="text/plain",g=u):typeof FormData<"u"&&u instanceof FormData?g=u:(f["Content-Type"]="application/json",g=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?g=JSON.stringify(u):g=u;let y=c;d&&(i=new AbortController,s=setTimeout(()=>i.abort(),d),c?(y=i.signal,c.addEventListener("abort",()=>i.abort())):y=i.signal);let p=yield this.fetch(h.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},f),this.headers),a),body:g,signal:y}).catch(N=>{throw new Tn(N)}),b=p.headers.get("x-relay-error");if(b&&b==="true")throw new vo(p);if(!p.ok)throw new So(p);let _=((n=p.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),v;return _==="application/json"?v=yield p.json():_==="application/octet-stream"||_==="application/pdf"?v=yield p.blob():_==="text/event-stream"?v=p:_==="multipart/form-data"?v=yield p.formData():v=yield p.text(),{data:v,error:null,response:p}}catch(a){return{data:null,error:a,response:a instanceof So||a instanceof vo?a.context:void 0}}finally{s&&clearTimeout(s)}})}};var Vd=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},kb=class{constructor(t){var e,r,o;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(o=t.urlLengthLimit)!==null&&o!==void 0?o:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}then(t,e){var r=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 o=this.fetch,n=o(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{let i=null,a=null,l=null,u=s.status,c=s.statusText;if(s.ok){var d,f;if(r.method!=="HEAD"){var m;let y=await s.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((m=r.headers.get("Accept"))===null||m===void 0)&&m.includes("application/vnd.pgrst.plan+text"))?a=y:a=JSON.parse(y))}let h=(d=r.headers.get("Prefer"))===null||d===void 0?void 0:d.match(/count=(exact|planned|estimated)/),g=(f=s.headers.get("content-range"))===null||f===void 0?void 0:f.split("/");h&&g&&g.length>1&&(l=parseInt(g[1])),r.isMaybeSingle&&Array.isArray(a)&&(a.length>1?(i={code:"PGRST116",details:`Results contain ${a.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},a=null,l=null,u=406,c="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{let h=await s.text();try{i=JSON.parse(h),Array.isArray(i)&&s.status===404&&(a=[],i=null,u=200,c="OK")}catch{s.status===404&&h===""?(u=204,c="No Content"):i={message:h}}if(i&&r.shouldThrowOnError)throw new Vd(i)}return{error:i,data:a,count:l,status:u,statusText:c}});return this.shouldThrowOnError||(n=n.catch(s=>{var i;let a="",l="",u="",c=s?.cause;if(c){var d,f,m,h;let p=(d=c?.message)!==null&&d!==void 0?d:"",b=(f=c?.code)!==null&&f!==void 0?f:"";a=`${(m=s?.name)!==null&&m!==void 0?m:"FetchError"}: ${s?.message}`,a+=`
|
|
3
3
|
|
|
4
4
|
Caused by: ${(h=c?.name)!==null&&h!==void 0?h:"Error"}: ${p}`,b&&(a+=` (${b})`),c?.stack&&(a+=`
|
|
5
|
-
${c.stack}`)}else{var g;a=(g=s?.stack)!==null&&g!==void 0?g:""}let y=this.url.toString().length;return s?.name==="AbortError"||s?.code==="ABORT_ERR"?(u="",l="Request was aborted (timeout or manual cancellation)",y>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${y} 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.`)):(c?.name==="HeadersOverflowError"||c?.code==="UND_ERR_HEADERS_OVERFLOW")&&(u="",l="HTTP headers exceeded server limits (typically 16KB)",y>this.urlLengthLimit&&(l+=`. Your request URL is ${y} 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:`${(i=s?.name)!==null&&i!==void 0?i:"FetchError"}: ${s?.message}`,details:a,hint:l,code:u},data:null,count:null,status:0,statusText:""}})),n.then(t,e)}returns(){return this}overrideTypes(){return this}},Tb=class extends kb{select(t){let e=!1,r=(t??"*").split("").map(o=>/\s/.test(o)&&!e?"":(o==='"'&&(e=!e),o)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:o,referencedTable:n=o}={}){let s=n?`${n}.order`:"order",i=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${i?`${i},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let o=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(o,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:o=r}={}){let n=typeof o>"u"?"offset":`${o}.offset`,s=typeof o>"u"?"limit":`${o}.limit`;return this.url.searchParams.set(n,`${t}`),this.url.searchParams.set(s,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return 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:t=!1,verbose:e=!1,settings:r=!1,buffers:o=!1,wal:n=!1,format:s="text"}={}){var i;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,o?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=(i=this.headers.get("Accept"))!==null&&i!==void 0?i:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${l}"; options=${a};`),s==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},Bd=new RegExp("[,()]"),xo=class extends Tb{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(o=>typeof o=="string"&&Bd.test(o)?`"${o}"`:`${o}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(o=>typeof o=="string"&&Bd.test(o)?`"${o}"`:`${o}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:o}={}){let n="";o==="plain"?n="pl":o==="phrase"?n="ph":o==="websearch"&&(n="w");let s=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}fts${s}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let o=r?`${r}.or`:"or";return this.url.searchParams.append(o,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Cb=class{constructor(t,{headers:e={},schema:r,fetch:o,urlLengthLimit:n=8e3}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=o,this.urlLengthLimit=n}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=!1,count:o}=e??{},n=r?"HEAD":"GET",s=!1,i=(t??"*").split("").map(u=>/\s/.test(u)&&!s?"":(u==='"'&&(s=!s),u)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",i),o&&l.append("Prefer",`count=${o}`),new xo({method:n,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var o;let n="POST",{url:s,headers:i}=this.cloneRequestState();if(e&&i.append("Prefer",`count=${e}`),r||i.append("Prefer","missing=default"),Array.isArray(t)){let a=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(a.length>0){let l=[...new Set(a)].map(u=>`"${u}"`);s.searchParams.set("columns",l.join(","))}}return new xo({method:n,url:s,headers:i,schema:this.schema,body:t,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:o,defaultToNull:n=!0}={}){var s;let i="POST",{url:a,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&a.searchParams.set("on_conflict",e),o&&l.append("Prefer",`count=${o}`),n||l.append("Prefer","missing=default"),Array.isArray(t)){let u=t.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(u.length>0){let c=[...new Set(u)].map(d=>`"${d}"`);a.searchParams.set("columns",c.join(","))}}return new xo({method:i,url:a,headers:l,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let o="PATCH",{url:n,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new xo({method:o,url:n,headers:s,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;let r="DELETE",{url:o,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new xo({method:r,url:o,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function Pn(t){"@babel/helpers - typeof";return Pn=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},Pn(t)}function Eb(t,e){if(Pn(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(Pn(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Pb(t){var e=Eb(t,"string");return Pn(e)=="symbol"?e:e+""}function Ob(t,e,r){return(e=Pb(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function qd(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function Js(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?qd(Object(r),!0).forEach(function(o){Ob(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):qd(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var Wd=class Hd{constructor(e,{headers:r={},schema:o,fetch:n,timeout:s,urlLengthLimit:i=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=o,this.urlLengthLimit=i;let a=n??globalThis.fetch;s!==void 0&&s>0?this.fetch=(l,u)=>{let c=new AbortController,d=setTimeout(()=>c.abort(),s),f=u?.signal;if(f){if(f.aborted)return clearTimeout(d),a(l,u);let m=()=>{clearTimeout(d),c.abort()};return f.addEventListener("abort",m,{once:!0}),a(l,Js(Js({},u),{},{signal:c.signal})).finally(()=>{clearTimeout(d),f.removeEventListener("abort",m)})}return a(l,Js(Js({},u),{},{signal:c.signal})).finally(()=>clearTimeout(d))}:this.fetch=a}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Cb(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Hd(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:o=!1,get:n=!1,count:s}={}){var i;let a,l=new URL(`${this.url}/rpc/${e}`),u,c=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(c)),d=o&&Object.values(r).some(c);d?(a="POST",u=r):o||n?(a=o?"HEAD":"GET",Object.entries(r).filter(([m,h])=>h!==void 0).map(([m,h])=>[m,Array.isArray(h)?`{${h.join(",")}}`:`${h}`]).forEach(([m,h])=>{l.searchParams.append(m,h)})):(a="POST",u=r);let f=new Headers(this.headers);return d?f.set("Prefer",s?`count=${s},return=minimal`:"return=minimal"):s&&f.set("Prefer",`count=${s}`),new xo({method:a,url:l,headers:f,schema:this.schemaName,body:u,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}};var Al=class{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")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"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let r=globalThis.process;if(r){let o=r.versions;if(o&&o.node){let n=o.node,s=parseInt(n.replace(/^v/,"").split(".")[0]);return s>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${s} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${s} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
|
|
5
|
+
${c.stack}`)}else{var g;a=(g=s?.stack)!==null&&g!==void 0?g:""}let y=this.url.toString().length;return s?.name==="AbortError"||s?.code==="ABORT_ERR"?(u="",l="Request was aborted (timeout or manual cancellation)",y>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${y} 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.`)):(c?.name==="HeadersOverflowError"||c?.code==="UND_ERR_HEADERS_OVERFLOW")&&(u="",l="HTTP headers exceeded server limits (typically 16KB)",y>this.urlLengthLimit&&(l+=`. Your request URL is ${y} 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:`${(i=s?.name)!==null&&i!==void 0?i:"FetchError"}: ${s?.message}`,details:a,hint:l,code:u},data:null,count:null,status:0,statusText:""}})),n.then(t,e)}returns(){return this}overrideTypes(){return this}},Tb=class extends kb{select(t){let e=!1,r=(t??"*").split("").map(o=>/\s/.test(o)&&!e?"":(o==='"'&&(e=!e),o)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:o,referencedTable:n=o}={}){let s=n?`${n}.order`:"order",i=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${i?`${i},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let o=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(o,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:o=r}={}){let n=typeof o>"u"?"offset":`${o}.offset`,s=typeof o>"u"?"limit":`${o}.limit`;return this.url.searchParams.set(n,`${t}`),this.url.searchParams.set(s,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return 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:t=!1,verbose:e=!1,settings:r=!1,buffers:o=!1,wal:n=!1,format:s="text"}={}){var i;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,o?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=(i=this.headers.get("Accept"))!==null&&i!==void 0?i:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${l}"; options=${a};`),s==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},Bd=new RegExp("[,()]"),xo=class extends Tb{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(o=>typeof o=="string"&&Bd.test(o)?`"${o}"`:`${o}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(o=>typeof o=="string"&&Bd.test(o)?`"${o}"`:`${o}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:o}={}){let n="";o==="plain"?n="pl":o==="phrase"?n="ph":o==="websearch"&&(n="w");let s=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}fts${s}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let o=r?`${r}.or`:"or";return this.url.searchParams.append(o,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Cb=class{constructor(t,{headers:e={},schema:r,fetch:o,urlLengthLimit:n=8e3}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=o,this.urlLengthLimit=n}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=!1,count:o}=e??{},n=r?"HEAD":"GET",s=!1,i=(t??"*").split("").map(u=>/\s/.test(u)&&!s?"":(u==='"'&&(s=!s),u)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",i),o&&l.append("Prefer",`count=${o}`),new xo({method:n,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var o;let n="POST",{url:s,headers:i}=this.cloneRequestState();if(e&&i.append("Prefer",`count=${e}`),r||i.append("Prefer","missing=default"),Array.isArray(t)){let a=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(a.length>0){let l=[...new Set(a)].map(u=>`"${u}"`);s.searchParams.set("columns",l.join(","))}}return new xo({method:n,url:s,headers:i,schema:this.schema,body:t,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:o,defaultToNull:n=!0}={}){var s;let i="POST",{url:a,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&a.searchParams.set("on_conflict",e),o&&l.append("Prefer",`count=${o}`),n||l.append("Prefer","missing=default"),Array.isArray(t)){let u=t.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(u.length>0){let c=[...new Set(u)].map(d=>`"${d}"`);a.searchParams.set("columns",c.join(","))}}return new xo({method:i,url:a,headers:l,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let o="PATCH",{url:n,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new xo({method:o,url:n,headers:s,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;let r="DELETE",{url:o,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new xo({method:r,url:o,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function Pn(t){"@babel/helpers - typeof";return Pn=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},Pn(t)}function Eb(t,e){if(Pn(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(Pn(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Pb(t){var e=Eb(t,"string");return Pn(e)=="symbol"?e:e+""}function Ob(t,e,r){return(e=Pb(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function qd(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function Xs(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?qd(Object(r),!0).forEach(function(o){Ob(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):qd(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var Wd=class Hd{constructor(e,{headers:r={},schema:o,fetch:n,timeout:s,urlLengthLimit:i=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=o,this.urlLengthLimit=i;let a=n??globalThis.fetch;s!==void 0&&s>0?this.fetch=(l,u)=>{let c=new AbortController,d=setTimeout(()=>c.abort(),s),f=u?.signal;if(f){if(f.aborted)return clearTimeout(d),a(l,u);let m=()=>{clearTimeout(d),c.abort()};return f.addEventListener("abort",m,{once:!0}),a(l,Xs(Xs({},u),{},{signal:c.signal})).finally(()=>{clearTimeout(d),f.removeEventListener("abort",m)})}return a(l,Xs(Xs({},u),{},{signal:c.signal})).finally(()=>clearTimeout(d))}:this.fetch=a}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Cb(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Hd(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:o=!1,get:n=!1,count:s}={}){var i;let a,l=new URL(`${this.url}/rpc/${e}`),u,c=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(c)),d=o&&Object.values(r).some(c);d?(a="POST",u=r):o||n?(a=o?"HEAD":"GET",Object.entries(r).filter(([m,h])=>h!==void 0).map(([m,h])=>[m,Array.isArray(h)?`{${h.join(",")}}`:`${h}`]).forEach(([m,h])=>{l.searchParams.append(m,h)})):(a="POST",u=r);let f=new Headers(this.headers);return d?f.set("Prefer",s?`count=${s},return=minimal`:"return=minimal"):s&&f.set("Prefer",`count=${s}`),new xo({method:a,url:l,headers:f,schema:this.schemaName,body:u,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}};var Il=class{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")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"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let r=globalThis.process;if(r){let o=r.versions;if(o&&o.node){let n=o.node,s=parseInt(n.replace(/^v/,"").split(".")[0]);return s>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${s} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${s} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
|
|
6
6
|
import ws from "ws"
|
|
7
7
|
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 r=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(r+=`
|
|
8
8
|
|
|
9
|
-
Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}},Rl=Al;var zd="2.100.1";var Gd=`realtime-js/${zd}`,Kd="1.0.0",Il="2.0.0",Jd=Il;var Yd=1e4;var Xd=100;var It={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Ys={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"};var On={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};var An=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,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let o=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(o))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,o;let n=(o=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&o!==void 0?o:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var r,o;let n=(o=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&o!==void 0?o:{},i=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,i)}_encodeUserBroadcastPush(e,r,o){var n,s;let i=e.topic,a=(n=e.ref)!==null&&n!==void 0?n:"",l=(s=e.join_ref)!==null&&s!==void 0?s:"",u=e.payload.event,c=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},d=Object.keys(c).length===0?"":JSON.stringify(c);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(i.length>255)throw new Error(`topic length ${i.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`metadata length ${d.length} exceeds maximum of 255`);let f=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+i.length+u.length+d.length,m=new ArrayBuffer(this.HEADER_LENGTH+f),h=new DataView(m),g=0;h.setUint8(g++,this.KINDS.userBroadcastPush),h.setUint8(g++,l.length),h.setUint8(g++,a.length),h.setUint8(g++,i.length),h.setUint8(g++,u.length),h.setUint8(g++,d.length),h.setUint8(g++,r),Array.from(l,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(a,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(i,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(u,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(d,p=>h.setUint8(g++,p.charCodeAt(0)));var y=new Uint8Array(m.byteLength+o.byteLength);return y.set(new Uint8Array(m),0),y.set(new Uint8Array(o),m.byteLength),y.buffer}decode(e,r){if(this._isArrayBuffer(e)){let o=this._binaryDecode(e);return r(o)}if(typeof e=="string"){let o=JSON.parse(e),[n,s,i,a,l]=o;return r({join_ref:n,ref:s,topic:i,event:a,payload:l})}return r({})}_binaryDecode(e){let r=new DataView(e),o=r.getUint8(0),n=new TextDecoder;if(o===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,n)}_decodeUserBroadcast(e,r,o){let n=r.getUint8(1),s=r.getUint8(2),i=r.getUint8(3),a=r.getUint8(4),l=this.HEADER_LENGTH+4,u=o.decode(e.slice(l,l+n));l=l+n;let c=o.decode(e.slice(l,l+s));l=l+s;let d=o.decode(e.slice(l,l+i));l=l+i;let f=e.slice(l,e.byteLength),m=a===this.JSON_ENCODING?JSON.parse(o.decode(f)):f,h={type:this.BROADCAST_EVENT,event:c,payload:m};return i>0&&(h.meta=JSON.parse(d)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:h}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([o])=>r.includes(o)))}};var oe;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(oe||(oe={}));var Ll=(t,e,r={})=>{var o;let n=(o=r.skipTypes)!==null&&o!==void 0?o:[];return e?Object.keys(e).reduce((s,i)=>(s[i]=Ab(i,t,e,n),s),{}):{}},Ab=(t,e,r,o)=>{let n=e.find(a=>a.name===t),s=n?.type,i=r[t];return s&&!o.includes(s)?Qd(s,i):Dl(i)},Qd=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return Lb(e,r)}switch(t){case oe.bool:return Rb(e);case oe.float4:case oe.float8:case oe.int2:case oe.int4:case oe.int8:case oe.numeric:case oe.oid:return Ib(e);case oe.json:case oe.jsonb:return Db(e);case oe.timestamp:return Nb(e);case oe.abstime:case oe.date:case oe.daterange:case oe.int4range:case oe.int8range:case oe.money:case oe.reltime:case oe.text:case oe.time:case oe.timestamptz:case oe.timetz:case oe.tsrange:case oe.tstzrange:return Dl(e);default:return Dl(e)}},Dl=t=>t,Rb=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},Ib=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t},Db=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Lb=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,o=t[r];if(t[0]==="{"&&o==="}"){let s,i=t.slice(1,r);try{s=JSON.parse("["+i+"]")}catch{s=i?i.split(","):[]}return s.map(a=>Qd(e,a))}return t},Nb=t=>typeof t=="string"?t.replace(" ","T"):t,Xs=t=>{let e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var In=t=>typeof t=="function"?t:function(){return t},Mb=typeof self<"u"?self:null,To=typeof window<"u"?window:null,Dt=Mb||To||globalThis,Ub="2.0.0",Fb=1e4,$b=1e3,Lt={connecting:0,open:1,closing:2,closed:3},He={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},or={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Nl={longpoll:"longpoll",websocket:"websocket"},Bb={complete:4},jl="base64url.bearer.phx.",Qs=class{constructor(t,e,r,o){this.channel=t,this.event=e,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=o,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(t){this.timeout=t,this.reset(),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()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(o=>o.status===t).forEach(o=>o.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},Zd=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},qb=class{constructor(t,e,r){this.state=He.closed,this.topic=t,this.params=In(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new Qs(this,or.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Zd(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=He.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(o=>o.send()),this.pushBuffer=[]}),this.joinPush.receive("error",o=>{this.state=He.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,o),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=He.closed,this.socket.remove(this)}),this.onError(o=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,o),this.isJoining()&&this.joinPush.reset(),this.state=He.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new Qs(this,or.leave,In({}),this.timeout).send(),this.state=He.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(or.reply,(o,n)=>{this.trigger(this.replyEventName(n),o)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=He.closed,this.bindings=[]}onClose(t){this.on(or.close,t)}onError(t){return this.on(or.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let o=new Qs(this,t,function(){return e},r);return this.canPush()?o.send():(o.startTimeout(),this.pushBuffer.push(o)),o}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=He.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(or.close,"leave")},r=new Qs(this,or.leave,In({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return!0}isMember(t,e,r,o){return this.topic!==t?!1:o&&o!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:o}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=He.joining,this.joinPush.resend(t))}trigger(t,e,r,o){let n=this.onMessage(t,e,r,o);if(e&&!n)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let s=this.bindings.filter(i=>i.event===t&&this.filterBindings(i,e,r));for(let i=0;i<s.length;i++)s[i].callback(n,r,o||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===He.closed}isErrored(){return this.state===He.errored}isJoined(){return this.state===He.joined}isJoining(){return this.state===He.joining}isLeaving(){return this.state===He.leaving}},ei=class{static request(t,e,r,o,n,s,i){if(Dt.XDomainRequest){let a=new Dt.XDomainRequest;return this.xdomainRequest(a,t,e,o,n,s,i)}else if(Dt.XMLHttpRequest){let a=new Dt.XMLHttpRequest;return this.xhrRequest(a,t,e,r,o,n,s,i)}else{if(Dt.fetch&&Dt.AbortController)return this.fetchRequest(t,e,r,o,n,s,i);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,o,n,s,i){let a={method:t,headers:r,body:o},l=null;if(n){l=new AbortController;let u=setTimeout(()=>l.abort(),n);a.signal=l.signal}return Dt.fetch(e,a).then(u=>u.text()).then(u=>this.parseJSON(u)).then(u=>i&&i(u)).catch(u=>{u.name==="AbortError"&&s?s():i&&i(null)}),l}static xdomainRequest(t,e,r,o,n,s,i){return t.timeout=n,t.open(e,r),t.onload=()=>{let a=this.parseJSON(t.responseText);i&&i(a)},s&&(t.ontimeout=s),t.onprogress=()=>{},t.send(o),t}static xhrRequest(t,e,r,o,n,s,i,a){t.open(e,r,!0),t.timeout=s;for(let[l,u]of Object.entries(o))t.setRequestHeader(l,u);return t.onerror=()=>a&&a(null),t.onreadystatechange=()=>{if(t.readyState===Bb.complete&&a){let l=this.parseJSON(t.responseText);a(l)}},i&&(t.ontimeout=i),t.send(n),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var o in t){if(!Object.prototype.hasOwnProperty.call(t,o))continue;let n=e?`${e}[${o}]`:o,s=t[o];typeof s=="object"?r.push(this.serialize(s,n)):r.push(encodeURIComponent(n)+"="+encodeURIComponent(s))}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return`${t}${r}${this.serialize(e)}`}},Vb=t=>{let e="",r=new Uint8Array(t),o=r.byteLength;for(let n=0;n<o;n++)e+=String.fromCharCode(r[n]);return btoa(e)},ko=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(jl)&&(this.authToken=atob(e[1].slice(jl.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=Lt.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+Nl.websocket),"$1/"+Nl.longpoll)}endpointURL(){return ei.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=Lt.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Lt.open||this.readyState===Lt.connecting}poll(){let t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:o,messages:n}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=o}else r=0;switch(r){case 200:n.forEach(s=>{setTimeout(()=>this.onmessage({data:s}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=Lt.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}})}send(t){typeof t!="string"&&(t=Vb(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},t.join(`
|
|
10
|
-
`),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(t,e,r){for(let n of this.reqs)n.abort();this.readyState=Lt.closed;let o=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",o)):this.onclose(o)}ajax(t,e,r,o,n){let s,i=()=>{this.reqs.delete(s),o()};s=ei.request(t,this.endpointURL(),e,r,this.timeout,i,a=>{this.reqs.delete(s),this.isActive()&&n(a)}),this.reqs.add(s)}},ti=class Rn{constructor(e,r={}){let o=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(o.state,n=>{let{onJoin:s,onLeave:i,onSync:a}=this.caller;this.joinRef=this.channel.joinRef(),this.state=Rn.syncState(this.state,n,s,i),this.pendingDiffs.forEach(l=>{this.state=Rn.syncDiff(this.state,l,s,i)}),this.pendingDiffs=[],a()}),this.channel.on(o.diff,n=>{let{onJoin:s,onLeave:i,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=Rn.syncDiff(this.state,n,s,i),a())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return Rn.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,o,n){let s=this.clone(e),i={},a={};return this.map(s,(l,u)=>{r[l]||(a[l]=u)}),this.map(r,(l,u)=>{let c=s[l];if(c){let d=u.metas.map(g=>g.phx_ref),f=c.metas.map(g=>g.phx_ref),m=u.metas.filter(g=>f.indexOf(g.phx_ref)<0),h=c.metas.filter(g=>d.indexOf(g.phx_ref)<0);m.length>0&&(i[l]=u,i[l].metas=m),h.length>0&&(a[l]=this.clone(c),a[l].metas=h)}else i[l]=u}),this.syncDiff(s,{joins:i,leaves:a},o,n)}static syncDiff(e,r,o,n){let{joins:s,leaves:i}=this.clone(r);return o||(o=function(){}),n||(n=function(){}),this.map(s,(a,l)=>{let u=e[a];if(e[a]=this.clone(l),u){let c=e[a].metas.map(f=>f.phx_ref),d=u.metas.filter(f=>c.indexOf(f.phx_ref)<0);e[a].metas.unshift(...d)}o(a,u,l)}),this.map(i,(a,l)=>{let u=e[a];if(!u)return;let c=l.metas.map(d=>d.phx_ref);u.metas=u.metas.filter(d=>c.indexOf(d.phx_ref)<0),n(a,u,l),u.metas.length===0&&delete e[a]}),e}static list(e,r){return r||(r=function(o,n){return n}),this.map(e,(o,n)=>r(o,n))}static map(e,r){return Object.getOwnPropertyNames(e).map(o=>r(o,e[o]))}static clone(e){return JSON.parse(JSON.stringify(e))}},Zs={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,o,n,s,i]=JSON.parse(t);return e({join_ref:r,ref:o,topic:n,event:s,payload:i})}},binaryEncode(t){let{join_ref:e,ref:r,event:o,topic:n,payload:s}=t,i=this.META_LENGTH+e.length+r.length+n.length+o.length,a=new ArrayBuffer(this.HEADER_LENGTH+i),l=new DataView(a),u=0;l.setUint8(u++,this.KINDS.push),l.setUint8(u++,e.length),l.setUint8(u++,r.length),l.setUint8(u++,n.length),l.setUint8(u++,o.length),Array.from(e,d=>l.setUint8(u++,d.charCodeAt(0))),Array.from(r,d=>l.setUint8(u++,d.charCodeAt(0))),Array.from(n,d=>l.setUint8(u++,d.charCodeAt(0))),Array.from(o,d=>l.setUint8(u++,d.charCodeAt(0)));var c=new Uint8Array(a.byteLength+s.byteLength);return c.set(new Uint8Array(a),0),c.set(new Uint8Array(s),a.byteLength),c.buffer},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),o=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,o);case this.KINDS.reply:return this.decodeReply(t,e,o);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,o)}},decodePush(t,e,r){let o=e.getUint8(1),n=e.getUint8(2),s=e.getUint8(3),i=this.HEADER_LENGTH+this.META_LENGTH-1,a=r.decode(t.slice(i,i+o));i=i+o;let l=r.decode(t.slice(i,i+n));i=i+n;let u=r.decode(t.slice(i,i+s));i=i+s;let c=t.slice(i,t.byteLength);return{join_ref:a,ref:null,topic:l,event:u,payload:c}},decodeReply(t,e,r){let o=e.getUint8(1),n=e.getUint8(2),s=e.getUint8(3),i=e.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(t.slice(a,a+o));a=a+o;let u=r.decode(t.slice(a,a+n));a=a+n;let c=r.decode(t.slice(a,a+s));a=a+s;let d=r.decode(t.slice(a,a+i));a=a+i;let f=t.slice(a,t.byteLength),m={status:d,response:f};return{join_ref:l,ref:u,topic:c,event:or.reply,payload:m}},decodeBroadcast(t,e,r){let o=e.getUint8(1),n=e.getUint8(2),s=this.HEADER_LENGTH+2,i=r.decode(t.slice(s,s+o));s=s+o;let a=r.decode(t.slice(s,s+n));s=s+n;let l=t.slice(s,t.byteLength);return{join_ref:null,ref:null,topic:i,event:a,payload:l}}},ri=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||Fb,this.transport=e.transport||Dt.WebSocket||ko,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||Dt&&Dt.sessionStorage,this.establishedConnections=0,this.defaultEncoder=Zs.encode.bind(Zs),this.defaultDecoder=Zs.decode.bind(Zs),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==ko?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let r=null;To&&To.addEventListener&&(To.addEventListener("pagehide",o=>{this.conn&&(this.disconnect(),r=this.connectClock)}),To.addEventListener("pageshow",o=>{r===this.connectClock&&(r=null,this.connect())}),To.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=o=>e.rejoinAfterMs?e.rejoinAfterMs(o):[1e3,2e3,5e3][o-1]||1e4,this.reconnectAfterMs=o=>e.reconnectAfterMs?e.reconnectAfterMs(o):[10,50,100,150,200,250,500,1e3,2e3][o-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(o,n,s)=>{console.log(`${o}: ${n}`,s)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=In(e.params||{}),this.endPoint=`${t}/${Nl.websocket}`,this.vsn=e.vsn||Ub,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Zd(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken}getLongPollTransport(){return ko}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=ei.appendParams(ei.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,t&&t()},e,r)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=In(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==ko?this.connectWithFallback(ko,this.longPollFallbackMs):this.transportConnect())}log(t,e,r){this.logger&&this.logger(t,e,r)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let o=this.onMessage(n=>{n.ref===e&&(this.off([o]),t(Date.now()-r))});return!0}transportName(t){return t===ko?"LongPoll":t.name}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${jl}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,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)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=!1,o=!0,n,s,i=this.transportName(t),a=l=>{this.log("transport",`falling back to ${i}...`,l),this.off([n,s]),o=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${i}`))return a("memorized");this.fallbackTimer=setTimeout(a,e),s=this.onError(l=>{this.log("transport","error",l),o&&!r&&(clearTimeout(this.fallbackTimer),a(l))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!o){let l=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(a,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),$b,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,r){if(!this.conn)return t&&t();let o=this.conn;this.waitForBufferDone(o,()=>{e?o.close(e,r||""):o.close(),this.waitForSocketClosed(o,()=>{this.conn===o&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1)},150*r)}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===Lt.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1)},150*r)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(or.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case Lt.connecting:return"connecting";case Lt.open:return"open";case Lt.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1)}channel(t,e={}){let r=new qb(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:o,ref:n,join_ref:s}=t;this.log("push",`${e} ${r} (${s}, ${n})`,o)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:o,payload:n,ref:s,join_ref:i}=e;if(s&&s===this.pendingHeartbeatRef){let a=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(n.status==="ok"?"ok":"error",a)}catch(l){this.log("error","error in heartbeat callback",l)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${n.status||""} ${r} ${o} ${s&&"("+s+")"||""}`.trim(),n);for(let a=0;a<this.channels.length;a++){let l=this.channels[a];l.isMember(r,o,n,i)&&l.trigger(o,n,s,i)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,o])=>{try{o(...e)}catch(n){this.log("error",`error in ${t} callback`,n)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};var Dn=class t{constructor(e,r){let o=Hb(r);this.presence=new ti(e.getChannel(),o),this.presence.onJoin((n,s,i)=>{let a=t.onJoinPayload(n,s,i);e.getChannel().trigger("presence",a)}),this.presence.onLeave((n,s,i)=>{let a=t.onLeavePayload(n,s,i);e.getChannel().trigger("presence",a)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return t.transformState(this.presence.state)}static transformState(e){return e=Wb(e),Object.getOwnPropertyNames(e).reduce((r,o)=>{let n=e[o];return r[o]=oi(n),r},{})}static onJoinPayload(e,r,o){let n=ef(r),s=oi(o);return{event:"join",key:e,currentPresences:n,newPresences:s}}static onLeavePayload(e,r,o){let n=ef(r),s=oi(o);return{event:"leave",key:e,currentPresences:n,leftPresences:s}}};function oi(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function Wb(t){return JSON.parse(JSON.stringify(t))}function Hb(t){return t?.events&&{events:t.events}}function ef(t){return t?.metas?oi(t):[]}var Ml;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(Ml||(Ml={}));var Co=class{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new Dn(this.channel.channelAdapter,r)}};var Ln=class{constructor(e,r,o){let n=zb(o);this.channel=e.getSocket().channel(r,n),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,r,o){let n;try{n=this.channel.push(e,r,o)}catch{throw`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>Xd){let s=this.channel.pushBuffer.shift();s.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${s.event}`,s.payload())}return n}updateJoinPayload(e){let r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===It.joined}isJoined(){return this.state===It.joined}isJoining(){return this.state===It.joining}isClosed(){return this.state===It.closed}isLeaving(){return this.state===It.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}};function zb(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var Ul;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Ul||(Ul={}));var Eo;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(Eo||(Eo={}));var Nt;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(Nt||(Nt={}));var Po=class t{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},o){var n,s;if(this.topic=e,this.params=r,this.socket=o,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new Ln(this.socket.socketAdapter,e,this.params),this.presence=new Co(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=Xs(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((s=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||s===void 0)&&s.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var o,n,s;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:i,presence:a,private:l}}=this.params,u=(n=(o=this.bindings.postgres_changes)===null||o===void 0?void 0:o.map(m=>m.filter))!==null&&n!==void 0?n:[],c=!!this.bindings[Eo.PRESENCE]&&this.bindings[Eo.PRESENCE].length>0||((s=this.params.config.presence)===null||s===void 0?void 0:s.enabled)===!0,d={},f={broadcast:i,presence:Object.assign(Object.assign({},a),{enabled:c}),postgres_changes:u,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(m=>{e?.(Nt.CHANNEL_ERROR,m)}),this._onClose(()=>e?.(Nt.CLOSED)),this.updateJoinPayload(Object.assign({config:f},d)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:m})=>{if(this.socket._isManualToken()||this.socket.setAuth(),m===void 0){e?.(Nt.SUBSCRIBED);return}this._updatePostgresBindings(m,e)}).receive("error",m=>{this.state=It.errored,e?.(Nt.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(m).join(", ")||"error")))}).receive("timeout",()=>{e?.(Nt.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var o;let n=this.bindings.postgres_changes,s=(o=n?.length)!==null&&o!==void 0?o:0,i=[];for(let a=0;a<s;a++){let l=n[a],{filter:{event:u,schema:c,table:d,filter:f}}=l,m=e&&e[a];if(m&&m.event===u&&t.isFilterValueEqual(m.schema,c)&&t.isFilterValueEqual(m.table,d)&&t.isFilterValueEqual(m.filter,f))i.push(Object.assign(Object.assign({},l),{id:m.id}));else{this.unsubscribe(),this.state=It.errored,r?.(Nt.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=i,this.state!=It.errored&&r&&r(Nt.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,o){if(this.channelAdapter.isJoined()&&e===Eo.PRESENCE)throw this.socket.log("channel",`cannot add presence callbacks for ${this.topic} after joining.`),new Error("cannot add presence callbacks after joining a channel");return this._on(e,r,o)}async httpSend(e,r,o={}){var n;if(r==null)return Promise.reject("Payload is required for httpSend()");let s={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(s.Authorization=`Bearer ${this.socket.accessTokenValue}`);let i={method:"POST",headers:s,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,i,(n=o.timeout)!==null&&n!==void 0?n:this.timeout);if(a.status===202)return{success:!0};let l=a.statusText;try{let u=await a.json();l=u.error||u.message||l}catch{}return Promise.reject(new Error(l))}async send(e,r={}){var o,n;if(!this.channelAdapter.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:s,payload:i}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);let l={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:s,payload:i,private:this.private}]})};try{let u=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(o=r.timeout)!==null&&o!==void 0?o:this.timeout);return await((n=u.body)===null||n===void 0?void 0:n.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(s=>{var i,a,l;let u=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(i=this.params)===null||i===void 0?void 0:i.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&s("ok"),u.receive("ok",()=>s("ok")),u.receive("error",()=>s("error")),u.receive("timeout",()=>s("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,o){let n=new AbortController,s=setTimeout(()=>n.abort(),o),i=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(s),i}_on(e,r,o){let n=e.toLocaleLowerCase(),s=this.channelAdapter.on(e,o),i={type:n,filter:r,callback:o,ref:s};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,o)=>{var n,s,i,a,l,u,c;let d=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(d,o))return!1;let f=(n=this.bindings[d])===null||n===void 0?void 0:n.find(m=>m.ref===e.ref);if(!f)return!0;if(["broadcast","presence","postgres_changes"].includes(d))if("id"in f){let m=f.id,h=(s=f.filter)===null||s===void 0?void 0:s.event;return m&&((i=r.ids)===null||i===void 0?void 0:i.includes(m))&&(h==="*"||h?.toLocaleLowerCase()===((a=r.data)===null||a===void 0?void 0:a.type.toLocaleLowerCase()))}else{let m=(u=(l=f?.filter)===null||l===void 0?void 0:l.event)===null||u===void 0?void 0:u.toLocaleLowerCase();return m==="*"||m===((c=r?.event)===null||c===void 0?void 0:c.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===d})}_notThisChannelEvent(e,r){let{close:o,error:n,leave:s,join:i}=Ys;return r&&[o,n,s,i].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,o)=>{if(typeof r=="object"&&"ids"in r){let n=r.data,{schema:s,table:i,commit_timestamp:a,type:l,errors:u}=n;return Object.assign(Object.assign({},{schema:s,table:i,commit_timestamp:a,eventType:l,new:{},old:{},errors:u}),this._getPayloadRecords(n))}return r})}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_getPayloadRecords(e){let r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=Ll(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Ll(e.columns,e.old_record)),r}};var Nn=class{constructor(e,r){this.socket=new ri(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,o,n=1e4){return new Promise(s=>{setTimeout(()=>s("timeout"),n),this.socket.disconnect(()=>{e(),s("ok")},r,o)})}push(e){this.socket.push(e)}log(e,r,o){this.socket.log(e,r,o)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==On.connecting}isDisconnecting(){return this.socket.connectionState()==On.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}};var Gb={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Kb=[1e3,2e3,5e3,1e4],Jb=1e4,Yb=`
|
|
9
|
+
Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}},Dl=Il;var zd="2.100.1";var Gd=`realtime-js/${zd}`,Kd="1.0.0",Ll="2.0.0",Jd=Ll;var Yd=1e4;var Xd=100;var It={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Qs={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"};var On={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};var An=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,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let o=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(o))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,o;let n=(o=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&o!==void 0?o:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var r,o;let n=(o=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&o!==void 0?o:{},i=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,i)}_encodeUserBroadcastPush(e,r,o){var n,s;let i=e.topic,a=(n=e.ref)!==null&&n!==void 0?n:"",l=(s=e.join_ref)!==null&&s!==void 0?s:"",u=e.payload.event,c=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},d=Object.keys(c).length===0?"":JSON.stringify(c);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(i.length>255)throw new Error(`topic length ${i.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`metadata length ${d.length} exceeds maximum of 255`);let f=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+i.length+u.length+d.length,m=new ArrayBuffer(this.HEADER_LENGTH+f),h=new DataView(m),g=0;h.setUint8(g++,this.KINDS.userBroadcastPush),h.setUint8(g++,l.length),h.setUint8(g++,a.length),h.setUint8(g++,i.length),h.setUint8(g++,u.length),h.setUint8(g++,d.length),h.setUint8(g++,r),Array.from(l,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(a,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(i,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(u,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(d,p=>h.setUint8(g++,p.charCodeAt(0)));var y=new Uint8Array(m.byteLength+o.byteLength);return y.set(new Uint8Array(m),0),y.set(new Uint8Array(o),m.byteLength),y.buffer}decode(e,r){if(this._isArrayBuffer(e)){let o=this._binaryDecode(e);return r(o)}if(typeof e=="string"){let o=JSON.parse(e),[n,s,i,a,l]=o;return r({join_ref:n,ref:s,topic:i,event:a,payload:l})}return r({})}_binaryDecode(e){let r=new DataView(e),o=r.getUint8(0),n=new TextDecoder;if(o===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,n)}_decodeUserBroadcast(e,r,o){let n=r.getUint8(1),s=r.getUint8(2),i=r.getUint8(3),a=r.getUint8(4),l=this.HEADER_LENGTH+4,u=o.decode(e.slice(l,l+n));l=l+n;let c=o.decode(e.slice(l,l+s));l=l+s;let d=o.decode(e.slice(l,l+i));l=l+i;let f=e.slice(l,e.byteLength),m=a===this.JSON_ENCODING?JSON.parse(o.decode(f)):f,h={type:this.BROADCAST_EVENT,event:c,payload:m};return i>0&&(h.meta=JSON.parse(d)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:h}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([o])=>r.includes(o)))}};var oe;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(oe||(oe={}));var jl=(t,e,r={})=>{var o;let n=(o=r.skipTypes)!==null&&o!==void 0?o:[];return e?Object.keys(e).reduce((s,i)=>(s[i]=Ab(i,t,e,n),s),{}):{}},Ab=(t,e,r,o)=>{let n=e.find(a=>a.name===t),s=n?.type,i=r[t];return s&&!o.includes(s)?Qd(s,i):Nl(i)},Qd=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return Lb(e,r)}switch(t){case oe.bool:return Rb(e);case oe.float4:case oe.float8:case oe.int2:case oe.int4:case oe.int8:case oe.numeric:case oe.oid:return Ib(e);case oe.json:case oe.jsonb:return Db(e);case oe.timestamp:return Nb(e);case oe.abstime:case oe.date:case oe.daterange:case oe.int4range:case oe.int8range:case oe.money:case oe.reltime:case oe.text:case oe.time:case oe.timestamptz:case oe.timetz:case oe.tsrange:case oe.tstzrange:return Nl(e);default:return Nl(e)}},Nl=t=>t,Rb=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},Ib=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t},Db=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Lb=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,o=t[r];if(t[0]==="{"&&o==="}"){let s,i=t.slice(1,r);try{s=JSON.parse("["+i+"]")}catch{s=i?i.split(","):[]}return s.map(a=>Qd(e,a))}return t},Nb=t=>typeof t=="string"?t.replace(" ","T"):t,Zs=t=>{let e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var In=t=>typeof t=="function"?t:function(){return t},Mb=typeof self<"u"?self:null,To=typeof window<"u"?window:null,Dt=Mb||To||globalThis,Ub="2.0.0",Fb=1e4,$b=1e3,Lt={connecting:0,open:1,closing:2,closed:3},He={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},or={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Ml={longpoll:"longpoll",websocket:"websocket"},Bb={complete:4},Ul="base64url.bearer.phx.",ei=class{constructor(t,e,r,o){this.channel=t,this.event=e,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=o,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(t){this.timeout=t,this.reset(),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()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(o=>o.status===t).forEach(o=>o.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},Zd=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},qb=class{constructor(t,e,r){this.state=He.closed,this.topic=t,this.params=In(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new ei(this,or.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Zd(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=He.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(o=>o.send()),this.pushBuffer=[]}),this.joinPush.receive("error",o=>{this.state=He.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,o),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=He.closed,this.socket.remove(this)}),this.onError(o=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,o),this.isJoining()&&this.joinPush.reset(),this.state=He.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new ei(this,or.leave,In({}),this.timeout).send(),this.state=He.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(or.reply,(o,n)=>{this.trigger(this.replyEventName(n),o)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=He.closed,this.bindings=[]}onClose(t){this.on(or.close,t)}onError(t){return this.on(or.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let o=new ei(this,t,function(){return e},r);return this.canPush()?o.send():(o.startTimeout(),this.pushBuffer.push(o)),o}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=He.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(or.close,"leave")},r=new ei(this,or.leave,In({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return!0}isMember(t,e,r,o){return this.topic!==t?!1:o&&o!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:o}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=He.joining,this.joinPush.resend(t))}trigger(t,e,r,o){let n=this.onMessage(t,e,r,o);if(e&&!n)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let s=this.bindings.filter(i=>i.event===t&&this.filterBindings(i,e,r));for(let i=0;i<s.length;i++)s[i].callback(n,r,o||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===He.closed}isErrored(){return this.state===He.errored}isJoined(){return this.state===He.joined}isJoining(){return this.state===He.joining}isLeaving(){return this.state===He.leaving}},ri=class{static request(t,e,r,o,n,s,i){if(Dt.XDomainRequest){let a=new Dt.XDomainRequest;return this.xdomainRequest(a,t,e,o,n,s,i)}else if(Dt.XMLHttpRequest){let a=new Dt.XMLHttpRequest;return this.xhrRequest(a,t,e,r,o,n,s,i)}else{if(Dt.fetch&&Dt.AbortController)return this.fetchRequest(t,e,r,o,n,s,i);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,o,n,s,i){let a={method:t,headers:r,body:o},l=null;if(n){l=new AbortController;let u=setTimeout(()=>l.abort(),n);a.signal=l.signal}return Dt.fetch(e,a).then(u=>u.text()).then(u=>this.parseJSON(u)).then(u=>i&&i(u)).catch(u=>{u.name==="AbortError"&&s?s():i&&i(null)}),l}static xdomainRequest(t,e,r,o,n,s,i){return t.timeout=n,t.open(e,r),t.onload=()=>{let a=this.parseJSON(t.responseText);i&&i(a)},s&&(t.ontimeout=s),t.onprogress=()=>{},t.send(o),t}static xhrRequest(t,e,r,o,n,s,i,a){t.open(e,r,!0),t.timeout=s;for(let[l,u]of Object.entries(o))t.setRequestHeader(l,u);return t.onerror=()=>a&&a(null),t.onreadystatechange=()=>{if(t.readyState===Bb.complete&&a){let l=this.parseJSON(t.responseText);a(l)}},i&&(t.ontimeout=i),t.send(n),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var o in t){if(!Object.prototype.hasOwnProperty.call(t,o))continue;let n=e?`${e}[${o}]`:o,s=t[o];typeof s=="object"?r.push(this.serialize(s,n)):r.push(encodeURIComponent(n)+"="+encodeURIComponent(s))}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return`${t}${r}${this.serialize(e)}`}},Vb=t=>{let e="",r=new Uint8Array(t),o=r.byteLength;for(let n=0;n<o;n++)e+=String.fromCharCode(r[n]);return btoa(e)},ko=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(Ul)&&(this.authToken=atob(e[1].slice(Ul.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=Lt.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+Ml.websocket),"$1/"+Ml.longpoll)}endpointURL(){return ri.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=Lt.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Lt.open||this.readyState===Lt.connecting}poll(){let t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:o,messages:n}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=o}else r=0;switch(r){case 200:n.forEach(s=>{setTimeout(()=>this.onmessage({data:s}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=Lt.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}})}send(t){typeof t!="string"&&(t=Vb(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},t.join(`
|
|
10
|
+
`),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(t,e,r){for(let n of this.reqs)n.abort();this.readyState=Lt.closed;let o=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",o)):this.onclose(o)}ajax(t,e,r,o,n){let s,i=()=>{this.reqs.delete(s),o()};s=ri.request(t,this.endpointURL(),e,r,this.timeout,i,a=>{this.reqs.delete(s),this.isActive()&&n(a)}),this.reqs.add(s)}},oi=class Rn{constructor(e,r={}){let o=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(o.state,n=>{let{onJoin:s,onLeave:i,onSync:a}=this.caller;this.joinRef=this.channel.joinRef(),this.state=Rn.syncState(this.state,n,s,i),this.pendingDiffs.forEach(l=>{this.state=Rn.syncDiff(this.state,l,s,i)}),this.pendingDiffs=[],a()}),this.channel.on(o.diff,n=>{let{onJoin:s,onLeave:i,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=Rn.syncDiff(this.state,n,s,i),a())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return Rn.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,o,n){let s=this.clone(e),i={},a={};return this.map(s,(l,u)=>{r[l]||(a[l]=u)}),this.map(r,(l,u)=>{let c=s[l];if(c){let d=u.metas.map(g=>g.phx_ref),f=c.metas.map(g=>g.phx_ref),m=u.metas.filter(g=>f.indexOf(g.phx_ref)<0),h=c.metas.filter(g=>d.indexOf(g.phx_ref)<0);m.length>0&&(i[l]=u,i[l].metas=m),h.length>0&&(a[l]=this.clone(c),a[l].metas=h)}else i[l]=u}),this.syncDiff(s,{joins:i,leaves:a},o,n)}static syncDiff(e,r,o,n){let{joins:s,leaves:i}=this.clone(r);return o||(o=function(){}),n||(n=function(){}),this.map(s,(a,l)=>{let u=e[a];if(e[a]=this.clone(l),u){let c=e[a].metas.map(f=>f.phx_ref),d=u.metas.filter(f=>c.indexOf(f.phx_ref)<0);e[a].metas.unshift(...d)}o(a,u,l)}),this.map(i,(a,l)=>{let u=e[a];if(!u)return;let c=l.metas.map(d=>d.phx_ref);u.metas=u.metas.filter(d=>c.indexOf(d.phx_ref)<0),n(a,u,l),u.metas.length===0&&delete e[a]}),e}static list(e,r){return r||(r=function(o,n){return n}),this.map(e,(o,n)=>r(o,n))}static map(e,r){return Object.getOwnPropertyNames(e).map(o=>r(o,e[o]))}static clone(e){return JSON.parse(JSON.stringify(e))}},ti={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,o,n,s,i]=JSON.parse(t);return e({join_ref:r,ref:o,topic:n,event:s,payload:i})}},binaryEncode(t){let{join_ref:e,ref:r,event:o,topic:n,payload:s}=t,i=this.META_LENGTH+e.length+r.length+n.length+o.length,a=new ArrayBuffer(this.HEADER_LENGTH+i),l=new DataView(a),u=0;l.setUint8(u++,this.KINDS.push),l.setUint8(u++,e.length),l.setUint8(u++,r.length),l.setUint8(u++,n.length),l.setUint8(u++,o.length),Array.from(e,d=>l.setUint8(u++,d.charCodeAt(0))),Array.from(r,d=>l.setUint8(u++,d.charCodeAt(0))),Array.from(n,d=>l.setUint8(u++,d.charCodeAt(0))),Array.from(o,d=>l.setUint8(u++,d.charCodeAt(0)));var c=new Uint8Array(a.byteLength+s.byteLength);return c.set(new Uint8Array(a),0),c.set(new Uint8Array(s),a.byteLength),c.buffer},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),o=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,o);case this.KINDS.reply:return this.decodeReply(t,e,o);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,o)}},decodePush(t,e,r){let o=e.getUint8(1),n=e.getUint8(2),s=e.getUint8(3),i=this.HEADER_LENGTH+this.META_LENGTH-1,a=r.decode(t.slice(i,i+o));i=i+o;let l=r.decode(t.slice(i,i+n));i=i+n;let u=r.decode(t.slice(i,i+s));i=i+s;let c=t.slice(i,t.byteLength);return{join_ref:a,ref:null,topic:l,event:u,payload:c}},decodeReply(t,e,r){let o=e.getUint8(1),n=e.getUint8(2),s=e.getUint8(3),i=e.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(t.slice(a,a+o));a=a+o;let u=r.decode(t.slice(a,a+n));a=a+n;let c=r.decode(t.slice(a,a+s));a=a+s;let d=r.decode(t.slice(a,a+i));a=a+i;let f=t.slice(a,t.byteLength),m={status:d,response:f};return{join_ref:l,ref:u,topic:c,event:or.reply,payload:m}},decodeBroadcast(t,e,r){let o=e.getUint8(1),n=e.getUint8(2),s=this.HEADER_LENGTH+2,i=r.decode(t.slice(s,s+o));s=s+o;let a=r.decode(t.slice(s,s+n));s=s+n;let l=t.slice(s,t.byteLength);return{join_ref:null,ref:null,topic:i,event:a,payload:l}}},ni=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||Fb,this.transport=e.transport||Dt.WebSocket||ko,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||Dt&&Dt.sessionStorage,this.establishedConnections=0,this.defaultEncoder=ti.encode.bind(ti),this.defaultDecoder=ti.decode.bind(ti),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==ko?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let r=null;To&&To.addEventListener&&(To.addEventListener("pagehide",o=>{this.conn&&(this.disconnect(),r=this.connectClock)}),To.addEventListener("pageshow",o=>{r===this.connectClock&&(r=null,this.connect())}),To.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=o=>e.rejoinAfterMs?e.rejoinAfterMs(o):[1e3,2e3,5e3][o-1]||1e4,this.reconnectAfterMs=o=>e.reconnectAfterMs?e.reconnectAfterMs(o):[10,50,100,150,200,250,500,1e3,2e3][o-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(o,n,s)=>{console.log(`${o}: ${n}`,s)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=In(e.params||{}),this.endPoint=`${t}/${Ml.websocket}`,this.vsn=e.vsn||Ub,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Zd(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken}getLongPollTransport(){return ko}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=ri.appendParams(ri.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,t&&t()},e,r)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=In(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==ko?this.connectWithFallback(ko,this.longPollFallbackMs):this.transportConnect())}log(t,e,r){this.logger&&this.logger(t,e,r)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let o=this.onMessage(n=>{n.ref===e&&(this.off([o]),t(Date.now()-r))});return!0}transportName(t){return t===ko?"LongPoll":t.name}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${Ul}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,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)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=!1,o=!0,n,s,i=this.transportName(t),a=l=>{this.log("transport",`falling back to ${i}...`,l),this.off([n,s]),o=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${i}`))return a("memorized");this.fallbackTimer=setTimeout(a,e),s=this.onError(l=>{this.log("transport","error",l),o&&!r&&(clearTimeout(this.fallbackTimer),a(l))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!o){let l=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(a,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),$b,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,r){if(!this.conn)return t&&t();let o=this.conn;this.waitForBufferDone(o,()=>{e?o.close(e,r||""):o.close(),this.waitForSocketClosed(o,()=>{this.conn===o&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1)},150*r)}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===Lt.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1)},150*r)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError()}triggerChanError(){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(or.error)})}connectionState(){switch(this.conn&&this.conn.readyState){case Lt.connecting:return"connecting";case Lt.open:return"open";case Lt.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1)}channel(t,e={}){let r=new qb(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:o,ref:n,join_ref:s}=t;this.log("push",`${e} ${r} (${s}, ${n})`,o)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:o,payload:n,ref:s,join_ref:i}=e;if(s&&s===this.pendingHeartbeatRef){let a=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(n.status==="ok"?"ok":"error",a)}catch(l){this.log("error","error in heartbeat callback",l)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${n.status||""} ${r} ${o} ${s&&"("+s+")"||""}`.trim(),n);for(let a=0;a<this.channels.length;a++){let l=this.channels[a];l.isMember(r,o,n,i)&&l.trigger(o,n,s,i)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,o])=>{try{o(...e)}catch(n){this.log("error",`error in ${t} callback`,n)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};var Dn=class t{constructor(e,r){let o=Hb(r);this.presence=new oi(e.getChannel(),o),this.presence.onJoin((n,s,i)=>{let a=t.onJoinPayload(n,s,i);e.getChannel().trigger("presence",a)}),this.presence.onLeave((n,s,i)=>{let a=t.onLeavePayload(n,s,i);e.getChannel().trigger("presence",a)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return t.transformState(this.presence.state)}static transformState(e){return e=Wb(e),Object.getOwnPropertyNames(e).reduce((r,o)=>{let n=e[o];return r[o]=si(n),r},{})}static onJoinPayload(e,r,o){let n=ef(r),s=si(o);return{event:"join",key:e,currentPresences:n,newPresences:s}}static onLeavePayload(e,r,o){let n=ef(r),s=si(o);return{event:"leave",key:e,currentPresences:n,leftPresences:s}}};function si(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function Wb(t){return JSON.parse(JSON.stringify(t))}function Hb(t){return t?.events&&{events:t.events}}function ef(t){return t?.metas?si(t):[]}var Fl;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(Fl||(Fl={}));var Co=class{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new Dn(this.channel.channelAdapter,r)}};var Ln=class{constructor(e,r,o){let n=zb(o);this.channel=e.getSocket().channel(r,n),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,r,o){let n;try{n=this.channel.push(e,r,o)}catch{throw`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>Xd){let s=this.channel.pushBuffer.shift();s.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${s.event}`,s.payload())}return n}updateJoinPayload(e){let r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===It.joined}isJoined(){return this.state===It.joined}isJoining(){return this.state===It.joining}isClosed(){return this.state===It.closed}isLeaving(){return this.state===It.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}};function zb(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var $l;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})($l||($l={}));var Eo;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(Eo||(Eo={}));var Nt;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(Nt||(Nt={}));var Po=class t{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},o){var n,s;if(this.topic=e,this.params=r,this.socket=o,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new Ln(this.socket.socketAdapter,e,this.params),this.presence=new Co(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=Zs(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((s=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||s===void 0)&&s.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var o,n,s;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:i,presence:a,private:l}}=this.params,u=(n=(o=this.bindings.postgres_changes)===null||o===void 0?void 0:o.map(m=>m.filter))!==null&&n!==void 0?n:[],c=!!this.bindings[Eo.PRESENCE]&&this.bindings[Eo.PRESENCE].length>0||((s=this.params.config.presence)===null||s===void 0?void 0:s.enabled)===!0,d={},f={broadcast:i,presence:Object.assign(Object.assign({},a),{enabled:c}),postgres_changes:u,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(m=>{e?.(Nt.CHANNEL_ERROR,m)}),this._onClose(()=>e?.(Nt.CLOSED)),this.updateJoinPayload(Object.assign({config:f},d)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:m})=>{if(this.socket._isManualToken()||this.socket.setAuth(),m===void 0){e?.(Nt.SUBSCRIBED);return}this._updatePostgresBindings(m,e)}).receive("error",m=>{this.state=It.errored,e?.(Nt.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(m).join(", ")||"error")))}).receive("timeout",()=>{e?.(Nt.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var o;let n=this.bindings.postgres_changes,s=(o=n?.length)!==null&&o!==void 0?o:0,i=[];for(let a=0;a<s;a++){let l=n[a],{filter:{event:u,schema:c,table:d,filter:f}}=l,m=e&&e[a];if(m&&m.event===u&&t.isFilterValueEqual(m.schema,c)&&t.isFilterValueEqual(m.table,d)&&t.isFilterValueEqual(m.filter,f))i.push(Object.assign(Object.assign({},l),{id:m.id}));else{this.unsubscribe(),this.state=It.errored,r?.(Nt.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=i,this.state!=It.errored&&r&&r(Nt.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,o){if(this.channelAdapter.isJoined()&&e===Eo.PRESENCE)throw this.socket.log("channel",`cannot add presence callbacks for ${this.topic} after joining.`),new Error("cannot add presence callbacks after joining a channel");return this._on(e,r,o)}async httpSend(e,r,o={}){var n;if(r==null)return Promise.reject("Payload is required for httpSend()");let s={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(s.Authorization=`Bearer ${this.socket.accessTokenValue}`);let i={method:"POST",headers:s,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,i,(n=o.timeout)!==null&&n!==void 0?n:this.timeout);if(a.status===202)return{success:!0};let l=a.statusText;try{let u=await a.json();l=u.error||u.message||l}catch{}return Promise.reject(new Error(l))}async send(e,r={}){var o,n;if(!this.channelAdapter.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:s,payload:i}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);let l={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:s,payload:i,private:this.private}]})};try{let u=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(o=r.timeout)!==null&&o!==void 0?o:this.timeout);return await((n=u.body)===null||n===void 0?void 0:n.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(s=>{var i,a,l;let u=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(i=this.params)===null||i===void 0?void 0:i.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&s("ok"),u.receive("ok",()=>s("ok")),u.receive("error",()=>s("error")),u.receive("timeout",()=>s("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,o){let n=new AbortController,s=setTimeout(()=>n.abort(),o),i=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(s),i}_on(e,r,o){let n=e.toLocaleLowerCase(),s=this.channelAdapter.on(e,o),i={type:n,filter:r,callback:o,ref:s};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,o)=>{var n,s,i,a,l,u,c;let d=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(d,o))return!1;let f=(n=this.bindings[d])===null||n===void 0?void 0:n.find(m=>m.ref===e.ref);if(!f)return!0;if(["broadcast","presence","postgres_changes"].includes(d))if("id"in f){let m=f.id,h=(s=f.filter)===null||s===void 0?void 0:s.event;return m&&((i=r.ids)===null||i===void 0?void 0:i.includes(m))&&(h==="*"||h?.toLocaleLowerCase()===((a=r.data)===null||a===void 0?void 0:a.type.toLocaleLowerCase()))}else{let m=(u=(l=f?.filter)===null||l===void 0?void 0:l.event)===null||u===void 0?void 0:u.toLocaleLowerCase();return m==="*"||m===((c=r?.event)===null||c===void 0?void 0:c.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===d})}_notThisChannelEvent(e,r){let{close:o,error:n,leave:s,join:i}=Qs;return r&&[o,n,s,i].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,o)=>{if(typeof r=="object"&&"ids"in r){let n=r.data,{schema:s,table:i,commit_timestamp:a,type:l,errors:u}=n;return Object.assign(Object.assign({},{schema:s,table:i,commit_timestamp:a,eventType:l,new:{},old:{},errors:u}),this._getPayloadRecords(n))}return r})}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_getPayloadRecords(e){let r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=jl(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=jl(e.columns,e.old_record)),r}};var Nn=class{constructor(e,r){this.socket=new ni(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,o,n=1e4){return new Promise(s=>{setTimeout(()=>s("timeout"),n),this.socket.disconnect(()=>{e(),s("ok")},r,o)})}push(e){this.socket.push(e)}log(e,r,o){this.socket.log(e,r,o)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==On.connecting}isDisconnecting(){return this.socket.connectionState()==On.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}};var Gb={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Kb=[1e3,2e3,5e3,1e4],Jb=1e4,Yb=`
|
|
11
11
|
addEventListener("message", (e) => {
|
|
12
12
|
if (e.data.event === "start") {
|
|
13
13
|
setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
|
|
14
14
|
}
|
|
15
|
-
});`,Oo=class{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,r){var o;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new An,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._resolveFetch=s=>s?(...i)=>s(...i):(...i)=>fetch(...i),!(!((o=r?.params)===null||o===void 0)&&o.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;let n=this._initializeOptions(r);this.socketAdapter=new Nn(e,n),this.httpEndpoint=
|
|
15
|
+
});`,Oo=class{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,r){var o;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new An,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._resolveFetch=s=>s?(...i)=>s(...i):(...i)=>fetch(...i),!(!((o=r?.params)===null||o===void 0)&&o.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;let n=this._initializeOptions(r);this.socketAdapter=new Nn(e,n),this.httpEndpoint=Zs(e),this.fetch=this._resolveFetch(r?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){let r=e.message;throw r.includes("Node.js")?new Error(`${r}
|
|
16
16
|
|
|
17
17
|
To use Realtime in Node.js, you need to provide a WebSocket implementation:
|
|
18
18
|
|
|
@@ -25,9 +25,9 @@ Option 2: Install and provide the "ws" package:
|
|
|
25
25
|
const client = new RealtimeClient(url, {
|
|
26
26
|
...options,
|
|
27
27
|
transport: ws
|
|
28
|
-
})`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){let r=await e.unsubscribe();return r==="ok"&&e.teardown(),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){let e=this.channels.map(async o=>{let n=await o.unsubscribe();return o.teardown(),n}),r=await Promise.all(e);return this.disconnect(),r}log(e,r,o){this.socketAdapter.log(e,r,o)}connectionState(){return this.socketAdapter.connectionState()||On.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){let o=`realtime:${e}`,n=this.getChannels().find(s=>s.topic===o);if(n)return n;{let s=new Po(`realtime:${e}`,r,this);return this.channels.push(s),s}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}async _performAuth(e=null){let r,o=!1;if(e)r=e,o=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(n){this.log("error","Error fetching access token from callback",n),r=this.accessTokenValue}else r=this.accessTokenValue;o?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{let s={access_token:r,version:Gd};r&&n.updateJoinPayload(s),n.joinedOnce&&n.channelAdapter.isJoined()&&n.channelAdapter.push(Ys.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,o)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,o)}}_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=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let r;if(e)r=e;else{let o=new Blob([Yb],{type:"application/javascript"});r=URL.createObjectURL(o)}return r}_initializeOptions(e){var r,o,n,s,i,a,l,u,c;this.worker=(r=e?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(o=e?.accessToken)!==null&&o!==void 0?o:null;let d={};d.timeout=(n=e?.timeout)!==null&&n!==void 0?n:Yd,d.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:Gb.HEARTBEAT_INTERVAL,d.transport=(i=e?.transport)!==null&&i!==void 0?i:Rl.getWebSocketConstructor(),d.params=e?.params,d.logger=e?.logger,d.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),d.reconnectAfterMs=(a=e?.reconnectAfterMs)!==null&&a!==void 0?a:(g=>Kb[g-1]||Jb);let f,m,h=(l=e?.vsn)!==null&&l!==void 0?l:Jd;switch(h){case Kd:f=(g,y)=>y(JSON.stringify(g)),m=(g,y)=>y(JSON.parse(g));break;case Il:f=this.serializer.encode.bind(this.serializer),m=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${d.vsn}`)}if(d.vsn=h,d.encode=(u=e?.encode)!==null&&u!==void 0?u:f,d.decode=(c=e?.decode)!==null&&c!==void 0?c:m,d.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,d.params=Object.assign(Object.assign({},d.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,d.autoSendHeartbeat=!this.worker}return d}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}};var jn=class extends Error{constructor(t,e){super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&e.icebergType?.includes("CommitState")===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function Xb(t,e,r){let o=new URL(e,t);if(r)for(let[n,s]of Object.entries(r))s!==void 0&&o.searchParams.set(n,s);return o.toString()}async function Qb(t){return!t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function Zb(t){let e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:o,query:n,body:s,headers:i}){let a=Xb(t.baseUrl,o,n),l=await Qb(t.auth),u=await e(a,{method:r,headers:{...s?{"Content-Type":"application/json"}:{},...l,...i},body:s?JSON.stringify(s):void 0}),c=await u.text(),d=(u.headers.get("content-type")||"").includes("application/json"),f=d&&c?JSON.parse(c):c;if(!u.ok){let m=d?f:void 0,h=m?.error;throw new jn(h?.message??`Request failed with status ${u.status}`,{status:u.status,icebergType:h?.type,icebergCode:h?.code,details:m})}return{status:u.status,headers:u.headers,data:f}}}}function ni(t){return t.join("")}var e_=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){let e=t?{parent:ni(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(o=>({namespace:o}))}async createNamespace(t,e){let r={namespace:t.namespace,properties:e?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${ni(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ni(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${ni(t.namespace)}`}),!0}catch(e){if(e instanceof jn&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof jn&&r.status===409)return;throw r}}};function Ao(t){return t.join("")}var t_=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r}async listTables(t){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Ao(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Ao(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Ao(t.namespace)}/tables/${t.name}`,body:e});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Ao(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String(e?.purge??!1)}})}async loadTable(t){let e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Ao(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){let e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Ao(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof jn&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof jn&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},si=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);let r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=Zb({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new e_(this.client,e),this.tableOps=new t_(this.client,e,this.accessDelegation)}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t)}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e)}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};var ii=class extends Error{constructor(t,e="storage",r,o){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=o}};function ai(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var Fl=class extends ii{constructor(t,e,r,o="storage"){super(t,o,e,r),this.name=o==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},nf=class extends ii{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};var r_=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),o_=t=>{if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},$l=t=>{if(Array.isArray(t))return t.map(r=>$l(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,o])=>{let n=r.replace(/([-_][a-z])/gi,s=>s.toUpperCase().replace(/[-_]/g,""));e[n]=$l(o)}),e},n_=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function Un(t){"@babel/helpers - typeof";return Un=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},Un(t)}function s_(t,e){if(Un(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(Un(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function i_(t){var e=s_(t,"string");return Un(e)=="symbol"?e:e+""}function a_(t,e,r){return(e=i_(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function tf(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function I(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?tf(Object(r),!0).forEach(function(o){a_(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):tf(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var rf=t=>{var e;return t.msg||t.message||t.error_description||(typeof t.error=="string"?t.error:(e=t.error)===null||e===void 0?void 0:e.message)||JSON.stringify(t)},l_=async(t,e,r,o)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){let n=t,s=parseInt(n.status,10);Number.isFinite(s)||(s=500),n.json().then(i=>{let a=i?.statusCode||i?.code||s+"";e(new Fl(rf(i),s,a,o))}).catch(()=>{let i=s+"";e(new Fl(n.statusText||`HTTP ${s} error`,s,i,o))})}else e(new nf(rf(t),t,o))},u_=(t,e,r,o)=>{let n={method:t,headers:e?.headers||{}};return t==="GET"||t==="HEAD"||!o?I(I({},n),r):(o_(o)?(n.headers=I({"Content-Type":"application/json"},e?.headers),n.body=JSON.stringify(o)):n.body=o,e?.duplex&&(n.duplex=e.duplex),I(I({},n),r))};async function Mn(t,e,r,o,n,s,i){return new Promise((a,l)=>{t(r,u_(e,o,n,s)).then(u=>{if(!u.ok)throw u;if(o?.noResolveJson)return u;if(i==="vectors"){let c=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!c||!c.includes("application/json"))return{}}return u.json()}).then(u=>a(u)).catch(u=>l_(u,l,o,i))})}function sf(t="storage"){return{get:async(e,r,o,n)=>Mn(e,"GET",r,o,n,void 0,t),post:async(e,r,o,n,s)=>Mn(e,"POST",r,n,s,o,t),put:async(e,r,o,n,s)=>Mn(e,"PUT",r,n,s,o,t),head:async(e,r,o,n)=>Mn(e,"HEAD",r,I(I({},o),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,o,n,s)=>Mn(e,"DELETE",r,n,s,o,t)}}var c_=sf("storage"),{get:Fn,post:wt,put:Bl,head:d_,remove:ql}=c_,Ye=sf("vectors"),Ro=class{constructor(t,e={},r,o="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=r_(r),this.namespace=o}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=I(I({},this.headers),{},{[t]:e}),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(ai(r))return{data:null,error:r};throw r}}},f_=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ai(e))return{data:null,error:e};throw e}}},af;af=Symbol.toStringTag;var m_=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[af]="BlobDownloadBuilder",this.promise=null}asStream(){return new f_(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ai(e))return{data:null,error:e};throw e}}},h_={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},of={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},p_=class extends Ro{constructor(t,e={},r,o){super(t,e,o,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,o){var n=this;return n.handleOperation(async()=>{let s,i=I(I({},of),o),a=I(I({},n.headers),t==="POST"&&{"x-upsert":String(i.upsert)}),l=i.metadata;typeof Blob<"u"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",i.cacheControl),l&&s.append("metadata",n.encodeMetadata(l)),s.append("",r)):typeof FormData<"u"&&r instanceof FormData?(s=r,s.has("cacheControl")||s.append("cacheControl",i.cacheControl),l&&!s.has("metadata")&&s.append("metadata",n.encodeMetadata(l))):(s=r,a["cache-control"]=`max-age=${i.cacheControl}`,a["content-type"]=i.contentType,l&&(a["x-metadata"]=n.toBase64(n.encodeMetadata(l))),(typeof ReadableStream<"u"&&s instanceof ReadableStream||s&&typeof s=="object"&&"pipe"in s&&typeof s.pipe=="function")&&!i.duplex&&(i.duplex="half")),o?.headers&&(a=I(I({},a),o.headers));let u=n._removeEmptyFolders(e),c=n._getFinalPath(u),d=await(t=="PUT"?Bl:wt)(n.fetch,`${n.url}/object/${c}`,s,I({headers:a},i?.duplex?{duplex:i.duplex}:{}));return{path:u,id:d.Id,fullPath:d.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,o){var n=this;let s=n._removeEmptyFolders(t),i=n._getFinalPath(s),a=new URL(n.url+`/object/upload/sign/${i}`);return a.searchParams.set("token",e),n.handleOperation(async()=>{let l,u=I(I({},of),o),c=I(I({},n.headers),{"x-upsert":String(u.upsert)});return typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",u.cacheControl)):(l=r,c["cache-control"]=`max-age=${u.cacheControl}`,c["content-type"]=u.contentType),{path:s,fullPath:(await Bl(n.fetch,a.toString(),l,{headers:c})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let o=r._getFinalPath(t),n=I({},r.headers);e?.upsert&&(n["x-upsert"]="true");let s=await wt(r.fetch,`${r.url}/object/upload/sign/${o}`,{},{headers:n}),i=new URL(r.url+s.url),a=i.searchParams.get("token");if(!a)throw new ii("No token returned by API");return{signedUrl:i.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var o=this;return o.handleOperation(async()=>await wt(o.fetch,`${o.url}/object/move`,{bucketId:o.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:o.headers}))}async copy(t,e,r){var o=this;return o.handleOperation(async()=>({path:(await wt(o.fetch,`${o.url}/object/copy`,{bucketId:o.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:o.headers})).Key}))}async createSignedUrl(t,e,r){var o=this;return o.handleOperation(async()=>{let n=o._getFinalPath(t),s=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0,i=await wt(o.fetch,`${o.url}/object/sign/${n}`,I({expiresIn:e},s?{transform:r.transform}:{}),{headers:o.headers}),a=r?.download?`&download=${r.download===!0?"":r.download}`:"",l=s&&i.signedURL.includes("/object/sign/")?i.signedURL.replace("/object/sign/","/render/image/sign/"):i.signedURL;return{signedUrl:encodeURI(`${o.url}${l}${a}`)}})}async createSignedUrls(t,e,r){var o=this;return o.handleOperation(async()=>{let n=await wt(o.fetch,`${o.url}/object/sign/${o.bucketId}`,{expiresIn:e,paths:t},{headers:o.headers}),s=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n.map(i=>I(I({},i),{},{signedUrl:i.signedURL?encodeURI(`${o.url}${i.signedURL}${s}`):null}))})}download(t,e,r){let o=typeof e?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(e?.transform||{}),s=n?`?${n}`:"",i=this._getFinalPath(t),a=()=>Fn(this.fetch,`${this.url}/${o}/${i}${s}`,{headers:this.headers,noResolveJson:!0},r);return new m_(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>$l(await Fn(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await d_(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(ai(n)){var o;let s=n instanceof Fl?n.status:n instanceof nf?(o=n.originalError)===null||o===void 0?void 0:o.status:void 0;if(s!==void 0&&[400,404].includes(s))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){let r=this._getFinalPath(t),o=[],n=e?.download?`download=${e.download===!0?"":e.download}`:"";n!==""&&o.push(n);let s=typeof e?.transform<"u"?"render/image":"object",i=this.transformOptsToQueryString(e?.transform||{});i!==""&&o.push(i);let a=o.join("&");return a!==""&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${s}/public/${r}${a}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await ql(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var o=this;return o.handleOperation(async()=>{let n=I(I(I({},h_),e),{},{prefix:t||""});return await wt(o.fetch,`${o.url}/object/list/${o.bucketId}`,n,{headers:o.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let o=I({},t);return await wt(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,o,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){let e=[];return t.width&&e.push(`width=${t.width}`),t.height&&e.push(`height=${t.height}`),t.resize&&e.push(`resize=${t.resize}`),t.format&&e.push(`format=${t.format}`),t.quality&&e.push(`quality=${t.quality}`),e.join("&")}},g_="2.100.1",$n={"X-Client-Info":`storage-js/${g_}`},y_=class extends Ro{constructor(t,e={},r,o){let n=new URL(t);o?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));let s=n.href.replace(/\/$/,""),i=I(I({},$n),e);super(s,i,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await Fn(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Fn(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await wt(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await Bl(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await wt(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await ql(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){let e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},b_=class extends Ro{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=I(I({},$n),e);super(o,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await wt(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);let o=r.toString(),n=o?`${e.url}/bucket?${o}`:`${e.url}/bucket`;return await Fn(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await ql(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!n_(t))throw new ii("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let r=new si({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),o=this.shouldThrowOnError;return new Proxy(r,{get(n,s){let i=n[s];return typeof i!="function"?i:async(...a)=>{try{return{data:await i.apply(n,a),error:null}}catch(l){if(o)throw l;return{data:null,error:l}}}}})}},__=class extends Ro{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=I(I({},$n),{},{"Content-Type":"application/json"},e);super(o,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await Ye.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await Ye.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},w_=class extends Ro{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=I(I({},$n),{},{"Content-Type":"application/json"},e);super(o,n,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},v_=class extends Ro{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=I(I({},$n),{},{"Content-Type":"application/json"},e);super(o,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},S_=class extends v_{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new x_(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},x_=class extends __{constructor(t,e,r,o){super(t,e,o),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new k_(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},k_=class extends w_{constructor(t,e,r,o,n){super(t,e,n),this.vectorBucketName=r,this.indexName=o}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},lf=class extends y_{constructor(t,e={},r,o){super(t,e,r,o)}from(t){return new p_(this.url,this.headers,t,this.fetch)}get vectors(){return new S_(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new b_(this.url+"/iceberg",this.headers,this.fetch)}};var li="2.100.1";var jr=30*1e3,ui=3,ci=ui*jr,uf="http://localhost:9999",cf="supabase.auth.token";var df={"X-Client-Info":`gotrue-js/${li}`};var Bn="X-Supabase-Api-Version",Vl={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},ff=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,mf=600*1e3;var gr=class extends Error{constructor(e,r,o){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=o}};function k(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}var di=class extends gr{constructor(e,r,o){super(e,r,o),this.name="AuthApiError",this.status=r,this.code=o}};function hf(t){return k(t)&&t.name==="AuthApiError"}var at=class extends gr{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}},vt=class extends gr{constructor(e,r,o,n){super(e,o,n),this.name=r,this.status=o}},Ne=class extends vt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function mi(t){return k(t)&&t.name==="AuthSessionMissingError"}var nr=class extends vt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Mr=class extends vt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Ur=class extends vt{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};function pf(t){return k(t)&&t.name==="AuthImplicitGrantRedirectError"}var qn=class extends vt{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},fi=class extends vt{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")}};var Io=class extends vt{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}};function hi(t){return k(t)&&t.name==="AuthRetryableFetchError"}var Vn=class extends vt{constructor(e,r,o){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=o}};var Fr=class extends vt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};var pi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),gf=`
|
|
29
|
-
\r=`.split(""),T_=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<gf.length;e+=1)t[gf[e].charCodeAt(0)]=-2;for(let e=0;e<pi.length;e+=1)t[pi[e].charCodeAt(0)]=e;return t})();function yf(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){let o=e.queue>>e.queuedBits-6&63;r(pi[o]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let o=e.queue>>e.queuedBits-6&63;r(pi[o]),e.queuedBits-=6}}function bf(t,e,r){let o=T_[t];if(o>-1)for(e.queue=e.queue<<6|o,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(o===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function Wl(t){let e=[],r=i=>{e.push(String.fromCodePoint(i))},o={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},s=i=>{P_(i,o,r)};for(let i=0;i<t.length;i+=1)bf(t.charCodeAt(i),n,s);return e.join("")}function C_(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function E_(t,e){for(let r=0;r<t.length;r+=1){let o=t.charCodeAt(r);if(o>55295&&o<=56319){let n=(o-55296)*1024&65535;o=(t.charCodeAt(r+1)-56320&65535|n)+65536,r+=1}C_(o,e)}}function P_(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let o=1;o<6;o+=1)if((t>>7-o&1)===0){e.utf8seq=o;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function yr(t){let e=[],r={queue:0,queuedBits:0},o=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)bf(t.charCodeAt(n),r,o);return new Uint8Array(e)}function _f(t){let e=[];return E_(t,r=>e.push(r)),new Uint8Array(e)}function sr(t){let e=[],r={queue:0,queuedBits:0},o=n=>{e.push(n)};return t.forEach(n=>yf(n,r,o)),yf(null,r,o),e.join("")}function wf(t){return Math.round(Date.now()/1e3)+t}function vf(){return Symbol("auth-callback")}var ke=()=>typeof window<"u"&&typeof document<"u",$r={tested:!1,writable:!1},gi=()=>{if(!ke())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if($r.tested)return $r.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),$r.tested=!0,$r.writable=!0}catch{$r.tested=!0,$r.writable=!1}return $r.writable};function Sf(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((n,s)=>{e[s]=n})}catch{}return r.searchParams.forEach((o,n)=>{e[n]=o}),e}var yi=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),xf=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Br=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},br=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},Pe=async(t,e)=>{await t.removeItem(e)},Wn=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}};Wn.promiseConstructor=Promise;function Hn(t){let e=t.split(".");if(e.length!==3)throw new Fr("Invalid JWT structure");for(let o=0;o<e.length;o++)if(!ff.test(e[o]))throw new Fr("JWT not in base64url format");return{header:JSON.parse(Wl(e[0])),payload:JSON.parse(Wl(e[1])),signature:yr(e[2]),raw:{header:e[0],payload:e[1]}}}async function kf(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function Tf(t,e){return new Promise((o,n)=>{(async()=>{for(let s=0;s<1/0;s++)try{let i=await t(s);if(!e(s,null,i)){o(i);return}}catch(i){if(!e(s,i)){n(i);return}}})()})}function O_(t){return("0"+t.toString(16)).substr(-2)}function A_(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",o=r.length,n="";for(let s=0;s<56;s++)n+=r.charAt(Math.floor(Math.random()*o));return n}return crypto.getRandomValues(e),Array.from(e,O_).join("")}async function R_(t){let r=new TextEncoder().encode(t),o=await crypto.subtle.digest("SHA-256",r),n=new Uint8Array(o);return Array.from(n).map(s=>String.fromCharCode(s)).join("")}async function I_(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;let r=await R_(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function qr(t,e,r=!1){let o=A_(),n=o;r&&(n+="/PASSWORD_RECOVERY"),await Br(t,`${e}-code-verifier`,n);let s=await I_(o);return[s,o===s?"plain":"s256"]}var D_=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Cf(t){let e=t.headers.get(Bn);if(!e||!e.match(D_))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Ef(t){if(!t)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function Pf(t){switch(t){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var L_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Vr(t){if(!L_.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function bi(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){let o=r.toString();if(o==="Symbol(Symbol.toPrimitive)"||o==="Symbol(Symbol.toStringTag)"||o==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Of(t,e){return new Proxy(t,{get:(r,o,n)=>{if(o==="__isInsecureUserWarningProxy")return!0;if(typeof o=="symbol"){let s=o.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)"||s==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,o,n)}return!e.value&&typeof o=="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."),e.value=!0),Reflect.get(r,o,n)}})}function Hl(t){return JSON.parse(JSON.stringify(t))}var Wr=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),N_=[502,503,504];async function Af(t){var e;if(!xf(t))throw new Io(Wr(t),0);if(N_.includes(t.status))throw new Io(Wr(t),t.status);let r;try{r=await t.json()}catch(s){throw new at(Wr(s),s)}let o,n=Cf(t);if(n&&n.getTime()>=Vl["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?o=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(o=r.error_code),o){if(o==="weak_password")throw new Vn(Wr(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(o==="session_not_found")throw new Ne}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((s,i)=>s&&typeof i=="string",!0))throw new Vn(Wr(r),t.status,r.weak_password.reasons);throw new di(Wr(r),t.status||500,o)}var j_=(t,e,r,o)=>{let n={method:t,headers:e?.headers||{}};return t==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),n.body=JSON.stringify(o),Object.assign(Object.assign({},n),r))};async function O(t,e,r,o){var n;let s=Object.assign({},o?.headers);s[Bn]||(s[Bn]=Vl["2024-01-01"].name),o?.jwt&&(s.Authorization=`Bearer ${o.jwt}`);let i=(n=o?.query)!==null&&n!==void 0?n:{};o?.redirectTo&&(i.redirect_to=o.redirectTo);let a=Object.keys(i).length?"?"+new URLSearchParams(i).toString():"",l=await M_(t,e,r+a,{headers:s,noResolveJson:o?.noResolveJson},{},o?.body);return o?.xform?o?.xform(l):{data:Object.assign({},l),error:null}}async function M_(t,e,r,o,n,s){let i=j_(e,o,n,s),a;try{a=await t(r,Object.assign({},i))}catch(l){throw console.error(l),new Io(Wr(l),0)}if(a.ok||await Af(a),o?.noResolveJson)return a;try{return await a.json()}catch(l){await Af(l)}}function lt(t){var e;let r=null;U_(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=wf(t.expires_in)));let o=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:o},error:null}}function zl(t){let e=lt(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,o)=>r&&typeof o=="string",!0)&&(e.data.weak_password=t.weak_password),e}function jt(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Rf(t){return{data:t,error:null}}function If(t){let{action_link:e,email_otp:r,hashed_token:o,redirect_to:n,verification_type:s}=t,i=We(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:o,redirect_to:n,verification_type:s},l=Object.assign({},i);return{data:{properties:a,user:l},error:null}}function Gl(t){return t}function U_(t){return t.access_token&&t.refresh_token&&t.expires_in}var _i=["global","local","others"];var Hr=class{constructor({url:e="",headers:r={},fetch:o}){this.url=e,this.headers=r,this.fetch=yi(o),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,r=_i[0]){if(_i.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${_i.join(", ")}`);try{return await O(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(o){if(k(o))return{data:null,error:o};throw o}}async inviteUserByEmail(e,r={}){try{return await O(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:jt})}catch(o){if(k(o))return{data:{user:null},error:o};throw o}}async generateLink(e){try{let{options:r}=e,o=We(e,["options"]),n=Object.assign(Object.assign({},o),r);return"newEmail"in o&&(n.new_email=o?.newEmail,delete n.newEmail),await O(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:If,redirectTo:r?.redirectTo})}catch(r){if(k(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await O(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:jt})}catch(r){if(k(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,o,n,s,i,a,l;try{let u={nextPage:null,lastPage:0,total:0},c=await O(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(o=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&o!==void 0?o:"",per_page:(s=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:""},xform:Gl});if(c.error)throw c.error;let d=await c.json(),f=(i=c.headers.get("x-total-count"))!==null&&i!==void 0?i:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(h=>{let g=parseInt(h.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(h.split(";")[1].split("=")[1]);u[`${y}Page`]=g}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(k(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){Vr(e);try{return await O(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:jt})}catch(r){if(k(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){Vr(e);try{return await O(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:jt})}catch(o){if(k(o))return{data:{user:null},error:o};throw o}}async deleteUser(e,r=!1){Vr(e);try{return await O(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:jt})}catch(o){if(k(o))return{data:{user:null},error:o};throw o}}async _listFactors(e){Vr(e.userId);try{let{data:r,error:o}=await O(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:r,error:o}}catch(r){if(k(r))return{data:null,error:r};throw r}}async _deleteFactor(e){Vr(e.userId),Vr(e.id);try{return{data:await O(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,o,n,s,i,a,l;try{let u={nextPage:null,lastPage:0,total:0},c=await O(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(o=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&o!==void 0?o:"",per_page:(s=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:""},xform:Gl});if(c.error)throw c.error;let d=await c.json(),f=(i=c.headers.get("x-total-count"))!==null&&i!==void 0?i:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(h=>{let g=parseInt(h.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(h.split(";")[1].split("=")[1]);u[`${y}Page`]=g}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(k(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await O(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(k(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await O(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(k(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await O(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:o=>({data:o,error:null})})}catch(o){if(k(o))return{data:null,error:o};throw o}}async _deleteOAuthClient(e){try{return await O(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await O(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(k(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{let r={};return e?.type&&(r.type=e.type),await O(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:o=>{var n;return{data:{providers:(n=o?.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(k(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await O(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(k(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await O(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(k(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await O(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:o=>({data:o,error:null})})}catch(o){if(k(o))return{data:null,error:o};throw o}}async _deleteCustomProvider(e){try{return await O(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}}};function Kl(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}var St={debug:!!(globalThis&&gi()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Do=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},zn=class extends Do{},Jl=class extends Do{};async function Yl(t,e,r){St.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);let o=new globalThis.AbortController,n;e>0&&(n=setTimeout(()=>{o.abort(),St.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:o.signal},async s=>{if(s){clearTimeout(n),St.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,s.name);try{return await r()}finally{St.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,s.name)}}else{if(e===0)throw St.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new zn(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(St.debug)try{let i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}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(n),await r()}})}catch(s){if(e>0&&clearTimeout(n),s?.name==="AbortError"&&e>0){if(o.signal.aborted)return St.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}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(t,{mode:"exclusive",steal:!0},async i=>{if(i){St.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,i.name);try{return await r()}finally{St.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,i.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw St.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new zn(`Lock "${t}" was released because another request stole it`)}throw s}}var Df={};async function Xl(t,e,r){var o;let n=(o=Df[t])!==null&&o!==void 0?o:Promise.resolve(),s=(async()=>{try{return await n,null}catch{return null}})(),i=(async()=>{let a=null;try{let l=e>=0?new Promise((u,c)=>{a=setTimeout(()=>{console.warn(`@supabase/gotrue-js: Lock "${t}" acquisition timed out after ${e}ms. This may be caused by another operation holding the lock. Consider increasing lockAcquireTimeout or checking for stuck operations.`),c(new Jl(`Acquiring process lock with name "${t}" timed out`))},e)}):null;await Promise.race([s,l].filter(u=>u)),a!==null&&clearTimeout(a)}catch(l){if(a!==null&&clearTimeout(a),l&&l.isAcquireTimeout)throw l}return await r()})();return Df[t]=(async()=>{try{return await i}catch(a){if(a&&a.isAcquireTimeout){try{await n}catch{}return null}throw a}})(),await i}function Lf(){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 Ql(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function Nf(t){return parseInt(t,16)}function jf(t){let e=new TextEncoder().encode(t);return"0x"+Array.from(e,o=>o.toString(16).padStart(2,"0")).join("")}function Mf(t){var e;let{chainId:r,domain:o,expirationTime:n,issuedAt:s=new Date,nonce:i,notBefore:a,requestId:l,resources:u,scheme:c,uri:d,version:f}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!o)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(i&&i.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${i}`);if(!d)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(f!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${f}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
|
|
30
|
-
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}let m=
|
|
28
|
+
})`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){let r=await e.unsubscribe();return r==="ok"&&e.teardown(),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){let e=this.channels.map(async o=>{let n=await o.unsubscribe();return o.teardown(),n}),r=await Promise.all(e);return this.disconnect(),r}log(e,r,o){this.socketAdapter.log(e,r,o)}connectionState(){return this.socketAdapter.connectionState()||On.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){let o=`realtime:${e}`,n=this.getChannels().find(s=>s.topic===o);if(n)return n;{let s=new Po(`realtime:${e}`,r,this);return this.channels.push(s),s}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}async _performAuth(e=null){let r,o=!1;if(e)r=e,o=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(n){this.log("error","Error fetching access token from callback",n),r=this.accessTokenValue}else r=this.accessTokenValue;o?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{let s={access_token:r,version:Gd};r&&n.updateJoinPayload(s),n.joinedOnce&&n.channelAdapter.isJoined()&&n.channelAdapter.push(Qs.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,o)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,o)}}_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=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let r;if(e)r=e;else{let o=new Blob([Yb],{type:"application/javascript"});r=URL.createObjectURL(o)}return r}_initializeOptions(e){var r,o,n,s,i,a,l,u,c;this.worker=(r=e?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(o=e?.accessToken)!==null&&o!==void 0?o:null;let d={};d.timeout=(n=e?.timeout)!==null&&n!==void 0?n:Yd,d.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:Gb.HEARTBEAT_INTERVAL,d.transport=(i=e?.transport)!==null&&i!==void 0?i:Dl.getWebSocketConstructor(),d.params=e?.params,d.logger=e?.logger,d.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),d.reconnectAfterMs=(a=e?.reconnectAfterMs)!==null&&a!==void 0?a:(g=>Kb[g-1]||Jb);let f,m,h=(l=e?.vsn)!==null&&l!==void 0?l:Jd;switch(h){case Kd:f=(g,y)=>y(JSON.stringify(g)),m=(g,y)=>y(JSON.parse(g));break;case Ll:f=this.serializer.encode.bind(this.serializer),m=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${d.vsn}`)}if(d.vsn=h,d.encode=(u=e?.encode)!==null&&u!==void 0?u:f,d.decode=(c=e?.decode)!==null&&c!==void 0?c:m,d.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,d.params=Object.assign(Object.assign({},d.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,d.autoSendHeartbeat=!this.worker}return d}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}};var jn=class extends Error{constructor(t,e){super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&e.icebergType?.includes("CommitState")===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function Xb(t,e,r){let o=new URL(e,t);if(r)for(let[n,s]of Object.entries(r))s!==void 0&&o.searchParams.set(n,s);return o.toString()}async function Qb(t){return!t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function Zb(t){let e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:o,query:n,body:s,headers:i}){let a=Xb(t.baseUrl,o,n),l=await Qb(t.auth),u=await e(a,{method:r,headers:{...s?{"Content-Type":"application/json"}:{},...l,...i},body:s?JSON.stringify(s):void 0}),c=await u.text(),d=(u.headers.get("content-type")||"").includes("application/json"),f=d&&c?JSON.parse(c):c;if(!u.ok){let m=d?f:void 0,h=m?.error;throw new jn(h?.message??`Request failed with status ${u.status}`,{status:u.status,icebergType:h?.type,icebergCode:h?.code,details:m})}return{status:u.status,headers:u.headers,data:f}}}}function ii(t){return t.join("")}var e_=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){let e=t?{parent:ii(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(o=>({namespace:o}))}async createNamespace(t,e){let r={namespace:t.namespace,properties:e?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${ii(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ii(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${ii(t.namespace)}`}),!0}catch(e){if(e instanceof jn&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof jn&&r.status===409)return;throw r}}};function Ao(t){return t.join("")}var t_=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r}async listTables(t){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Ao(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Ao(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Ao(t.namespace)}/tables/${t.name}`,body:e});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Ao(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String(e?.purge??!1)}})}async loadTable(t){let e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Ao(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){let e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Ao(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof jn&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof jn&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},ai=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);let r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=Zb({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new e_(this.client,e),this.tableOps=new t_(this.client,e,this.accessDelegation)}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t)}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e)}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};var li=class extends Error{constructor(t,e="storage",r,o){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=o}};function ui(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var Bl=class extends li{constructor(t,e,r,o="storage"){super(t,o,e,r),this.name=o==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},nf=class extends li{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};var r_=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),o_=t=>{if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},ql=t=>{if(Array.isArray(t))return t.map(r=>ql(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,o])=>{let n=r.replace(/([-_][a-z])/gi,s=>s.toUpperCase().replace(/[-_]/g,""));e[n]=ql(o)}),e},n_=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function Un(t){"@babel/helpers - typeof";return Un=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},Un(t)}function s_(t,e){if(Un(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(Un(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function i_(t){var e=s_(t,"string");return Un(e)=="symbol"?e:e+""}function a_(t,e,r){return(e=i_(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function tf(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function I(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?tf(Object(r),!0).forEach(function(o){a_(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):tf(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var rf=t=>{var e;return t.msg||t.message||t.error_description||(typeof t.error=="string"?t.error:(e=t.error)===null||e===void 0?void 0:e.message)||JSON.stringify(t)},l_=async(t,e,r,o)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){let n=t,s=parseInt(n.status,10);Number.isFinite(s)||(s=500),n.json().then(i=>{let a=i?.statusCode||i?.code||s+"";e(new Bl(rf(i),s,a,o))}).catch(()=>{let i=s+"";e(new Bl(n.statusText||`HTTP ${s} error`,s,i,o))})}else e(new nf(rf(t),t,o))},u_=(t,e,r,o)=>{let n={method:t,headers:e?.headers||{}};return t==="GET"||t==="HEAD"||!o?I(I({},n),r):(o_(o)?(n.headers=I({"Content-Type":"application/json"},e?.headers),n.body=JSON.stringify(o)):n.body=o,e?.duplex&&(n.duplex=e.duplex),I(I({},n),r))};async function Mn(t,e,r,o,n,s,i){return new Promise((a,l)=>{t(r,u_(e,o,n,s)).then(u=>{if(!u.ok)throw u;if(o?.noResolveJson)return u;if(i==="vectors"){let c=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!c||!c.includes("application/json"))return{}}return u.json()}).then(u=>a(u)).catch(u=>l_(u,l,o,i))})}function sf(t="storage"){return{get:async(e,r,o,n)=>Mn(e,"GET",r,o,n,void 0,t),post:async(e,r,o,n,s)=>Mn(e,"POST",r,n,s,o,t),put:async(e,r,o,n,s)=>Mn(e,"PUT",r,n,s,o,t),head:async(e,r,o,n)=>Mn(e,"HEAD",r,I(I({},o),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,o,n,s)=>Mn(e,"DELETE",r,n,s,o,t)}}var c_=sf("storage"),{get:Fn,post:wt,put:Vl,head:d_,remove:Wl}=c_,Ye=sf("vectors"),Ro=class{constructor(t,e={},r,o="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=r_(r),this.namespace=o}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=I(I({},this.headers),{},{[t]:e}),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(ui(r))return{data:null,error:r};throw r}}},f_=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ui(e))return{data:null,error:e};throw e}}},af;af=Symbol.toStringTag;var m_=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[af]="BlobDownloadBuilder",this.promise=null}asStream(){return new f_(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ui(e))return{data:null,error:e};throw e}}},h_={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},of={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},p_=class extends Ro{constructor(t,e={},r,o){super(t,e,o,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,o){var n=this;return n.handleOperation(async()=>{let s,i=I(I({},of),o),a=I(I({},n.headers),t==="POST"&&{"x-upsert":String(i.upsert)}),l=i.metadata;typeof Blob<"u"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",i.cacheControl),l&&s.append("metadata",n.encodeMetadata(l)),s.append("",r)):typeof FormData<"u"&&r instanceof FormData?(s=r,s.has("cacheControl")||s.append("cacheControl",i.cacheControl),l&&!s.has("metadata")&&s.append("metadata",n.encodeMetadata(l))):(s=r,a["cache-control"]=`max-age=${i.cacheControl}`,a["content-type"]=i.contentType,l&&(a["x-metadata"]=n.toBase64(n.encodeMetadata(l))),(typeof ReadableStream<"u"&&s instanceof ReadableStream||s&&typeof s=="object"&&"pipe"in s&&typeof s.pipe=="function")&&!i.duplex&&(i.duplex="half")),o?.headers&&(a=I(I({},a),o.headers));let u=n._removeEmptyFolders(e),c=n._getFinalPath(u),d=await(t=="PUT"?Vl:wt)(n.fetch,`${n.url}/object/${c}`,s,I({headers:a},i?.duplex?{duplex:i.duplex}:{}));return{path:u,id:d.Id,fullPath:d.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,o){var n=this;let s=n._removeEmptyFolders(t),i=n._getFinalPath(s),a=new URL(n.url+`/object/upload/sign/${i}`);return a.searchParams.set("token",e),n.handleOperation(async()=>{let l,u=I(I({},of),o),c=I(I({},n.headers),{"x-upsert":String(u.upsert)});return typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",u.cacheControl)):(l=r,c["cache-control"]=`max-age=${u.cacheControl}`,c["content-type"]=u.contentType),{path:s,fullPath:(await Vl(n.fetch,a.toString(),l,{headers:c})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let o=r._getFinalPath(t),n=I({},r.headers);e?.upsert&&(n["x-upsert"]="true");let s=await wt(r.fetch,`${r.url}/object/upload/sign/${o}`,{},{headers:n}),i=new URL(r.url+s.url),a=i.searchParams.get("token");if(!a)throw new li("No token returned by API");return{signedUrl:i.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var o=this;return o.handleOperation(async()=>await wt(o.fetch,`${o.url}/object/move`,{bucketId:o.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:o.headers}))}async copy(t,e,r){var o=this;return o.handleOperation(async()=>({path:(await wt(o.fetch,`${o.url}/object/copy`,{bucketId:o.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:o.headers})).Key}))}async createSignedUrl(t,e,r){var o=this;return o.handleOperation(async()=>{let n=o._getFinalPath(t),s=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0,i=await wt(o.fetch,`${o.url}/object/sign/${n}`,I({expiresIn:e},s?{transform:r.transform}:{}),{headers:o.headers}),a=r?.download?`&download=${r.download===!0?"":r.download}`:"",l=s&&i.signedURL.includes("/object/sign/")?i.signedURL.replace("/object/sign/","/render/image/sign/"):i.signedURL;return{signedUrl:encodeURI(`${o.url}${l}${a}`)}})}async createSignedUrls(t,e,r){var o=this;return o.handleOperation(async()=>{let n=await wt(o.fetch,`${o.url}/object/sign/${o.bucketId}`,{expiresIn:e,paths:t},{headers:o.headers}),s=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n.map(i=>I(I({},i),{},{signedUrl:i.signedURL?encodeURI(`${o.url}${i.signedURL}${s}`):null}))})}download(t,e,r){let o=typeof e?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(e?.transform||{}),s=n?`?${n}`:"",i=this._getFinalPath(t),a=()=>Fn(this.fetch,`${this.url}/${o}/${i}${s}`,{headers:this.headers,noResolveJson:!0},r);return new m_(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>ql(await Fn(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await d_(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(ui(n)){var o;let s=n instanceof Bl?n.status:n instanceof nf?(o=n.originalError)===null||o===void 0?void 0:o.status:void 0;if(s!==void 0&&[400,404].includes(s))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){let r=this._getFinalPath(t),o=[],n=e?.download?`download=${e.download===!0?"":e.download}`:"";n!==""&&o.push(n);let s=typeof e?.transform<"u"?"render/image":"object",i=this.transformOptsToQueryString(e?.transform||{});i!==""&&o.push(i);let a=o.join("&");return a!==""&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${s}/public/${r}${a}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await Wl(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var o=this;return o.handleOperation(async()=>{let n=I(I(I({},h_),e),{},{prefix:t||""});return await wt(o.fetch,`${o.url}/object/list/${o.bucketId}`,n,{headers:o.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let o=I({},t);return await wt(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,o,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){let e=[];return t.width&&e.push(`width=${t.width}`),t.height&&e.push(`height=${t.height}`),t.resize&&e.push(`resize=${t.resize}`),t.format&&e.push(`format=${t.format}`),t.quality&&e.push(`quality=${t.quality}`),e.join("&")}},g_="2.100.1",$n={"X-Client-Info":`storage-js/${g_}`},y_=class extends Ro{constructor(t,e={},r,o){let n=new URL(t);o?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));let s=n.href.replace(/\/$/,""),i=I(I({},$n),e);super(s,i,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await Fn(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Fn(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await wt(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await Vl(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await wt(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Wl(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){let e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},b_=class extends Ro{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=I(I({},$n),e);super(o,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await wt(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);let o=r.toString(),n=o?`${e.url}/bucket?${o}`:`${e.url}/bucket`;return await Fn(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Wl(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!n_(t))throw new li("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let r=new ai({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),o=this.shouldThrowOnError;return new Proxy(r,{get(n,s){let i=n[s];return typeof i!="function"?i:async(...a)=>{try{return{data:await i.apply(n,a),error:null}}catch(l){if(o)throw l;return{data:null,error:l}}}}})}},__=class extends Ro{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=I(I({},$n),{},{"Content-Type":"application/json"},e);super(o,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await Ye.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await Ye.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},w_=class extends Ro{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=I(I({},$n),{},{"Content-Type":"application/json"},e);super(o,n,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},v_=class extends Ro{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=I(I({},$n),{},{"Content-Type":"application/json"},e);super(o,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Ye.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},S_=class extends v_{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new x_(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},x_=class extends __{constructor(t,e,r,o){super(t,e,o),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new k_(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},k_=class extends w_{constructor(t,e,r,o,n){super(t,e,n),this.vectorBucketName=r,this.indexName=o}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,I(I({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},lf=class extends y_{constructor(t,e={},r,o){super(t,e,r,o)}from(t){return new p_(this.url,this.headers,t,this.fetch)}get vectors(){return new S_(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new b_(this.url+"/iceberg",this.headers,this.fetch)}};var ci="2.100.1";var jr=30*1e3,di=3,fi=di*jr,uf="http://localhost:9999",cf="supabase.auth.token";var df={"X-Client-Info":`gotrue-js/${ci}`};var Bn="X-Supabase-Api-Version",Hl={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},ff=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,mf=600*1e3;var gr=class extends Error{constructor(e,r,o){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=o}};function k(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}var mi=class extends gr{constructor(e,r,o){super(e,r,o),this.name="AuthApiError",this.status=r,this.code=o}};function hf(t){return k(t)&&t.name==="AuthApiError"}var at=class extends gr{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}},vt=class extends gr{constructor(e,r,o,n){super(e,o,n),this.name=r,this.status=o}},Ne=class extends vt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function pi(t){return k(t)&&t.name==="AuthSessionMissingError"}var nr=class extends vt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Mr=class extends vt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Ur=class extends vt{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};function pf(t){return k(t)&&t.name==="AuthImplicitGrantRedirectError"}var qn=class extends vt{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},hi=class extends vt{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")}};var Io=class extends vt{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}};function gi(t){return k(t)&&t.name==="AuthRetryableFetchError"}var Vn=class extends vt{constructor(e,r,o){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=o}};var Fr=class extends vt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};var yi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),gf=`
|
|
29
|
+
\r=`.split(""),T_=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<gf.length;e+=1)t[gf[e].charCodeAt(0)]=-2;for(let e=0;e<yi.length;e+=1)t[yi[e].charCodeAt(0)]=e;return t})();function yf(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){let o=e.queue>>e.queuedBits-6&63;r(yi[o]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let o=e.queue>>e.queuedBits-6&63;r(yi[o]),e.queuedBits-=6}}function bf(t,e,r){let o=T_[t];if(o>-1)for(e.queue=e.queue<<6|o,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(o===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function zl(t){let e=[],r=i=>{e.push(String.fromCodePoint(i))},o={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},s=i=>{P_(i,o,r)};for(let i=0;i<t.length;i+=1)bf(t.charCodeAt(i),n,s);return e.join("")}function C_(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function E_(t,e){for(let r=0;r<t.length;r+=1){let o=t.charCodeAt(r);if(o>55295&&o<=56319){let n=(o-55296)*1024&65535;o=(t.charCodeAt(r+1)-56320&65535|n)+65536,r+=1}C_(o,e)}}function P_(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let o=1;o<6;o+=1)if((t>>7-o&1)===0){e.utf8seq=o;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function yr(t){let e=[],r={queue:0,queuedBits:0},o=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)bf(t.charCodeAt(n),r,o);return new Uint8Array(e)}function _f(t){let e=[];return E_(t,r=>e.push(r)),new Uint8Array(e)}function sr(t){let e=[],r={queue:0,queuedBits:0},o=n=>{e.push(n)};return t.forEach(n=>yf(n,r,o)),yf(null,r,o),e.join("")}function wf(t){return Math.round(Date.now()/1e3)+t}function vf(){return Symbol("auth-callback")}var ke=()=>typeof window<"u"&&typeof document<"u",$r={tested:!1,writable:!1},bi=()=>{if(!ke())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if($r.tested)return $r.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),$r.tested=!0,$r.writable=!0}catch{$r.tested=!0,$r.writable=!1}return $r.writable};function Sf(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((n,s)=>{e[s]=n})}catch{}return r.searchParams.forEach((o,n)=>{e[n]=o}),e}var _i=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),xf=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Br=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},br=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},Pe=async(t,e)=>{await t.removeItem(e)},Wn=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}};Wn.promiseConstructor=Promise;function Hn(t){let e=t.split(".");if(e.length!==3)throw new Fr("Invalid JWT structure");for(let o=0;o<e.length;o++)if(!ff.test(e[o]))throw new Fr("JWT not in base64url format");return{header:JSON.parse(zl(e[0])),payload:JSON.parse(zl(e[1])),signature:yr(e[2]),raw:{header:e[0],payload:e[1]}}}async function kf(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function Tf(t,e){return new Promise((o,n)=>{(async()=>{for(let s=0;s<1/0;s++)try{let i=await t(s);if(!e(s,null,i)){o(i);return}}catch(i){if(!e(s,i)){n(i);return}}})()})}function O_(t){return("0"+t.toString(16)).substr(-2)}function A_(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",o=r.length,n="";for(let s=0;s<56;s++)n+=r.charAt(Math.floor(Math.random()*o));return n}return crypto.getRandomValues(e),Array.from(e,O_).join("")}async function R_(t){let r=new TextEncoder().encode(t),o=await crypto.subtle.digest("SHA-256",r),n=new Uint8Array(o);return Array.from(n).map(s=>String.fromCharCode(s)).join("")}async function I_(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;let r=await R_(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function qr(t,e,r=!1){let o=A_(),n=o;r&&(n+="/PASSWORD_RECOVERY"),await Br(t,`${e}-code-verifier`,n);let s=await I_(o);return[s,o===s?"plain":"s256"]}var D_=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Cf(t){let e=t.headers.get(Bn);if(!e||!e.match(D_))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Ef(t){if(!t)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function Pf(t){switch(t){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var L_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Vr(t){if(!L_.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function wi(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){let o=r.toString();if(o==="Symbol(Symbol.toPrimitive)"||o==="Symbol(Symbol.toStringTag)"||o==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Of(t,e){return new Proxy(t,{get:(r,o,n)=>{if(o==="__isInsecureUserWarningProxy")return!0;if(typeof o=="symbol"){let s=o.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)"||s==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,o,n)}return!e.value&&typeof o=="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."),e.value=!0),Reflect.get(r,o,n)}})}function Gl(t){return JSON.parse(JSON.stringify(t))}var Wr=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),N_=[502,503,504];async function Af(t){var e;if(!xf(t))throw new Io(Wr(t),0);if(N_.includes(t.status))throw new Io(Wr(t),t.status);let r;try{r=await t.json()}catch(s){throw new at(Wr(s),s)}let o,n=Cf(t);if(n&&n.getTime()>=Hl["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?o=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(o=r.error_code),o){if(o==="weak_password")throw new Vn(Wr(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(o==="session_not_found")throw new Ne}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((s,i)=>s&&typeof i=="string",!0))throw new Vn(Wr(r),t.status,r.weak_password.reasons);throw new mi(Wr(r),t.status||500,o)}var j_=(t,e,r,o)=>{let n={method:t,headers:e?.headers||{}};return t==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),n.body=JSON.stringify(o),Object.assign(Object.assign({},n),r))};async function O(t,e,r,o){var n;let s=Object.assign({},o?.headers);s[Bn]||(s[Bn]=Hl["2024-01-01"].name),o?.jwt&&(s.Authorization=`Bearer ${o.jwt}`);let i=(n=o?.query)!==null&&n!==void 0?n:{};o?.redirectTo&&(i.redirect_to=o.redirectTo);let a=Object.keys(i).length?"?"+new URLSearchParams(i).toString():"",l=await M_(t,e,r+a,{headers:s,noResolveJson:o?.noResolveJson},{},o?.body);return o?.xform?o?.xform(l):{data:Object.assign({},l),error:null}}async function M_(t,e,r,o,n,s){let i=j_(e,o,n,s),a;try{a=await t(r,Object.assign({},i))}catch(l){throw console.error(l),new Io(Wr(l),0)}if(a.ok||await Af(a),o?.noResolveJson)return a;try{return await a.json()}catch(l){await Af(l)}}function lt(t){var e;let r=null;U_(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=wf(t.expires_in)));let o=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:o},error:null}}function Kl(t){let e=lt(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,o)=>r&&typeof o=="string",!0)&&(e.data.weak_password=t.weak_password),e}function jt(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Rf(t){return{data:t,error:null}}function If(t){let{action_link:e,email_otp:r,hashed_token:o,redirect_to:n,verification_type:s}=t,i=We(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:o,redirect_to:n,verification_type:s},l=Object.assign({},i);return{data:{properties:a,user:l},error:null}}function Jl(t){return t}function U_(t){return t.access_token&&t.refresh_token&&t.expires_in}var vi=["global","local","others"];var Hr=class{constructor({url:e="",headers:r={},fetch:o}){this.url=e,this.headers=r,this.fetch=_i(o),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,r=vi[0]){if(vi.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${vi.join(", ")}`);try{return await O(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(o){if(k(o))return{data:null,error:o};throw o}}async inviteUserByEmail(e,r={}){try{return await O(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:jt})}catch(o){if(k(o))return{data:{user:null},error:o};throw o}}async generateLink(e){try{let{options:r}=e,o=We(e,["options"]),n=Object.assign(Object.assign({},o),r);return"newEmail"in o&&(n.new_email=o?.newEmail,delete n.newEmail),await O(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:If,redirectTo:r?.redirectTo})}catch(r){if(k(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await O(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:jt})}catch(r){if(k(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,o,n,s,i,a,l;try{let u={nextPage:null,lastPage:0,total:0},c=await O(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(o=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&o!==void 0?o:"",per_page:(s=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:""},xform:Jl});if(c.error)throw c.error;let d=await c.json(),f=(i=c.headers.get("x-total-count"))!==null&&i!==void 0?i:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(h=>{let g=parseInt(h.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(h.split(";")[1].split("=")[1]);u[`${y}Page`]=g}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(k(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){Vr(e);try{return await O(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:jt})}catch(r){if(k(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){Vr(e);try{return await O(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:jt})}catch(o){if(k(o))return{data:{user:null},error:o};throw o}}async deleteUser(e,r=!1){Vr(e);try{return await O(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:jt})}catch(o){if(k(o))return{data:{user:null},error:o};throw o}}async _listFactors(e){Vr(e.userId);try{let{data:r,error:o}=await O(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:r,error:o}}catch(r){if(k(r))return{data:null,error:r};throw r}}async _deleteFactor(e){Vr(e.userId),Vr(e.id);try{return{data:await O(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,o,n,s,i,a,l;try{let u={nextPage:null,lastPage:0,total:0},c=await O(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(o=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&o!==void 0?o:"",per_page:(s=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:""},xform:Jl});if(c.error)throw c.error;let d=await c.json(),f=(i=c.headers.get("x-total-count"))!==null&&i!==void 0?i:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(h=>{let g=parseInt(h.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(h.split(";")[1].split("=")[1]);u[`${y}Page`]=g}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(k(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await O(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(k(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await O(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(k(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await O(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:o=>({data:o,error:null})})}catch(o){if(k(o))return{data:null,error:o};throw o}}async _deleteOAuthClient(e){try{return await O(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await O(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(k(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{let r={};return e?.type&&(r.type=e.type),await O(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:o=>{var n;return{data:{providers:(n=o?.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(k(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await O(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(k(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await O(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(k(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await O(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:o=>({data:o,error:null})})}catch(o){if(k(o))return{data:null,error:o};throw o}}async _deleteCustomProvider(e){try{return await O(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(k(r))return{data:null,error:r};throw r}}};function Yl(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}var St={debug:!!(globalThis&&bi()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Do=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},zn=class extends Do{},Xl=class extends Do{};async function Ql(t,e,r){St.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);let o=new globalThis.AbortController,n;e>0&&(n=setTimeout(()=>{o.abort(),St.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:o.signal},async s=>{if(s){clearTimeout(n),St.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,s.name);try{return await r()}finally{St.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,s.name)}}else{if(e===0)throw St.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new zn(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(St.debug)try{let i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}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(n),await r()}})}catch(s){if(e>0&&clearTimeout(n),s?.name==="AbortError"&&e>0){if(o.signal.aborted)return St.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}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(t,{mode:"exclusive",steal:!0},async i=>{if(i){St.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,i.name);try{return await r()}finally{St.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,i.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw St.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new zn(`Lock "${t}" was released because another request stole it`)}throw s}}var Df={};async function Zl(t,e,r){var o;let n=(o=Df[t])!==null&&o!==void 0?o:Promise.resolve(),s=(async()=>{try{return await n,null}catch{return null}})(),i=(async()=>{let a=null;try{let l=e>=0?new Promise((u,c)=>{a=setTimeout(()=>{console.warn(`@supabase/gotrue-js: Lock "${t}" acquisition timed out after ${e}ms. This may be caused by another operation holding the lock. Consider increasing lockAcquireTimeout or checking for stuck operations.`),c(new Xl(`Acquiring process lock with name "${t}" timed out`))},e)}):null;await Promise.race([s,l].filter(u=>u)),a!==null&&clearTimeout(a)}catch(l){if(a!==null&&clearTimeout(a),l&&l.isAcquireTimeout)throw l}return await r()})();return Df[t]=(async()=>{try{return await i}catch(a){if(a&&a.isAcquireTimeout){try{await n}catch{}return null}throw a}})(),await i}function Lf(){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 eu(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function Nf(t){return parseInt(t,16)}function jf(t){let e=new TextEncoder().encode(t);return"0x"+Array.from(e,o=>o.toString(16).padStart(2,"0")).join("")}function Mf(t){var e;let{chainId:r,domain:o,expirationTime:n,issuedAt:s=new Date,nonce:i,notBefore:a,requestId:l,resources:u,scheme:c,uri:d,version:f}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!o)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(i&&i.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${i}`);if(!d)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(f!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${f}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
|
|
30
|
+
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}let m=eu(t.address),h=c?`${c}://${o}`:o,g=t.statement?`${t.statement}
|
|
31
31
|
`:"",y=`${h} wants you to sign in with your Ethereum account:
|
|
32
32
|
${m}
|
|
33
33
|
|
|
@@ -41,20 +41,20 @@ Not Before: ${a.toISOString()}`),l&&(p+=`
|
|
|
41
41
|
Request ID: ${l}`),u){let b=`
|
|
42
42
|
Resources:`;for(let _ of u){if(!_||typeof _!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${_}`);b+=`
|
|
43
43
|
- ${_}`}p+=b}return`${y}
|
|
44
|
-
${p}`}var le=class extends Error{constructor({message:e,code:r,cause:o,name:n}){var s;super(e,{cause:o}),this.__isWebAuthnError=!0,this.name=(s=n??(o instanceof Error?o.name:void 0))!==null&&s!==void 0?s:"Unknown Error",this.code=r}},zr=class extends le{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}};function Uf({error:t,options:e}){var r,o,n;let{publicKey:s}=e;if(!s)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new le({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=s.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new le({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((o=s.authenticatorSelection)===null||o===void 0?void 0:o.userVerification)==="required")return new le({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((n=s.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new le({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new le({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new le({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return s.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new le({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new le({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){let i=window.location.hostname;if(Zl(i)){if(s.rp.id!==i)return new le({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new le({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(s.user.id.byteLength<1||s.user.id.byteLength>64)return new le({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new le({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new le({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Ff({error:t,options:e}){let{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new le({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new le({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if(Zl(o)){if(r.rpId!==o)return new le({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new le({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new le({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new le({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}var eu=class{createNewAbortSignal(){if(this.controller){let r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},F_=new eu;function Bf(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);let{challenge:e,user:r,excludeCredentials:o}=t,n=We(t,["challenge","user","excludeCredentials"]),s=yr(e).buffer,i=Object.assign(Object.assign({},r),{id:yr(r.id).buffer}),a=Object.assign(Object.assign({},n),{challenge:s,user:i});if(o&&o.length>0){a.excludeCredentials=new Array(o.length);for(let l=0;l<o.length;l++){let u=o[l];a.excludeCredentials[l]=Object.assign(Object.assign({},u),{id:yr(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return a}function qf(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);let{challenge:e,allowCredentials:r}=t,o=We(t,["challenge","allowCredentials"]),n=yr(e).buffer,s=Object.assign(Object.assign({},o),{challenge:n});if(r&&r.length>0){s.allowCredentials=new Array(r.length);for(let i=0;i<r.length;i++){let a=r[i];s.allowCredentials[i]=Object.assign(Object.assign({},a),{id:yr(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return s}function Vf(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t;return{id:t.id,rawId:t.id,response:{attestationObject:sr(new Uint8Array(t.response.attestationObject)),clientDataJSON:sr(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Wf(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,o=t.getClientExtensionResults(),n=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:sr(new Uint8Array(n.authenticatorData)),clientDataJSON:sr(new Uint8Array(n.clientDataJSON)),signature:sr(new Uint8Array(n.signature)),userHandle:n.userHandle?sr(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:o,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Zl(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function $f(){var t,e;return!!(ke()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function $_(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new zr("Browser returned unexpected credential type",e)}:{data:null,error:new zr("Empty credential response",e)}}catch(e){return{data:null,error:Uf({error:e,options:t})}}}async function B_(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new zr("Browser returned unexpected credential type",e)}:{data:null,error:new zr("Empty credential response",e)}}catch(e){return{data:null,error:Ff({error:e,options:t})}}}var q_={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},V_={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function wi(...t){let e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),o={};for(let n of t)if(n)for(let s in n){let i=n[s];if(i!==void 0)if(Array.isArray(i))o[s]=i;else if(r(i))o[s]=i;else if(e(i)){let a=o[s];e(a)?o[s]=wi(a,i):o[s]=wi(i)}else o[s]=i}return o}function W_(t,e){return wi(q_,t,e||{})}function H_(t,e){return wi(V_,t,e||{})}var vi=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:r,friendlyName:o,signal:n},s){var i;try{let{data:a,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:l};let u=n??F_.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:c}=a.webauthn.credential_options.publicKey;if(!c.name){let d=o;if(d)c.name=`${c.id}:${d}`;else{let m=(await this.client.getUser()).data.user,h=((i=m?.user_metadata)===null||i===void 0?void 0:i.name)||m?.email||m?.id||"User";c.name=`${c.id}:${h}`}}c.displayName||(c.displayName=c.name)}switch(a.webauthn.type){case"create":{let c=W_(a.webauthn.credential_options.publicKey,s?.create),{data:d,error:f}=await $_({publicKey:c,signal:u});return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:f}}case"request":{let c=H_(a.webauthn.credential_options.publicKey,s?.request),{data:d,error:f}=await B_(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:c,signal:u}));return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:f}}}}catch(a){return k(a)?{data:null,error:a}:{data:null,error:new at("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:o}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:o})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:o=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},s){if(!r)return{data:null,error:new gr("rpId is required for WebAuthn authentication")};try{if(!$f())return{data:null,error:new at("Browser does not support WebAuthn",null)};let{data:i,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:o},signal:n},{request:s});if(!i)return{data:null,error:a};let{webauthn:l}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:o,credential_response:l.credential_response}})}catch(i){return k(i)?{data:null,error:i}:{data:null,error:new at("Unexpected error in authenticate",i)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:o=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},s){if(!r)return{data:null,error:new gr("rpId is required for WebAuthn registration")};try{if(!$f())return{data:null,error:new at("Browser does not support WebAuthn",null)};let{data:i,error:a}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then(c=>{var d;return(d=c.data)===null||d===void 0?void 0:d.all.find(f=>f.factor_type==="webauthn"&&f.friendly_name===e&&f.status!=="unverified")}).then(c=>c?this.client.mfa.unenroll({factorId:c?.id}):void 0),{data:null,error:a};let{data:l,error:u}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:r,rpOrigins:o},signal:n},{create:s});return l?this._verify({factorId:i.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:o,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:u}}catch(i){return k(i)?{data:null,error:i}:{data:null,error:new at("Unexpected error in register",i)}}}};Lf();var z_={url:uf,storageKey:cf,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:df,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function Hf(t,e,r){return await r()}var Lo={},Si=class t{get jwks(){var e,r;return(r=(e=Lo[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Lo[this.storageKey]=Object.assign(Object.assign({},Lo[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Lo[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Lo[this.storageKey]=Object.assign(Object.assign({},Lo[this.storageKey]),{cachedAt:e})}constructor(e){var r,o,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 s=Object.assign(Object.assign({},z_),e);if(this.storageKey=s.storageKey,this.instanceID=(r=t.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,t.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.instanceID>0&&ke()){let i=`${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(i),this.logDebugMessages&&console.trace(i)}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.admin=new Hr({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=yi(s.fetch),this.lock=s.lock||Hf,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,this.lockAcquireTimeout=s.lockAcquireTimeout,s.lock?this.lock=s.lock:this.persistSession&&ke()&&(!((o=globalThis?.navigator)===null||o===void 0)&&o.locks)?this.lock=Yl:this.lock=Hf,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new vi(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?(s.storage?this.storage=s.storage:gi()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Kl(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=Kl(this.memoryStorage)),ke()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i);try{await this._notifyAllSubscribers(i.data.event,i.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}s.skipAutoInitialize||this.initialize().catch(i=>{this._debug("#initialize()","error",i)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${li}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},o="none";if(ke()&&(r=Sf(window.location.href),this._isImplicitGrantCallback(r)?o="implicit":await this._isPKCECallback(r)&&(o="pkce")),ke()&&this.detectSessionInUrl&&o!=="none"){let{data:n,error:s}=await this._getSessionFromURL(r,o);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),pf(s)){let l=(e=s.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:s}}return{error:s}}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(r){return k(r)?this._returnResult({error:r}):this._returnResult({error:new at("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,o,n;try{let s=await O(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(o=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&o!==void 0?o:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:lt}),{data:i,error:a}=s;if(a||!i)return this._returnResult({data:{user:null,session:null},error:a});let l=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(k(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signUp(e){var r,o,n;try{let s;if("email"in e){let{email:c,password:d,options:f}=e,m=null,h=null;this.flowType==="pkce"&&([m,h]=await qr(this.storage,this.storageKey)),s=await O(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:c,password:d,data:(r=f?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:m,code_challenge_method:h},xform:lt})}else if("phone"in e){let{phone:c,password:d,options:f}=e;s=await O(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:d,data:(o=f?.data)!==null&&o!==void 0?o:{},channel:(n=f?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:lt})}else throw new Mr("You must provide either an email or phone number and a password");let{data:i,error:a}=s;if(a||!i)return await Pe(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let l=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(await Pe(this.storage,`${this.storageKey}-code-verifier`),k(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithPassword(e){try{let r;if("email"in e){let{email:s,password:i,options:a}=e;r=await O(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:i,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:zl})}else if("phone"in e){let{phone:s,password:i,options:a}=e;r=await O(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:i,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:zl})}else throw new Mr("You must provide either an email or phone number and a password");let{data:o,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!o||!o.session||!o.user){let s=new nr;return this._returnResult({data:{user:null,session:null},error:s})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),this._returnResult({data:Object.assign({user:o.user,session:o.session},o.weak_password?{weakPassword:o.weak_password}:null),error:n})}catch(r){if(k(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,o,n,s;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(s=e.options)===null||s===void 0?void 0:s.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,o,n,s,i,a,l,u,c,d,f;let m,h;if("message"in e)m=e.message,h=e.signature;else{let{chain:g,wallet:y,statement:p,options:b}=e,_;if(ke())if(typeof y=="object")_=y;else{let q=window;if("ethereum"in q&&typeof q.ethereum=="object"&&"request"in q.ethereum&&typeof q.ethereum.request=="function")_=q.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof y!="object"||!b?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=y}let v=new URL((r=b?.url)!==null&&r!==void 0?r:window.location.href),N=await _.request({method:"eth_requestAccounts"}).then(q=>q).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!N||N.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let x=Ql(N[0]),P=(o=b?.signInWithEthereum)===null||o===void 0?void 0:o.chainId;if(!P){let q=await _.request({method:"eth_chainId"});P=Nf(q)}let Z={domain:v.host,address:x,statement:p,uri:v.href,version:"1",chainId:P,nonce:(n=b?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(i=(s=b?.signInWithEthereum)===null||s===void 0?void 0:s.issuedAt)!==null&&i!==void 0?i:new Date,expirationTime:(a=b?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=b?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=b?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(c=b?.signInWithEthereum)===null||c===void 0?void 0:c.resources};m=Mf(Z),h=await _.request({method:"personal_sign",params:[jf(m),x]})}try{let{data:g,error:y}=await O(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:m,signature:h},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:lt});if(y)throw y;if(!g||!g.session||!g.user){let p=new nr;return this._returnResult({data:{user:null,session:null},error:p})}return g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),this._returnResult({data:Object.assign({},g),error:y})}catch(g){if(k(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async signInWithSolana(e){var r,o,n,s,i,a,l,u,c,d,f,m;let h,g;if("message"in e)h=e.message,g=e.signature;else{let{chain:y,wallet:p,statement:b,options:_}=e,v;if(ke())if(typeof p=="object")v=p;else{let x=window;if("solana"in x&&typeof x.solana=="object"&&("signIn"in x.solana&&typeof x.solana.signIn=="function"||"signMessage"in x.solana&&typeof x.solana.signMessage=="function"))v=x.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof p!="object"||!_?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");v=p}let N=new URL((r=_?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in v&&v.signIn){let x=await v.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},_?.signInWithSolana),{version:"1",domain:N.host,uri:N.href}),b?{statement:b}:null)),P;if(Array.isArray(x)&&x[0]&&typeof x[0]=="object")P=x[0];else if(x&&typeof x=="object"&&"signedMessage"in x&&"signature"in x)P=x;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in P&&"signature"in P&&(typeof P.signedMessage=="string"||P.signedMessage instanceof Uint8Array)&&P.signature instanceof Uint8Array)h=typeof P.signedMessage=="string"?P.signedMessage:new TextDecoder().decode(P.signedMessage),g=P.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in v)||typeof v.signMessage!="function"||!("publicKey"in v)||typeof v!="object"||!v.publicKey||!("toBase58"in v.publicKey)||typeof v.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");h=[`${N.host} wants you to sign in with your Solana account:`,v.publicKey.toBase58(),...b?["",b,""]:[""],"Version: 1",`URI: ${N.href}`,`Issued At: ${(n=(o=_?.signInWithSolana)===null||o===void 0?void 0:o.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((s=_?.signInWithSolana)===null||s===void 0)&&s.notBefore?[`Not Before: ${_.signInWithSolana.notBefore}`]:[],...!((i=_?.signInWithSolana)===null||i===void 0)&&i.expirationTime?[`Expiration Time: ${_.signInWithSolana.expirationTime}`]:[],...!((a=_?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${_.signInWithSolana.chainId}`]:[],...!((l=_?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${_.signInWithSolana.nonce}`]:[],...!((u=_?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${_.signInWithSolana.requestId}`]:[],...!((d=(c=_?.signInWithSolana)===null||c===void 0?void 0:c.resources)===null||d===void 0)&&d.length?["Resources",..._.signInWithSolana.resources.map(P=>`- ${P}`)]:[]].join(`
|
|
45
|
-
`);let x=await v.signMessage(new TextEncoder().encode(h),"utf8");if(!x||!(x instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=x}}try{let{data:y,error:p}=await O(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:h,signature:sr(g)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(m=e.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:lt});if(p)throw p;if(!y||!y.session||!y.user){let b=new nr;return this._returnResult({data:{user:null,session:null},error:b})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:p})}catch(y){if(k(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async _exchangeCodeForSession(e){let r=await br(this.storage,`${this.storageKey}-code-verifier`),[o,n]=(r??"").split("/");try{if(!o&&this.flowType==="pkce")throw new fi;let{data:s,error:i}=await O(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:o},xform:lt});if(await Pe(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!s||!s.session||!s.user){let a=new nr;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign(Object.assign({},s),{redirectType:n??null}),error:i})}catch(s){if(await Pe(this.storage,`${this.storageKey}-code-verifier`),k(s))return this._returnResult({data:{user:null,session:null,redirectType:null},error:s});throw s}}async signInWithIdToken(e){try{let{options:r,provider:o,token:n,access_token:s,nonce:i}=e,a=await O(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:o,id_token:n,access_token:s,nonce:i,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:lt}),{data:l,error:u}=a;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){let c=new nr;return this._returnResult({data:{user:null,session:null},error:c})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:u})}catch(r){if(k(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,o,n,s,i;try{if("email"in e){let{email:a,options:l}=e,u=null,c=null;this.flowType==="pkce"&&([u,c]=await qr(this.storage,this.storageKey));let{error:d}=await O(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(o=l?.shouldCreateUser)!==null&&o!==void 0?o:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:u,code_challenge_method:c},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){let{phone:a,options:l}=e,{data:u,error:c}=await O(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(n=l?.data)!==null&&n!==void 0?n:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(i=l?.channel)!==null&&i!==void 0?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u?.message_id},error:c})}throw new Mr("You must provide either an email or phone number.")}catch(a){if(await Pe(this.storage,`${this.storageKey}-code-verifier`),k(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,o;try{let n,s;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,s=(o=e.options)===null||o===void 0?void 0:o.captchaToken);let{data:i,error:a}=await O(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:s}}),redirectTo:n,xform:lt});if(a)throw a;if(!i)throw new Error("An error occurred on token verification.");let l=i.session,u=i.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(n){if(k(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,o,n,s,i;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await qr(this.storage,this.storageKey));let u=await O(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:(o=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&o!==void 0?o:void 0}),!((n=e?.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:l}),headers:this.headers,xform:Rf});return!((s=u.data)===null||s===void 0)&&s.url&&ke()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(a){if(await Pe(this.storage,`${this.storageKey}-code-verifier`),k(a))return this._returnResult({data:null,error:a});throw a}}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:r},error:o}=e;if(o)throw o;if(!r)throw new Ne;let{error:n}=await O(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(k(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let r=`${this.url}/resend`;if("email"in e){let{email:o,type:n,options:s}=e,{error:i}=await O(this.fetch,"POST",r,{headers:this.headers,body:{email:o,type:n,gotrue_meta_security:{captcha_token:s?.captchaToken}},redirectTo:s?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}else if("phone"in e){let{phone:o,type:n,options:s}=e,{data:i,error:a}=await O(this.fetch,"POST",r,{headers:this.headers,body:{phone:o,type:n,gotrue_meta_security:{captcha_token:s?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:i?.message_id},error:a})}throw new Mr("You must provide either an email or phone number and a type")}catch(r){if(k(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let o=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await o,await r()))();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 o=r();for(this.pendingInLock.push((async()=>{try{await o}catch{}})()),await o;this.pendingInLock.length;){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await o}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,r=await br(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let o=e.expires_at?e.expires_at*1e3-Date.now()<ci:!1;if(this._debug("#__loadSession()",`session has${o?"":" not"} expired`,"expires_at",e.expires_at),!o){if(this.userStorage){let i=await br(this.userStorage,this.storageKey+"-user");i?.user?e.user=i.user:e.user=bi()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let i={value:this.suppressGetSessionWarning};e.user=Of(e.user,i),i.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{session:null},error:s}):this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await O(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:jt}):await this._useSession(async r=>{var o,n,s;let{data:i,error:a}=r;if(a)throw a;return!(!((o=i.session)===null||o===void 0)&&o.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Ne}:await O(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(s=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0,xform:jt})})}catch(r){if(k(r))return mi(r)&&(await this._removeSession(),await Pe(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async o=>{let{data:n,error:s}=o;if(s)throw s;if(!n.session)throw new Ne;let i=n.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await qr(this.storage,this.storageKey));let{data:u,error:c}=await O(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:i.access_token,xform:jt});if(c)throw c;return i.user=u.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})})}catch(o){if(await Pe(this.storage,`${this.storageKey}-code-verifier`),k(o))return this._returnResult({data:{user:null},error:o});throw o}}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 Ne;let r=Date.now()/1e3,o=r,n=!0,s=null,{payload:i}=Hn(e.access_token);if(i.exp&&(o=i.exp,n=o<=r),n){let{data:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a)return{data:{user:null,session:null},error:null};s=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});s={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:o-r,expires_at:o},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)}return this._returnResult({data:{user:s.user,session:s},error:null})}catch(r){if(k(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}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 r=>{var o;if(!e){let{data:i,error:a}=r;if(a)throw a;e=(o=i.session)!==null&&o!==void 0?o:void 0}if(!e?.refresh_token)throw new Ne;let{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(k(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!ke())throw new Ur("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Ur(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new qn("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ur("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new qn("No code detected.");let{data:b,error:_}=await this._exchangeCodeForSession(e.code);if(_)throw _;let v=new URL(window.location.href);return v.searchParams.delete("code"),window.history.replaceState(window.history.state,"",v.toString()),{data:{session:b.session,redirectType:null},error:null}}let{provider_token:o,provider_refresh_token:n,access_token:s,refresh_token:i,expires_in:a,expires_at:l,token_type:u}=e;if(!s||!a||!i||!u)throw new Ur("No session defined in URL");let c=Math.round(Date.now()/1e3),d=parseInt(a),f=c+d;l&&(f=parseInt(l));let m=f-c;m*1e3<=jr&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${d}s`);let h=f-d;c-h>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",h,f,c):c-h<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",h,f,c);let{data:g,error:y}=await this._getUser(s);if(y)throw y;let p={provider_token:o,provider_refresh_token:n,access_token:s,expires_in:d,expires_at:f,refresh_token:i,token_type:u,user:g.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:p,redirectType:e.type},error:null})}catch(o){if(k(o))return this._returnResult({data:{session:null,redirectType:null},error:o});throw o}}_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 r=await br(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}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 r=>{var o;let{data:n,error:s}=r;if(s&&!mi(s))return this._returnResult({error:s});let i=(o=n.session)===null||o===void 0?void 0:o.access_token;if(i){let{error:a}=await this.admin.signOut(i,e);if(a&&!(hf(a)&&(a.status===404||a.status===401||a.status===403)||mi(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await Pe(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=vf(),o={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,o),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:o}}}async _emitInitialSession(e){return await this._useSession(async r=>{var o,n;try{let{data:{session:s},error:i}=r;if(i)throw i;await((o=this.stateChangeEmitters.get(e))===null||o===void 0?void 0:o.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(s){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",s),console.error(s)}})}async resetPasswordForEmail(e,r={}){let o=null,n=null;this.flowType==="pkce"&&([o,n]=await qr(this.storage,this.storageKey,!0));try{return await O(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:o,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(s){if(await Pe(this.storage,`${this.storageKey}-code-verifier`),k(s))return this._returnResult({data:null,error:s});throw s}}async getUserIdentities(){var e;try{let{data:r,error:o}=await this.getUser();if(o)throw o;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{let{data:o,error:n}=await this._useSession(async s=>{var i,a,l,u,c;let{data:d,error:f}=s;if(f)throw f;let m=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(i=e.options)===null||i===void 0?void 0:i.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await O(this.fetch,"GET",m,{headers:this.headers,jwt:(c=(u=d.session)===null||u===void 0?void 0:u.access_token)!==null&&c!==void 0?c:void 0})});if(n)throw n;return ke()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(o?.url),this._returnResult({data:{provider:e.provider,url:o?.url},error:null})}catch(o){if(k(o))return this._returnResult({data:{provider:e.provider,url:null},error:o});throw o}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var o;try{let{error:n,data:{session:s}}=r;if(n)throw n;let{options:i,provider:a,token:l,access_token:u,nonce:c}=e,d=await O(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(o=s?.access_token)!==null&&o!==void 0?o:void 0,body:{provider:a,id_token:l,access_token:u,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:lt}),{data:f,error:m}=d;return m?this._returnResult({data:{user:null,session:null},error:m}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new nr}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:m}))}catch(n){if(await Pe(this.storage,`${this.storageKey}-code-verifier`),k(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var o,n;let{data:s,error:i}=r;if(i)throw i;return await O(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(o=s.session)===null||o===void 0?void 0:o.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){let r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{let o=Date.now();return await Tf(async n=>(n>0&&await kf(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await O(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:lt})),(n,s)=>{let i=200*Math.pow(2,n);return s&&hi(s)&&Date.now()+i-o<jr})}catch(o){if(this._debug(r,"error",o),k(o))return this._returnResult({data:{session:null,user:null},error:o});throw o}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){let o=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",o),ke()&&!r.skipBrowserRedirect&&window.location.assign(o),{data:{provider:e,url:o},error:null}}async _recoverAndRefresh(){var e,r;let o="#_recoverAndRefresh()";this._debug(o,"begin");try{let n=await br(this.storage,this.storageKey);if(n&&this.userStorage){let i=await br(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!i&&(i={user:n.user},await Br(this.userStorage,this.storageKey+"-user",i)),n.user=(e=i?.user)!==null&&e!==void 0?e:bi()}else if(n&&!n.user&&!n.user){let i=await br(this.storage,this.storageKey+"-user");i&&i?.user?(n.user=i.user,await Pe(this.storage,this.storageKey+"-user"),await Br(this.storage,this.storageKey,n)):n.user=bi()}if(this._debug(o,"session from storage",n),!this._isValidSession(n)){this._debug(o,"session is not valid"),n!==null&&await this._removeSession();return}let s=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<ci;if(this._debug(o,`session has${s?"":" not"} expired with margin of ${ci}s`),s){if(this.autoRefreshToken&&n.refresh_token){let{error:i}=await this._callRefreshToken(n.refresh_token);i&&(console.error(i),hi(i)||(this._debug(o,"refresh failed with a non-retryable error, removing the session",i),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{let{data:i,error:a}=await this._getUser(n.access_token);!a&&i?.user?(n.user=i.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(o,"could not get user data, skipping SIGNED_IN notification")}catch(i){console.error("Error getting user data:",i),this._debug(o,"error getting user data, skipping SIGNED_IN notification",i)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(o,"error",n),console.error(n);return}finally{this._debug(o,"end")}}async _callRefreshToken(e){var r,o;if(!e)throw new Ne;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new Wn;let{data:s,error:i}=await this._refreshAccessToken(e);if(i)throw i;if(!s.session)throw new Ne;await this._saveSession(s.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",s.session);let a={data:s.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(s){if(this._debug(n,"error",s),k(s)){let i={data:null,error:s};return hi(s)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(i),i}throw(o=this.refreshingDeferred)===null||o===void 0||o.reject(s),s}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,o=!0){let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${o}`);try{this.broadcastChannel&&o&&this.broadcastChannel.postMessage({event:e,session:r});let s=[],i=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(l){s.push(l)}});if(await Promise.all(i),s.length>0){for(let a=0;a<s.length;a+=1)console.error(s[a]);throw s[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Pe(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),o=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!o&&r.user&&await Br(this.userStorage,this.storageKey+"-user",{user:r.user});let n=Object.assign({},r);delete n.user;let s=Hl(n);await Br(this.storage,this.storageKey,s)}else{let n=Hl(r);await Br(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Pe(this.storage,this.storageKey),await Pe(this.storage,this.storageKey+"-code-verifier"),await Pe(this.storage,this.storageKey+"-user"),this.userStorage&&await Pe(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&ke()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),jr);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}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 r=>{let{data:{session:o}}=r;if(!o||!o.refresh_token||!o.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((o.expires_at*1e3-e)/jr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${jr}ms, refresh threshold is ${ui} ticks`),n<=ui&&await this._callRefreshToken(o.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Do)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!ke()||!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?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let r=`#_onVisibilityChanged(${e})`;this._debug(r,"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(r,"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,r,o){let n=[`provider=${encodeURIComponent(r)}`];if(o?.redirectTo&&n.push(`redirect_to=${encodeURIComponent(o.redirectTo)}`),o?.scopes&&n.push(`scopes=${encodeURIComponent(o.scopes)}`),this.flowType==="pkce"){let[s,i]=await qr(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(i)}`});n.push(a.toString())}if(o?.queryParams){let s=new URLSearchParams(o.queryParams);n.push(s.toString())}return o?.skipBrowserRedirect&&n.push(`skip_http_redirect=${o.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var o;let{data:n,error:s}=r;return s?this._returnResult({data:null,error:s}):await O(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.access_token})})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var o,n;let{data:s,error:i}=r;if(i)return this._returnResult({data:null,error:i});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:u}=await O(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(o=s?.session)===null||o===void 0?void 0:o.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&l.type==="totp"&&(!((n=l?.totp)===null||n===void 0)&&n.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var o;let{data:n,error:s}=r;if(s)return this._returnResult({data:null,error:s});let i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Vf(e.webauthn.credential_response):Wf(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await O(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.access_token});return l?this._returnResult({data:null,error:l}):(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:l}))})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var o;let{data:n,error:s}=r;if(s)return this._returnResult({data:null,error:s});let i=await O(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.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:Bf(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:qf(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){let{data:r,error:o}=await this._challenge({factorId:e.factorId});return o?this._returnResult({data:null,error:o}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:o}=await this.getUser();if(o)return{data:null,error:o};let n={all:[],phone:[],totp:[],webauthn:[]};for(let s of(e=r?.factors)!==null&&e!==void 0?e:[])n.all.push(s),s.status==="verified"&&n[s.factor_type].push(s);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,o,n,s;if(e)try{let{payload:m}=Hn(e),h=null;m.aal&&(h=m.aal);let g=h,{data:{user:y},error:p}=await this.getUser(e);if(p)return this._returnResult({data:null,error:p});((o=(r=y?.factors)===null||r===void 0?void 0:r.filter(v=>v.status==="verified"))!==null&&o!==void 0?o:[]).length>0&&(g="aal2");let _=m.amr||[];return{data:{currentLevel:h,nextLevel:g,currentAuthenticationMethods:_},error:null}}catch(m){if(k(m))return this._returnResult({data:null,error:m});throw m}let{data:{session:i},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:l}=Hn(i.access_token),u=null;l.aal&&(u=l.aal);let c=u;((s=(n=i.user.factors)===null||n===void 0?void 0:n.filter(m=>m.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let f=l.amr||[];return{data:{currentLevel:u,nextLevel:c,currentAuthenticationMethods:f},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:o},error:n}=r;return n?this._returnResult({data:null,error:n}):o?await O(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:o.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new Ne})})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async o=>{let{data:{session:n},error:s}=o;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new Ne});let i=await O(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return i.data&&i.data.redirect_url&&ke()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(o){if(k(o))return this._returnResult({data:null,error:o});throw o}}async _denyAuthorization(e,r){try{return await this._useSession(async o=>{let{data:{session:n},error:s}=o;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new Ne});let i=await O(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return i.data&&i.data.redirect_url&&ke()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(o){if(k(o))return this._returnResult({data:null,error:o});throw o}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:o}=e;return o?this._returnResult({data:null,error:o}):r?await O(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new Ne})})}catch(e){if(k(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:o},error:n}=r;return n?this._returnResult({data:null,error:n}):o?(await O(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:o.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Ne})})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let o=r.keys.find(a=>a.kid===e);if(o)return o;let n=Date.now();if(o=this.jwks.keys.find(a=>a.kid===e),o&&this.jwks_cached_at+mf>n)return o;let{data:s,error:i}=await O(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return!s.keys||s.keys.length===0||(this.jwks=s,this.jwks_cached_at=n,o=s.keys.find(a=>a.kid===e),!o)?null:o}async getClaims(e,r={}){try{let o=e;if(!o){let{data:m,error:h}=await this.getSession();if(h||!m.session)return this._returnResult({data:null,error:h});o=m.session.access_token}let{header:n,payload:s,signature:i,raw:{header:a,payload:l}}=Hn(o);r?.allowExpired||Ef(s.exp);let u=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!u){let{error:m}=await this.getUser(o);if(m)throw m;return{data:{claims:s,header:n,signature:i},error:null}}let c=Pf(n.alg),d=await crypto.subtle.importKey("jwk",u,c,!0,["verify"]);if(!await crypto.subtle.verify(c,d,i,_f(`${a}.${l}`)))throw new Fr("Invalid JWT signature");return{data:{claims:s,header:n,signature:i},error:null}}catch(o){if(k(o))return this._returnResult({data:null,error:o});throw o}}};Si.nextInstanceID={};var tu=Si;var G_=tu,ru=G_;var K_="2.100.1",Gn="";typeof Deno<"u"?Gn="deno":typeof document<"u"?Gn="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Gn="react-native":Gn="node";var J_={"X-Client-Info":`supabase-js-${Gn}/${K_}`},Y_={headers:J_},X_={schema:"public"},Q_={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Z_={};function Kn(t){"@babel/helpers - typeof";return Kn=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},Kn(t)}function ew(t,e){if(Kn(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(Kn(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function tw(t){var e=ew(t,"string");return Kn(e)=="symbol"?e:e+""}function rw(t,e,r){return(e=tw(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function zf(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function fe(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?zf(Object(r),!0).forEach(function(o){rw(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):zf(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var ow=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),nw=()=>Headers,sw=(t,e,r)=>{let o=ow(r),n=nw();return async(s,i)=>{var a;let l=(a=await e())!==null&&a!==void 0?a:t,u=new n(i?.headers);return u.has("apikey")||u.set("apikey",t),u.has("Authorization")||u.set("Authorization",`Bearer ${l}`),o(s,fe(fe({},i),{},{headers:u}))}};function iw(t){return t.endsWith("/")?t:t+"/"}function aw(t,e){var r,o;let{db:n,auth:s,realtime:i,global:a}=t,{db:l,auth:u,realtime:c,global:d}=e,f={db:fe(fe({},l),n),auth:fe(fe({},u),s),realtime:fe(fe({},c),i),storage:{},global:fe(fe(fe({},d),a),{},{headers:fe(fe({},(r=d?.headers)!==null&&r!==void 0?r:{}),(o=a?.headers)!==null&&o!==void 0?o:{})}),accessToken:async()=>""};return t.accessToken?f.accessToken=t.accessToken:delete f.accessToken,f}function lw(t){let e=t?.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(iw(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var uw=class extends ru{constructor(t){super(t)}},cw=class{constructor(t,e,r){var o,n;this.supabaseUrl=t,this.supabaseKey=e;let s=lw(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",s),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",s),this.storageUrl=new URL("storage/v1",s),this.functionsUrl=new URL("functions/v1",s);let i=`sb-${s.hostname.split(".")[0]}-auth-token`,a={db:X_,realtime:Z_,auth:fe(fe({},Q_),{},{storageKey:i}),global:Y_},l=aw(r??{},a);if(this.storageKey=(o=l.auth.storageKey)!==null&&o!==void 0?o:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(c,d)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} is not possible`)}});else{var u;this.auth=this._initSupabaseAuthClient((u=l.auth)!==null&&u!==void 0?u:{},this.headers,l.global.fetch)}this.fetch=sw(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(fe({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(c=>this.realtime.setAuth(c)).catch(c=>console.warn("Failed to set initial Realtime auth token:",c)),this.rest=new Wd(new URL("rest/v1",s).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new lf(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new En(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();let{data:o}=await t.auth.getSession();return(e=(r=o.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:o,userStorage:n,storageKey:s,flowType:i,lock:a,debug:l,throwOnError:u},c,d){let f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new uw({url:this.authUrl.href,headers:fe(fe({},f),c),storageKey:s,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:o,userStorage:n,flowType:i,lock:a,debug:l,throwOnError:u,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(m=>m.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Oo(this.realtimeUrl.href,fe(fe({},t),{},{params:fe(fe({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},Gf=(t,e,r)=>new cw(t,e,r);function dw(){if(typeof window<"u")return!1;let t=globalThis.process;if(!t)return!1;let e=t.version;if(e==null)return!1;let r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}dw()&&console.warn("\u26A0\uFE0F 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 Kf=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);var No=class extends Error{constructor(e,r="FunctionsError",o){super(e),this.name=r,this.context=o}},Jn=class extends No{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},jo=class extends No{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Mo=class extends No{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Yn;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(Yn||(Yn={}));var Xn=class{constructor(e,{headers:r={},customFetch:o,region:n=Yn.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=Kf(o)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Ks(this,arguments,void 0,function*(r,o={}){var n;let s,i;try{let{headers:a,method:l,body:u,signal:c,timeout:d}=o,f={},{region:m}=o;m||(m=this.region);let h=new URL(`${this.url}/${r}`);m&&m!=="any"&&(f["x-region"]=m,h.searchParams.set("forceFunctionRegion",m));let g;u&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(f["Content-Type"]="application/octet-stream",g=u):typeof u=="string"?(f["Content-Type"]="text/plain",g=u):typeof FormData<"u"&&u instanceof FormData?g=u:(f["Content-Type"]="application/json",g=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?g=JSON.stringify(u):g=u;let y=c;d&&(i=new AbortController,s=setTimeout(()=>i.abort(),d),c?(y=i.signal,c.addEventListener("abort",()=>i.abort())):y=i.signal);let p=yield this.fetch(h.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},f),this.headers),a),body:g,signal:y}).catch(N=>{throw new Jn(N)}),b=p.headers.get("x-relay-error");if(b&&b==="true")throw new jo(p);if(!p.ok)throw new Mo(p);let _=((n=p.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),v;return _==="application/json"?v=yield p.json():_==="application/octet-stream"||_==="application/pdf"?v=yield p.blob():_==="text/event-stream"?v=p:_==="multipart/form-data"?v=yield p.formData():v=yield p.text(),{data:v,error:null,response:p}}catch(a){return{data:null,error:a,response:a instanceof Mo||a instanceof jo?a.context:void 0}}finally{s&&clearTimeout(s)}})}};var Xf=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},fw=class{constructor(t){var e,r,o;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(o=t.urlLengthLimit)!==null&&o!==void 0?o:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}then(t,e){var r=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 o=this.fetch,n=o(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{let i=null,a=null,l=null,u=s.status,c=s.statusText;if(s.ok){var d,f;if(r.method!=="HEAD"){var m;let y=await s.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((m=r.headers.get("Accept"))===null||m===void 0)&&m.includes("application/vnd.pgrst.plan+text"))?a=y:a=JSON.parse(y))}let h=(d=r.headers.get("Prefer"))===null||d===void 0?void 0:d.match(/count=(exact|planned|estimated)/),g=(f=s.headers.get("content-range"))===null||f===void 0?void 0:f.split("/");h&&g&&g.length>1&&(l=parseInt(g[1])),r.isMaybeSingle&&Array.isArray(a)&&(a.length>1?(i={code:"PGRST116",details:`Results contain ${a.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},a=null,l=null,u=406,c="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{let h=await s.text();try{i=JSON.parse(h),Array.isArray(i)&&s.status===404&&(a=[],i=null,u=200,c="OK")}catch{s.status===404&&h===""?(u=204,c="No Content"):i={message:h}}if(i&&r.shouldThrowOnError)throw new Xf(i)}return{error:i,data:a,count:l,status:u,statusText:c}});return this.shouldThrowOnError||(n=n.catch(s=>{var i;let a="",l="",u="",c=s?.cause;if(c){var d,f,m,h;let p=(d=c?.message)!==null&&d!==void 0?d:"",b=(f=c?.code)!==null&&f!==void 0?f:"";a=`${(m=s?.name)!==null&&m!==void 0?m:"FetchError"}: ${s?.message}`,a+=`
|
|
44
|
+
${p}`}var le=class extends Error{constructor({message:e,code:r,cause:o,name:n}){var s;super(e,{cause:o}),this.__isWebAuthnError=!0,this.name=(s=n??(o instanceof Error?o.name:void 0))!==null&&s!==void 0?s:"Unknown Error",this.code=r}},zr=class extends le{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}};function Uf({error:t,options:e}){var r,o,n;let{publicKey:s}=e;if(!s)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new le({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=s.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new le({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((o=s.authenticatorSelection)===null||o===void 0?void 0:o.userVerification)==="required")return new le({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((n=s.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new le({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new le({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new le({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return s.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new le({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new le({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){let i=window.location.hostname;if(tu(i)){if(s.rp.id!==i)return new le({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new le({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(s.user.id.byteLength<1||s.user.id.byteLength>64)return new le({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new le({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new le({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Ff({error:t,options:e}){let{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new le({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new le({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if(tu(o)){if(r.rpId!==o)return new le({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new le({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new le({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new le({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}var ru=class{createNewAbortSignal(){if(this.controller){let r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},F_=new ru;function Bf(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);let{challenge:e,user:r,excludeCredentials:o}=t,n=We(t,["challenge","user","excludeCredentials"]),s=yr(e).buffer,i=Object.assign(Object.assign({},r),{id:yr(r.id).buffer}),a=Object.assign(Object.assign({},n),{challenge:s,user:i});if(o&&o.length>0){a.excludeCredentials=new Array(o.length);for(let l=0;l<o.length;l++){let u=o[l];a.excludeCredentials[l]=Object.assign(Object.assign({},u),{id:yr(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return a}function qf(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);let{challenge:e,allowCredentials:r}=t,o=We(t,["challenge","allowCredentials"]),n=yr(e).buffer,s=Object.assign(Object.assign({},o),{challenge:n});if(r&&r.length>0){s.allowCredentials=new Array(r.length);for(let i=0;i<r.length;i++){let a=r[i];s.allowCredentials[i]=Object.assign(Object.assign({},a),{id:yr(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return s}function Vf(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t;return{id:t.id,rawId:t.id,response:{attestationObject:sr(new Uint8Array(t.response.attestationObject)),clientDataJSON:sr(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Wf(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,o=t.getClientExtensionResults(),n=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:sr(new Uint8Array(n.authenticatorData)),clientDataJSON:sr(new Uint8Array(n.clientDataJSON)),signature:sr(new Uint8Array(n.signature)),userHandle:n.userHandle?sr(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:o,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function tu(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function $f(){var t,e;return!!(ke()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function $_(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new zr("Browser returned unexpected credential type",e)}:{data:null,error:new zr("Empty credential response",e)}}catch(e){return{data:null,error:Uf({error:e,options:t})}}}async function B_(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new zr("Browser returned unexpected credential type",e)}:{data:null,error:new zr("Empty credential response",e)}}catch(e){return{data:null,error:Ff({error:e,options:t})}}}var q_={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},V_={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Si(...t){let e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),o={};for(let n of t)if(n)for(let s in n){let i=n[s];if(i!==void 0)if(Array.isArray(i))o[s]=i;else if(r(i))o[s]=i;else if(e(i)){let a=o[s];e(a)?o[s]=Si(a,i):o[s]=Si(i)}else o[s]=i}return o}function W_(t,e){return Si(q_,t,e||{})}function H_(t,e){return Si(V_,t,e||{})}var xi=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:r,friendlyName:o,signal:n},s){var i;try{let{data:a,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:l};let u=n??F_.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:c}=a.webauthn.credential_options.publicKey;if(!c.name){let d=o;if(d)c.name=`${c.id}:${d}`;else{let m=(await this.client.getUser()).data.user,h=((i=m?.user_metadata)===null||i===void 0?void 0:i.name)||m?.email||m?.id||"User";c.name=`${c.id}:${h}`}}c.displayName||(c.displayName=c.name)}switch(a.webauthn.type){case"create":{let c=W_(a.webauthn.credential_options.publicKey,s?.create),{data:d,error:f}=await $_({publicKey:c,signal:u});return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:f}}case"request":{let c=H_(a.webauthn.credential_options.publicKey,s?.request),{data:d,error:f}=await B_(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:c,signal:u}));return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:f}}}}catch(a){return k(a)?{data:null,error:a}:{data:null,error:new at("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:o}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:o})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:o=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},s){if(!r)return{data:null,error:new gr("rpId is required for WebAuthn authentication")};try{if(!$f())return{data:null,error:new at("Browser does not support WebAuthn",null)};let{data:i,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:o},signal:n},{request:s});if(!i)return{data:null,error:a};let{webauthn:l}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:o,credential_response:l.credential_response}})}catch(i){return k(i)?{data:null,error:i}:{data:null,error:new at("Unexpected error in authenticate",i)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:o=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},s){if(!r)return{data:null,error:new gr("rpId is required for WebAuthn registration")};try{if(!$f())return{data:null,error:new at("Browser does not support WebAuthn",null)};let{data:i,error:a}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then(c=>{var d;return(d=c.data)===null||d===void 0?void 0:d.all.find(f=>f.factor_type==="webauthn"&&f.friendly_name===e&&f.status!=="unverified")}).then(c=>c?this.client.mfa.unenroll({factorId:c?.id}):void 0),{data:null,error:a};let{data:l,error:u}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:r,rpOrigins:o},signal:n},{create:s});return l?this._verify({factorId:i.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:o,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:u}}catch(i){return k(i)?{data:null,error:i}:{data:null,error:new at("Unexpected error in register",i)}}}};Lf();var z_={url:uf,storageKey:cf,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:df,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function Hf(t,e,r){return await r()}var Lo={},ki=class t{get jwks(){var e,r;return(r=(e=Lo[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Lo[this.storageKey]=Object.assign(Object.assign({},Lo[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Lo[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Lo[this.storageKey]=Object.assign(Object.assign({},Lo[this.storageKey]),{cachedAt:e})}constructor(e){var r,o,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 s=Object.assign(Object.assign({},z_),e);if(this.storageKey=s.storageKey,this.instanceID=(r=t.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,t.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.instanceID>0&&ke()){let i=`${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(i),this.logDebugMessages&&console.trace(i)}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.admin=new Hr({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=_i(s.fetch),this.lock=s.lock||Hf,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,this.lockAcquireTimeout=s.lockAcquireTimeout,s.lock?this.lock=s.lock:this.persistSession&&ke()&&(!((o=globalThis?.navigator)===null||o===void 0)&&o.locks)?this.lock=Ql:this.lock=Hf,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new xi(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?(s.storage?this.storage=s.storage:bi()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Yl(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=Yl(this.memoryStorage)),ke()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i);try{await this._notifyAllSubscribers(i.data.event,i.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}s.skipAutoInitialize||this.initialize().catch(i=>{this._debug("#initialize()","error",i)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${ci}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},o="none";if(ke()&&(r=Sf(window.location.href),this._isImplicitGrantCallback(r)?o="implicit":await this._isPKCECallback(r)&&(o="pkce")),ke()&&this.detectSessionInUrl&&o!=="none"){let{data:n,error:s}=await this._getSessionFromURL(r,o);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),pf(s)){let l=(e=s.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:s}}return{error:s}}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(r){return k(r)?this._returnResult({error:r}):this._returnResult({error:new at("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,o,n;try{let s=await O(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(o=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&o!==void 0?o:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:lt}),{data:i,error:a}=s;if(a||!i)return this._returnResult({data:{user:null,session:null},error:a});let l=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(k(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signUp(e){var r,o,n;try{let s;if("email"in e){let{email:c,password:d,options:f}=e,m=null,h=null;this.flowType==="pkce"&&([m,h]=await qr(this.storage,this.storageKey)),s=await O(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:c,password:d,data:(r=f?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:m,code_challenge_method:h},xform:lt})}else if("phone"in e){let{phone:c,password:d,options:f}=e;s=await O(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:d,data:(o=f?.data)!==null&&o!==void 0?o:{},channel:(n=f?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:lt})}else throw new Mr("You must provide either an email or phone number and a password");let{data:i,error:a}=s;if(a||!i)return await Pe(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let l=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(await Pe(this.storage,`${this.storageKey}-code-verifier`),k(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithPassword(e){try{let r;if("email"in e){let{email:s,password:i,options:a}=e;r=await O(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:i,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Kl})}else if("phone"in e){let{phone:s,password:i,options:a}=e;r=await O(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:i,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Kl})}else throw new Mr("You must provide either an email or phone number and a password");let{data:o,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!o||!o.session||!o.user){let s=new nr;return this._returnResult({data:{user:null,session:null},error:s})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),this._returnResult({data:Object.assign({user:o.user,session:o.session},o.weak_password?{weakPassword:o.weak_password}:null),error:n})}catch(r){if(k(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,o,n,s;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(s=e.options)===null||s===void 0?void 0:s.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,o,n,s,i,a,l,u,c,d,f;let m,h;if("message"in e)m=e.message,h=e.signature;else{let{chain:g,wallet:y,statement:p,options:b}=e,_;if(ke())if(typeof y=="object")_=y;else{let q=window;if("ethereum"in q&&typeof q.ethereum=="object"&&"request"in q.ethereum&&typeof q.ethereum.request=="function")_=q.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof y!="object"||!b?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=y}let v=new URL((r=b?.url)!==null&&r!==void 0?r:window.location.href),N=await _.request({method:"eth_requestAccounts"}).then(q=>q).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!N||N.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let x=eu(N[0]),P=(o=b?.signInWithEthereum)===null||o===void 0?void 0:o.chainId;if(!P){let q=await _.request({method:"eth_chainId"});P=Nf(q)}let Z={domain:v.host,address:x,statement:p,uri:v.href,version:"1",chainId:P,nonce:(n=b?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(i=(s=b?.signInWithEthereum)===null||s===void 0?void 0:s.issuedAt)!==null&&i!==void 0?i:new Date,expirationTime:(a=b?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=b?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=b?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(c=b?.signInWithEthereum)===null||c===void 0?void 0:c.resources};m=Mf(Z),h=await _.request({method:"personal_sign",params:[jf(m),x]})}try{let{data:g,error:y}=await O(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:m,signature:h},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:lt});if(y)throw y;if(!g||!g.session||!g.user){let p=new nr;return this._returnResult({data:{user:null,session:null},error:p})}return g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),this._returnResult({data:Object.assign({},g),error:y})}catch(g){if(k(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async signInWithSolana(e){var r,o,n,s,i,a,l,u,c,d,f,m;let h,g;if("message"in e)h=e.message,g=e.signature;else{let{chain:y,wallet:p,statement:b,options:_}=e,v;if(ke())if(typeof p=="object")v=p;else{let x=window;if("solana"in x&&typeof x.solana=="object"&&("signIn"in x.solana&&typeof x.solana.signIn=="function"||"signMessage"in x.solana&&typeof x.solana.signMessage=="function"))v=x.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof p!="object"||!_?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");v=p}let N=new URL((r=_?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in v&&v.signIn){let x=await v.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},_?.signInWithSolana),{version:"1",domain:N.host,uri:N.href}),b?{statement:b}:null)),P;if(Array.isArray(x)&&x[0]&&typeof x[0]=="object")P=x[0];else if(x&&typeof x=="object"&&"signedMessage"in x&&"signature"in x)P=x;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in P&&"signature"in P&&(typeof P.signedMessage=="string"||P.signedMessage instanceof Uint8Array)&&P.signature instanceof Uint8Array)h=typeof P.signedMessage=="string"?P.signedMessage:new TextDecoder().decode(P.signedMessage),g=P.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in v)||typeof v.signMessage!="function"||!("publicKey"in v)||typeof v!="object"||!v.publicKey||!("toBase58"in v.publicKey)||typeof v.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");h=[`${N.host} wants you to sign in with your Solana account:`,v.publicKey.toBase58(),...b?["",b,""]:[""],"Version: 1",`URI: ${N.href}`,`Issued At: ${(n=(o=_?.signInWithSolana)===null||o===void 0?void 0:o.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((s=_?.signInWithSolana)===null||s===void 0)&&s.notBefore?[`Not Before: ${_.signInWithSolana.notBefore}`]:[],...!((i=_?.signInWithSolana)===null||i===void 0)&&i.expirationTime?[`Expiration Time: ${_.signInWithSolana.expirationTime}`]:[],...!((a=_?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${_.signInWithSolana.chainId}`]:[],...!((l=_?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${_.signInWithSolana.nonce}`]:[],...!((u=_?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${_.signInWithSolana.requestId}`]:[],...!((d=(c=_?.signInWithSolana)===null||c===void 0?void 0:c.resources)===null||d===void 0)&&d.length?["Resources",..._.signInWithSolana.resources.map(P=>`- ${P}`)]:[]].join(`
|
|
45
|
+
`);let x=await v.signMessage(new TextEncoder().encode(h),"utf8");if(!x||!(x instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=x}}try{let{data:y,error:p}=await O(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:h,signature:sr(g)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(m=e.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:lt});if(p)throw p;if(!y||!y.session||!y.user){let b=new nr;return this._returnResult({data:{user:null,session:null},error:b})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:p})}catch(y){if(k(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async _exchangeCodeForSession(e){let r=await br(this.storage,`${this.storageKey}-code-verifier`),[o,n]=(r??"").split("/");try{if(!o&&this.flowType==="pkce")throw new hi;let{data:s,error:i}=await O(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:o},xform:lt});if(await Pe(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!s||!s.session||!s.user){let a=new nr;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign(Object.assign({},s),{redirectType:n??null}),error:i})}catch(s){if(await Pe(this.storage,`${this.storageKey}-code-verifier`),k(s))return this._returnResult({data:{user:null,session:null,redirectType:null},error:s});throw s}}async signInWithIdToken(e){try{let{options:r,provider:o,token:n,access_token:s,nonce:i}=e,a=await O(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:o,id_token:n,access_token:s,nonce:i,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:lt}),{data:l,error:u}=a;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){let c=new nr;return this._returnResult({data:{user:null,session:null},error:c})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:u})}catch(r){if(k(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,o,n,s,i;try{if("email"in e){let{email:a,options:l}=e,u=null,c=null;this.flowType==="pkce"&&([u,c]=await qr(this.storage,this.storageKey));let{error:d}=await O(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(o=l?.shouldCreateUser)!==null&&o!==void 0?o:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:u,code_challenge_method:c},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){let{phone:a,options:l}=e,{data:u,error:c}=await O(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(n=l?.data)!==null&&n!==void 0?n:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(i=l?.channel)!==null&&i!==void 0?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u?.message_id},error:c})}throw new Mr("You must provide either an email or phone number.")}catch(a){if(await Pe(this.storage,`${this.storageKey}-code-verifier`),k(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,o;try{let n,s;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,s=(o=e.options)===null||o===void 0?void 0:o.captchaToken);let{data:i,error:a}=await O(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:s}}),redirectTo:n,xform:lt});if(a)throw a;if(!i)throw new Error("An error occurred on token verification.");let l=i.session,u=i.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(n){if(k(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,o,n,s,i;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await qr(this.storage,this.storageKey));let u=await O(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:(o=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&o!==void 0?o:void 0}),!((n=e?.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:l}),headers:this.headers,xform:Rf});return!((s=u.data)===null||s===void 0)&&s.url&&ke()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(a){if(await Pe(this.storage,`${this.storageKey}-code-verifier`),k(a))return this._returnResult({data:null,error:a});throw a}}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:r},error:o}=e;if(o)throw o;if(!r)throw new Ne;let{error:n}=await O(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(k(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let r=`${this.url}/resend`;if("email"in e){let{email:o,type:n,options:s}=e,{error:i}=await O(this.fetch,"POST",r,{headers:this.headers,body:{email:o,type:n,gotrue_meta_security:{captcha_token:s?.captchaToken}},redirectTo:s?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}else if("phone"in e){let{phone:o,type:n,options:s}=e,{data:i,error:a}=await O(this.fetch,"POST",r,{headers:this.headers,body:{phone:o,type:n,gotrue_meta_security:{captcha_token:s?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:i?.message_id},error:a})}throw new Mr("You must provide either an email or phone number and a type")}catch(r){if(k(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let o=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await o,await r()))();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 o=r();for(this.pendingInLock.push((async()=>{try{await o}catch{}})()),await o;this.pendingInLock.length;){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await o}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,r=await br(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let o=e.expires_at?e.expires_at*1e3-Date.now()<fi:!1;if(this._debug("#__loadSession()",`session has${o?"":" not"} expired`,"expires_at",e.expires_at),!o){if(this.userStorage){let i=await br(this.userStorage,this.storageKey+"-user");i?.user?e.user=i.user:e.user=wi()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let i={value:this.suppressGetSessionWarning};e.user=Of(e.user,i),i.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{session:null},error:s}):this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await O(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:jt}):await this._useSession(async r=>{var o,n,s;let{data:i,error:a}=r;if(a)throw a;return!(!((o=i.session)===null||o===void 0)&&o.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Ne}:await O(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(s=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0,xform:jt})})}catch(r){if(k(r))return pi(r)&&(await this._removeSession(),await Pe(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async o=>{let{data:n,error:s}=o;if(s)throw s;if(!n.session)throw new Ne;let i=n.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await qr(this.storage,this.storageKey));let{data:u,error:c}=await O(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:i.access_token,xform:jt});if(c)throw c;return i.user=u.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})})}catch(o){if(await Pe(this.storage,`${this.storageKey}-code-verifier`),k(o))return this._returnResult({data:{user:null},error:o});throw o}}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 Ne;let r=Date.now()/1e3,o=r,n=!0,s=null,{payload:i}=Hn(e.access_token);if(i.exp&&(o=i.exp,n=o<=r),n){let{data:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a)return{data:{user:null,session:null},error:null};s=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});s={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:o-r,expires_at:o},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)}return this._returnResult({data:{user:s.user,session:s},error:null})}catch(r){if(k(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}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 r=>{var o;if(!e){let{data:i,error:a}=r;if(a)throw a;e=(o=i.session)!==null&&o!==void 0?o:void 0}if(!e?.refresh_token)throw new Ne;let{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(k(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!ke())throw new Ur("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Ur(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new qn("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ur("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new qn("No code detected.");let{data:b,error:_}=await this._exchangeCodeForSession(e.code);if(_)throw _;let v=new URL(window.location.href);return v.searchParams.delete("code"),window.history.replaceState(window.history.state,"",v.toString()),{data:{session:b.session,redirectType:null},error:null}}let{provider_token:o,provider_refresh_token:n,access_token:s,refresh_token:i,expires_in:a,expires_at:l,token_type:u}=e;if(!s||!a||!i||!u)throw new Ur("No session defined in URL");let c=Math.round(Date.now()/1e3),d=parseInt(a),f=c+d;l&&(f=parseInt(l));let m=f-c;m*1e3<=jr&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${d}s`);let h=f-d;c-h>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",h,f,c):c-h<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",h,f,c);let{data:g,error:y}=await this._getUser(s);if(y)throw y;let p={provider_token:o,provider_refresh_token:n,access_token:s,expires_in:d,expires_at:f,refresh_token:i,token_type:u,user:g.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:p,redirectType:e.type},error:null})}catch(o){if(k(o))return this._returnResult({data:{session:null,redirectType:null},error:o});throw o}}_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 r=await br(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}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 r=>{var o;let{data:n,error:s}=r;if(s&&!pi(s))return this._returnResult({error:s});let i=(o=n.session)===null||o===void 0?void 0:o.access_token;if(i){let{error:a}=await this.admin.signOut(i,e);if(a&&!(hf(a)&&(a.status===404||a.status===401||a.status===403)||pi(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await Pe(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=vf(),o={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,o),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:o}}}async _emitInitialSession(e){return await this._useSession(async r=>{var o,n;try{let{data:{session:s},error:i}=r;if(i)throw i;await((o=this.stateChangeEmitters.get(e))===null||o===void 0?void 0:o.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(s){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",s),console.error(s)}})}async resetPasswordForEmail(e,r={}){let o=null,n=null;this.flowType==="pkce"&&([o,n]=await qr(this.storage,this.storageKey,!0));try{return await O(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:o,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(s){if(await Pe(this.storage,`${this.storageKey}-code-verifier`),k(s))return this._returnResult({data:null,error:s});throw s}}async getUserIdentities(){var e;try{let{data:r,error:o}=await this.getUser();if(o)throw o;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{let{data:o,error:n}=await this._useSession(async s=>{var i,a,l,u,c;let{data:d,error:f}=s;if(f)throw f;let m=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(i=e.options)===null||i===void 0?void 0:i.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await O(this.fetch,"GET",m,{headers:this.headers,jwt:(c=(u=d.session)===null||u===void 0?void 0:u.access_token)!==null&&c!==void 0?c:void 0})});if(n)throw n;return ke()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(o?.url),this._returnResult({data:{provider:e.provider,url:o?.url},error:null})}catch(o){if(k(o))return this._returnResult({data:{provider:e.provider,url:null},error:o});throw o}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var o;try{let{error:n,data:{session:s}}=r;if(n)throw n;let{options:i,provider:a,token:l,access_token:u,nonce:c}=e,d=await O(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(o=s?.access_token)!==null&&o!==void 0?o:void 0,body:{provider:a,id_token:l,access_token:u,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:lt}),{data:f,error:m}=d;return m?this._returnResult({data:{user:null,session:null},error:m}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new nr}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:m}))}catch(n){if(await Pe(this.storage,`${this.storageKey}-code-verifier`),k(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var o,n;let{data:s,error:i}=r;if(i)throw i;return await O(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(o=s.session)===null||o===void 0?void 0:o.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){let r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{let o=Date.now();return await Tf(async n=>(n>0&&await kf(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await O(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:lt})),(n,s)=>{let i=200*Math.pow(2,n);return s&&gi(s)&&Date.now()+i-o<jr})}catch(o){if(this._debug(r,"error",o),k(o))return this._returnResult({data:{session:null,user:null},error:o});throw o}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){let o=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",o),ke()&&!r.skipBrowserRedirect&&window.location.assign(o),{data:{provider:e,url:o},error:null}}async _recoverAndRefresh(){var e,r;let o="#_recoverAndRefresh()";this._debug(o,"begin");try{let n=await br(this.storage,this.storageKey);if(n&&this.userStorage){let i=await br(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!i&&(i={user:n.user},await Br(this.userStorage,this.storageKey+"-user",i)),n.user=(e=i?.user)!==null&&e!==void 0?e:wi()}else if(n&&!n.user&&!n.user){let i=await br(this.storage,this.storageKey+"-user");i&&i?.user?(n.user=i.user,await Pe(this.storage,this.storageKey+"-user"),await Br(this.storage,this.storageKey,n)):n.user=wi()}if(this._debug(o,"session from storage",n),!this._isValidSession(n)){this._debug(o,"session is not valid"),n!==null&&await this._removeSession();return}let s=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<fi;if(this._debug(o,`session has${s?"":" not"} expired with margin of ${fi}s`),s){if(this.autoRefreshToken&&n.refresh_token){let{error:i}=await this._callRefreshToken(n.refresh_token);i&&(console.error(i),gi(i)||(this._debug(o,"refresh failed with a non-retryable error, removing the session",i),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{let{data:i,error:a}=await this._getUser(n.access_token);!a&&i?.user?(n.user=i.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(o,"could not get user data, skipping SIGNED_IN notification")}catch(i){console.error("Error getting user data:",i),this._debug(o,"error getting user data, skipping SIGNED_IN notification",i)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(o,"error",n),console.error(n);return}finally{this._debug(o,"end")}}async _callRefreshToken(e){var r,o;if(!e)throw new Ne;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new Wn;let{data:s,error:i}=await this._refreshAccessToken(e);if(i)throw i;if(!s.session)throw new Ne;await this._saveSession(s.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",s.session);let a={data:s.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(s){if(this._debug(n,"error",s),k(s)){let i={data:null,error:s};return gi(s)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(i),i}throw(o=this.refreshingDeferred)===null||o===void 0||o.reject(s),s}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,o=!0){let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${o}`);try{this.broadcastChannel&&o&&this.broadcastChannel.postMessage({event:e,session:r});let s=[],i=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(l){s.push(l)}});if(await Promise.all(i),s.length>0){for(let a=0;a<s.length;a+=1)console.error(s[a]);throw s[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Pe(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),o=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!o&&r.user&&await Br(this.userStorage,this.storageKey+"-user",{user:r.user});let n=Object.assign({},r);delete n.user;let s=Gl(n);await Br(this.storage,this.storageKey,s)}else{let n=Gl(r);await Br(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Pe(this.storage,this.storageKey),await Pe(this.storage,this.storageKey+"-code-verifier"),await Pe(this.storage,this.storageKey+"-user"),this.userStorage&&await Pe(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&ke()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),jr);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}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 r=>{let{data:{session:o}}=r;if(!o||!o.refresh_token||!o.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((o.expires_at*1e3-e)/jr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${jr}ms, refresh threshold is ${di} ticks`),n<=di&&await this._callRefreshToken(o.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Do)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!ke()||!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?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let r=`#_onVisibilityChanged(${e})`;this._debug(r,"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(r,"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,r,o){let n=[`provider=${encodeURIComponent(r)}`];if(o?.redirectTo&&n.push(`redirect_to=${encodeURIComponent(o.redirectTo)}`),o?.scopes&&n.push(`scopes=${encodeURIComponent(o.scopes)}`),this.flowType==="pkce"){let[s,i]=await qr(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(i)}`});n.push(a.toString())}if(o?.queryParams){let s=new URLSearchParams(o.queryParams);n.push(s.toString())}return o?.skipBrowserRedirect&&n.push(`skip_http_redirect=${o.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var o;let{data:n,error:s}=r;return s?this._returnResult({data:null,error:s}):await O(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.access_token})})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var o,n;let{data:s,error:i}=r;if(i)return this._returnResult({data:null,error:i});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:u}=await O(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(o=s?.session)===null||o===void 0?void 0:o.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&l.type==="totp"&&(!((n=l?.totp)===null||n===void 0)&&n.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var o;let{data:n,error:s}=r;if(s)return this._returnResult({data:null,error:s});let i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Vf(e.webauthn.credential_response):Wf(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await O(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.access_token});return l?this._returnResult({data:null,error:l}):(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:l}))})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var o;let{data:n,error:s}=r;if(s)return this._returnResult({data:null,error:s});let i=await O(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.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:Bf(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:qf(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){let{data:r,error:o}=await this._challenge({factorId:e.factorId});return o?this._returnResult({data:null,error:o}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:o}=await this.getUser();if(o)return{data:null,error:o};let n={all:[],phone:[],totp:[],webauthn:[]};for(let s of(e=r?.factors)!==null&&e!==void 0?e:[])n.all.push(s),s.status==="verified"&&n[s.factor_type].push(s);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,o,n,s;if(e)try{let{payload:m}=Hn(e),h=null;m.aal&&(h=m.aal);let g=h,{data:{user:y},error:p}=await this.getUser(e);if(p)return this._returnResult({data:null,error:p});((o=(r=y?.factors)===null||r===void 0?void 0:r.filter(v=>v.status==="verified"))!==null&&o!==void 0?o:[]).length>0&&(g="aal2");let _=m.amr||[];return{data:{currentLevel:h,nextLevel:g,currentAuthenticationMethods:_},error:null}}catch(m){if(k(m))return this._returnResult({data:null,error:m});throw m}let{data:{session:i},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:l}=Hn(i.access_token),u=null;l.aal&&(u=l.aal);let c=u;((s=(n=i.user.factors)===null||n===void 0?void 0:n.filter(m=>m.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let f=l.amr||[];return{data:{currentLevel:u,nextLevel:c,currentAuthenticationMethods:f},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:o},error:n}=r;return n?this._returnResult({data:null,error:n}):o?await O(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:o.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new Ne})})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async o=>{let{data:{session:n},error:s}=o;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new Ne});let i=await O(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return i.data&&i.data.redirect_url&&ke()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(o){if(k(o))return this._returnResult({data:null,error:o});throw o}}async _denyAuthorization(e,r){try{return await this._useSession(async o=>{let{data:{session:n},error:s}=o;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new Ne});let i=await O(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return i.data&&i.data.redirect_url&&ke()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(o){if(k(o))return this._returnResult({data:null,error:o});throw o}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:o}=e;return o?this._returnResult({data:null,error:o}):r?await O(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new Ne})})}catch(e){if(k(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:o},error:n}=r;return n?this._returnResult({data:null,error:n}):o?(await O(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:o.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Ne})})}catch(r){if(k(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let o=r.keys.find(a=>a.kid===e);if(o)return o;let n=Date.now();if(o=this.jwks.keys.find(a=>a.kid===e),o&&this.jwks_cached_at+mf>n)return o;let{data:s,error:i}=await O(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return!s.keys||s.keys.length===0||(this.jwks=s,this.jwks_cached_at=n,o=s.keys.find(a=>a.kid===e),!o)?null:o}async getClaims(e,r={}){try{let o=e;if(!o){let{data:m,error:h}=await this.getSession();if(h||!m.session)return this._returnResult({data:null,error:h});o=m.session.access_token}let{header:n,payload:s,signature:i,raw:{header:a,payload:l}}=Hn(o);r?.allowExpired||Ef(s.exp);let u=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!u){let{error:m}=await this.getUser(o);if(m)throw m;return{data:{claims:s,header:n,signature:i},error:null}}let c=Pf(n.alg),d=await crypto.subtle.importKey("jwk",u,c,!0,["verify"]);if(!await crypto.subtle.verify(c,d,i,_f(`${a}.${l}`)))throw new Fr("Invalid JWT signature");return{data:{claims:s,header:n,signature:i},error:null}}catch(o){if(k(o))return this._returnResult({data:null,error:o});throw o}}};ki.nextInstanceID={};var ou=ki;var G_=ou,nu=G_;var K_="2.100.1",Gn="";typeof Deno<"u"?Gn="deno":typeof document<"u"?Gn="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Gn="react-native":Gn="node";var J_={"X-Client-Info":`supabase-js-${Gn}/${K_}`},Y_={headers:J_},X_={schema:"public"},Q_={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Z_={};function Kn(t){"@babel/helpers - typeof";return Kn=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},Kn(t)}function ew(t,e){if(Kn(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(Kn(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function tw(t){var e=ew(t,"string");return Kn(e)=="symbol"?e:e+""}function rw(t,e,r){return(e=tw(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function zf(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function fe(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?zf(Object(r),!0).forEach(function(o){rw(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):zf(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var ow=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),nw=()=>Headers,sw=(t,e,r)=>{let o=ow(r),n=nw();return async(s,i)=>{var a;let l=(a=await e())!==null&&a!==void 0?a:t,u=new n(i?.headers);return u.has("apikey")||u.set("apikey",t),u.has("Authorization")||u.set("Authorization",`Bearer ${l}`),o(s,fe(fe({},i),{},{headers:u}))}};function iw(t){return t.endsWith("/")?t:t+"/"}function aw(t,e){var r,o;let{db:n,auth:s,realtime:i,global:a}=t,{db:l,auth:u,realtime:c,global:d}=e,f={db:fe(fe({},l),n),auth:fe(fe({},u),s),realtime:fe(fe({},c),i),storage:{},global:fe(fe(fe({},d),a),{},{headers:fe(fe({},(r=d?.headers)!==null&&r!==void 0?r:{}),(o=a?.headers)!==null&&o!==void 0?o:{})}),accessToken:async()=>""};return t.accessToken?f.accessToken=t.accessToken:delete f.accessToken,f}function lw(t){let e=t?.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(iw(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var uw=class extends nu{constructor(t){super(t)}},cw=class{constructor(t,e,r){var o,n;this.supabaseUrl=t,this.supabaseKey=e;let s=lw(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",s),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",s),this.storageUrl=new URL("storage/v1",s),this.functionsUrl=new URL("functions/v1",s);let i=`sb-${s.hostname.split(".")[0]}-auth-token`,a={db:X_,realtime:Z_,auth:fe(fe({},Q_),{},{storageKey:i}),global:Y_},l=aw(r??{},a);if(this.storageKey=(o=l.auth.storageKey)!==null&&o!==void 0?o:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(c,d)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} is not possible`)}});else{var u;this.auth=this._initSupabaseAuthClient((u=l.auth)!==null&&u!==void 0?u:{},this.headers,l.global.fetch)}this.fetch=sw(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(fe({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(c=>this.realtime.setAuth(c)).catch(c=>console.warn("Failed to set initial Realtime auth token:",c)),this.rest=new Wd(new URL("rest/v1",s).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new lf(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new En(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();let{data:o}=await t.auth.getSession();return(e=(r=o.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:o,userStorage:n,storageKey:s,flowType:i,lock:a,debug:l,throwOnError:u},c,d){let f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new uw({url:this.authUrl.href,headers:fe(fe({},f),c),storageKey:s,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:o,userStorage:n,flowType:i,lock:a,debug:l,throwOnError:u,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(m=>m.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Oo(this.realtimeUrl.href,fe(fe({},t),{},{params:fe(fe({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},Gf=(t,e,r)=>new cw(t,e,r);function dw(){if(typeof window<"u")return!1;let t=globalThis.process;if(!t)return!1;let e=t.version;if(e==null)return!1;let r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}dw()&&console.warn("\u26A0\uFE0F 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 Kf=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);var No=class extends Error{constructor(e,r="FunctionsError",o){super(e),this.name=r,this.context=o}},Jn=class extends No{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},jo=class extends No{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},Mo=class extends No{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}},Yn;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(Yn||(Yn={}));var Xn=class{constructor(e,{headers:r={},customFetch:o,region:n=Yn.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=Kf(o)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Ys(this,arguments,void 0,function*(r,o={}){var n;let s,i;try{let{headers:a,method:l,body:u,signal:c,timeout:d}=o,f={},{region:m}=o;m||(m=this.region);let h=new URL(`${this.url}/${r}`);m&&m!=="any"&&(f["x-region"]=m,h.searchParams.set("forceFunctionRegion",m));let g;u&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(f["Content-Type"]="application/octet-stream",g=u):typeof u=="string"?(f["Content-Type"]="text/plain",g=u):typeof FormData<"u"&&u instanceof FormData?g=u:(f["Content-Type"]="application/json",g=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?g=JSON.stringify(u):g=u;let y=c;d&&(i=new AbortController,s=setTimeout(()=>i.abort(),d),c?(y=i.signal,c.addEventListener("abort",()=>i.abort())):y=i.signal);let p=yield this.fetch(h.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},f),this.headers),a),body:g,signal:y}).catch(N=>{throw new Jn(N)}),b=p.headers.get("x-relay-error");if(b&&b==="true")throw new jo(p);if(!p.ok)throw new Mo(p);let _=((n=p.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),v;return _==="application/json"?v=yield p.json():_==="application/octet-stream"||_==="application/pdf"?v=yield p.blob():_==="text/event-stream"?v=p:_==="multipart/form-data"?v=yield p.formData():v=yield p.text(),{data:v,error:null,response:p}}catch(a){return{data:null,error:a,response:a instanceof Mo||a instanceof jo?a.context:void 0}}finally{s&&clearTimeout(s)}})}};var Xf=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},fw=class{constructor(t){var e,r,o;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(o=t.urlLengthLimit)!==null&&o!==void 0?o:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}then(t,e){var r=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 o=this.fetch,n=o(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{let i=null,a=null,l=null,u=s.status,c=s.statusText;if(s.ok){var d,f;if(r.method!=="HEAD"){var m;let y=await s.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((m=r.headers.get("Accept"))===null||m===void 0)&&m.includes("application/vnd.pgrst.plan+text"))?a=y:a=JSON.parse(y))}let h=(d=r.headers.get("Prefer"))===null||d===void 0?void 0:d.match(/count=(exact|planned|estimated)/),g=(f=s.headers.get("content-range"))===null||f===void 0?void 0:f.split("/");h&&g&&g.length>1&&(l=parseInt(g[1])),r.isMaybeSingle&&Array.isArray(a)&&(a.length>1?(i={code:"PGRST116",details:`Results contain ${a.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},a=null,l=null,u=406,c="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{let h=await s.text();try{i=JSON.parse(h),Array.isArray(i)&&s.status===404&&(a=[],i=null,u=200,c="OK")}catch{s.status===404&&h===""?(u=204,c="No Content"):i={message:h}}if(i&&r.shouldThrowOnError)throw new Xf(i)}return{error:i,data:a,count:l,status:u,statusText:c}});return this.shouldThrowOnError||(n=n.catch(s=>{var i;let a="",l="",u="",c=s?.cause;if(c){var d,f,m,h;let p=(d=c?.message)!==null&&d!==void 0?d:"",b=(f=c?.code)!==null&&f!==void 0?f:"";a=`${(m=s?.name)!==null&&m!==void 0?m:"FetchError"}: ${s?.message}`,a+=`
|
|
46
46
|
|
|
47
47
|
Caused by: ${(h=c?.name)!==null&&h!==void 0?h:"Error"}: ${p}`,b&&(a+=` (${b})`),c?.stack&&(a+=`
|
|
48
|
-
${c.stack}`)}else{var g;a=(g=s?.stack)!==null&&g!==void 0?g:""}let y=this.url.toString().length;return s?.name==="AbortError"||s?.code==="ABORT_ERR"?(u="",l="Request was aborted (timeout or manual cancellation)",y>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${y} 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.`)):(c?.name==="HeadersOverflowError"||c?.code==="UND_ERR_HEADERS_OVERFLOW")&&(u="",l="HTTP headers exceeded server limits (typically 16KB)",y>this.urlLengthLimit&&(l+=`. Your request URL is ${y} 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:`${(i=s?.name)!==null&&i!==void 0?i:"FetchError"}: ${s?.message}`,details:a,hint:l,code:u},data:null,count:null,status:0,statusText:""}})),n.then(t,e)}returns(){return this}overrideTypes(){return this}},mw=class extends fw{select(t){let e=!1,r=(t??"*").split("").map(o=>/\s/.test(o)&&!e?"":(o==='"'&&(e=!e),o)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:o,referencedTable:n=o}={}){let s=n?`${n}.order`:"order",i=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${i?`${i},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let o=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(o,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:o=r}={}){let n=typeof o>"u"?"offset":`${o}.offset`,s=typeof o>"u"?"limit":`${o}.limit`;return this.url.searchParams.set(n,`${t}`),this.url.searchParams.set(s,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return 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:t=!1,verbose:e=!1,settings:r=!1,buffers:o=!1,wal:n=!1,format:s="text"}={}){var i;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,o?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=(i=this.headers.get("Accept"))!==null&&i!==void 0?i:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${l}"; options=${a};`),s==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},Jf=new RegExp("[,()]"),Uo=class extends mw{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(o=>typeof o=="string"&&Jf.test(o)?`"${o}"`:`${o}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(o=>typeof o=="string"&&Jf.test(o)?`"${o}"`:`${o}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:o}={}){let n="";o==="plain"?n="pl":o==="phrase"?n="ph":o==="websearch"&&(n="w");let s=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}fts${s}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let o=r?`${r}.or`:"or";return this.url.searchParams.append(o,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},hw=class{constructor(t,{headers:e={},schema:r,fetch:o,urlLengthLimit:n=8e3}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=o,this.urlLengthLimit=n}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=!1,count:o}=e??{},n=r?"HEAD":"GET",s=!1,i=(t??"*").split("").map(u=>/\s/.test(u)&&!s?"":(u==='"'&&(s=!s),u)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",i),o&&l.append("Prefer",`count=${o}`),new Uo({method:n,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var o;let n="POST",{url:s,headers:i}=this.cloneRequestState();if(e&&i.append("Prefer",`count=${e}`),r||i.append("Prefer","missing=default"),Array.isArray(t)){let a=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(a.length>0){let l=[...new Set(a)].map(u=>`"${u}"`);s.searchParams.set("columns",l.join(","))}}return new Uo({method:n,url:s,headers:i,schema:this.schema,body:t,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:o,defaultToNull:n=!0}={}){var s;let i="POST",{url:a,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&a.searchParams.set("on_conflict",e),o&&l.append("Prefer",`count=${o}`),n||l.append("Prefer","missing=default"),Array.isArray(t)){let u=t.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(u.length>0){let c=[...new Set(u)].map(d=>`"${d}"`);a.searchParams.set("columns",c.join(","))}}return new Uo({method:i,url:a,headers:l,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let o="PATCH",{url:n,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new Uo({method:o,url:n,headers:s,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;let r="DELETE",{url:o,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new Uo({method:r,url:o,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function Qn(t){"@babel/helpers - typeof";return Qn=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},Qn(t)}function pw(t,e){if(Qn(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(Qn(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function gw(t){var e=pw(t,"string");return Qn(e)=="symbol"?e:e+""}function yw(t,e,r){return(e=gw(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Yf(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function xi(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Yf(Object(r),!0).forEach(function(o){yw(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Yf(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var Qf=class Zf{constructor(e,{headers:r={},schema:o,fetch:n,timeout:s,urlLengthLimit:i=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=o,this.urlLengthLimit=i;let a=n??globalThis.fetch;s!==void 0&&s>0?this.fetch=(l,u)=>{let c=new AbortController,d=setTimeout(()=>c.abort(),s),f=u?.signal;if(f){if(f.aborted)return clearTimeout(d),a(l,u);let m=()=>{clearTimeout(d),c.abort()};return f.addEventListener("abort",m,{once:!0}),a(l,xi(xi({},u),{},{signal:c.signal})).finally(()=>{clearTimeout(d),f.removeEventListener("abort",m)})}return a(l,xi(xi({},u),{},{signal:c.signal})).finally(()=>clearTimeout(d))}:this.fetch=a}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new hw(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Zf(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:o=!1,get:n=!1,count:s}={}){var i;let a,l=new URL(`${this.url}/rpc/${e}`),u,c=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(c)),d=o&&Object.values(r).some(c);d?(a="POST",u=r):o||n?(a=o?"HEAD":"GET",Object.entries(r).filter(([m,h])=>h!==void 0).map(([m,h])=>[m,Array.isArray(h)?`{${h.join(",")}}`:`${h}`]).forEach(([m,h])=>{l.searchParams.append(m,h)})):(a="POST",u=r);let f=new Headers(this.headers);return d?f.set("Prefer",s?`count=${s},return=minimal`:"return=minimal"):s&&f.set("Prefer",`count=${s}`),new Uo({method:a,url:l,headers:f,schema:this.schemaName,body:u,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}};var ou=class{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")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"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let r=globalThis.process;if(r){let o=r.versions;if(o&&o.node){let n=o.node,s=parseInt(n.replace(/^v/,"").split(".")[0]);return s>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${s} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${s} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
|
|
48
|
+
${c.stack}`)}else{var g;a=(g=s?.stack)!==null&&g!==void 0?g:""}let y=this.url.toString().length;return s?.name==="AbortError"||s?.code==="ABORT_ERR"?(u="",l="Request was aborted (timeout or manual cancellation)",y>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${y} 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.`)):(c?.name==="HeadersOverflowError"||c?.code==="UND_ERR_HEADERS_OVERFLOW")&&(u="",l="HTTP headers exceeded server limits (typically 16KB)",y>this.urlLengthLimit&&(l+=`. Your request URL is ${y} 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:`${(i=s?.name)!==null&&i!==void 0?i:"FetchError"}: ${s?.message}`,details:a,hint:l,code:u},data:null,count:null,status:0,statusText:""}})),n.then(t,e)}returns(){return this}overrideTypes(){return this}},mw=class extends fw{select(t){let e=!1,r=(t??"*").split("").map(o=>/\s/.test(o)&&!e?"":(o==='"'&&(e=!e),o)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:o,referencedTable:n=o}={}){let s=n?`${n}.order`:"order",i=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${i?`${i},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let o=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(o,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:o=r}={}){let n=typeof o>"u"?"offset":`${o}.offset`,s=typeof o>"u"?"limit":`${o}.limit`;return this.url.searchParams.set(n,`${t}`),this.url.searchParams.set(s,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return 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:t=!1,verbose:e=!1,settings:r=!1,buffers:o=!1,wal:n=!1,format:s="text"}={}){var i;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,o?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=(i=this.headers.get("Accept"))!==null&&i!==void 0?i:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${l}"; options=${a};`),s==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},Jf=new RegExp("[,()]"),Uo=class extends mw{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(o=>typeof o=="string"&&Jf.test(o)?`"${o}"`:`${o}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(o=>typeof o=="string"&&Jf.test(o)?`"${o}"`:`${o}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:o}={}){let n="";o==="plain"?n="pl":o==="phrase"?n="ph":o==="websearch"&&(n="w");let s=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}fts${s}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let o=r?`${r}.or`:"or";return this.url.searchParams.append(o,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},hw=class{constructor(t,{headers:e={},schema:r,fetch:o,urlLengthLimit:n=8e3}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=o,this.urlLengthLimit=n}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=!1,count:o}=e??{},n=r?"HEAD":"GET",s=!1,i=(t??"*").split("").map(u=>/\s/.test(u)&&!s?"":(u==='"'&&(s=!s),u)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",i),o&&l.append("Prefer",`count=${o}`),new Uo({method:n,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var o;let n="POST",{url:s,headers:i}=this.cloneRequestState();if(e&&i.append("Prefer",`count=${e}`),r||i.append("Prefer","missing=default"),Array.isArray(t)){let a=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(a.length>0){let l=[...new Set(a)].map(u=>`"${u}"`);s.searchParams.set("columns",l.join(","))}}return new Uo({method:n,url:s,headers:i,schema:this.schema,body:t,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:o,defaultToNull:n=!0}={}){var s;let i="POST",{url:a,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&a.searchParams.set("on_conflict",e),o&&l.append("Prefer",`count=${o}`),n||l.append("Prefer","missing=default"),Array.isArray(t)){let u=t.reduce((c,d)=>c.concat(Object.keys(d)),[]);if(u.length>0){let c=[...new Set(u)].map(d=>`"${d}"`);a.searchParams.set("columns",c.join(","))}}return new Uo({method:i,url:a,headers:l,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let o="PATCH",{url:n,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new Uo({method:o,url:n,headers:s,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;let r="DELETE",{url:o,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new Uo({method:r,url:o,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function Qn(t){"@babel/helpers - typeof";return Qn=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},Qn(t)}function pw(t,e){if(Qn(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(Qn(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function gw(t){var e=pw(t,"string");return Qn(e)=="symbol"?e:e+""}function yw(t,e,r){return(e=gw(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Yf(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function Ti(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Yf(Object(r),!0).forEach(function(o){yw(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Yf(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var Qf=class Zf{constructor(e,{headers:r={},schema:o,fetch:n,timeout:s,urlLengthLimit:i=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=o,this.urlLengthLimit=i;let a=n??globalThis.fetch;s!==void 0&&s>0?this.fetch=(l,u)=>{let c=new AbortController,d=setTimeout(()=>c.abort(),s),f=u?.signal;if(f){if(f.aborted)return clearTimeout(d),a(l,u);let m=()=>{clearTimeout(d),c.abort()};return f.addEventListener("abort",m,{once:!0}),a(l,Ti(Ti({},u),{},{signal:c.signal})).finally(()=>{clearTimeout(d),f.removeEventListener("abort",m)})}return a(l,Ti(Ti({},u),{},{signal:c.signal})).finally(()=>clearTimeout(d))}:this.fetch=a}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new hw(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Zf(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:o=!1,get:n=!1,count:s}={}){var i;let a,l=new URL(`${this.url}/rpc/${e}`),u,c=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(c)),d=o&&Object.values(r).some(c);d?(a="POST",u=r):o||n?(a=o?"HEAD":"GET",Object.entries(r).filter(([m,h])=>h!==void 0).map(([m,h])=>[m,Array.isArray(h)?`{${h.join(",")}}`:`${h}`]).forEach(([m,h])=>{l.searchParams.append(m,h)})):(a="POST",u=r);let f=new Headers(this.headers);return d?f.set("Prefer",s?`count=${s},return=minimal`:"return=minimal"):s&&f.set("Prefer",`count=${s}`),new Uo({method:a,url:l,headers:f,schema:this.schemaName,body:u,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}};var su=class{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")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"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let r=globalThis.process;if(r){let o=r.versions;if(o&&o.node){let n=o.node,s=parseInt(n.replace(/^v/,"").split(".")[0]);return s>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${s} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${s} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
|
|
49
49
|
import ws from "ws"
|
|
50
50
|
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 r=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(r+=`
|
|
51
51
|
|
|
52
|
-
Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}},nu=ou;var em="2.100.1";var tm=`realtime-js/${em}`,rm="1.0.0",su="2.0.0",om=su;var nm=1e4;var sm=100;var Mt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},ki={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"};var Zn={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};var es=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,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let o=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(o))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,o;let n=(o=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&o!==void 0?o:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var r,o;let n=(o=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&o!==void 0?o:{},i=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,i)}_encodeUserBroadcastPush(e,r,o){var n,s;let i=e.topic,a=(n=e.ref)!==null&&n!==void 0?n:"",l=(s=e.join_ref)!==null&&s!==void 0?s:"",u=e.payload.event,c=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},d=Object.keys(c).length===0?"":JSON.stringify(c);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(i.length>255)throw new Error(`topic length ${i.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`metadata length ${d.length} exceeds maximum of 255`);let f=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+i.length+u.length+d.length,m=new ArrayBuffer(this.HEADER_LENGTH+f),h=new DataView(m),g=0;h.setUint8(g++,this.KINDS.userBroadcastPush),h.setUint8(g++,l.length),h.setUint8(g++,a.length),h.setUint8(g++,i.length),h.setUint8(g++,u.length),h.setUint8(g++,d.length),h.setUint8(g++,r),Array.from(l,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(a,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(i,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(u,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(d,p=>h.setUint8(g++,p.charCodeAt(0)));var y=new Uint8Array(m.byteLength+o.byteLength);return y.set(new Uint8Array(m),0),y.set(new Uint8Array(o),m.byteLength),y.buffer}decode(e,r){if(this._isArrayBuffer(e)){let o=this._binaryDecode(e);return r(o)}if(typeof e=="string"){let o=JSON.parse(e),[n,s,i,a,l]=o;return r({join_ref:n,ref:s,topic:i,event:a,payload:l})}return r({})}_binaryDecode(e){let r=new DataView(e),o=r.getUint8(0),n=new TextDecoder;if(o===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,n)}_decodeUserBroadcast(e,r,o){let n=r.getUint8(1),s=r.getUint8(2),i=r.getUint8(3),a=r.getUint8(4),l=this.HEADER_LENGTH+4,u=o.decode(e.slice(l,l+n));l=l+n;let c=o.decode(e.slice(l,l+s));l=l+s;let d=o.decode(e.slice(l,l+i));l=l+i;let f=e.slice(l,e.byteLength),m=a===this.JSON_ENCODING?JSON.parse(o.decode(f)):f,h={type:this.BROADCAST_EVENT,event:c,payload:m};return i>0&&(h.meta=JSON.parse(d)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:h}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([o])=>r.includes(o)))}};var ne;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(ne||(ne={}));var au=(t,e,r={})=>{var o;let n=(o=r.skipTypes)!==null&&o!==void 0?o:[];return e?Object.keys(e).reduce((s,i)=>(s[i]=bw(i,t,e,n),s),{}):{}},bw=(t,e,r,o)=>{let n=e.find(a=>a.name===t),s=n?.type,i=r[t];return s&&!o.includes(s)?im(s,i):iu(i)},im=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return Sw(e,r)}switch(t){case ne.bool:return _w(e);case ne.float4:case ne.float8:case ne.int2:case ne.int4:case ne.int8:case ne.numeric:case ne.oid:return ww(e);case ne.json:case ne.jsonb:return vw(e);case ne.timestamp:return xw(e);case ne.abstime:case ne.date:case ne.daterange:case ne.int4range:case ne.int8range:case ne.money:case ne.reltime:case ne.text:case ne.time:case ne.timestamptz:case ne.timetz:case ne.tsrange:case ne.tstzrange:return iu(e);default:return iu(e)}},iu=t=>t,_w=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},ww=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t},vw=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Sw=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,o=t[r];if(t[0]==="{"&&o==="}"){let s,i=t.slice(1,r);try{s=JSON.parse("["+i+"]")}catch{s=i?i.split(","):[]}return s.map(a=>im(e,a))}return t},xw=t=>typeof t=="string"?t.replace(" ","T"):t,Ti=t=>{let e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var ts=class t{constructor(e,r){let o=Cw(r);this.presence=new ti(e.getChannel(),o),this.presence.onJoin((n,s,i)=>{let a=t.onJoinPayload(n,s,i);e.getChannel().trigger("presence",a)}),this.presence.onLeave((n,s,i)=>{let a=t.onLeavePayload(n,s,i);e.getChannel().trigger("presence",a)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return t.transformState(this.presence.state)}static transformState(e){return e=Tw(e),Object.getOwnPropertyNames(e).reduce((r,o)=>{let n=e[o];return r[o]=Ci(n),r},{})}static onJoinPayload(e,r,o){let n=am(r),s=Ci(o);return{event:"join",key:e,currentPresences:n,newPresences:s}}static onLeavePayload(e,r,o){let n=am(r),s=Ci(o);return{event:"leave",key:e,currentPresences:n,leftPresences:s}}};function Ci(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function Tw(t){return JSON.parse(JSON.stringify(t))}function Cw(t){return t?.events&&{events:t.events}}function am(t){return t?.metas?Ci(t):[]}var lu;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(lu||(lu={}));var Fo=class{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new ts(this.channel.channelAdapter,r)}};var rs=class{constructor(e,r,o){let n=Ew(o);this.channel=e.getSocket().channel(r,n),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,r,o){let n;try{n=this.channel.push(e,r,o)}catch{throw`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>sm){let s=this.channel.pushBuffer.shift();s.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${s.event}`,s.payload())}return n}updateJoinPayload(e){let r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===Mt.joined}isJoined(){return this.state===Mt.joined}isJoining(){return this.state===Mt.joining}isClosed(){return this.state===Mt.closed}isLeaving(){return this.state===Mt.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}};function Ew(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var uu;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(uu||(uu={}));var $o;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})($o||($o={}));var Ut;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(Ut||(Ut={}));var Bo=class t{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},o){var n,s;if(this.topic=e,this.params=r,this.socket=o,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new rs(this.socket.socketAdapter,e,this.params),this.presence=new Fo(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=Ti(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((s=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||s===void 0)&&s.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var o,n,s;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:i,presence:a,private:l}}=this.params,u=(n=(o=this.bindings.postgres_changes)===null||o===void 0?void 0:o.map(m=>m.filter))!==null&&n!==void 0?n:[],c=!!this.bindings[$o.PRESENCE]&&this.bindings[$o.PRESENCE].length>0||((s=this.params.config.presence)===null||s===void 0?void 0:s.enabled)===!0,d={},f={broadcast:i,presence:Object.assign(Object.assign({},a),{enabled:c}),postgres_changes:u,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(m=>{e?.(Ut.CHANNEL_ERROR,m)}),this._onClose(()=>e?.(Ut.CLOSED)),this.updateJoinPayload(Object.assign({config:f},d)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:m})=>{if(this.socket._isManualToken()||this.socket.setAuth(),m===void 0){e?.(Ut.SUBSCRIBED);return}this._updatePostgresBindings(m,e)}).receive("error",m=>{this.state=Mt.errored,e?.(Ut.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(m).join(", ")||"error")))}).receive("timeout",()=>{e?.(Ut.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var o;let n=this.bindings.postgres_changes,s=(o=n?.length)!==null&&o!==void 0?o:0,i=[];for(let a=0;a<s;a++){let l=n[a],{filter:{event:u,schema:c,table:d,filter:f}}=l,m=e&&e[a];if(m&&m.event===u&&t.isFilterValueEqual(m.schema,c)&&t.isFilterValueEqual(m.table,d)&&t.isFilterValueEqual(m.filter,f))i.push(Object.assign(Object.assign({},l),{id:m.id}));else{this.unsubscribe(),this.state=Mt.errored,r?.(Ut.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=i,this.state!=Mt.errored&&r&&r(Ut.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,o){if(this.channelAdapter.isJoined()&&e===$o.PRESENCE)throw this.socket.log("channel",`cannot add presence callbacks for ${this.topic} after joining.`),new Error("cannot add presence callbacks after joining a channel");return this._on(e,r,o)}async httpSend(e,r,o={}){var n;if(r==null)return Promise.reject("Payload is required for httpSend()");let s={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(s.Authorization=`Bearer ${this.socket.accessTokenValue}`);let i={method:"POST",headers:s,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,i,(n=o.timeout)!==null&&n!==void 0?n:this.timeout);if(a.status===202)return{success:!0};let l=a.statusText;try{let u=await a.json();l=u.error||u.message||l}catch{}return Promise.reject(new Error(l))}async send(e,r={}){var o,n;if(!this.channelAdapter.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:s,payload:i}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);let l={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:s,payload:i,private:this.private}]})};try{let u=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(o=r.timeout)!==null&&o!==void 0?o:this.timeout);return await((n=u.body)===null||n===void 0?void 0:n.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(s=>{var i,a,l;let u=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(i=this.params)===null||i===void 0?void 0:i.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&s("ok"),u.receive("ok",()=>s("ok")),u.receive("error",()=>s("error")),u.receive("timeout",()=>s("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,o){let n=new AbortController,s=setTimeout(()=>n.abort(),o),i=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(s),i}_on(e,r,o){let n=e.toLocaleLowerCase(),s=this.channelAdapter.on(e,o),i={type:n,filter:r,callback:o,ref:s};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,o)=>{var n,s,i,a,l,u,c;let d=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(d,o))return!1;let f=(n=this.bindings[d])===null||n===void 0?void 0:n.find(m=>m.ref===e.ref);if(!f)return!0;if(["broadcast","presence","postgres_changes"].includes(d))if("id"in f){let m=f.id,h=(s=f.filter)===null||s===void 0?void 0:s.event;return m&&((i=r.ids)===null||i===void 0?void 0:i.includes(m))&&(h==="*"||h?.toLocaleLowerCase()===((a=r.data)===null||a===void 0?void 0:a.type.toLocaleLowerCase()))}else{let m=(u=(l=f?.filter)===null||l===void 0?void 0:l.event)===null||u===void 0?void 0:u.toLocaleLowerCase();return m==="*"||m===((c=r?.event)===null||c===void 0?void 0:c.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===d})}_notThisChannelEvent(e,r){let{close:o,error:n,leave:s,join:i}=ki;return r&&[o,n,s,i].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,o)=>{if(typeof r=="object"&&"ids"in r){let n=r.data,{schema:s,table:i,commit_timestamp:a,type:l,errors:u}=n;return Object.assign(Object.assign({},{schema:s,table:i,commit_timestamp:a,eventType:l,new:{},old:{},errors:u}),this._getPayloadRecords(n))}return r})}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_getPayloadRecords(e){let r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=au(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=au(e.columns,e.old_record)),r}};var os=class{constructor(e,r){this.socket=new ri(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,o,n=1e4){return new Promise(s=>{setTimeout(()=>s("timeout"),n),this.socket.disconnect(()=>{e(),s("ok")},r,o)})}push(e){this.socket.push(e)}log(e,r,o){this.socket.log(e,r,o)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==Zn.connecting}isDisconnecting(){return this.socket.connectionState()==Zn.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}};var Pw={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Ow=[1e3,2e3,5e3,1e4],Aw=1e4,Rw=`
|
|
52
|
+
Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}},iu=su;var em="2.100.1";var tm=`realtime-js/${em}`,rm="1.0.0",au="2.0.0",om=au;var nm=1e4;var sm=100;var Mt={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Ci={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"};var Zn={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};var es=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,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let o=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(o))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,o;let n=(o=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&o!==void 0?o:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var r,o;let n=(o=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&o!==void 0?o:{},i=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,i)}_encodeUserBroadcastPush(e,r,o){var n,s;let i=e.topic,a=(n=e.ref)!==null&&n!==void 0?n:"",l=(s=e.join_ref)!==null&&s!==void 0?s:"",u=e.payload.event,c=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},d=Object.keys(c).length===0?"":JSON.stringify(c);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(i.length>255)throw new Error(`topic length ${i.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`metadata length ${d.length} exceeds maximum of 255`);let f=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+i.length+u.length+d.length,m=new ArrayBuffer(this.HEADER_LENGTH+f),h=new DataView(m),g=0;h.setUint8(g++,this.KINDS.userBroadcastPush),h.setUint8(g++,l.length),h.setUint8(g++,a.length),h.setUint8(g++,i.length),h.setUint8(g++,u.length),h.setUint8(g++,d.length),h.setUint8(g++,r),Array.from(l,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(a,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(i,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(u,p=>h.setUint8(g++,p.charCodeAt(0))),Array.from(d,p=>h.setUint8(g++,p.charCodeAt(0)));var y=new Uint8Array(m.byteLength+o.byteLength);return y.set(new Uint8Array(m),0),y.set(new Uint8Array(o),m.byteLength),y.buffer}decode(e,r){if(this._isArrayBuffer(e)){let o=this._binaryDecode(e);return r(o)}if(typeof e=="string"){let o=JSON.parse(e),[n,s,i,a,l]=o;return r({join_ref:n,ref:s,topic:i,event:a,payload:l})}return r({})}_binaryDecode(e){let r=new DataView(e),o=r.getUint8(0),n=new TextDecoder;if(o===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,n)}_decodeUserBroadcast(e,r,o){let n=r.getUint8(1),s=r.getUint8(2),i=r.getUint8(3),a=r.getUint8(4),l=this.HEADER_LENGTH+4,u=o.decode(e.slice(l,l+n));l=l+n;let c=o.decode(e.slice(l,l+s));l=l+s;let d=o.decode(e.slice(l,l+i));l=l+i;let f=e.slice(l,e.byteLength),m=a===this.JSON_ENCODING?JSON.parse(o.decode(f)):f,h={type:this.BROADCAST_EVENT,event:c,payload:m};return i>0&&(h.meta=JSON.parse(d)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:h}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([o])=>r.includes(o)))}};var ne;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(ne||(ne={}));var uu=(t,e,r={})=>{var o;let n=(o=r.skipTypes)!==null&&o!==void 0?o:[];return e?Object.keys(e).reduce((s,i)=>(s[i]=bw(i,t,e,n),s),{}):{}},bw=(t,e,r,o)=>{let n=e.find(a=>a.name===t),s=n?.type,i=r[t];return s&&!o.includes(s)?im(s,i):lu(i)},im=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return Sw(e,r)}switch(t){case ne.bool:return _w(e);case ne.float4:case ne.float8:case ne.int2:case ne.int4:case ne.int8:case ne.numeric:case ne.oid:return ww(e);case ne.json:case ne.jsonb:return vw(e);case ne.timestamp:return xw(e);case ne.abstime:case ne.date:case ne.daterange:case ne.int4range:case ne.int8range:case ne.money:case ne.reltime:case ne.text:case ne.time:case ne.timestamptz:case ne.timetz:case ne.tsrange:case ne.tstzrange:return lu(e);default:return lu(e)}},lu=t=>t,_w=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},ww=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t},vw=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Sw=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,o=t[r];if(t[0]==="{"&&o==="}"){let s,i=t.slice(1,r);try{s=JSON.parse("["+i+"]")}catch{s=i?i.split(","):[]}return s.map(a=>im(e,a))}return t},xw=t=>typeof t=="string"?t.replace(" ","T"):t,Ei=t=>{let e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var ts=class t{constructor(e,r){let o=Cw(r);this.presence=new oi(e.getChannel(),o),this.presence.onJoin((n,s,i)=>{let a=t.onJoinPayload(n,s,i);e.getChannel().trigger("presence",a)}),this.presence.onLeave((n,s,i)=>{let a=t.onLeavePayload(n,s,i);e.getChannel().trigger("presence",a)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return t.transformState(this.presence.state)}static transformState(e){return e=Tw(e),Object.getOwnPropertyNames(e).reduce((r,o)=>{let n=e[o];return r[o]=Pi(n),r},{})}static onJoinPayload(e,r,o){let n=am(r),s=Pi(o);return{event:"join",key:e,currentPresences:n,newPresences:s}}static onLeavePayload(e,r,o){let n=am(r),s=Pi(o);return{event:"leave",key:e,currentPresences:n,leftPresences:s}}};function Pi(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function Tw(t){return JSON.parse(JSON.stringify(t))}function Cw(t){return t?.events&&{events:t.events}}function am(t){return t?.metas?Pi(t):[]}var cu;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(cu||(cu={}));var Fo=class{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new ts(this.channel.channelAdapter,r)}};var rs=class{constructor(e,r,o){let n=Ew(o);this.channel=e.getSocket().channel(r,n),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,r,o){let n;try{n=this.channel.push(e,r,o)}catch{throw`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>sm){let s=this.channel.pushBuffer.shift();s.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${s.event}`,s.payload())}return n}updateJoinPayload(e){let r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===Mt.joined}isJoined(){return this.state===Mt.joined}isJoining(){return this.state===Mt.joining}isClosed(){return this.state===Mt.closed}isLeaving(){return this.state===Mt.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}};function Ew(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var du;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(du||(du={}));var $o;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})($o||($o={}));var Ut;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(Ut||(Ut={}));var Bo=class t{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},o){var n,s;if(this.topic=e,this.params=r,this.socket=o,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new rs(this.socket.socketAdapter,e,this.params),this.presence=new Fo(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=Ei(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((s=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||s===void 0)&&s.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var o,n,s;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:i,presence:a,private:l}}=this.params,u=(n=(o=this.bindings.postgres_changes)===null||o===void 0?void 0:o.map(m=>m.filter))!==null&&n!==void 0?n:[],c=!!this.bindings[$o.PRESENCE]&&this.bindings[$o.PRESENCE].length>0||((s=this.params.config.presence)===null||s===void 0?void 0:s.enabled)===!0,d={},f={broadcast:i,presence:Object.assign(Object.assign({},a),{enabled:c}),postgres_changes:u,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(m=>{e?.(Ut.CHANNEL_ERROR,m)}),this._onClose(()=>e?.(Ut.CLOSED)),this.updateJoinPayload(Object.assign({config:f},d)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:m})=>{if(this.socket._isManualToken()||this.socket.setAuth(),m===void 0){e?.(Ut.SUBSCRIBED);return}this._updatePostgresBindings(m,e)}).receive("error",m=>{this.state=Mt.errored,e?.(Ut.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(m).join(", ")||"error")))}).receive("timeout",()=>{e?.(Ut.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var o;let n=this.bindings.postgres_changes,s=(o=n?.length)!==null&&o!==void 0?o:0,i=[];for(let a=0;a<s;a++){let l=n[a],{filter:{event:u,schema:c,table:d,filter:f}}=l,m=e&&e[a];if(m&&m.event===u&&t.isFilterValueEqual(m.schema,c)&&t.isFilterValueEqual(m.table,d)&&t.isFilterValueEqual(m.filter,f))i.push(Object.assign(Object.assign({},l),{id:m.id}));else{this.unsubscribe(),this.state=Mt.errored,r?.(Ut.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=i,this.state!=Mt.errored&&r&&r(Ut.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,o){if(this.channelAdapter.isJoined()&&e===$o.PRESENCE)throw this.socket.log("channel",`cannot add presence callbacks for ${this.topic} after joining.`),new Error("cannot add presence callbacks after joining a channel");return this._on(e,r,o)}async httpSend(e,r,o={}){var n;if(r==null)return Promise.reject("Payload is required for httpSend()");let s={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(s.Authorization=`Bearer ${this.socket.accessTokenValue}`);let i={method:"POST",headers:s,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,i,(n=o.timeout)!==null&&n!==void 0?n:this.timeout);if(a.status===202)return{success:!0};let l=a.statusText;try{let u=await a.json();l=u.error||u.message||l}catch{}return Promise.reject(new Error(l))}async send(e,r={}){var o,n;if(!this.channelAdapter.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:s,payload:i}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);let l={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:s,payload:i,private:this.private}]})};try{let u=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(o=r.timeout)!==null&&o!==void 0?o:this.timeout);return await((n=u.body)===null||n===void 0?void 0:n.cancel()),u.ok?"ok":"error"}catch(u){return u.name==="AbortError"?"timed out":"error"}}else return new Promise(s=>{var i,a,l;let u=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(i=this.params)===null||i===void 0?void 0:i.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&s("ok"),u.receive("ok",()=>s("ok")),u.receive("error",()=>s("error")),u.receive("timeout",()=>s("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,o){let n=new AbortController,s=setTimeout(()=>n.abort(),o),i=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(s),i}_on(e,r,o){let n=e.toLocaleLowerCase(),s=this.channelAdapter.on(e,o),i={type:n,filter:r,callback:o,ref:s};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,o)=>{var n,s,i,a,l,u,c;let d=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(d,o))return!1;let f=(n=this.bindings[d])===null||n===void 0?void 0:n.find(m=>m.ref===e.ref);if(!f)return!0;if(["broadcast","presence","postgres_changes"].includes(d))if("id"in f){let m=f.id,h=(s=f.filter)===null||s===void 0?void 0:s.event;return m&&((i=r.ids)===null||i===void 0?void 0:i.includes(m))&&(h==="*"||h?.toLocaleLowerCase()===((a=r.data)===null||a===void 0?void 0:a.type.toLocaleLowerCase()))}else{let m=(u=(l=f?.filter)===null||l===void 0?void 0:l.event)===null||u===void 0?void 0:u.toLocaleLowerCase();return m==="*"||m===((c=r?.event)===null||c===void 0?void 0:c.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===d})}_notThisChannelEvent(e,r){let{close:o,error:n,leave:s,join:i}=Ci;return r&&[o,n,s,i].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,o)=>{if(typeof r=="object"&&"ids"in r){let n=r.data,{schema:s,table:i,commit_timestamp:a,type:l,errors:u}=n;return Object.assign(Object.assign({},{schema:s,table:i,commit_timestamp:a,eventType:l,new:{},old:{},errors:u}),this._getPayloadRecords(n))}return r})}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_getPayloadRecords(e){let r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=uu(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=uu(e.columns,e.old_record)),r}};var os=class{constructor(e,r){this.socket=new ni(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,o,n=1e4){return new Promise(s=>{setTimeout(()=>s("timeout"),n),this.socket.disconnect(()=>{e(),s("ok")},r,o)})}push(e){this.socket.push(e)}log(e,r,o){this.socket.log(e,r,o)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==Zn.connecting}isDisconnecting(){return this.socket.connectionState()==Zn.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}};var Pw={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Ow=[1e3,2e3,5e3,1e4],Aw=1e4,Rw=`
|
|
53
53
|
addEventListener("message", (e) => {
|
|
54
54
|
if (e.data.event === "start") {
|
|
55
55
|
setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
|
|
56
56
|
}
|
|
57
|
-
});`,qo=class{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,r){var o;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new es,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._resolveFetch=s=>s?(...i)=>s(...i):(...i)=>fetch(...i),!(!((o=r?.params)===null||o===void 0)&&o.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;let n=this._initializeOptions(r);this.socketAdapter=new os(e,n),this.httpEndpoint=
|
|
57
|
+
});`,qo=class{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,r){var o;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new es,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._resolveFetch=s=>s?(...i)=>s(...i):(...i)=>fetch(...i),!(!((o=r?.params)===null||o===void 0)&&o.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;let n=this._initializeOptions(r);this.socketAdapter=new os(e,n),this.httpEndpoint=Ei(e),this.fetch=this._resolveFetch(r?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){let r=e.message;throw r.includes("Node.js")?new Error(`${r}
|
|
58
58
|
|
|
59
59
|
To use Realtime in Node.js, you need to provide a WebSocket implementation:
|
|
60
60
|
|
|
@@ -67,9 +67,9 @@ Option 2: Install and provide the "ws" package:
|
|
|
67
67
|
const client = new RealtimeClient(url, {
|
|
68
68
|
...options,
|
|
69
69
|
transport: ws
|
|
70
|
-
})`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){let r=await e.unsubscribe();return r==="ok"&&e.teardown(),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){let e=this.channels.map(async o=>{let n=await o.unsubscribe();return o.teardown(),n}),r=await Promise.all(e);return this.disconnect(),r}log(e,r,o){this.socketAdapter.log(e,r,o)}connectionState(){return this.socketAdapter.connectionState()||Zn.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){let o=`realtime:${e}`,n=this.getChannels().find(s=>s.topic===o);if(n)return n;{let s=new Bo(`realtime:${e}`,r,this);return this.channels.push(s),s}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}async _performAuth(e=null){let r,o=!1;if(e)r=e,o=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(n){this.log("error","Error fetching access token from callback",n),r=this.accessTokenValue}else r=this.accessTokenValue;o?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{let s={access_token:r,version:tm};r&&n.updateJoinPayload(s),n.joinedOnce&&n.channelAdapter.isJoined()&&n.channelAdapter.push(ki.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,o)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,o)}}_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=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let r;if(e)r=e;else{let o=new Blob([Rw],{type:"application/javascript"});r=URL.createObjectURL(o)}return r}_initializeOptions(e){var r,o,n,s,i,a,l,u,c;this.worker=(r=e?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(o=e?.accessToken)!==null&&o!==void 0?o:null;let d={};d.timeout=(n=e?.timeout)!==null&&n!==void 0?n:nm,d.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:Pw.HEARTBEAT_INTERVAL,d.transport=(i=e?.transport)!==null&&i!==void 0?i:nu.getWebSocketConstructor(),d.params=e?.params,d.logger=e?.logger,d.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),d.reconnectAfterMs=(a=e?.reconnectAfterMs)!==null&&a!==void 0?a:(g=>Ow[g-1]||Aw);let f,m,h=(l=e?.vsn)!==null&&l!==void 0?l:om;switch(h){case rm:f=(g,y)=>y(JSON.stringify(g)),m=(g,y)=>y(JSON.parse(g));break;case su:f=this.serializer.encode.bind(this.serializer),m=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${d.vsn}`)}if(d.vsn=h,d.encode=(u=e?.encode)!==null&&u!==void 0?u:f,d.decode=(c=e?.decode)!==null&&c!==void 0?c:m,d.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,d.params=Object.assign(Object.assign({},d.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,d.autoSendHeartbeat=!this.worker}return d}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}};var Ei=class extends Error{constructor(t,e="storage",r,o){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=o}};function Pi(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var cu=class extends Ei{constructor(t,e,r,o="storage"){super(t,o,e,r),this.name=o==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},dm=class extends Ei{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};var Iw=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Dw=t=>{if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},du=t=>{if(Array.isArray(t))return t.map(r=>du(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,o])=>{let n=r.replace(/([-_][a-z])/gi,s=>s.toUpperCase().replace(/[-_]/g,""));e[n]=du(o)}),e},Lw=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function ss(t){"@babel/helpers - typeof";return ss=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},ss(t)}function Nw(t,e){if(ss(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(ss(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function jw(t){var e=Nw(t,"string");return ss(e)=="symbol"?e:e+""}function Mw(t,e,r){return(e=jw(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function lm(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function D(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?lm(Object(r),!0).forEach(function(o){Mw(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):lm(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var um=t=>{var e;return t.msg||t.message||t.error_description||(typeof t.error=="string"?t.error:(e=t.error)===null||e===void 0?void 0:e.message)||JSON.stringify(t)},Uw=async(t,e,r,o)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){let n=t,s=parseInt(n.status,10);Number.isFinite(s)||(s=500),n.json().then(i=>{let a=i?.statusCode||i?.code||s+"";e(new cu(um(i),s,a,o))}).catch(()=>{let i=s+"";e(new cu(n.statusText||`HTTP ${s} error`,s,i,o))})}else e(new dm(um(t),t,o))},Fw=(t,e,r,o)=>{let n={method:t,headers:e?.headers||{}};return t==="GET"||t==="HEAD"||!o?D(D({},n),r):(Dw(o)?(n.headers=D({"Content-Type":"application/json"},e?.headers),n.body=JSON.stringify(o)):n.body=o,e?.duplex&&(n.duplex=e.duplex),D(D({},n),r))};async function ns(t,e,r,o,n,s,i){return new Promise((a,l)=>{t(r,Fw(e,o,n,s)).then(u=>{if(!u.ok)throw u;if(o?.noResolveJson)return u;if(i==="vectors"){let c=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!c||!c.includes("application/json"))return{}}return u.json()}).then(u=>a(u)).catch(u=>Uw(u,l,o,i))})}function fm(t="storage"){return{get:async(e,r,o,n)=>ns(e,"GET",r,o,n,void 0,t),post:async(e,r,o,n,s)=>ns(e,"POST",r,n,s,o,t),put:async(e,r,o,n,s)=>ns(e,"PUT",r,n,s,o,t),head:async(e,r,o,n)=>ns(e,"HEAD",r,D(D({},o),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,o,n,s)=>ns(e,"DELETE",r,n,s,o,t)}}var $w=fm("storage"),{get:is,post:xt,put:fu,head:Bw,remove:mu}=$w,Xe=fm("vectors"),Vo=class{constructor(t,e={},r,o="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=Iw(r),this.namespace=o}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=D(D({},this.headers),{},{[t]:e}),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(Pi(r))return{data:null,error:r};throw r}}},qw=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pi(e))return{data:null,error:e};throw e}}},mm;mm=Symbol.toStringTag;var Vw=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[mm]="BlobDownloadBuilder",this.promise=null}asStream(){return new qw(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pi(e))return{data:null,error:e};throw e}}},Ww={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},cm={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Hw=class extends Vo{constructor(t,e={},r,o){super(t,e,o,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,o){var n=this;return n.handleOperation(async()=>{let s,i=D(D({},cm),o),a=D(D({},n.headers),t==="POST"&&{"x-upsert":String(i.upsert)}),l=i.metadata;typeof Blob<"u"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",i.cacheControl),l&&s.append("metadata",n.encodeMetadata(l)),s.append("",r)):typeof FormData<"u"&&r instanceof FormData?(s=r,s.has("cacheControl")||s.append("cacheControl",i.cacheControl),l&&!s.has("metadata")&&s.append("metadata",n.encodeMetadata(l))):(s=r,a["cache-control"]=`max-age=${i.cacheControl}`,a["content-type"]=i.contentType,l&&(a["x-metadata"]=n.toBase64(n.encodeMetadata(l))),(typeof ReadableStream<"u"&&s instanceof ReadableStream||s&&typeof s=="object"&&"pipe"in s&&typeof s.pipe=="function")&&!i.duplex&&(i.duplex="half")),o?.headers&&(a=D(D({},a),o.headers));let u=n._removeEmptyFolders(e),c=n._getFinalPath(u),d=await(t=="PUT"?fu:xt)(n.fetch,`${n.url}/object/${c}`,s,D({headers:a},i?.duplex?{duplex:i.duplex}:{}));return{path:u,id:d.Id,fullPath:d.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,o){var n=this;let s=n._removeEmptyFolders(t),i=n._getFinalPath(s),a=new URL(n.url+`/object/upload/sign/${i}`);return a.searchParams.set("token",e),n.handleOperation(async()=>{let l,u=D(D({},cm),o),c=D(D({},n.headers),{"x-upsert":String(u.upsert)});return typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",u.cacheControl)):(l=r,c["cache-control"]=`max-age=${u.cacheControl}`,c["content-type"]=u.contentType),{path:s,fullPath:(await fu(n.fetch,a.toString(),l,{headers:c})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let o=r._getFinalPath(t),n=D({},r.headers);e?.upsert&&(n["x-upsert"]="true");let s=await xt(r.fetch,`${r.url}/object/upload/sign/${o}`,{},{headers:n}),i=new URL(r.url+s.url),a=i.searchParams.get("token");if(!a)throw new Ei("No token returned by API");return{signedUrl:i.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var o=this;return o.handleOperation(async()=>await xt(o.fetch,`${o.url}/object/move`,{bucketId:o.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:o.headers}))}async copy(t,e,r){var o=this;return o.handleOperation(async()=>({path:(await xt(o.fetch,`${o.url}/object/copy`,{bucketId:o.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:o.headers})).Key}))}async createSignedUrl(t,e,r){var o=this;return o.handleOperation(async()=>{let n=o._getFinalPath(t),s=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0,i=await xt(o.fetch,`${o.url}/object/sign/${n}`,D({expiresIn:e},s?{transform:r.transform}:{}),{headers:o.headers}),a=r?.download?`&download=${r.download===!0?"":r.download}`:"",l=s&&i.signedURL.includes("/object/sign/")?i.signedURL.replace("/object/sign/","/render/image/sign/"):i.signedURL;return{signedUrl:encodeURI(`${o.url}${l}${a}`)}})}async createSignedUrls(t,e,r){var o=this;return o.handleOperation(async()=>{let n=await xt(o.fetch,`${o.url}/object/sign/${o.bucketId}`,{expiresIn:e,paths:t},{headers:o.headers}),s=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n.map(i=>D(D({},i),{},{signedUrl:i.signedURL?encodeURI(`${o.url}${i.signedURL}${s}`):null}))})}download(t,e,r){let o=typeof e?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(e?.transform||{}),s=n?`?${n}`:"",i=this._getFinalPath(t),a=()=>is(this.fetch,`${this.url}/${o}/${i}${s}`,{headers:this.headers,noResolveJson:!0},r);return new Vw(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>du(await is(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await Bw(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(Pi(n)){var o;let s=n instanceof cu?n.status:n instanceof dm?(o=n.originalError)===null||o===void 0?void 0:o.status:void 0;if(s!==void 0&&[400,404].includes(s))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){let r=this._getFinalPath(t),o=[],n=e?.download?`download=${e.download===!0?"":e.download}`:"";n!==""&&o.push(n);let s=typeof e?.transform<"u"?"render/image":"object",i=this.transformOptsToQueryString(e?.transform||{});i!==""&&o.push(i);let a=o.join("&");return a!==""&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${s}/public/${r}${a}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await mu(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var o=this;return o.handleOperation(async()=>{let n=D(D(D({},Ww),e),{},{prefix:t||""});return await xt(o.fetch,`${o.url}/object/list/${o.bucketId}`,n,{headers:o.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let o=D({},t);return await xt(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,o,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){let e=[];return t.width&&e.push(`width=${t.width}`),t.height&&e.push(`height=${t.height}`),t.resize&&e.push(`resize=${t.resize}`),t.format&&e.push(`format=${t.format}`),t.quality&&e.push(`quality=${t.quality}`),e.join("&")}},zw="2.100.1",as={"X-Client-Info":`storage-js/${zw}`},Gw=class extends Vo{constructor(t,e={},r,o){let n=new URL(t);o?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));let s=n.href.replace(/\/$/,""),i=D(D({},as),e);super(s,i,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await is(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await is(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await xt(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await fu(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await xt(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await mu(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){let e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},Kw=class extends Vo{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=D(D({},as),e);super(o,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await xt(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);let o=r.toString(),n=o?`${e.url}/bucket?${o}`:`${e.url}/bucket`;return await is(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await mu(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!Lw(t))throw new Ei("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let r=new si({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),o=this.shouldThrowOnError;return new Proxy(r,{get(n,s){let i=n[s];return typeof i!="function"?i:async(...a)=>{try{return{data:await i.apply(n,a),error:null}}catch(l){if(o)throw l;return{data:null,error:l}}}}})}},Jw=class extends Vo{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=D(D({},as),{},{"Content-Type":"application/json"},e);super(o,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await Xe.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await Xe.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},Yw=class extends Vo{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=D(D({},as),{},{"Content-Type":"application/json"},e);super(o,n,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},Xw=class extends Vo{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=D(D({},as),{},{"Content-Type":"application/json"},e);super(o,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Qw=class extends Xw{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new Zw(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},Zw=class extends Jw{constructor(t,e,r,o){super(t,e,o),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new ev(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},ev=class extends Yw{constructor(t,e,r,o,n){super(t,e,n),this.vectorBucketName=r,this.indexName=o}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},hm=class extends Gw{constructor(t,e={},r,o){super(t,e,r,o)}from(t){return new Hw(this.url,this.headers,t,this.fetch)}get vectors(){return new Qw(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Kw(this.url+"/iceberg",this.headers,this.fetch)}};var Oi="2.100.1";var Gr=30*1e3,Ai=3,Ri=Ai*Gr,pm="http://localhost:9999",gm="supabase.auth.token";var ym={"X-Client-Info":`gotrue-js/${Oi}`};var ls="X-Supabase-Api-Version",hu={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},bm=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,_m=600*1e3;var _r=class extends Error{constructor(e,r,o){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=o}};function T(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}var Ii=class extends _r{constructor(e,r,o){super(e,r,o),this.name="AuthApiError",this.status=r,this.code=o}};function wm(t){return T(t)&&t.name==="AuthApiError"}var ut=class extends _r{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}},kt=class extends _r{constructor(e,r,o,n){super(e,o,n),this.name=r,this.status=o}},je=class extends kt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function Li(t){return T(t)&&t.name==="AuthSessionMissingError"}var ir=class extends kt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Kr=class extends kt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Jr=class extends kt{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};function vm(t){return T(t)&&t.name==="AuthImplicitGrantRedirectError"}var us=class extends kt{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},Di=class extends kt{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")}};var Wo=class extends kt{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}};function Ni(t){return T(t)&&t.name==="AuthRetryableFetchError"}var cs=class extends kt{constructor(e,r,o){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=o}};var Yr=class extends kt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};var ji="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Sm=`
|
|
71
|
-
\r=`.split(""),tv=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<Sm.length;e+=1)t[Sm[e].charCodeAt(0)]=-2;for(let e=0;e<ji.length;e+=1)t[ji[e].charCodeAt(0)]=e;return t})();function xm(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){let o=e.queue>>e.queuedBits-6&63;r(ji[o]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let o=e.queue>>e.queuedBits-6&63;r(ji[o]),e.queuedBits-=6}}function km(t,e,r){let o=tv[t];if(o>-1)for(e.queue=e.queue<<6|o,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(o===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function pu(t){let e=[],r=i=>{e.push(String.fromCodePoint(i))},o={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},s=i=>{nv(i,o,r)};for(let i=0;i<t.length;i+=1)km(t.charCodeAt(i),n,s);return e.join("")}function rv(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function ov(t,e){for(let r=0;r<t.length;r+=1){let o=t.charCodeAt(r);if(o>55295&&o<=56319){let n=(o-55296)*1024&65535;o=(t.charCodeAt(r+1)-56320&65535|n)+65536,r+=1}rv(o,e)}}function nv(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let o=1;o<6;o+=1)if((t>>7-o&1)===0){e.utf8seq=o;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function wr(t){let e=[],r={queue:0,queuedBits:0},o=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)km(t.charCodeAt(n),r,o);return new Uint8Array(e)}function Tm(t){let e=[];return ov(t,r=>e.push(r)),new Uint8Array(e)}function ar(t){let e=[],r={queue:0,queuedBits:0},o=n=>{e.push(n)};return t.forEach(n=>xm(n,r,o)),xm(null,r,o),e.join("")}function Cm(t){return Math.round(Date.now()/1e3)+t}function Em(){return Symbol("auth-callback")}var Te=()=>typeof window<"u"&&typeof document<"u",Xr={tested:!1,writable:!1},Mi=()=>{if(!Te())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Xr.tested)return Xr.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),Xr.tested=!0,Xr.writable=!0}catch{Xr.tested=!0,Xr.writable=!1}return Xr.writable};function Pm(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((n,s)=>{e[s]=n})}catch{}return r.searchParams.forEach((o,n)=>{e[n]=o}),e}var Ui=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Om=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Qr=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},vr=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},Oe=async(t,e)=>{await t.removeItem(e)},ds=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}};ds.promiseConstructor=Promise;function fs(t){let e=t.split(".");if(e.length!==3)throw new Yr("Invalid JWT structure");for(let o=0;o<e.length;o++)if(!bm.test(e[o]))throw new Yr("JWT not in base64url format");return{header:JSON.parse(pu(e[0])),payload:JSON.parse(pu(e[1])),signature:wr(e[2]),raw:{header:e[0],payload:e[1]}}}async function Am(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function Rm(t,e){return new Promise((o,n)=>{(async()=>{for(let s=0;s<1/0;s++)try{let i=await t(s);if(!e(s,null,i)){o(i);return}}catch(i){if(!e(s,i)){n(i);return}}})()})}function sv(t){return("0"+t.toString(16)).substr(-2)}function iv(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",o=r.length,n="";for(let s=0;s<56;s++)n+=r.charAt(Math.floor(Math.random()*o));return n}return crypto.getRandomValues(e),Array.from(e,sv).join("")}async function av(t){let r=new TextEncoder().encode(t),o=await crypto.subtle.digest("SHA-256",r),n=new Uint8Array(o);return Array.from(n).map(s=>String.fromCharCode(s)).join("")}async function lv(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;let r=await av(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Zr(t,e,r=!1){let o=iv(),n=o;r&&(n+="/PASSWORD_RECOVERY"),await Qr(t,`${e}-code-verifier`,n);let s=await lv(o);return[s,o===s?"plain":"s256"]}var uv=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Im(t){let e=t.headers.get(ls);if(!e||!e.match(uv))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Dm(t){if(!t)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function Lm(t){switch(t){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var cv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function eo(t){if(!cv.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Fi(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){let o=r.toString();if(o==="Symbol(Symbol.toPrimitive)"||o==="Symbol(Symbol.toStringTag)"||o==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Nm(t,e){return new Proxy(t,{get:(r,o,n)=>{if(o==="__isInsecureUserWarningProxy")return!0;if(typeof o=="symbol"){let s=o.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)"||s==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,o,n)}return!e.value&&typeof o=="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."),e.value=!0),Reflect.get(r,o,n)}})}function gu(t){return JSON.parse(JSON.stringify(t))}var to=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),dv=[502,503,504];async function jm(t){var e;if(!Om(t))throw new Wo(to(t),0);if(dv.includes(t.status))throw new Wo(to(t),t.status);let r;try{r=await t.json()}catch(s){throw new ut(to(s),s)}let o,n=Im(t);if(n&&n.getTime()>=hu["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?o=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(o=r.error_code),o){if(o==="weak_password")throw new cs(to(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(o==="session_not_found")throw new je}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((s,i)=>s&&typeof i=="string",!0))throw new cs(to(r),t.status,r.weak_password.reasons);throw new Ii(to(r),t.status||500,o)}var fv=(t,e,r,o)=>{let n={method:t,headers:e?.headers||{}};return t==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),n.body=JSON.stringify(o),Object.assign(Object.assign({},n),r))};async function A(t,e,r,o){var n;let s=Object.assign({},o?.headers);s[ls]||(s[ls]=hu["2024-01-01"].name),o?.jwt&&(s.Authorization=`Bearer ${o.jwt}`);let i=(n=o?.query)!==null&&n!==void 0?n:{};o?.redirectTo&&(i.redirect_to=o.redirectTo);let a=Object.keys(i).length?"?"+new URLSearchParams(i).toString():"",l=await mv(t,e,r+a,{headers:s,noResolveJson:o?.noResolveJson},{},o?.body);return o?.xform?o?.xform(l):{data:Object.assign({},l),error:null}}async function mv(t,e,r,o,n,s){let i=fv(e,o,n,s),a;try{a=await t(r,Object.assign({},i))}catch(l){throw console.error(l),new Wo(to(l),0)}if(a.ok||await jm(a),o?.noResolveJson)return a;try{return await a.json()}catch(l){await jm(l)}}function ct(t){var e;let r=null;hv(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Cm(t.expires_in)));let o=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:o},error:null}}function yu(t){let e=ct(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,o)=>r&&typeof o=="string",!0)&&(e.data.weak_password=t.weak_password),e}function Ft(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Mm(t){return{data:t,error:null}}function Um(t){let{action_link:e,email_otp:r,hashed_token:o,redirect_to:n,verification_type:s}=t,i=We(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:o,redirect_to:n,verification_type:s},l=Object.assign({},i);return{data:{properties:a,user:l},error:null}}function bu(t){return t}function hv(t){return t.access_token&&t.refresh_token&&t.expires_in}var $i=["global","local","others"];var ro=class{constructor({url:e="",headers:r={},fetch:o}){this.url=e,this.headers=r,this.fetch=Ui(o),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,r=$i[0]){if($i.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${$i.join(", ")}`);try{return await A(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(o){if(T(o))return{data:null,error:o};throw o}}async inviteUserByEmail(e,r={}){try{return await A(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Ft})}catch(o){if(T(o))return{data:{user:null},error:o};throw o}}async generateLink(e){try{let{options:r}=e,o=We(e,["options"]),n=Object.assign(Object.assign({},o),r);return"newEmail"in o&&(n.new_email=o?.newEmail,delete n.newEmail),await A(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:Um,redirectTo:r?.redirectTo})}catch(r){if(T(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await A(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Ft})}catch(r){if(T(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,o,n,s,i,a,l;try{let u={nextPage:null,lastPage:0,total:0},c=await A(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(o=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&o!==void 0?o:"",per_page:(s=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:""},xform:bu});if(c.error)throw c.error;let d=await c.json(),f=(i=c.headers.get("x-total-count"))!==null&&i!==void 0?i:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(h=>{let g=parseInt(h.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(h.split(";")[1].split("=")[1]);u[`${y}Page`]=g}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(T(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){eo(e);try{return await A(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Ft})}catch(r){if(T(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){eo(e);try{return await A(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Ft})}catch(o){if(T(o))return{data:{user:null},error:o};throw o}}async deleteUser(e,r=!1){eo(e);try{return await A(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Ft})}catch(o){if(T(o))return{data:{user:null},error:o};throw o}}async _listFactors(e){eo(e.userId);try{let{data:r,error:o}=await A(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:r,error:o}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _deleteFactor(e){eo(e.userId),eo(e.id);try{return{data:await A(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,o,n,s,i,a,l;try{let u={nextPage:null,lastPage:0,total:0},c=await A(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(o=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&o!==void 0?o:"",per_page:(s=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:""},xform:bu});if(c.error)throw c.error;let d=await c.json(),f=(i=c.headers.get("x-total-count"))!==null&&i!==void 0?i:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(h=>{let g=parseInt(h.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(h.split(";")[1].split("=")[1]);u[`${y}Page`]=g}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(T(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await A(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await A(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await A(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:o=>({data:o,error:null})})}catch(o){if(T(o))return{data:null,error:o};throw o}}async _deleteOAuthClient(e){try{return await A(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await A(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{let r={};return e?.type&&(r.type=e.type),await A(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:o=>{var n;return{data:{providers:(n=o?.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(T(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await A(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await A(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await A(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:o=>({data:o,error:null})})}catch(o){if(T(o))return{data:null,error:o};throw o}}async _deleteCustomProvider(e){try{return await A(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}};function _u(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}var Tt={debug:!!(globalThis&&Mi()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},ms=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},hs=class extends ms{};async function wu(t,e,r){Tt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);let o=new globalThis.AbortController,n;e>0&&(n=setTimeout(()=>{o.abort(),Tt.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:o.signal},async s=>{if(s){clearTimeout(n),Tt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,s.name);try{return await r()}finally{Tt.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,s.name)}}else{if(e===0)throw Tt.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new hs(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(Tt.debug)try{let i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}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(n),await r()}})}catch(s){if(e>0&&clearTimeout(n),s?.name==="AbortError"&&e>0){if(o.signal.aborted)return Tt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}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(t,{mode:"exclusive",steal:!0},async i=>{if(i){Tt.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,i.name);try{return await r()}finally{Tt.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,i.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw Tt.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new hs(`Lock "${t}" was released because another request stole it`)}throw s}}function Fm(){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 vu(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function $m(t){return parseInt(t,16)}function Bm(t){let e=new TextEncoder().encode(t);return"0x"+Array.from(e,o=>o.toString(16).padStart(2,"0")).join("")}function qm(t){var e;let{chainId:r,domain:o,expirationTime:n,issuedAt:s=new Date,nonce:i,notBefore:a,requestId:l,resources:u,scheme:c,uri:d,version:f}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!o)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(i&&i.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${i}`);if(!d)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(f!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${f}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
|
|
72
|
-
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}let m=
|
|
70
|
+
})`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){let r=await e.unsubscribe();return r==="ok"&&e.teardown(),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){let e=this.channels.map(async o=>{let n=await o.unsubscribe();return o.teardown(),n}),r=await Promise.all(e);return this.disconnect(),r}log(e,r,o){this.socketAdapter.log(e,r,o)}connectionState(){return this.socketAdapter.connectionState()||Zn.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){let o=`realtime:${e}`,n=this.getChannels().find(s=>s.topic===o);if(n)return n;{let s=new Bo(`realtime:${e}`,r,this);return this.channels.push(s),s}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}async _performAuth(e=null){let r,o=!1;if(e)r=e,o=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(n){this.log("error","Error fetching access token from callback",n),r=this.accessTokenValue}else r=this.accessTokenValue;o?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{let s={access_token:r,version:tm};r&&n.updateJoinPayload(s),n.joinedOnce&&n.channelAdapter.isJoined()&&n.channelAdapter.push(Ci.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,o)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,o)}}_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=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let r;if(e)r=e;else{let o=new Blob([Rw],{type:"application/javascript"});r=URL.createObjectURL(o)}return r}_initializeOptions(e){var r,o,n,s,i,a,l,u,c;this.worker=(r=e?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(o=e?.accessToken)!==null&&o!==void 0?o:null;let d={};d.timeout=(n=e?.timeout)!==null&&n!==void 0?n:nm,d.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:Pw.HEARTBEAT_INTERVAL,d.transport=(i=e?.transport)!==null&&i!==void 0?i:iu.getWebSocketConstructor(),d.params=e?.params,d.logger=e?.logger,d.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),d.reconnectAfterMs=(a=e?.reconnectAfterMs)!==null&&a!==void 0?a:(g=>Ow[g-1]||Aw);let f,m,h=(l=e?.vsn)!==null&&l!==void 0?l:om;switch(h){case rm:f=(g,y)=>y(JSON.stringify(g)),m=(g,y)=>y(JSON.parse(g));break;case au:f=this.serializer.encode.bind(this.serializer),m=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${d.vsn}`)}if(d.vsn=h,d.encode=(u=e?.encode)!==null&&u!==void 0?u:f,d.decode=(c=e?.decode)!==null&&c!==void 0?c:m,d.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,d.params=Object.assign(Object.assign({},d.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,d.autoSendHeartbeat=!this.worker}return d}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}};var Oi=class extends Error{constructor(t,e="storage",r,o){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=o}};function Ai(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var fu=class extends Oi{constructor(t,e,r,o="storage"){super(t,o,e,r),this.name=o==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},dm=class extends Oi{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};var Iw=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Dw=t=>{if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},mu=t=>{if(Array.isArray(t))return t.map(r=>mu(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,o])=>{let n=r.replace(/([-_][a-z])/gi,s=>s.toUpperCase().replace(/[-_]/g,""));e[n]=mu(o)}),e},Lw=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function ss(t){"@babel/helpers - typeof";return ss=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},ss(t)}function Nw(t,e){if(ss(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(ss(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function jw(t){var e=Nw(t,"string");return ss(e)=="symbol"?e:e+""}function Mw(t,e,r){return(e=jw(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function lm(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function D(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?lm(Object(r),!0).forEach(function(o){Mw(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):lm(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var um=t=>{var e;return t.msg||t.message||t.error_description||(typeof t.error=="string"?t.error:(e=t.error)===null||e===void 0?void 0:e.message)||JSON.stringify(t)},Uw=async(t,e,r,o)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){let n=t,s=parseInt(n.status,10);Number.isFinite(s)||(s=500),n.json().then(i=>{let a=i?.statusCode||i?.code||s+"";e(new fu(um(i),s,a,o))}).catch(()=>{let i=s+"";e(new fu(n.statusText||`HTTP ${s} error`,s,i,o))})}else e(new dm(um(t),t,o))},Fw=(t,e,r,o)=>{let n={method:t,headers:e?.headers||{}};return t==="GET"||t==="HEAD"||!o?D(D({},n),r):(Dw(o)?(n.headers=D({"Content-Type":"application/json"},e?.headers),n.body=JSON.stringify(o)):n.body=o,e?.duplex&&(n.duplex=e.duplex),D(D({},n),r))};async function ns(t,e,r,o,n,s,i){return new Promise((a,l)=>{t(r,Fw(e,o,n,s)).then(u=>{if(!u.ok)throw u;if(o?.noResolveJson)return u;if(i==="vectors"){let c=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!c||!c.includes("application/json"))return{}}return u.json()}).then(u=>a(u)).catch(u=>Uw(u,l,o,i))})}function fm(t="storage"){return{get:async(e,r,o,n)=>ns(e,"GET",r,o,n,void 0,t),post:async(e,r,o,n,s)=>ns(e,"POST",r,n,s,o,t),put:async(e,r,o,n,s)=>ns(e,"PUT",r,n,s,o,t),head:async(e,r,o,n)=>ns(e,"HEAD",r,D(D({},o),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,o,n,s)=>ns(e,"DELETE",r,n,s,o,t)}}var $w=fm("storage"),{get:is,post:xt,put:hu,head:Bw,remove:pu}=$w,Xe=fm("vectors"),Vo=class{constructor(t,e={},r,o="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=Iw(r),this.namespace=o}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=D(D({},this.headers),{},{[t]:e}),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(Ai(r))return{data:null,error:r};throw r}}},qw=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Ai(e))return{data:null,error:e};throw e}}},mm;mm=Symbol.toStringTag;var Vw=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[mm]="BlobDownloadBuilder",this.promise=null}asStream(){return new qw(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Ai(e))return{data:null,error:e};throw e}}},Ww={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},cm={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Hw=class extends Vo{constructor(t,e={},r,o){super(t,e,o,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,o){var n=this;return n.handleOperation(async()=>{let s,i=D(D({},cm),o),a=D(D({},n.headers),t==="POST"&&{"x-upsert":String(i.upsert)}),l=i.metadata;typeof Blob<"u"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",i.cacheControl),l&&s.append("metadata",n.encodeMetadata(l)),s.append("",r)):typeof FormData<"u"&&r instanceof FormData?(s=r,s.has("cacheControl")||s.append("cacheControl",i.cacheControl),l&&!s.has("metadata")&&s.append("metadata",n.encodeMetadata(l))):(s=r,a["cache-control"]=`max-age=${i.cacheControl}`,a["content-type"]=i.contentType,l&&(a["x-metadata"]=n.toBase64(n.encodeMetadata(l))),(typeof ReadableStream<"u"&&s instanceof ReadableStream||s&&typeof s=="object"&&"pipe"in s&&typeof s.pipe=="function")&&!i.duplex&&(i.duplex="half")),o?.headers&&(a=D(D({},a),o.headers));let u=n._removeEmptyFolders(e),c=n._getFinalPath(u),d=await(t=="PUT"?hu:xt)(n.fetch,`${n.url}/object/${c}`,s,D({headers:a},i?.duplex?{duplex:i.duplex}:{}));return{path:u,id:d.Id,fullPath:d.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,o){var n=this;let s=n._removeEmptyFolders(t),i=n._getFinalPath(s),a=new URL(n.url+`/object/upload/sign/${i}`);return a.searchParams.set("token",e),n.handleOperation(async()=>{let l,u=D(D({},cm),o),c=D(D({},n.headers),{"x-upsert":String(u.upsert)});return typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",u.cacheControl)):(l=r,c["cache-control"]=`max-age=${u.cacheControl}`,c["content-type"]=u.contentType),{path:s,fullPath:(await hu(n.fetch,a.toString(),l,{headers:c})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let o=r._getFinalPath(t),n=D({},r.headers);e?.upsert&&(n["x-upsert"]="true");let s=await xt(r.fetch,`${r.url}/object/upload/sign/${o}`,{},{headers:n}),i=new URL(r.url+s.url),a=i.searchParams.get("token");if(!a)throw new Oi("No token returned by API");return{signedUrl:i.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var o=this;return o.handleOperation(async()=>await xt(o.fetch,`${o.url}/object/move`,{bucketId:o.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:o.headers}))}async copy(t,e,r){var o=this;return o.handleOperation(async()=>({path:(await xt(o.fetch,`${o.url}/object/copy`,{bucketId:o.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:o.headers})).Key}))}async createSignedUrl(t,e,r){var o=this;return o.handleOperation(async()=>{let n=o._getFinalPath(t),s=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0,i=await xt(o.fetch,`${o.url}/object/sign/${n}`,D({expiresIn:e},s?{transform:r.transform}:{}),{headers:o.headers}),a=r?.download?`&download=${r.download===!0?"":r.download}`:"",l=s&&i.signedURL.includes("/object/sign/")?i.signedURL.replace("/object/sign/","/render/image/sign/"):i.signedURL;return{signedUrl:encodeURI(`${o.url}${l}${a}`)}})}async createSignedUrls(t,e,r){var o=this;return o.handleOperation(async()=>{let n=await xt(o.fetch,`${o.url}/object/sign/${o.bucketId}`,{expiresIn:e,paths:t},{headers:o.headers}),s=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n.map(i=>D(D({},i),{},{signedUrl:i.signedURL?encodeURI(`${o.url}${i.signedURL}${s}`):null}))})}download(t,e,r){let o=typeof e?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(e?.transform||{}),s=n?`?${n}`:"",i=this._getFinalPath(t),a=()=>is(this.fetch,`${this.url}/${o}/${i}${s}`,{headers:this.headers,noResolveJson:!0},r);return new Vw(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>mu(await is(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await Bw(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(Ai(n)){var o;let s=n instanceof fu?n.status:n instanceof dm?(o=n.originalError)===null||o===void 0?void 0:o.status:void 0;if(s!==void 0&&[400,404].includes(s))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){let r=this._getFinalPath(t),o=[],n=e?.download?`download=${e.download===!0?"":e.download}`:"";n!==""&&o.push(n);let s=typeof e?.transform<"u"?"render/image":"object",i=this.transformOptsToQueryString(e?.transform||{});i!==""&&o.push(i);let a=o.join("&");return a!==""&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${s}/public/${r}${a}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await pu(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var o=this;return o.handleOperation(async()=>{let n=D(D(D({},Ww),e),{},{prefix:t||""});return await xt(o.fetch,`${o.url}/object/list/${o.bucketId}`,n,{headers:o.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let o=D({},t);return await xt(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,o,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){let e=[];return t.width&&e.push(`width=${t.width}`),t.height&&e.push(`height=${t.height}`),t.resize&&e.push(`resize=${t.resize}`),t.format&&e.push(`format=${t.format}`),t.quality&&e.push(`quality=${t.quality}`),e.join("&")}},zw="2.100.1",as={"X-Client-Info":`storage-js/${zw}`},Gw=class extends Vo{constructor(t,e={},r,o){let n=new URL(t);o?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));let s=n.href.replace(/\/$/,""),i=D(D({},as),e);super(s,i,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await is(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await is(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await xt(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await hu(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await xt(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await pu(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){let e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},Kw=class extends Vo{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=D(D({},as),e);super(o,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await xt(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);let o=r.toString(),n=o?`${e.url}/bucket?${o}`:`${e.url}/bucket`;return await is(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await pu(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!Lw(t))throw new Oi("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let r=new ai({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),o=this.shouldThrowOnError;return new Proxy(r,{get(n,s){let i=n[s];return typeof i!="function"?i:async(...a)=>{try{return{data:await i.apply(n,a),error:null}}catch(l){if(o)throw l;return{data:null,error:l}}}}})}},Jw=class extends Vo{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=D(D({},as),{},{"Content-Type":"application/json"},e);super(o,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await Xe.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await Xe.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},Yw=class extends Vo{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=D(D({},as),{},{"Content-Type":"application/json"},e);super(o,n,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},Xw=class extends Vo{constructor(t,e={},r){let o=t.replace(/\/$/,""),n=D(D({},as),{},{"Content-Type":"application/json"},e);super(o,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await Xe.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Qw=class extends Xw{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new Zw(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},Zw=class extends Jw{constructor(t,e,r,o){super(t,e,o),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new ev(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},ev=class extends Yw{constructor(t,e,r,o,n){super(t,e,n),this.vectorBucketName=r,this.indexName=o}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,D(D({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},hm=class extends Gw{constructor(t,e={},r,o){super(t,e,r,o)}from(t){return new Hw(this.url,this.headers,t,this.fetch)}get vectors(){return new Qw(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Kw(this.url+"/iceberg",this.headers,this.fetch)}};var Ri="2.100.1";var Gr=30*1e3,Ii=3,Di=Ii*Gr,pm="http://localhost:9999",gm="supabase.auth.token";var ym={"X-Client-Info":`gotrue-js/${Ri}`};var ls="X-Supabase-Api-Version",gu={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},bm=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,_m=600*1e3;var _r=class extends Error{constructor(e,r,o){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=o}};function T(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}var Li=class extends _r{constructor(e,r,o){super(e,r,o),this.name="AuthApiError",this.status=r,this.code=o}};function wm(t){return T(t)&&t.name==="AuthApiError"}var ut=class extends _r{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}},kt=class extends _r{constructor(e,r,o,n){super(e,o,n),this.name=r,this.status=o}},je=class extends kt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function ji(t){return T(t)&&t.name==="AuthSessionMissingError"}var ir=class extends kt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Kr=class extends kt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Jr=class extends kt{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};function vm(t){return T(t)&&t.name==="AuthImplicitGrantRedirectError"}var us=class extends kt{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},Ni=class extends kt{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")}};var Wo=class extends kt{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}};function Mi(t){return T(t)&&t.name==="AuthRetryableFetchError"}var cs=class extends kt{constructor(e,r,o){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=o}};var Yr=class extends kt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};var Ui="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Sm=`
|
|
71
|
+
\r=`.split(""),tv=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<Sm.length;e+=1)t[Sm[e].charCodeAt(0)]=-2;for(let e=0;e<Ui.length;e+=1)t[Ui[e].charCodeAt(0)]=e;return t})();function xm(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){let o=e.queue>>e.queuedBits-6&63;r(Ui[o]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let o=e.queue>>e.queuedBits-6&63;r(Ui[o]),e.queuedBits-=6}}function km(t,e,r){let o=tv[t];if(o>-1)for(e.queue=e.queue<<6|o,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(o===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function yu(t){let e=[],r=i=>{e.push(String.fromCodePoint(i))},o={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},s=i=>{nv(i,o,r)};for(let i=0;i<t.length;i+=1)km(t.charCodeAt(i),n,s);return e.join("")}function rv(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function ov(t,e){for(let r=0;r<t.length;r+=1){let o=t.charCodeAt(r);if(o>55295&&o<=56319){let n=(o-55296)*1024&65535;o=(t.charCodeAt(r+1)-56320&65535|n)+65536,r+=1}rv(o,e)}}function nv(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let o=1;o<6;o+=1)if((t>>7-o&1)===0){e.utf8seq=o;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function wr(t){let e=[],r={queue:0,queuedBits:0},o=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)km(t.charCodeAt(n),r,o);return new Uint8Array(e)}function Tm(t){let e=[];return ov(t,r=>e.push(r)),new Uint8Array(e)}function ar(t){let e=[],r={queue:0,queuedBits:0},o=n=>{e.push(n)};return t.forEach(n=>xm(n,r,o)),xm(null,r,o),e.join("")}function Cm(t){return Math.round(Date.now()/1e3)+t}function Em(){return Symbol("auth-callback")}var Te=()=>typeof window<"u"&&typeof document<"u",Xr={tested:!1,writable:!1},Fi=()=>{if(!Te())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Xr.tested)return Xr.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),Xr.tested=!0,Xr.writable=!0}catch{Xr.tested=!0,Xr.writable=!1}return Xr.writable};function Pm(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((n,s)=>{e[s]=n})}catch{}return r.searchParams.forEach((o,n)=>{e[n]=o}),e}var $i=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Om=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Qr=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},vr=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},Oe=async(t,e)=>{await t.removeItem(e)},ds=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}};ds.promiseConstructor=Promise;function fs(t){let e=t.split(".");if(e.length!==3)throw new Yr("Invalid JWT structure");for(let o=0;o<e.length;o++)if(!bm.test(e[o]))throw new Yr("JWT not in base64url format");return{header:JSON.parse(yu(e[0])),payload:JSON.parse(yu(e[1])),signature:wr(e[2]),raw:{header:e[0],payload:e[1]}}}async function Am(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function Rm(t,e){return new Promise((o,n)=>{(async()=>{for(let s=0;s<1/0;s++)try{let i=await t(s);if(!e(s,null,i)){o(i);return}}catch(i){if(!e(s,i)){n(i);return}}})()})}function sv(t){return("0"+t.toString(16)).substr(-2)}function iv(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",o=r.length,n="";for(let s=0;s<56;s++)n+=r.charAt(Math.floor(Math.random()*o));return n}return crypto.getRandomValues(e),Array.from(e,sv).join("")}async function av(t){let r=new TextEncoder().encode(t),o=await crypto.subtle.digest("SHA-256",r),n=new Uint8Array(o);return Array.from(n).map(s=>String.fromCharCode(s)).join("")}async function lv(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;let r=await av(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Zr(t,e,r=!1){let o=iv(),n=o;r&&(n+="/PASSWORD_RECOVERY"),await Qr(t,`${e}-code-verifier`,n);let s=await lv(o);return[s,o===s?"plain":"s256"]}var uv=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Im(t){let e=t.headers.get(ls);if(!e||!e.match(uv))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Dm(t){if(!t)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function Lm(t){switch(t){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var cv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function eo(t){if(!cv.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Bi(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){let o=r.toString();if(o==="Symbol(Symbol.toPrimitive)"||o==="Symbol(Symbol.toStringTag)"||o==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Nm(t,e){return new Proxy(t,{get:(r,o,n)=>{if(o==="__isInsecureUserWarningProxy")return!0;if(typeof o=="symbol"){let s=o.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)"||s==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,o,n)}return!e.value&&typeof o=="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."),e.value=!0),Reflect.get(r,o,n)}})}function bu(t){return JSON.parse(JSON.stringify(t))}var to=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),dv=[502,503,504];async function jm(t){var e;if(!Om(t))throw new Wo(to(t),0);if(dv.includes(t.status))throw new Wo(to(t),t.status);let r;try{r=await t.json()}catch(s){throw new ut(to(s),s)}let o,n=Im(t);if(n&&n.getTime()>=gu["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?o=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(o=r.error_code),o){if(o==="weak_password")throw new cs(to(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(o==="session_not_found")throw new je}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((s,i)=>s&&typeof i=="string",!0))throw new cs(to(r),t.status,r.weak_password.reasons);throw new Li(to(r),t.status||500,o)}var fv=(t,e,r,o)=>{let n={method:t,headers:e?.headers||{}};return t==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),n.body=JSON.stringify(o),Object.assign(Object.assign({},n),r))};async function A(t,e,r,o){var n;let s=Object.assign({},o?.headers);s[ls]||(s[ls]=gu["2024-01-01"].name),o?.jwt&&(s.Authorization=`Bearer ${o.jwt}`);let i=(n=o?.query)!==null&&n!==void 0?n:{};o?.redirectTo&&(i.redirect_to=o.redirectTo);let a=Object.keys(i).length?"?"+new URLSearchParams(i).toString():"",l=await mv(t,e,r+a,{headers:s,noResolveJson:o?.noResolveJson},{},o?.body);return o?.xform?o?.xform(l):{data:Object.assign({},l),error:null}}async function mv(t,e,r,o,n,s){let i=fv(e,o,n,s),a;try{a=await t(r,Object.assign({},i))}catch(l){throw console.error(l),new Wo(to(l),0)}if(a.ok||await jm(a),o?.noResolveJson)return a;try{return await a.json()}catch(l){await jm(l)}}function ct(t){var e;let r=null;hv(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Cm(t.expires_in)));let o=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:o},error:null}}function _u(t){let e=ct(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,o)=>r&&typeof o=="string",!0)&&(e.data.weak_password=t.weak_password),e}function Ft(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Mm(t){return{data:t,error:null}}function Um(t){let{action_link:e,email_otp:r,hashed_token:o,redirect_to:n,verification_type:s}=t,i=We(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:o,redirect_to:n,verification_type:s},l=Object.assign({},i);return{data:{properties:a,user:l},error:null}}function wu(t){return t}function hv(t){return t.access_token&&t.refresh_token&&t.expires_in}var qi=["global","local","others"];var ro=class{constructor({url:e="",headers:r={},fetch:o}){this.url=e,this.headers=r,this.fetch=$i(o),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,r=qi[0]){if(qi.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${qi.join(", ")}`);try{return await A(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(o){if(T(o))return{data:null,error:o};throw o}}async inviteUserByEmail(e,r={}){try{return await A(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Ft})}catch(o){if(T(o))return{data:{user:null},error:o};throw o}}async generateLink(e){try{let{options:r}=e,o=We(e,["options"]),n=Object.assign(Object.assign({},o),r);return"newEmail"in o&&(n.new_email=o?.newEmail,delete n.newEmail),await A(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:Um,redirectTo:r?.redirectTo})}catch(r){if(T(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await A(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Ft})}catch(r){if(T(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,o,n,s,i,a,l;try{let u={nextPage:null,lastPage:0,total:0},c=await A(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(o=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&o!==void 0?o:"",per_page:(s=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:""},xform:wu});if(c.error)throw c.error;let d=await c.json(),f=(i=c.headers.get("x-total-count"))!==null&&i!==void 0?i:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(h=>{let g=parseInt(h.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(h.split(";")[1].split("=")[1]);u[`${y}Page`]=g}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(T(u))return{data:{users:[]},error:u};throw u}}async getUserById(e){eo(e);try{return await A(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Ft})}catch(r){if(T(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){eo(e);try{return await A(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Ft})}catch(o){if(T(o))return{data:{user:null},error:o};throw o}}async deleteUser(e,r=!1){eo(e);try{return await A(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Ft})}catch(o){if(T(o))return{data:{user:null},error:o};throw o}}async _listFactors(e){eo(e.userId);try{let{data:r,error:o}=await A(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:r,error:o}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _deleteFactor(e){eo(e.userId),eo(e.id);try{return{data:await A(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,o,n,s,i,a,l;try{let u={nextPage:null,lastPage:0,total:0},c=await A(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(o=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&o!==void 0?o:"",per_page:(s=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:""},xform:wu});if(c.error)throw c.error;let d=await c.json(),f=(i=c.headers.get("x-total-count"))!==null&&i!==void 0?i:0,m=(l=(a=c.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(h=>{let g=parseInt(h.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(h.split(";")[1].split("=")[1]);u[`${y}Page`]=g}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},d),u),error:null}}catch(u){if(T(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(e){try{return await A(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await A(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await A(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:o=>({data:o,error:null})})}catch(o){if(T(o))return{data:null,error:o};throw o}}async _deleteOAuthClient(e){try{return await A(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await A(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{let r={};return e?.type&&(r.type=e.type),await A(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:o=>{var n;return{data:{providers:(n=o?.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(T(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await A(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{return await A(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(T(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await A(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:o=>({data:o,error:null})})}catch(o){if(T(o))return{data:null,error:o};throw o}}async _deleteCustomProvider(e){try{return await A(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(T(r))return{data:null,error:r};throw r}}};function vu(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}var Tt={debug:!!(globalThis&&Fi()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},ms=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},hs=class extends ms{};async function Su(t,e,r){Tt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);let o=new globalThis.AbortController,n;e>0&&(n=setTimeout(()=>{o.abort(),Tt.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:o.signal},async s=>{if(s){clearTimeout(n),Tt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,s.name);try{return await r()}finally{Tt.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,s.name)}}else{if(e===0)throw Tt.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new hs(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(Tt.debug)try{let i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}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(n),await r()}})}catch(s){if(e>0&&clearTimeout(n),s?.name==="AbortError"&&e>0){if(o.signal.aborted)return Tt.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}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(t,{mode:"exclusive",steal:!0},async i=>{if(i){Tt.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,i.name);try{return await r()}finally{Tt.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,i.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw Tt.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new hs(`Lock "${t}" was released because another request stole it`)}throw s}}function Fm(){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 xu(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function $m(t){return parseInt(t,16)}function Bm(t){let e=new TextEncoder().encode(t);return"0x"+Array.from(e,o=>o.toString(16).padStart(2,"0")).join("")}function qm(t){var e;let{chainId:r,domain:o,expirationTime:n,issuedAt:s=new Date,nonce:i,notBefore:a,requestId:l,resources:u,scheme:c,uri:d,version:f}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!o)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(i&&i.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${i}`);if(!d)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(f!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${f}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
|
|
72
|
+
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}let m=xu(t.address),h=c?`${c}://${o}`:o,g=t.statement?`${t.statement}
|
|
73
73
|
`:"",y=`${h} wants you to sign in with your Ethereum account:
|
|
74
74
|
${m}
|
|
75
75
|
|
|
@@ -83,13 +83,13 @@ Not Before: ${a.toISOString()}`),l&&(p+=`
|
|
|
83
83
|
Request ID: ${l}`),u){let b=`
|
|
84
84
|
Resources:`;for(let _ of u){if(!_||typeof _!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${_}`);b+=`
|
|
85
85
|
- ${_}`}p+=b}return`${y}
|
|
86
|
-
${p}`}var ue=class extends Error{constructor({message:e,code:r,cause:o,name:n}){var s;super(e,{cause:o}),this.__isWebAuthnError=!0,this.name=(s=n??(o instanceof Error?o.name:void 0))!==null&&s!==void 0?s:"Unknown Error",this.code=r}},oo=class extends ue{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}};function Vm({error:t,options:e}){var r,o,n;let{publicKey:s}=e;if(!s)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ue({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=s.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new ue({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((o=s.authenticatorSelection)===null||o===void 0?void 0:o.userVerification)==="required")return new ue({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((n=s.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new ue({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new ue({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new ue({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return s.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new ue({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new ue({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){let i=window.location.hostname;if(Su(i)){if(s.rp.id!==i)return new ue({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new ue({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(s.user.id.byteLength<1||s.user.id.byteLength>64)return new ue({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new ue({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new ue({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Wm({error:t,options:e}){let{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ue({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new ue({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if(Su(o)){if(r.rpId!==o)return new ue({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new ue({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new ue({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new ue({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}var xu=class{createNewAbortSignal(){if(this.controller){let r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},pv=new xu;function zm(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);let{challenge:e,user:r,excludeCredentials:o}=t,n=We(t,["challenge","user","excludeCredentials"]),s=wr(e).buffer,i=Object.assign(Object.assign({},r),{id:wr(r.id).buffer}),a=Object.assign(Object.assign({},n),{challenge:s,user:i});if(o&&o.length>0){a.excludeCredentials=new Array(o.length);for(let l=0;l<o.length;l++){let u=o[l];a.excludeCredentials[l]=Object.assign(Object.assign({},u),{id:wr(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return a}function Gm(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);let{challenge:e,allowCredentials:r}=t,o=We(t,["challenge","allowCredentials"]),n=wr(e).buffer,s=Object.assign(Object.assign({},o),{challenge:n});if(r&&r.length>0){s.allowCredentials=new Array(r.length);for(let i=0;i<r.length;i++){let a=r[i];s.allowCredentials[i]=Object.assign(Object.assign({},a),{id:wr(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return s}function Km(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t;return{id:t.id,rawId:t.id,response:{attestationObject:ar(new Uint8Array(t.response.attestationObject)),clientDataJSON:ar(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Jm(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,o=t.getClientExtensionResults(),n=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:ar(new Uint8Array(n.authenticatorData)),clientDataJSON:ar(new Uint8Array(n.clientDataJSON)),signature:ar(new Uint8Array(n.signature)),userHandle:n.userHandle?ar(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:o,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Su(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Hm(){var t,e;return!!(Te()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function gv(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new oo("Browser returned unexpected credential type",e)}:{data:null,error:new oo("Empty credential response",e)}}catch(e){return{data:null,error:Vm({error:e,options:t})}}}async function yv(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new oo("Browser returned unexpected credential type",e)}:{data:null,error:new oo("Empty credential response",e)}}catch(e){return{data:null,error:Wm({error:e,options:t})}}}var bv={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},_v={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Bi(...t){let e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),o={};for(let n of t)if(n)for(let s in n){let i=n[s];if(i!==void 0)if(Array.isArray(i))o[s]=i;else if(r(i))o[s]=i;else if(e(i)){let a=o[s];e(a)?o[s]=Bi(a,i):o[s]=Bi(i)}else o[s]=i}return o}function wv(t,e){return Bi(bv,t,e||{})}function vv(t,e){return Bi(_v,t,e||{})}var qi=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:r,friendlyName:o,signal:n},s){var i;try{let{data:a,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:l};let u=n??pv.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:c}=a.webauthn.credential_options.publicKey;if(!c.name){let d=o;if(d)c.name=`${c.id}:${d}`;else{let m=(await this.client.getUser()).data.user,h=((i=m?.user_metadata)===null||i===void 0?void 0:i.name)||m?.email||m?.id||"User";c.name=`${c.id}:${h}`}}c.displayName||(c.displayName=c.name)}switch(a.webauthn.type){case"create":{let c=wv(a.webauthn.credential_options.publicKey,s?.create),{data:d,error:f}=await gv({publicKey:c,signal:u});return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:f}}case"request":{let c=vv(a.webauthn.credential_options.publicKey,s?.request),{data:d,error:f}=await yv(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:c,signal:u}));return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:f}}}}catch(a){return T(a)?{data:null,error:a}:{data:null,error:new ut("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:o}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:o})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:o=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},s){if(!r)return{data:null,error:new _r("rpId is required for WebAuthn authentication")};try{if(!Hm())return{data:null,error:new ut("Browser does not support WebAuthn",null)};let{data:i,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:o},signal:n},{request:s});if(!i)return{data:null,error:a};let{webauthn:l}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:o,credential_response:l.credential_response}})}catch(i){return T(i)?{data:null,error:i}:{data:null,error:new ut("Unexpected error in authenticate",i)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:o=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},s){if(!r)return{data:null,error:new _r("rpId is required for WebAuthn registration")};try{if(!Hm())return{data:null,error:new ut("Browser does not support WebAuthn",null)};let{data:i,error:a}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then(c=>{var d;return(d=c.data)===null||d===void 0?void 0:d.all.find(f=>f.factor_type==="webauthn"&&f.friendly_name===e&&f.status!=="unverified")}).then(c=>c?this.client.mfa.unenroll({factorId:c?.id}):void 0),{data:null,error:a};let{data:l,error:u}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:r,rpOrigins:o},signal:n},{create:s});return l?this._verify({factorId:i.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:o,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:u}}catch(i){return T(i)?{data:null,error:i}:{data:null,error:new ut("Unexpected error in register",i)}}}};Fm();var Sv={url:pm,storageKey:gm,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:ym,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function Ym(t,e,r){return await r()}var Ho={},Vi=class t{get jwks(){var e,r;return(r=(e=Ho[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Ho[this.storageKey]=Object.assign(Object.assign({},Ho[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Ho[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Ho[this.storageKey]=Object.assign(Object.assign({},Ho[this.storageKey]),{cachedAt:e})}constructor(e){var r,o,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 s=Object.assign(Object.assign({},Sv),e);if(this.storageKey=s.storageKey,this.instanceID=(r=t.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,t.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.instanceID>0&&Te()){let i=`${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(i),this.logDebugMessages&&console.trace(i)}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.admin=new ro({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=Ui(s.fetch),this.lock=s.lock||Ym,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,this.lockAcquireTimeout=s.lockAcquireTimeout,s.lock?this.lock=s.lock:this.persistSession&&Te()&&(!((o=globalThis?.navigator)===null||o===void 0)&&o.locks)?this.lock=wu:this.lock=Ym,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new qi(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?(s.storage?this.storage=s.storage:Mi()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=_u(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=_u(this.memoryStorage)),Te()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i);try{await this._notifyAllSubscribers(i.data.event,i.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}s.skipAutoInitialize||this.initialize().catch(i=>{this._debug("#initialize()","error",i)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Oi}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},o="none";if(Te()&&(r=Pm(window.location.href),this._isImplicitGrantCallback(r)?o="implicit":await this._isPKCECallback(r)&&(o="pkce")),Te()&&this.detectSessionInUrl&&o!=="none"){let{data:n,error:s}=await this._getSessionFromURL(r,o);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),vm(s)){let l=(e=s.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:s}}return{error:s}}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(r){return T(r)?this._returnResult({error:r}):this._returnResult({error:new ut("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,o,n;try{let s=await A(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(o=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&o!==void 0?o:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:ct}),{data:i,error:a}=s;if(a||!i)return this._returnResult({data:{user:null,session:null},error:a});let l=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(T(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signUp(e){var r,o,n;try{let s;if("email"in e){let{email:c,password:d,options:f}=e,m=null,h=null;this.flowType==="pkce"&&([m,h]=await Zr(this.storage,this.storageKey)),s=await A(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:c,password:d,data:(r=f?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:m,code_challenge_method:h},xform:ct})}else if("phone"in e){let{phone:c,password:d,options:f}=e;s=await A(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:d,data:(o=f?.data)!==null&&o!==void 0?o:{},channel:(n=f?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:ct})}else throw new Kr("You must provide either an email or phone number and a password");let{data:i,error:a}=s;if(a||!i)return await Oe(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let l=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),T(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithPassword(e){try{let r;if("email"in e){let{email:s,password:i,options:a}=e;r=await A(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:i,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:yu})}else if("phone"in e){let{phone:s,password:i,options:a}=e;r=await A(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:i,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:yu})}else throw new Kr("You must provide either an email or phone number and a password");let{data:o,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!o||!o.session||!o.user){let s=new ir;return this._returnResult({data:{user:null,session:null},error:s})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),this._returnResult({data:Object.assign({user:o.user,session:o.session},o.weak_password?{weakPassword:o.weak_password}:null),error:n})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,o,n,s;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(s=e.options)===null||s===void 0?void 0:s.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,o,n,s,i,a,l,u,c,d,f;let m,h;if("message"in e)m=e.message,h=e.signature;else{let{chain:g,wallet:y,statement:p,options:b}=e,_;if(Te())if(typeof y=="object")_=y;else{let q=window;if("ethereum"in q&&typeof q.ethereum=="object"&&"request"in q.ethereum&&typeof q.ethereum.request=="function")_=q.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof y!="object"||!b?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=y}let v=new URL((r=b?.url)!==null&&r!==void 0?r:window.location.href),N=await _.request({method:"eth_requestAccounts"}).then(q=>q).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!N||N.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let x=vu(N[0]),P=(o=b?.signInWithEthereum)===null||o===void 0?void 0:o.chainId;if(!P){let q=await _.request({method:"eth_chainId"});P=$m(q)}let Z={domain:v.host,address:x,statement:p,uri:v.href,version:"1",chainId:P,nonce:(n=b?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(i=(s=b?.signInWithEthereum)===null||s===void 0?void 0:s.issuedAt)!==null&&i!==void 0?i:new Date,expirationTime:(a=b?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=b?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=b?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(c=b?.signInWithEthereum)===null||c===void 0?void 0:c.resources};m=qm(Z),h=await _.request({method:"personal_sign",params:[Bm(m),x]})}try{let{data:g,error:y}=await A(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:m,signature:h},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:ct});if(y)throw y;if(!g||!g.session||!g.user){let p=new ir;return this._returnResult({data:{user:null,session:null},error:p})}return g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),this._returnResult({data:Object.assign({},g),error:y})}catch(g){if(T(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async signInWithSolana(e){var r,o,n,s,i,a,l,u,c,d,f,m;let h,g;if("message"in e)h=e.message,g=e.signature;else{let{chain:y,wallet:p,statement:b,options:_}=e,v;if(Te())if(typeof p=="object")v=p;else{let x=window;if("solana"in x&&typeof x.solana=="object"&&("signIn"in x.solana&&typeof x.solana.signIn=="function"||"signMessage"in x.solana&&typeof x.solana.signMessage=="function"))v=x.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof p!="object"||!_?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");v=p}let N=new URL((r=_?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in v&&v.signIn){let x=await v.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},_?.signInWithSolana),{version:"1",domain:N.host,uri:N.href}),b?{statement:b}:null)),P;if(Array.isArray(x)&&x[0]&&typeof x[0]=="object")P=x[0];else if(x&&typeof x=="object"&&"signedMessage"in x&&"signature"in x)P=x;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in P&&"signature"in P&&(typeof P.signedMessage=="string"||P.signedMessage instanceof Uint8Array)&&P.signature instanceof Uint8Array)h=typeof P.signedMessage=="string"?P.signedMessage:new TextDecoder().decode(P.signedMessage),g=P.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in v)||typeof v.signMessage!="function"||!("publicKey"in v)||typeof v!="object"||!v.publicKey||!("toBase58"in v.publicKey)||typeof v.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");h=[`${N.host} wants you to sign in with your Solana account:`,v.publicKey.toBase58(),...b?["",b,""]:[""],"Version: 1",`URI: ${N.href}`,`Issued At: ${(n=(o=_?.signInWithSolana)===null||o===void 0?void 0:o.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((s=_?.signInWithSolana)===null||s===void 0)&&s.notBefore?[`Not Before: ${_.signInWithSolana.notBefore}`]:[],...!((i=_?.signInWithSolana)===null||i===void 0)&&i.expirationTime?[`Expiration Time: ${_.signInWithSolana.expirationTime}`]:[],...!((a=_?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${_.signInWithSolana.chainId}`]:[],...!((l=_?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${_.signInWithSolana.nonce}`]:[],...!((u=_?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${_.signInWithSolana.requestId}`]:[],...!((d=(c=_?.signInWithSolana)===null||c===void 0?void 0:c.resources)===null||d===void 0)&&d.length?["Resources",..._.signInWithSolana.resources.map(P=>`- ${P}`)]:[]].join(`
|
|
87
|
-
`);let x=await v.signMessage(new TextEncoder().encode(h),"utf8");if(!x||!(x instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=x}}try{let{data:y,error:p}=await A(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:h,signature:ar(g)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(m=e.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:ct});if(p)throw p;if(!y||!y.session||!y.user){let b=new ir;return this._returnResult({data:{user:null,session:null},error:b})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:p})}catch(y){if(T(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async _exchangeCodeForSession(e){let r=await vr(this.storage,`${this.storageKey}-code-verifier`),[o,n]=(r??"").split("/");try{if(!o&&this.flowType==="pkce")throw new Di;let{data:s,error:i}=await A(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:o},xform:ct});if(await Oe(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!s||!s.session||!s.user){let a=new ir;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign(Object.assign({},s),{redirectType:n??null}),error:i})}catch(s){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),T(s))return this._returnResult({data:{user:null,session:null,redirectType:null},error:s});throw s}}async signInWithIdToken(e){try{let{options:r,provider:o,token:n,access_token:s,nonce:i}=e,a=await A(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:o,id_token:n,access_token:s,nonce:i,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:ct}),{data:l,error:u}=a;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){let c=new ir;return this._returnResult({data:{user:null,session:null},error:c})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:u})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,o,n,s,i;try{if("email"in e){let{email:a,options:l}=e,u=null,c=null;this.flowType==="pkce"&&([u,c]=await Zr(this.storage,this.storageKey));let{error:d}=await A(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(o=l?.shouldCreateUser)!==null&&o!==void 0?o:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:u,code_challenge_method:c},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){let{phone:a,options:l}=e,{data:u,error:c}=await A(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(n=l?.data)!==null&&n!==void 0?n:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(i=l?.channel)!==null&&i!==void 0?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u?.message_id},error:c})}throw new Kr("You must provide either an email or phone number.")}catch(a){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),T(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,o;try{let n,s;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,s=(o=e.options)===null||o===void 0?void 0:o.captchaToken);let{data:i,error:a}=await A(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:s}}),redirectTo:n,xform:ct});if(a)throw a;if(!i)throw new Error("An error occurred on token verification.");let l=i.session,u=i.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(n){if(T(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,o,n,s,i;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await Zr(this.storage,this.storageKey));let u=await A(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:(o=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&o!==void 0?o:void 0}),!((n=e?.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:l}),headers:this.headers,xform:Mm});return!((s=u.data)===null||s===void 0)&&s.url&&Te()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(a){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),T(a))return this._returnResult({data:null,error:a});throw a}}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:r},error:o}=e;if(o)throw o;if(!r)throw new je;let{error:n}=await A(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(T(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let r=`${this.url}/resend`;if("email"in e){let{email:o,type:n,options:s}=e,{error:i}=await A(this.fetch,"POST",r,{headers:this.headers,body:{email:o,type:n,gotrue_meta_security:{captcha_token:s?.captchaToken}},redirectTo:s?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}else if("phone"in e){let{phone:o,type:n,options:s}=e,{data:i,error:a}=await A(this.fetch,"POST",r,{headers:this.headers,body:{phone:o,type:n,gotrue_meta_security:{captcha_token:s?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:i?.message_id},error:a})}throw new Kr("You must provide either an email or phone number and a type")}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let o=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await o,await r()))();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 o=r();for(this.pendingInLock.push((async()=>{try{await o}catch{}})()),await o;this.pendingInLock.length;){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await o}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,r=await vr(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let o=e.expires_at?e.expires_at*1e3-Date.now()<Ri:!1;if(this._debug("#__loadSession()",`session has${o?"":" not"} expired`,"expires_at",e.expires_at),!o){if(this.userStorage){let i=await vr(this.userStorage,this.storageKey+"-user");i?.user?e.user=i.user:e.user=Fi()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let i={value:this.suppressGetSessionWarning};e.user=Nm(e.user,i),i.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{session:null},error:s}):this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await A(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Ft}):await this._useSession(async r=>{var o,n,s;let{data:i,error:a}=r;if(a)throw a;return!(!((o=i.session)===null||o===void 0)&&o.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new je}:await A(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(s=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0,xform:Ft})})}catch(r){if(T(r))return Li(r)&&(await this._removeSession(),await Oe(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async o=>{let{data:n,error:s}=o;if(s)throw s;if(!n.session)throw new je;let i=n.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await Zr(this.storage,this.storageKey));let{data:u,error:c}=await A(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:i.access_token,xform:Ft});if(c)throw c;return i.user=u.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})})}catch(o){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),T(o))return this._returnResult({data:{user:null},error:o});throw o}}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 je;let r=Date.now()/1e3,o=r,n=!0,s=null,{payload:i}=fs(e.access_token);if(i.exp&&(o=i.exp,n=o<=r),n){let{data:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a)return{data:{user:null,session:null},error:null};s=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});s={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:o-r,expires_at:o},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)}return this._returnResult({data:{user:s.user,session:s},error:null})}catch(r){if(T(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}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 r=>{var o;if(!e){let{data:i,error:a}=r;if(a)throw a;e=(o=i.session)!==null&&o!==void 0?o:void 0}if(!e?.refresh_token)throw new je;let{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!Te())throw new Jr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Jr(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new us("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Jr("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new us("No code detected.");let{data:b,error:_}=await this._exchangeCodeForSession(e.code);if(_)throw _;let v=new URL(window.location.href);return v.searchParams.delete("code"),window.history.replaceState(window.history.state,"",v.toString()),{data:{session:b.session,redirectType:null},error:null}}let{provider_token:o,provider_refresh_token:n,access_token:s,refresh_token:i,expires_in:a,expires_at:l,token_type:u}=e;if(!s||!a||!i||!u)throw new Jr("No session defined in URL");let c=Math.round(Date.now()/1e3),d=parseInt(a),f=c+d;l&&(f=parseInt(l));let m=f-c;m*1e3<=Gr&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${d}s`);let h=f-d;c-h>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",h,f,c):c-h<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",h,f,c);let{data:g,error:y}=await this._getUser(s);if(y)throw y;let p={provider_token:o,provider_refresh_token:n,access_token:s,expires_in:d,expires_at:f,refresh_token:i,token_type:u,user:g.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:p,redirectType:e.type},error:null})}catch(o){if(T(o))return this._returnResult({data:{session:null,redirectType:null},error:o});throw o}}_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 r=await vr(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}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 r=>{var o;let{data:n,error:s}=r;if(s&&!Li(s))return this._returnResult({error:s});let i=(o=n.session)===null||o===void 0?void 0:o.access_token;if(i){let{error:a}=await this.admin.signOut(i,e);if(a&&!(wm(a)&&(a.status===404||a.status===401||a.status===403)||Li(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await Oe(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=Em(),o={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,o),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:o}}}async _emitInitialSession(e){return await this._useSession(async r=>{var o,n;try{let{data:{session:s},error:i}=r;if(i)throw i;await((o=this.stateChangeEmitters.get(e))===null||o===void 0?void 0:o.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(s){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",s),console.error(s)}})}async resetPasswordForEmail(e,r={}){let o=null,n=null;this.flowType==="pkce"&&([o,n]=await Zr(this.storage,this.storageKey,!0));try{return await A(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:o,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(s){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),T(s))return this._returnResult({data:null,error:s});throw s}}async getUserIdentities(){var e;try{let{data:r,error:o}=await this.getUser();if(o)throw o;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{let{data:o,error:n}=await this._useSession(async s=>{var i,a,l,u,c;let{data:d,error:f}=s;if(f)throw f;let m=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(i=e.options)===null||i===void 0?void 0:i.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await A(this.fetch,"GET",m,{headers:this.headers,jwt:(c=(u=d.session)===null||u===void 0?void 0:u.access_token)!==null&&c!==void 0?c:void 0})});if(n)throw n;return Te()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(o?.url),this._returnResult({data:{provider:e.provider,url:o?.url},error:null})}catch(o){if(T(o))return this._returnResult({data:{provider:e.provider,url:null},error:o});throw o}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var o;try{let{error:n,data:{session:s}}=r;if(n)throw n;let{options:i,provider:a,token:l,access_token:u,nonce:c}=e,d=await A(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(o=s?.access_token)!==null&&o!==void 0?o:void 0,body:{provider:a,id_token:l,access_token:u,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:ct}),{data:f,error:m}=d;return m?this._returnResult({data:{user:null,session:null},error:m}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new ir}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:m}))}catch(n){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),T(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var o,n;let{data:s,error:i}=r;if(i)throw i;return await A(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(o=s.session)===null||o===void 0?void 0:o.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){let r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{let o=Date.now();return await Rm(async n=>(n>0&&await Am(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await A(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:ct})),(n,s)=>{let i=200*Math.pow(2,n);return s&&Ni(s)&&Date.now()+i-o<Gr})}catch(o){if(this._debug(r,"error",o),T(o))return this._returnResult({data:{session:null,user:null},error:o});throw o}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){let o=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",o),Te()&&!r.skipBrowserRedirect&&window.location.assign(o),{data:{provider:e,url:o},error:null}}async _recoverAndRefresh(){var e,r;let o="#_recoverAndRefresh()";this._debug(o,"begin");try{let n=await vr(this.storage,this.storageKey);if(n&&this.userStorage){let i=await vr(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!i&&(i={user:n.user},await Qr(this.userStorage,this.storageKey+"-user",i)),n.user=(e=i?.user)!==null&&e!==void 0?e:Fi()}else if(n&&!n.user&&!n.user){let i=await vr(this.storage,this.storageKey+"-user");i&&i?.user?(n.user=i.user,await Oe(this.storage,this.storageKey+"-user"),await Qr(this.storage,this.storageKey,n)):n.user=Fi()}if(this._debug(o,"session from storage",n),!this._isValidSession(n)){this._debug(o,"session is not valid"),n!==null&&await this._removeSession();return}let s=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Ri;if(this._debug(o,`session has${s?"":" not"} expired with margin of ${Ri}s`),s){if(this.autoRefreshToken&&n.refresh_token){let{error:i}=await this._callRefreshToken(n.refresh_token);i&&(console.error(i),Ni(i)||(this._debug(o,"refresh failed with a non-retryable error, removing the session",i),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{let{data:i,error:a}=await this._getUser(n.access_token);!a&&i?.user?(n.user=i.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(o,"could not get user data, skipping SIGNED_IN notification")}catch(i){console.error("Error getting user data:",i),this._debug(o,"error getting user data, skipping SIGNED_IN notification",i)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(o,"error",n),console.error(n);return}finally{this._debug(o,"end")}}async _callRefreshToken(e){var r,o;if(!e)throw new je;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new ds;let{data:s,error:i}=await this._refreshAccessToken(e);if(i)throw i;if(!s.session)throw new je;await this._saveSession(s.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",s.session);let a={data:s.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(s){if(this._debug(n,"error",s),T(s)){let i={data:null,error:s};return Ni(s)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(i),i}throw(o=this.refreshingDeferred)===null||o===void 0||o.reject(s),s}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,o=!0){let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${o}`);try{this.broadcastChannel&&o&&this.broadcastChannel.postMessage({event:e,session:r});let s=[],i=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(l){s.push(l)}});if(await Promise.all(i),s.length>0){for(let a=0;a<s.length;a+=1)console.error(s[a]);throw s[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Oe(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),o=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!o&&r.user&&await Qr(this.userStorage,this.storageKey+"-user",{user:r.user});let n=Object.assign({},r);delete n.user;let s=gu(n);await Qr(this.storage,this.storageKey,s)}else{let n=gu(r);await Qr(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Oe(this.storage,this.storageKey),await Oe(this.storage,this.storageKey+"-code-verifier"),await Oe(this.storage,this.storageKey+"-user"),this.userStorage&&await Oe(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Te()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),Gr);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}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 r=>{let{data:{session:o}}=r;if(!o||!o.refresh_token||!o.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((o.expires_at*1e3-e)/Gr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${Gr}ms, refresh threshold is ${Ai} ticks`),n<=Ai&&await this._callRefreshToken(o.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof ms)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Te()||!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?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let r=`#_onVisibilityChanged(${e})`;this._debug(r,"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(r,"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,r,o){let n=[`provider=${encodeURIComponent(r)}`];if(o?.redirectTo&&n.push(`redirect_to=${encodeURIComponent(o.redirectTo)}`),o?.scopes&&n.push(`scopes=${encodeURIComponent(o.scopes)}`),this.flowType==="pkce"){let[s,i]=await Zr(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(i)}`});n.push(a.toString())}if(o?.queryParams){let s=new URLSearchParams(o.queryParams);n.push(s.toString())}return o?.skipBrowserRedirect&&n.push(`skip_http_redirect=${o.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var o;let{data:n,error:s}=r;return s?this._returnResult({data:null,error:s}):await A(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.access_token})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var o,n;let{data:s,error:i}=r;if(i)return this._returnResult({data:null,error:i});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:u}=await A(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(o=s?.session)===null||o===void 0?void 0:o.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&l.type==="totp"&&(!((n=l?.totp)===null||n===void 0)&&n.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var o;let{data:n,error:s}=r;if(s)return this._returnResult({data:null,error:s});let i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Km(e.webauthn.credential_response):Jm(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await A(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.access_token});return l?this._returnResult({data:null,error:l}):(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:l}))})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var o;let{data:n,error:s}=r;if(s)return this._returnResult({data:null,error:s});let i=await A(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.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:zm(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:Gm(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){let{data:r,error:o}=await this._challenge({factorId:e.factorId});return o?this._returnResult({data:null,error:o}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:o}=await this.getUser();if(o)return{data:null,error:o};let n={all:[],phone:[],totp:[],webauthn:[]};for(let s of(e=r?.factors)!==null&&e!==void 0?e:[])n.all.push(s),s.status==="verified"&&n[s.factor_type].push(s);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,o,n,s;if(e)try{let{payload:m}=fs(e),h=null;m.aal&&(h=m.aal);let g=h,{data:{user:y},error:p}=await this.getUser(e);if(p)return this._returnResult({data:null,error:p});((o=(r=y?.factors)===null||r===void 0?void 0:r.filter(v=>v.status==="verified"))!==null&&o!==void 0?o:[]).length>0&&(g="aal2");let _=m.amr||[];return{data:{currentLevel:h,nextLevel:g,currentAuthenticationMethods:_},error:null}}catch(m){if(T(m))return this._returnResult({data:null,error:m});throw m}let{data:{session:i},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:l}=fs(i.access_token),u=null;l.aal&&(u=l.aal);let c=u;((s=(n=i.user.factors)===null||n===void 0?void 0:n.filter(m=>m.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let f=l.amr||[];return{data:{currentLevel:u,nextLevel:c,currentAuthenticationMethods:f},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:o},error:n}=r;return n?this._returnResult({data:null,error:n}):o?await A(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:o.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new je})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async o=>{let{data:{session:n},error:s}=o;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new je});let i=await A(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return i.data&&i.data.redirect_url&&Te()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(o){if(T(o))return this._returnResult({data:null,error:o});throw o}}async _denyAuthorization(e,r){try{return await this._useSession(async o=>{let{data:{session:n},error:s}=o;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new je});let i=await A(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return i.data&&i.data.redirect_url&&Te()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(o){if(T(o))return this._returnResult({data:null,error:o});throw o}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:o}=e;return o?this._returnResult({data:null,error:o}):r?await A(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new je})})}catch(e){if(T(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:o},error:n}=r;return n?this._returnResult({data:null,error:n}):o?(await A(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:o.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new je})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let o=r.keys.find(a=>a.kid===e);if(o)return o;let n=Date.now();if(o=this.jwks.keys.find(a=>a.kid===e),o&&this.jwks_cached_at+_m>n)return o;let{data:s,error:i}=await A(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return!s.keys||s.keys.length===0||(this.jwks=s,this.jwks_cached_at=n,o=s.keys.find(a=>a.kid===e),!o)?null:o}async getClaims(e,r={}){try{let o=e;if(!o){let{data:m,error:h}=await this.getSession();if(h||!m.session)return this._returnResult({data:null,error:h});o=m.session.access_token}let{header:n,payload:s,signature:i,raw:{header:a,payload:l}}=fs(o);r?.allowExpired||Dm(s.exp);let u=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!u){let{error:m}=await this.getUser(o);if(m)throw m;return{data:{claims:s,header:n,signature:i},error:null}}let c=Lm(n.alg),d=await crypto.subtle.importKey("jwk",u,c,!0,["verify"]);if(!await crypto.subtle.verify(c,d,i,Tm(`${a}.${l}`)))throw new Yr("Invalid JWT signature");return{data:{claims:s,header:n,signature:i},error:null}}catch(o){if(T(o))return this._returnResult({data:null,error:o});throw o}}};Vi.nextInstanceID={};var ku=Vi;var xv=ku,Tu=xv;var kv="2.100.1",ps="";typeof Deno<"u"?ps="deno":typeof document<"u"?ps="web":typeof navigator<"u"&&navigator.product==="ReactNative"?ps="react-native":ps="node";var Tv={"X-Client-Info":`supabase-js-${ps}/${kv}`},Cv={headers:Tv},Ev={schema:"public"},Pv={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Ov={};function gs(t){"@babel/helpers - typeof";return gs=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},gs(t)}function Av(t,e){if(gs(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(gs(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Rv(t){var e=Av(t,"string");return gs(e)=="symbol"?e:e+""}function Iv(t,e,r){return(e=Rv(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Xm(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function me(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Xm(Object(r),!0).forEach(function(o){Iv(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Xm(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var Dv=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Lv=()=>Headers,Nv=(t,e,r)=>{let o=Dv(r),n=Lv();return async(s,i)=>{var a;let l=(a=await e())!==null&&a!==void 0?a:t,u=new n(i?.headers);return u.has("apikey")||u.set("apikey",t),u.has("Authorization")||u.set("Authorization",`Bearer ${l}`),o(s,me(me({},i),{},{headers:u}))}};function jv(t){return t.endsWith("/")?t:t+"/"}function Mv(t,e){var r,o;let{db:n,auth:s,realtime:i,global:a}=t,{db:l,auth:u,realtime:c,global:d}=e,f={db:me(me({},l),n),auth:me(me({},u),s),realtime:me(me({},c),i),storage:{},global:me(me(me({},d),a),{},{headers:me(me({},(r=d?.headers)!==null&&r!==void 0?r:{}),(o=a?.headers)!==null&&o!==void 0?o:{})}),accessToken:async()=>""};return t.accessToken?f.accessToken=t.accessToken:delete f.accessToken,f}function Uv(t){let e=t?.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(jv(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Fv=class extends Tu{constructor(t){super(t)}},$v=class{constructor(t,e,r){var o,n;this.supabaseUrl=t,this.supabaseKey=e;let s=Uv(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",s),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",s),this.storageUrl=new URL("storage/v1",s),this.functionsUrl=new URL("functions/v1",s);let i=`sb-${s.hostname.split(".")[0]}-auth-token`,a={db:Ev,realtime:Ov,auth:me(me({},Pv),{},{storageKey:i}),global:Cv},l=Mv(r??{},a);if(this.storageKey=(o=l.auth.storageKey)!==null&&o!==void 0?o:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(c,d)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} is not possible`)}});else{var u;this.auth=this._initSupabaseAuthClient((u=l.auth)!==null&&u!==void 0?u:{},this.headers,l.global.fetch)}this.fetch=Nv(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(me({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(c=>this.realtime.setAuth(c)).catch(c=>console.warn("Failed to set initial Realtime auth token:",c)),this.rest=new Qf(new URL("rest/v1",s).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new hm(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new Xn(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();let{data:o}=await t.auth.getSession();return(e=(r=o.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:o,userStorage:n,storageKey:s,flowType:i,lock:a,debug:l,throwOnError:u},c,d){let f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Fv({url:this.authUrl.href,headers:me(me({},f),c),storageKey:s,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:o,userStorage:n,flowType:i,lock:a,debug:l,throwOnError:u,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(m=>m.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new qo(this.realtimeUrl.href,me(me({},t),{},{params:me(me({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},Qm=(t,e,r)=>new $v(t,e,r);function Bv(){if(typeof window<"u")return!1;let t=globalThis.process;if(!t)return!1;let e=t.version;if(e==null)return!1;let r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}Bv()&&console.warn("\u26A0\uFE0F 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 Cu="0.5.2";var th=Le(Pu());function no(){return typeof window<"u"&&typeof window.document<"u"}var Sr={path:"/",sameSite:"lax",httpOnly:!1,maxAge:3456e4};var Zv=/^(.*)[.](0|[1-9][0-9]*)$/;function ys(t,e){if(t===e)return!0;let r=t.match(Zv);return!!(r&&r[1]===e)}function Ou(t,e,r){let o=r??3180,n=encodeURIComponent(e);if(n.length<=o)return[{name:t,value:e}];let s=[];for(;n.length>0;){let i=n.slice(0,o),a=i.lastIndexOf("%");a>o-3&&(i=i.slice(0,a));let l="";for(;i.length>0;)try{l=decodeURIComponent(i);break}catch(u){if(u instanceof URIError&&i.at(-3)==="%"&&i.length>3)i=i.slice(0,i.length-3);else throw u}s.push(l),n=n.slice(i.length)}return s.map((i,a)=>({name:`${t}.${a}`,value:i}))}async function Au(t,e){let r=await e(t);if(r)return r;let o=[];for(let n=0;;n++){let s=`${t}.${n}`,i=await e(s);if(!i)break;o.push(i)}return o.length>0?o.join(""):null}var Wi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),rh=`
|
|
88
|
-
\r=`.split(""),e0=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<rh.length;e+=1)t[rh[e].charCodeAt(0)]=-2;for(let e=0;e<
|
|
86
|
+
${p}`}var ue=class extends Error{constructor({message:e,code:r,cause:o,name:n}){var s;super(e,{cause:o}),this.__isWebAuthnError=!0,this.name=(s=n??(o instanceof Error?o.name:void 0))!==null&&s!==void 0?s:"Unknown Error",this.code=r}},oo=class extends ue{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}};function Vm({error:t,options:e}){var r,o,n;let{publicKey:s}=e;if(!s)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ue({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=s.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new ue({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((o=s.authenticatorSelection)===null||o===void 0?void 0:o.userVerification)==="required")return new ue({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((n=s.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new ue({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new ue({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new ue({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return s.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new ue({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new ue({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){let i=window.location.hostname;if(ku(i)){if(s.rp.id!==i)return new ue({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new ue({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(s.user.id.byteLength<1||s.user.id.byteLength>64)return new ue({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new ue({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new ue({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Wm({error:t,options:e}){let{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ue({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new ue({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if(ku(o)){if(r.rpId!==o)return new ue({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new ue({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new ue({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new ue({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}var Tu=class{createNewAbortSignal(){if(this.controller){let r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},pv=new Tu;function zm(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);let{challenge:e,user:r,excludeCredentials:o}=t,n=We(t,["challenge","user","excludeCredentials"]),s=wr(e).buffer,i=Object.assign(Object.assign({},r),{id:wr(r.id).buffer}),a=Object.assign(Object.assign({},n),{challenge:s,user:i});if(o&&o.length>0){a.excludeCredentials=new Array(o.length);for(let l=0;l<o.length;l++){let u=o[l];a.excludeCredentials[l]=Object.assign(Object.assign({},u),{id:wr(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return a}function Gm(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);let{challenge:e,allowCredentials:r}=t,o=We(t,["challenge","allowCredentials"]),n=wr(e).buffer,s=Object.assign(Object.assign({},o),{challenge:n});if(r&&r.length>0){s.allowCredentials=new Array(r.length);for(let i=0;i<r.length;i++){let a=r[i];s.allowCredentials[i]=Object.assign(Object.assign({},a),{id:wr(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return s}function Km(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t;return{id:t.id,rawId:t.id,response:{attestationObject:ar(new Uint8Array(t.response.attestationObject)),clientDataJSON:ar(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Jm(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,o=t.getClientExtensionResults(),n=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:ar(new Uint8Array(n.authenticatorData)),clientDataJSON:ar(new Uint8Array(n.clientDataJSON)),signature:ar(new Uint8Array(n.signature)),userHandle:n.userHandle?ar(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:o,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function ku(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Hm(){var t,e;return!!(Te()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function gv(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new oo("Browser returned unexpected credential type",e)}:{data:null,error:new oo("Empty credential response",e)}}catch(e){return{data:null,error:Vm({error:e,options:t})}}}async function yv(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new oo("Browser returned unexpected credential type",e)}:{data:null,error:new oo("Empty credential response",e)}}catch(e){return{data:null,error:Wm({error:e,options:t})}}}var bv={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},_v={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Vi(...t){let e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),o={};for(let n of t)if(n)for(let s in n){let i=n[s];if(i!==void 0)if(Array.isArray(i))o[s]=i;else if(r(i))o[s]=i;else if(e(i)){let a=o[s];e(a)?o[s]=Vi(a,i):o[s]=Vi(i)}else o[s]=i}return o}function wv(t,e){return Vi(bv,t,e||{})}function vv(t,e){return Vi(_v,t,e||{})}var Wi=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:r,friendlyName:o,signal:n},s){var i;try{let{data:a,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:l};let u=n??pv.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:c}=a.webauthn.credential_options.publicKey;if(!c.name){let d=o;if(d)c.name=`${c.id}:${d}`;else{let m=(await this.client.getUser()).data.user,h=((i=m?.user_metadata)===null||i===void 0?void 0:i.name)||m?.email||m?.id||"User";c.name=`${c.id}:${h}`}}c.displayName||(c.displayName=c.name)}switch(a.webauthn.type){case"create":{let c=wv(a.webauthn.credential_options.publicKey,s?.create),{data:d,error:f}=await gv({publicKey:c,signal:u});return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:f}}case"request":{let c=vv(a.webauthn.credential_options.publicKey,s?.request),{data:d,error:f}=await yv(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:c,signal:u}));return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:f}}}}catch(a){return T(a)?{data:null,error:a}:{data:null,error:new ut("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:o}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:o})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:o=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},s){if(!r)return{data:null,error:new _r("rpId is required for WebAuthn authentication")};try{if(!Hm())return{data:null,error:new ut("Browser does not support WebAuthn",null)};let{data:i,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:o},signal:n},{request:s});if(!i)return{data:null,error:a};let{webauthn:l}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:o,credential_response:l.credential_response}})}catch(i){return T(i)?{data:null,error:i}:{data:null,error:new ut("Unexpected error in authenticate",i)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:o=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},s){if(!r)return{data:null,error:new _r("rpId is required for WebAuthn registration")};try{if(!Hm())return{data:null,error:new ut("Browser does not support WebAuthn",null)};let{data:i,error:a}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then(c=>{var d;return(d=c.data)===null||d===void 0?void 0:d.all.find(f=>f.factor_type==="webauthn"&&f.friendly_name===e&&f.status!=="unverified")}).then(c=>c?this.client.mfa.unenroll({factorId:c?.id}):void 0),{data:null,error:a};let{data:l,error:u}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:r,rpOrigins:o},signal:n},{create:s});return l?this._verify({factorId:i.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:o,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:u}}catch(i){return T(i)?{data:null,error:i}:{data:null,error:new ut("Unexpected error in register",i)}}}};Fm();var Sv={url:pm,storageKey:gm,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:ym,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1};async function Ym(t,e,r){return await r()}var Ho={},Hi=class t{get jwks(){var e,r;return(r=(e=Ho[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Ho[this.storageKey]=Object.assign(Object.assign({},Ho[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Ho[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Ho[this.storageKey]=Object.assign(Object.assign({},Ho[this.storageKey]),{cachedAt:e})}constructor(e){var r,o,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 s=Object.assign(Object.assign({},Sv),e);if(this.storageKey=s.storageKey,this.instanceID=(r=t.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,t.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.instanceID>0&&Te()){let i=`${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(i),this.logDebugMessages&&console.trace(i)}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.admin=new ro({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=$i(s.fetch),this.lock=s.lock||Ym,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,this.lockAcquireTimeout=s.lockAcquireTimeout,s.lock?this.lock=s.lock:this.persistSession&&Te()&&(!((o=globalThis?.navigator)===null||o===void 0)&&o.locks)?this.lock=Su:this.lock=Ym,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new Wi(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?(s.storage?this.storage=s.storage:Fi()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=vu(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=vu(this.memoryStorage)),Te()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i);try{await this._notifyAllSubscribers(i.data.event,i.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}s.skipAutoInitialize||this.initialize().catch(i=>{this._debug("#initialize()","error",i)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Ri}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},o="none";if(Te()&&(r=Pm(window.location.href),this._isImplicitGrantCallback(r)?o="implicit":await this._isPKCECallback(r)&&(o="pkce")),Te()&&this.detectSessionInUrl&&o!=="none"){let{data:n,error:s}=await this._getSessionFromURL(r,o);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),vm(s)){let l=(e=s.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:s}}return{error:s}}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(r){return T(r)?this._returnResult({error:r}):this._returnResult({error:new ut("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,o,n;try{let s=await A(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(o=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&o!==void 0?o:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:ct}),{data:i,error:a}=s;if(a||!i)return this._returnResult({data:{user:null,session:null},error:a});let l=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(T(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signUp(e){var r,o,n;try{let s;if("email"in e){let{email:c,password:d,options:f}=e,m=null,h=null;this.flowType==="pkce"&&([m,h]=await Zr(this.storage,this.storageKey)),s=await A(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:c,password:d,data:(r=f?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:m,code_challenge_method:h},xform:ct})}else if("phone"in e){let{phone:c,password:d,options:f}=e;s=await A(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:d,data:(o=f?.data)!==null&&o!==void 0?o:{},channel:(n=f?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:ct})}else throw new Kr("You must provide either an email or phone number and a password");let{data:i,error:a}=s;if(a||!i)return await Oe(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let l=i.session,u=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(s){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),T(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithPassword(e){try{let r;if("email"in e){let{email:s,password:i,options:a}=e;r=await A(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:i,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:_u})}else if("phone"in e){let{phone:s,password:i,options:a}=e;r=await A(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:i,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:_u})}else throw new Kr("You must provide either an email or phone number and a password");let{data:o,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!o||!o.session||!o.user){let s=new ir;return this._returnResult({data:{user:null,session:null},error:s})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),this._returnResult({data:Object.assign({user:o.user,session:o.session},o.weak_password?{weakPassword:o.weak_password}:null),error:n})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,o,n,s;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(o=e.options)===null||o===void 0?void 0:o.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(s=e.options)===null||s===void 0?void 0:s.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,o,n,s,i,a,l,u,c,d,f;let m,h;if("message"in e)m=e.message,h=e.signature;else{let{chain:g,wallet:y,statement:p,options:b}=e,_;if(Te())if(typeof y=="object")_=y;else{let q=window;if("ethereum"in q&&typeof q.ethereum=="object"&&"request"in q.ethereum&&typeof q.ethereum.request=="function")_=q.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof y!="object"||!b?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=y}let v=new URL((r=b?.url)!==null&&r!==void 0?r:window.location.href),N=await _.request({method:"eth_requestAccounts"}).then(q=>q).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!N||N.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let x=xu(N[0]),P=(o=b?.signInWithEthereum)===null||o===void 0?void 0:o.chainId;if(!P){let q=await _.request({method:"eth_chainId"});P=$m(q)}let Z={domain:v.host,address:x,statement:p,uri:v.href,version:"1",chainId:P,nonce:(n=b?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(i=(s=b?.signInWithEthereum)===null||s===void 0?void 0:s.issuedAt)!==null&&i!==void 0?i:new Date,expirationTime:(a=b?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=b?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=b?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(c=b?.signInWithEthereum)===null||c===void 0?void 0:c.resources};m=qm(Z),h=await _.request({method:"personal_sign",params:[Bm(m),x]})}try{let{data:g,error:y}=await A(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:m,signature:h},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:ct});if(y)throw y;if(!g||!g.session||!g.user){let p=new ir;return this._returnResult({data:{user:null,session:null},error:p})}return g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),this._returnResult({data:Object.assign({},g),error:y})}catch(g){if(T(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async signInWithSolana(e){var r,o,n,s,i,a,l,u,c,d,f,m;let h,g;if("message"in e)h=e.message,g=e.signature;else{let{chain:y,wallet:p,statement:b,options:_}=e,v;if(Te())if(typeof p=="object")v=p;else{let x=window;if("solana"in x&&typeof x.solana=="object"&&("signIn"in x.solana&&typeof x.solana.signIn=="function"||"signMessage"in x.solana&&typeof x.solana.signMessage=="function"))v=x.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof p!="object"||!_?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");v=p}let N=new URL((r=_?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in v&&v.signIn){let x=await v.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},_?.signInWithSolana),{version:"1",domain:N.host,uri:N.href}),b?{statement:b}:null)),P;if(Array.isArray(x)&&x[0]&&typeof x[0]=="object")P=x[0];else if(x&&typeof x=="object"&&"signedMessage"in x&&"signature"in x)P=x;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in P&&"signature"in P&&(typeof P.signedMessage=="string"||P.signedMessage instanceof Uint8Array)&&P.signature instanceof Uint8Array)h=typeof P.signedMessage=="string"?P.signedMessage:new TextDecoder().decode(P.signedMessage),g=P.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in v)||typeof v.signMessage!="function"||!("publicKey"in v)||typeof v!="object"||!v.publicKey||!("toBase58"in v.publicKey)||typeof v.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");h=[`${N.host} wants you to sign in with your Solana account:`,v.publicKey.toBase58(),...b?["",b,""]:[""],"Version: 1",`URI: ${N.href}`,`Issued At: ${(n=(o=_?.signInWithSolana)===null||o===void 0?void 0:o.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((s=_?.signInWithSolana)===null||s===void 0)&&s.notBefore?[`Not Before: ${_.signInWithSolana.notBefore}`]:[],...!((i=_?.signInWithSolana)===null||i===void 0)&&i.expirationTime?[`Expiration Time: ${_.signInWithSolana.expirationTime}`]:[],...!((a=_?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${_.signInWithSolana.chainId}`]:[],...!((l=_?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${_.signInWithSolana.nonce}`]:[],...!((u=_?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${_.signInWithSolana.requestId}`]:[],...!((d=(c=_?.signInWithSolana)===null||c===void 0?void 0:c.resources)===null||d===void 0)&&d.length?["Resources",..._.signInWithSolana.resources.map(P=>`- ${P}`)]:[]].join(`
|
|
87
|
+
`);let x=await v.signMessage(new TextEncoder().encode(h),"utf8");if(!x||!(x instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=x}}try{let{data:y,error:p}=await A(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:h,signature:ar(g)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(m=e.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:ct});if(p)throw p;if(!y||!y.session||!y.user){let b=new ir;return this._returnResult({data:{user:null,session:null},error:b})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:p})}catch(y){if(T(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async _exchangeCodeForSession(e){let r=await vr(this.storage,`${this.storageKey}-code-verifier`),[o,n]=(r??"").split("/");try{if(!o&&this.flowType==="pkce")throw new Ni;let{data:s,error:i}=await A(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:o},xform:ct});if(await Oe(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!s||!s.session||!s.user){let a=new ir;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign(Object.assign({},s),{redirectType:n??null}),error:i})}catch(s){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),T(s))return this._returnResult({data:{user:null,session:null,redirectType:null},error:s});throw s}}async signInWithIdToken(e){try{let{options:r,provider:o,token:n,access_token:s,nonce:i}=e,a=await A(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:o,id_token:n,access_token:s,nonce:i,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:ct}),{data:l,error:u}=a;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){let c=new ir;return this._returnResult({data:{user:null,session:null},error:c})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:u})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,o,n,s,i;try{if("email"in e){let{email:a,options:l}=e,u=null,c=null;this.flowType==="pkce"&&([u,c]=await Zr(this.storage,this.storageKey));let{error:d}=await A(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(o=l?.shouldCreateUser)!==null&&o!==void 0?o:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:u,code_challenge_method:c},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){let{phone:a,options:l}=e,{data:u,error:c}=await A(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(n=l?.data)!==null&&n!==void 0?n:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(i=l?.channel)!==null&&i!==void 0?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u?.message_id},error:c})}throw new Kr("You must provide either an email or phone number.")}catch(a){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),T(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,o;try{let n,s;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,s=(o=e.options)===null||o===void 0?void 0:o.captchaToken);let{data:i,error:a}=await A(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:s}}),redirectTo:n,xform:ct});if(a)throw a;if(!i)throw new Error("An error occurred on token verification.");let l=i.session,u=i.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(n){if(T(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,o,n,s,i;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await Zr(this.storage,this.storageKey));let u=await A(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:(o=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&o!==void 0?o:void 0}),!((n=e?.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:l}),headers:this.headers,xform:Mm});return!((s=u.data)===null||s===void 0)&&s.url&&Te()&&!(!((i=e.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(a){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),T(a))return this._returnResult({data:null,error:a});throw a}}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:r},error:o}=e;if(o)throw o;if(!r)throw new je;let{error:n}=await A(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(T(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let r=`${this.url}/resend`;if("email"in e){let{email:o,type:n,options:s}=e,{error:i}=await A(this.fetch,"POST",r,{headers:this.headers,body:{email:o,type:n,gotrue_meta_security:{captcha_token:s?.captchaToken}},redirectTo:s?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}else if("phone"in e){let{phone:o,type:n,options:s}=e,{data:i,error:a}=await A(this.fetch,"POST",r,{headers:this.headers,body:{phone:o,type:n,gotrue_meta_security:{captcha_token:s?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:i?.message_id},error:a})}throw new Kr("You must provide either an email or phone number and a type")}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let o=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await o,await r()))();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 o=r();for(this.pendingInLock.push((async()=>{try{await o}catch{}})()),await o;this.pendingInLock.length;){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await o}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,r=await vr(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let o=e.expires_at?e.expires_at*1e3-Date.now()<Di:!1;if(this._debug("#__loadSession()",`session has${o?"":" not"} expired`,"expires_at",e.expires_at),!o){if(this.userStorage){let i=await vr(this.userStorage,this.storageKey+"-user");i?.user?e.user=i.user:e.user=Bi()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let i={value:this.suppressGetSessionWarning};e.user=Nm(e.user,i),i.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{session:null},error:s}):this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await A(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Ft}):await this._useSession(async r=>{var o,n,s;let{data:i,error:a}=r;if(a)throw a;return!(!((o=i.session)===null||o===void 0)&&o.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new je}:await A(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(s=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0,xform:Ft})})}catch(r){if(T(r))return ji(r)&&(await this._removeSession(),await Oe(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async o=>{let{data:n,error:s}=o;if(s)throw s;if(!n.session)throw new je;let i=n.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await Zr(this.storage,this.storageKey));let{data:u,error:c}=await A(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:i.access_token,xform:Ft});if(c)throw c;return i.user=u.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})})}catch(o){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),T(o))return this._returnResult({data:{user:null},error:o});throw o}}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 je;let r=Date.now()/1e3,o=r,n=!0,s=null,{payload:i}=fs(e.access_token);if(i.exp&&(o=i.exp,n=o<=r),n){let{data:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a)return{data:{user:null,session:null},error:null};s=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});s={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:o-r,expires_at:o},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)}return this._returnResult({data:{user:s.user,session:s},error:null})}catch(r){if(T(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}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 r=>{var o;if(!e){let{data:i,error:a}=r;if(a)throw a;e=(o=i.session)!==null&&o!==void 0?o:void 0}if(!e?.refresh_token)throw new je;let{data:n,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(T(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!Te())throw new Jr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Jr(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new us("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Jr("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new us("No code detected.");let{data:b,error:_}=await this._exchangeCodeForSession(e.code);if(_)throw _;let v=new URL(window.location.href);return v.searchParams.delete("code"),window.history.replaceState(window.history.state,"",v.toString()),{data:{session:b.session,redirectType:null},error:null}}let{provider_token:o,provider_refresh_token:n,access_token:s,refresh_token:i,expires_in:a,expires_at:l,token_type:u}=e;if(!s||!a||!i||!u)throw new Jr("No session defined in URL");let c=Math.round(Date.now()/1e3),d=parseInt(a),f=c+d;l&&(f=parseInt(l));let m=f-c;m*1e3<=Gr&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${d}s`);let h=f-d;c-h>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",h,f,c):c-h<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",h,f,c);let{data:g,error:y}=await this._getUser(s);if(y)throw y;let p={provider_token:o,provider_refresh_token:n,access_token:s,expires_in:d,expires_at:f,refresh_token:i,token_type:u,user:g.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:p,redirectType:e.type},error:null})}catch(o){if(T(o))return this._returnResult({data:{session:null,redirectType:null},error:o});throw o}}_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 r=await vr(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}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 r=>{var o;let{data:n,error:s}=r;if(s&&!ji(s))return this._returnResult({error:s});let i=(o=n.session)===null||o===void 0?void 0:o.access_token;if(i){let{error:a}=await this.admin.signOut(i,e);if(a&&!(wm(a)&&(a.status===404||a.status===401||a.status===403)||ji(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await Oe(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=Em(),o={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,o),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:o}}}async _emitInitialSession(e){return await this._useSession(async r=>{var o,n;try{let{data:{session:s},error:i}=r;if(i)throw i;await((o=this.stateChangeEmitters.get(e))===null||o===void 0?void 0:o.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(s){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",s),console.error(s)}})}async resetPasswordForEmail(e,r={}){let o=null,n=null;this.flowType==="pkce"&&([o,n]=await Zr(this.storage,this.storageKey,!0));try{return await A(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:o,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(s){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),T(s))return this._returnResult({data:null,error:s});throw s}}async getUserIdentities(){var e;try{let{data:r,error:o}=await this.getUser();if(o)throw o;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{let{data:o,error:n}=await this._useSession(async s=>{var i,a,l,u,c;let{data:d,error:f}=s;if(f)throw f;let m=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(i=e.options)===null||i===void 0?void 0:i.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await A(this.fetch,"GET",m,{headers:this.headers,jwt:(c=(u=d.session)===null||u===void 0?void 0:u.access_token)!==null&&c!==void 0?c:void 0})});if(n)throw n;return Te()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(o?.url),this._returnResult({data:{provider:e.provider,url:o?.url},error:null})}catch(o){if(T(o))return this._returnResult({data:{provider:e.provider,url:null},error:o});throw o}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var o;try{let{error:n,data:{session:s}}=r;if(n)throw n;let{options:i,provider:a,token:l,access_token:u,nonce:c}=e,d=await A(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(o=s?.access_token)!==null&&o!==void 0?o:void 0,body:{provider:a,id_token:l,access_token:u,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:ct}),{data:f,error:m}=d;return m?this._returnResult({data:{user:null,session:null},error:m}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new ir}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:m}))}catch(n){if(await Oe(this.storage,`${this.storageKey}-code-verifier`),T(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var o,n;let{data:s,error:i}=r;if(i)throw i;return await A(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(o=s.session)===null||o===void 0?void 0:o.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){let r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{let o=Date.now();return await Rm(async n=>(n>0&&await Am(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await A(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:ct})),(n,s)=>{let i=200*Math.pow(2,n);return s&&Mi(s)&&Date.now()+i-o<Gr})}catch(o){if(this._debug(r,"error",o),T(o))return this._returnResult({data:{session:null,user:null},error:o});throw o}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){let o=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",o),Te()&&!r.skipBrowserRedirect&&window.location.assign(o),{data:{provider:e,url:o},error:null}}async _recoverAndRefresh(){var e,r;let o="#_recoverAndRefresh()";this._debug(o,"begin");try{let n=await vr(this.storage,this.storageKey);if(n&&this.userStorage){let i=await vr(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!i&&(i={user:n.user},await Qr(this.userStorage,this.storageKey+"-user",i)),n.user=(e=i?.user)!==null&&e!==void 0?e:Bi()}else if(n&&!n.user&&!n.user){let i=await vr(this.storage,this.storageKey+"-user");i&&i?.user?(n.user=i.user,await Oe(this.storage,this.storageKey+"-user"),await Qr(this.storage,this.storageKey,n)):n.user=Bi()}if(this._debug(o,"session from storage",n),!this._isValidSession(n)){this._debug(o,"session is not valid"),n!==null&&await this._removeSession();return}let s=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Di;if(this._debug(o,`session has${s?"":" not"} expired with margin of ${Di}s`),s){if(this.autoRefreshToken&&n.refresh_token){let{error:i}=await this._callRefreshToken(n.refresh_token);i&&(console.error(i),Mi(i)||(this._debug(o,"refresh failed with a non-retryable error, removing the session",i),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{let{data:i,error:a}=await this._getUser(n.access_token);!a&&i?.user?(n.user=i.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(o,"could not get user data, skipping SIGNED_IN notification")}catch(i){console.error("Error getting user data:",i),this._debug(o,"error getting user data, skipping SIGNED_IN notification",i)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(o,"error",n),console.error(n);return}finally{this._debug(o,"end")}}async _callRefreshToken(e){var r,o;if(!e)throw new je;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new ds;let{data:s,error:i}=await this._refreshAccessToken(e);if(i)throw i;if(!s.session)throw new je;await this._saveSession(s.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",s.session);let a={data:s.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(s){if(this._debug(n,"error",s),T(s)){let i={data:null,error:s};return Mi(s)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(i),i}throw(o=this.refreshingDeferred)===null||o===void 0||o.reject(s),s}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,o=!0){let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${o}`);try{this.broadcastChannel&&o&&this.broadcastChannel.postMessage({event:e,session:r});let s=[],i=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(l){s.push(l)}});if(await Promise.all(i),s.length>0){for(let a=0;a<s.length;a+=1)console.error(s[a]);throw s[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await Oe(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),o=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!o&&r.user&&await Qr(this.userStorage,this.storageKey+"-user",{user:r.user});let n=Object.assign({},r);delete n.user;let s=bu(n);await Qr(this.storage,this.storageKey,s)}else{let n=bu(r);await Qr(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await Oe(this.storage,this.storageKey),await Oe(this.storage,this.storageKey+"-code-verifier"),await Oe(this.storage,this.storageKey+"-user"),this.userStorage&&await Oe(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Te()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),Gr);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}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 r=>{let{data:{session:o}}=r;if(!o||!o.refresh_token||!o.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((o.expires_at*1e3-e)/Gr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${Gr}ms, refresh threshold is ${Ii} ticks`),n<=Ii&&await this._callRefreshToken(o.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof ms)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Te()||!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?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let r=`#_onVisibilityChanged(${e})`;this._debug(r,"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(r,"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,r,o){let n=[`provider=${encodeURIComponent(r)}`];if(o?.redirectTo&&n.push(`redirect_to=${encodeURIComponent(o.redirectTo)}`),o?.scopes&&n.push(`scopes=${encodeURIComponent(o.scopes)}`),this.flowType==="pkce"){let[s,i]=await Zr(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(i)}`});n.push(a.toString())}if(o?.queryParams){let s=new URLSearchParams(o.queryParams);n.push(s.toString())}return o?.skipBrowserRedirect&&n.push(`skip_http_redirect=${o.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var o;let{data:n,error:s}=r;return s?this._returnResult({data:null,error:s}):await A(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.access_token})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var o,n;let{data:s,error:i}=r;if(i)return this._returnResult({data:null,error:i});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:u}=await A(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(o=s?.session)===null||o===void 0?void 0:o.access_token});return u?this._returnResult({data:null,error:u}):(e.factorType==="totp"&&l.type==="totp"&&(!((n=l?.totp)===null||n===void 0)&&n.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var o;let{data:n,error:s}=r;if(s)return this._returnResult({data:null,error:s});let i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Km(e.webauthn.credential_response):Jm(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await A(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.access_token});return l?this._returnResult({data:null,error:l}):(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:l}))})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var o;let{data:n,error:s}=r;if(s)return this._returnResult({data:null,error:s});let i=await A(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(o=n?.session)===null||o===void 0?void 0:o.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:zm(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:Gm(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){let{data:r,error:o}=await this._challenge({factorId:e.factorId});return o?this._returnResult({data:null,error:o}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:o}=await this.getUser();if(o)return{data:null,error:o};let n={all:[],phone:[],totp:[],webauthn:[]};for(let s of(e=r?.factors)!==null&&e!==void 0?e:[])n.all.push(s),s.status==="verified"&&n[s.factor_type].push(s);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,o,n,s;if(e)try{let{payload:m}=fs(e),h=null;m.aal&&(h=m.aal);let g=h,{data:{user:y},error:p}=await this.getUser(e);if(p)return this._returnResult({data:null,error:p});((o=(r=y?.factors)===null||r===void 0?void 0:r.filter(v=>v.status==="verified"))!==null&&o!==void 0?o:[]).length>0&&(g="aal2");let _=m.amr||[];return{data:{currentLevel:h,nextLevel:g,currentAuthenticationMethods:_},error:null}}catch(m){if(T(m))return this._returnResult({data:null,error:m});throw m}let{data:{session:i},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:l}=fs(i.access_token),u=null;l.aal&&(u=l.aal);let c=u;((s=(n=i.user.factors)===null||n===void 0?void 0:n.filter(m=>m.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(c="aal2");let f=l.amr||[];return{data:{currentLevel:u,nextLevel:c,currentAuthenticationMethods:f},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:o},error:n}=r;return n?this._returnResult({data:null,error:n}):o?await A(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:o.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new je})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async o=>{let{data:{session:n},error:s}=o;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new je});let i=await A(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return i.data&&i.data.redirect_url&&Te()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(o){if(T(o))return this._returnResult({data:null,error:o});throw o}}async _denyAuthorization(e,r){try{return await this._useSession(async o=>{let{data:{session:n},error:s}=o;if(s)return this._returnResult({data:null,error:s});if(!n)return this._returnResult({data:null,error:new je});let i=await A(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return i.data&&i.data.redirect_url&&Te()&&!r?.skipBrowserRedirect&&window.location.assign(i.data.redirect_url),i})}catch(o){if(T(o))return this._returnResult({data:null,error:o});throw o}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:o}=e;return o?this._returnResult({data:null,error:o}):r?await A(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new je})})}catch(e){if(T(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:o},error:n}=r;return n?this._returnResult({data:null,error:n}):o?(await A(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:o.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new je})})}catch(r){if(T(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let o=r.keys.find(a=>a.kid===e);if(o)return o;let n=Date.now();if(o=this.jwks.keys.find(a=>a.kid===e),o&&this.jwks_cached_at+_m>n)return o;let{data:s,error:i}=await A(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return!s.keys||s.keys.length===0||(this.jwks=s,this.jwks_cached_at=n,o=s.keys.find(a=>a.kid===e),!o)?null:o}async getClaims(e,r={}){try{let o=e;if(!o){let{data:m,error:h}=await this.getSession();if(h||!m.session)return this._returnResult({data:null,error:h});o=m.session.access_token}let{header:n,payload:s,signature:i,raw:{header:a,payload:l}}=fs(o);r?.allowExpired||Dm(s.exp);let u=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!u){let{error:m}=await this.getUser(o);if(m)throw m;return{data:{claims:s,header:n,signature:i},error:null}}let c=Lm(n.alg),d=await crypto.subtle.importKey("jwk",u,c,!0,["verify"]);if(!await crypto.subtle.verify(c,d,i,Tm(`${a}.${l}`)))throw new Yr("Invalid JWT signature");return{data:{claims:s,header:n,signature:i},error:null}}catch(o){if(T(o))return this._returnResult({data:null,error:o});throw o}}};Hi.nextInstanceID={};var Cu=Hi;var xv=Cu,Eu=xv;var kv="2.100.1",ps="";typeof Deno<"u"?ps="deno":typeof document<"u"?ps="web":typeof navigator<"u"&&navigator.product==="ReactNative"?ps="react-native":ps="node";var Tv={"X-Client-Info":`supabase-js-${ps}/${kv}`},Cv={headers:Tv},Ev={schema:"public"},Pv={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Ov={};function gs(t){"@babel/helpers - typeof";return gs=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},gs(t)}function Av(t,e){if(gs(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var o=r.call(t,e||"default");if(gs(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Rv(t){var e=Av(t,"string");return gs(e)=="symbol"?e:e+""}function Iv(t,e,r){return(e=Rv(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Xm(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,o)}return r}function me(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Xm(Object(r),!0).forEach(function(o){Iv(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Xm(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}var Dv=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Lv=()=>Headers,Nv=(t,e,r)=>{let o=Dv(r),n=Lv();return async(s,i)=>{var a;let l=(a=await e())!==null&&a!==void 0?a:t,u=new n(i?.headers);return u.has("apikey")||u.set("apikey",t),u.has("Authorization")||u.set("Authorization",`Bearer ${l}`),o(s,me(me({},i),{},{headers:u}))}};function jv(t){return t.endsWith("/")?t:t+"/"}function Mv(t,e){var r,o;let{db:n,auth:s,realtime:i,global:a}=t,{db:l,auth:u,realtime:c,global:d}=e,f={db:me(me({},l),n),auth:me(me({},u),s),realtime:me(me({},c),i),storage:{},global:me(me(me({},d),a),{},{headers:me(me({},(r=d?.headers)!==null&&r!==void 0?r:{}),(o=a?.headers)!==null&&o!==void 0?o:{})}),accessToken:async()=>""};return t.accessToken?f.accessToken=t.accessToken:delete f.accessToken,f}function Uv(t){let e=t?.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(jv(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Fv=class extends Eu{constructor(t){super(t)}},$v=class{constructor(t,e,r){var o,n;this.supabaseUrl=t,this.supabaseKey=e;let s=Uv(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",s),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",s),this.storageUrl=new URL("storage/v1",s),this.functionsUrl=new URL("functions/v1",s);let i=`sb-${s.hostname.split(".")[0]}-auth-token`,a={db:Ev,realtime:Ov,auth:me(me({},Pv),{},{storageKey:i}),global:Cv},l=Mv(r??{},a);if(this.storageKey=(o=l.auth.storageKey)!==null&&o!==void 0?o:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(c,d)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} is not possible`)}});else{var u;this.auth=this._initSupabaseAuthClient((u=l.auth)!==null&&u!==void 0?u:{},this.headers,l.global.fetch)}this.fetch=Nv(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(me({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(c=>this.realtime.setAuth(c)).catch(c=>console.warn("Failed to set initial Realtime auth token:",c)),this.rest=new Qf(new URL("rest/v1",s).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new hm(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new Xn(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();let{data:o}=await t.auth.getSession();return(e=(r=o.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:o,userStorage:n,storageKey:s,flowType:i,lock:a,debug:l,throwOnError:u},c,d){let f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Fv({url:this.authUrl.href,headers:me(me({},f),c),storageKey:s,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:o,userStorage:n,flowType:i,lock:a,debug:l,throwOnError:u,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(m=>m.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new qo(this.realtimeUrl.href,me(me({},t),{},{params:me(me({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},Qm=(t,e,r)=>new $v(t,e,r);function Bv(){if(typeof window<"u")return!1;let t=globalThis.process;if(!t)return!1;let e=t.version;if(e==null)return!1;let r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}Bv()&&console.warn("\u26A0\uFE0F 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 Pu="0.5.2";var th=Le(Au());function no(){return typeof window<"u"&&typeof window.document<"u"}var Sr={path:"/",sameSite:"lax",httpOnly:!1,maxAge:3456e4};var Zv=/^(.*)[.](0|[1-9][0-9]*)$/;function ys(t,e){if(t===e)return!0;let r=t.match(Zv);return!!(r&&r[1]===e)}function Ru(t,e,r){let o=r??3180,n=encodeURIComponent(e);if(n.length<=o)return[{name:t,value:e}];let s=[];for(;n.length>0;){let i=n.slice(0,o),a=i.lastIndexOf("%");a>o-3&&(i=i.slice(0,a));let l="";for(;i.length>0;)try{l=decodeURIComponent(i);break}catch(u){if(u instanceof URIError&&i.at(-3)==="%"&&i.length>3)i=i.slice(0,i.length-3);else throw u}s.push(l),n=n.slice(i.length)}return s.map((i,a)=>({name:`${t}.${a}`,value:i}))}async function Iu(t,e){let r=await e(t);if(r)return r;let o=[];for(let n=0;;n++){let s=`${t}.${n}`,i=await e(s);if(!i)break;o.push(i)}return o.length>0?o.join(""):null}var zi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),rh=`
|
|
88
|
+
\r=`.split(""),e0=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<rh.length;e+=1)t[rh[e].charCodeAt(0)]=-2;for(let e=0;e<zi.length;e+=1)t[zi[e].charCodeAt(0)]=e;return t})();function Du(t){let e=[],r=0,o=0;if(r0(t,s=>{for(r=r<<8|s,o+=8;o>=6;){let i=r>>o-6&63;e.push(zi[i]),o-=6}}),o>0)for(r=r<<6-o,o=6;o>=6;){let s=r>>o-6&63;e.push(zi[s]),o-=6}return e.join("")}function Lu(t){let e=[],r=i=>{e.push(String.fromCodePoint(i))},o={utf8seq:0,codepoint:0},n=0,s=0;for(let i=0;i<t.length;i+=1){let a=t.charCodeAt(i),l=e0[a];if(l>-1)for(n=n<<6|l,s+=6;s>=8;)o0(n>>s-8&255,o,r),s-=8;else{if(l===-2)continue;throw new Error(`Invalid Base64-URL character "${t.at(i)}" at position ${i}`)}}return e.join("")}function t0(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function r0(t,e){for(let r=0;r<t.length;r+=1){let o=t.charCodeAt(r);if(o>55295&&o<=56319){let n=(o-55296)*1024&65535;o=(t.charCodeAt(r+1)-56320&65535|n)+65536,r+=1}t0(o,e)}}function o0(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let o=1;o<6;o+=1)if((t>>7-o&1)===0){e.utf8seq=o;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}var Gi=Le(Au());var zo="base64-";function Nu(t,e){let r=t.cookies??null,o=t.cookieEncoding,n={},s={},i,a;if(r)if("get"in r){let l=async u=>{let c=u.flatMap(f=>[f,...Array.from({length:5}).map((m,h)=>`${f}.${h}`)]),d=[];for(let f=0;f<c.length;f+=1){let m=await r.get(c[f]);!m&&typeof m!="string"||d.push({name:c[f],value:m})}return d};if(i=async u=>await l(u),"set"in r&&"remove"in r)a=async u=>{for(let c=0;c<u.length;c+=1){let{name:d,value:f,options:m}=u[c];f?await r.set(d,f,m):await r.remove(d,m)}};else if(e)a=async()=>{console.warn("@supabase/ssr: createServerClient was configured without set and remove cookie methods, but the client needs to set cookies. This can lead to issues such as random logouts, early session termination or increased token refresh requests. If in NextJS, check your middleware.ts file, route handlers and server actions for correctness. Consider switching to the getAll and setAll cookie methods instead of get, set and remove which are deprecated and can be difficult to use correctly.")};else throw new Error("@supabase/ssr: createBrowserClient requires configuring a getAll and setAll cookie method (deprecated: alternatively both get, set and remove can be used)")}else if("getAll"in r)if(i=async()=>await r.getAll(),"setAll"in r)a=r.setAll;else if(e)a=async()=>{console.warn("@supabase/ssr: createServerClient was configured without the setAll cookie method, but the client needs to set cookies. This can lead to issues such as random logouts, early session termination or increased token refresh requests. If in NextJS, check your middleware.ts file, route handlers and server actions for correctness.")};else throw new Error("@supabase/ssr: createBrowserClient requires configuring both getAll and setAll cookie methods (deprecated: alternatively both get, set and remove can be used)");else throw new Error(`@supabase/ssr: ${e?"createServerClient":"createBrowserClient"} requires configuring getAll and setAll cookie methods (deprecated: alternatively use get, set and remove).${no()?" As this is called in a browser runtime, consider removing the cookies option object to use the document.cookie API automatically.":""}`);else if(!e&&no()){let l=()=>{let u=(0,Gi.parse)(document.cookie);return Object.keys(u).map(c=>({name:c,value:u[c]}))};i=()=>l(),a=u=>{u.forEach(({name:c,value:d,options:f})=>{document.cookie=(0,Gi.serialize)(c,d,f)})}}else{if(e)throw new Error("@supabase/ssr: createServerClient must be initialized with cookie options that specify getAll and setAll functions (deprecated, not recommended: alternatively use get, set and remove)");i=()=>[],a=()=>{throw new Error("@supabase/ssr: createBrowserClient in non-browser runtimes (including Next.js pre-rendering mode) was not initialized cookie options that specify getAll and setAll functions (deprecated: alternatively use get, set and remove), but they were needed")}}return e?{getAll:i,setAll:a,setItems:n,removedItems:s,storage:{isServer:!0,getItem:async l=>{if(typeof n[l]=="string")return n[l];if(s[l])return null;let u=await i([l]),c=await Iu(l,async f=>{let m=u?.find(({name:h})=>h===f)||null;return m?m.value:null});if(!c)return null;let d=c;return typeof c=="string"&&c.startsWith(zo)&&(d=Lu(c.substring(zo.length))),d},setItem:async(l,u)=>{l.endsWith("-code-verifier")&&await oh({getAll:i,setAll:a,setItems:{[l]:u},removedItems:{}},{cookieOptions:t?.cookieOptions??null,cookieEncoding:o}),n[l]=u,delete s[l]},removeItem:async l=>{delete n[l],s[l]=!0}}}:{getAll:i,setAll:a,setItems:n,removedItems:s,storage:{isServer:!1,getItem:async l=>{let u=await i([l]),c=await Iu(l,async f=>{let m=u?.find(({name:h})=>h===f)||null;return m?m.value:null});if(!c)return null;let d=c;return c.startsWith(zo)&&(d=Lu(c.substring(zo.length))),d},setItem:async(l,u)=>{let d=(await i([l]))?.map(({name:b})=>b)||[],f=new Set(d.filter(b=>ys(b,l))),m=u;o==="base64url"&&(m=zo+Du(u));let h=Ru(l,m);h.forEach(({name:b})=>{f.delete(b)});let g={...Sr,...t?.cookieOptions,maxAge:0},y={...Sr,...t?.cookieOptions,maxAge:Sr.maxAge};delete g.name,delete y.name;let p=[...[...f].map(b=>({name:b,value:"",options:g})),...h.map(({name:b,value:_})=>({name:b,value:_,options:y}))];p.length>0&&await a(p)},removeItem:async l=>{let d=((await i([l]))?.map(({name:m})=>m)||[]).filter(m=>ys(m,l)),f={...Sr,...t?.cookieOptions,maxAge:0};delete f.name,d.length>0&&await a(d.map(m=>({name:m,value:"",options:f})))}}}}async function oh({getAll:t,setAll:e,setItems:r,removedItems:o},n){let s=n.cookieEncoding,i=n.cookieOptions??null,l=(await t([...r?Object.keys(r):[],...o?Object.keys(o):[]]))?.map(({name:m})=>m)||[],u=Object.keys(o).flatMap(m=>l.filter(h=>ys(h,m))),c=Object.keys(r).flatMap(m=>{let h=new Set(l.filter(p=>ys(p,m))),g=r[m];s==="base64url"&&(g=zo+Du(g));let y=Ru(m,g);return y.forEach(p=>{h.delete(p.name)}),u.push(...h),y}),d={...Sr,...i,maxAge:0},f={...Sr,...i,maxAge:Sr.maxAge};delete d.name,delete f.name,await e([...u.map(m=>({name:m,value:"",options:d})),...c.map(({name:m,value:h})=>({name:m,value:h,options:f}))])}var ju;function nh(t,e,r){let o=r?.isSingleton===!0||(!r||!("isSingleton"in r))&&no();if(o&&ju)return ju;if(!t||!e)throw new Error(`@supabase/ssr: Your project's URL and API key are required to create a Supabase client!
|
|
89
89
|
|
|
90
90
|
Check your Supabase project's API settings to find these values
|
|
91
91
|
|
|
92
|
-
https://supabase.com/dashboard/project/_/settings/api`);let{storage:n}=
|
|
92
|
+
https://supabase.com/dashboard/project/_/settings/api`);let{storage:n}=Nu({...r,cookieEncoding:r?.cookieEncoding??"base64url"},!1),s=Qm(t,e,{...r,global:{...r?.global,headers:{...r?.global?.headers,"X-Client-Info":`supabase-ssr/${Pu}`}},auth:{...r?.auth,...r?.cookieOptions?.name?{storageKey:r.cookieOptions.name}:null,flowType:"pkce",autoRefreshToken:no(),detectSessionInUrl:no(),persistSession:!0,storage:n}});return o&&(ju=s),s}var Mu=process.env.NEXT_PUBLIC_SUPABASE_URL||process.env.EXPO_PUBLIC_SUPABASE_URL||"https://dhnpoxorllfdobwftkyb.supabase.co",Uu=process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY||process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY||"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRobnBveG9ybGxmZG9id2Z0a3liIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzkwNTQxMDgsImV4cCI6MjA1NDYzMDEwOH0.zI8PwbgKwijHZ1QmxJqmaPrFvg02w1vOY2Qcs7SddzI";var Ki=process.env.NODE_ENV==="production"?"https://api.zorgotech.com":"http://localhost:3000";var bs={DEFAULTS:{PREP_MINUTES:20,PAST_HOURS:24,FUTURE_HOURS:72},ORDER_STATUS:{STAGING:10,PENDING:1,COMPLETED:2,CANCELLED:4,PAID:6,PARTIALLY_PAID:7,KITCHEN_DONE:9,CONFIRMED:11,PREPARING:12,REQUESTED:13},POS_METHOD_ID:3,TEST_CUSTOMER_IDS:[85,90,91,93,95,96,97,203,238,240,241,244,245,246,317,318,319,322,579,580,658,1526,2567,2573,2703,2725,2737,2739,2740,2741,2742,2744,2746,2747,2749,2751,2752,2753,2754,2755,2767,2768,2778,2779,2780,2781,2783,2814,2816,2818,2819,2820,2821,2822,2823,2824,2835,2836,2851,2853,2859,2871,2882,2883,2887,2888,2889,2891,2892,2893,2894,2895,2896,2897,2898,2899,2900,2901,2902,2903,2904,2905,2907,2908,2919,2921,2922,2923,2924,2925,2926,2927,2946,3017,3018,3022,3024,3025,3026,3027,3028,3029,3030,3031,3082,3091,3092,3093],ORDER_TYPE:{DINE_IN:1,TAKEOUT:2,DELIVERY:3},MODIFICATION_HIGHLIGHT_MS:8e3,LISTENER_SYNC_INTERVAL_MS:6e4,ORDER_SELECT:`
|
|
93
93
|
*,
|
|
94
94
|
|
|
95
95
|
charges (
|
|
@@ -108,7 +108,7 @@ https://supabase.com/dashboard/project/_/settings/api`);let{storage:n}=Du({...r,
|
|
|
108
108
|
item_id, name, price,
|
|
109
109
|
portion_schemes (id, franchise_id, geometry, name, min_divisions, max_divisions),
|
|
110
110
|
base_items (
|
|
111
|
-
base_item_id, category_id, name,
|
|
111
|
+
base_item_id, category_id, name, per_person,
|
|
112
112
|
categories (category_id, name, is_catering)
|
|
113
113
|
)
|
|
114
114
|
),
|
|
@@ -137,7 +137,7 @@ https://supabase.com/dashboard/project/_/settings/api`);let{storage:n}=Du({...r,
|
|
|
137
137
|
components (id, name, component_type_id, serving_weight, measurement_type, display_unit)
|
|
138
138
|
)
|
|
139
139
|
)
|
|
140
|
-
`};var sh=null;var Mu=(t,e)=>{if(!sh)return fetch(t,e);let r=new Headers(e?.headers);return r.set("Authorization",`Bearer ${sh}`),fetch(t,{...e,headers:r})};var qu=globalThis?.navigator?.product==="ReactNative",wh=typeof process<"u"&&process.versions?.node,f0=!qu&&!wh&&typeof globalThis?.document<"u";function _h(){if(!wh&&qu)try{return(Bu(),Ol($u)).default}catch{return}}function m0(){return f0?nh(Nu,ju,{global:{fetch:Mu}}):Gf(Nu,ju,{auth:{autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!qu,..._h()?{storage:_h()}:{},lock:Xl},global:{fetch:Mu}})}var U=m0();var rg=require("zustand/middleware/immer"),ln=require("zustand/middleware");var h0=Math.pow(10,8)*24*60*60*1e3,lI=-h0,Yi=6048e5,vh=864e5,Xi=6e4,Qi=36e5,Sh=1e3;var p0=3600;var xh=p0*24,uI=xh*7,g0=xh*365.2425,y0=g0/12,cI=y0*3,Vu=Symbol.for("constructDateFrom");function H(t,e){return typeof t=="function"?t(e):t&&typeof t=="object"&&Vu in t?t[Vu](e):t instanceof Date?new t.constructor(e):new Date(e)}function R(t,e){return H(e||t,t)}function Zi(t,e,r){let o=R(t,r?.in);return isNaN(e)?H(r?.in||t,NaN):(e&&o.setDate(o.getDate()+e),o)}function kh(t,e,r){return H(r?.in||t,+R(t)+e)}function Yo(t,e,r){return kh(t,e*Qi,r)}var b0={};function dt(){return b0}function ze(t,e){let r=dt(),o=e?.weekStartsOn??e?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,n=R(t,e?.in),s=n.getDay(),i=(s<o?7:0)+s-o;return n.setDate(n.getDate()-i),n.setHours(0,0,0,0),n}function Ct(t,e){return ze(t,{...e,weekStartsOn:1})}function ea(t,e){let r=R(t,e?.in),o=r.getFullYear(),n=H(r,0);n.setFullYear(o+1,0,4),n.setHours(0,0,0,0);let s=Ct(n),i=H(r,0);i.setFullYear(o,0,4),i.setHours(0,0,0,0);let a=Ct(i);return r.getTime()>=s.getTime()?o+1:r.getTime()>=a.getTime()?o:o-1}function io(t){let e=R(t),r=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return r.setUTCFullYear(e.getFullYear()),+t-+r}function Th(t,...e){let r=H.bind(null,t||e.find(o=>typeof o=="object"));return e.map(r)}function Et(t,e){let r=R(t,e?.in);return r.setHours(0,0,0,0),r}function Ch(t,e,r){let[o,n]=Th(r?.in,t,e),s=Et(o),i=Et(n),a=+s-io(s),l=+i-io(i);return Math.round((a-l)/vh)}function Eh(t,e){let r=ea(t,e),o=H(e?.in||t,0);return o.setFullYear(r,0,4),o.setHours(0,0,0,0),Ct(o)}function Ph(t,e,r){let o=R(t,r?.in);return o.setTime(o.getTime()+e*Xi),o}function Oh(t){return t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"}function ao(t){return!(!Oh(t)&&typeof t!="number"||isNaN(+R(t)))}function Ah(t,e){return+R(t)-+R(e)}function Rh(t,e){let r=R(t,e?.in);return r.setFullYear(r.getFullYear(),0,1),r.setHours(0,0,0,0),r}var _0={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},Ih=(t,e,r)=>{let o,n=_0[t];return typeof n=="string"?o=n:e===1?o=n.one:o=n.other.replace("{{count}}",e.toString()),r?.addSuffix?r.comparison&&r.comparison>0?"in "+o:o+" ago":o};function ta(t){return(e={})=>{let r=e.width?String(e.width):t.defaultWidth;return t.formats[r]||t.formats[t.defaultWidth]}}var w0={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},v0={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},S0={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},Dh={date:ta({formats:w0,defaultWidth:"full"}),time:ta({formats:v0,defaultWidth:"full"}),dateTime:ta({formats:S0,defaultWidth:"full"})};var x0={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Lh=(t,e,r,o)=>x0[t];function Xo(t){return(e,r)=>{let o=r?.context?String(r.context):"standalone",n;if(o==="formatting"&&t.formattingValues){let i=t.defaultFormattingWidth||t.defaultWidth,a=r?.width?String(r.width):i;n=t.formattingValues[a]||t.formattingValues[i]}else{let i=t.defaultWidth,a=r?.width?String(r.width):t.defaultWidth;n=t.values[a]||t.values[i]}let s=t.argumentCallback?t.argumentCallback(e):e;return n[s]}}var k0={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},T0={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},C0={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},E0={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},P0={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},O0={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},A0=(t,e)=>{let r=Number(t),o=r%100;if(o>20||o<10)switch(o%10){case 1:return r+"st";case 2:return r+"nd";case 3:return r+"rd"}return r+"th"},Nh={ordinalNumber:A0,era:Xo({values:k0,defaultWidth:"wide"}),quarter:Xo({values:T0,defaultWidth:"wide",argumentCallback:t=>t-1}),month:Xo({values:C0,defaultWidth:"wide"}),day:Xo({values:E0,defaultWidth:"wide"}),dayPeriod:Xo({values:P0,defaultWidth:"wide",formattingValues:O0,defaultFormattingWidth:"wide"})};function Qo(t){return(e,r={})=>{let o=r.width,n=o&&t.matchPatterns[o]||t.matchPatterns[t.defaultMatchWidth],s=e.match(n);if(!s)return null;let i=s[0],a=o&&t.parsePatterns[o]||t.parsePatterns[t.defaultParseWidth],l=Array.isArray(a)?I0(a,d=>d.test(i)):R0(a,d=>d.test(i)),u;u=t.valueCallback?t.valueCallback(l):l,u=r.valueCallback?r.valueCallback(u):u;let c=e.slice(i.length);return{value:u,rest:c}}}function R0(t,e){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&e(t[r]))return r}function I0(t,e){for(let r=0;r<t.length;r++)if(e(t[r]))return r}function jh(t){return(e,r={})=>{let o=e.match(t.matchPattern);if(!o)return null;let n=o[0],s=e.match(t.parsePattern);if(!s)return null;let i=t.valueCallback?t.valueCallback(s[0]):s[0];i=r.valueCallback?r.valueCallback(i):i;let a=e.slice(n.length);return{value:i,rest:a}}}var D0=/^(\d+)(th|st|nd|rd)?/i,L0=/\d+/i,N0={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},j0={any:[/^b/i,/^(a|c)/i]},M0={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},U0={any:[/1/i,/2/i,/3/i,/4/i]},F0={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},$0={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},B0={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},q0={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},V0={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},W0={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},Mh={ordinalNumber:jh({matchPattern:D0,parsePattern:L0,valueCallback:t=>parseInt(t,10)}),era:Qo({matchPatterns:N0,defaultMatchWidth:"wide",parsePatterns:j0,defaultParseWidth:"any"}),quarter:Qo({matchPatterns:M0,defaultMatchWidth:"wide",parsePatterns:U0,defaultParseWidth:"any",valueCallback:t=>t+1}),month:Qo({matchPatterns:F0,defaultMatchWidth:"wide",parsePatterns:$0,defaultParseWidth:"any"}),day:Qo({matchPatterns:B0,defaultMatchWidth:"wide",parsePatterns:q0,defaultParseWidth:"any"}),dayPeriod:Qo({matchPatterns:V0,defaultMatchWidth:"any",parsePatterns:W0,defaultParseWidth:"any"})};var ws={code:"en-US",formatDistance:Ih,formatLong:Dh,formatRelative:Lh,localize:Nh,match:Mh,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Uh(t,e){let r=R(t,e?.in);return Ch(r,Rh(r))+1}function ra(t,e){let r=R(t,e?.in),o=+Ct(r)-+Eh(r);return Math.round(o/Yi)+1}function Zo(t,e){let r=R(t,e?.in),o=r.getFullYear(),n=dt(),s=e?.firstWeekContainsDate??e?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,i=H(e?.in||t,0);i.setFullYear(o+1,0,s),i.setHours(0,0,0,0);let a=ze(i,e),l=H(e?.in||t,0);l.setFullYear(o,0,s),l.setHours(0,0,0,0);let u=ze(l,e);return+r>=+a?o+1:+r>=+u?o:o-1}function Fh(t,e){let r=dt(),o=e?.firstWeekContainsDate??e?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,n=Zo(t,e),s=H(e?.in||t,0);return s.setFullYear(n,0,o),s.setHours(0,0,0,0),ze(s,e)}function oa(t,e){let r=R(t,e?.in),o=+ze(r,e)-+Fh(r,e);return Math.round(o/Yi)+1}function X(t,e){let r=t<0?"-":"",o=Math.abs(t).toString().padStart(e,"0");return r+o}var lr={y(t,e){let r=t.getFullYear(),o=r>0?r:1-r;return X(e==="yy"?o%100:o,e.length)},M(t,e){let r=t.getMonth();return e==="M"?String(r+1):X(r+1,2)},d(t,e){return X(t.getDate(),e.length)},a(t,e){let r=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];default:return r==="am"?"a.m.":"p.m."}},h(t,e){return X(t.getHours()%12||12,e.length)},H(t,e){return X(t.getHours(),e.length)},m(t,e){return X(t.getMinutes(),e.length)},s(t,e){return X(t.getSeconds(),e.length)},S(t,e){let r=e.length,o=t.getMilliseconds(),n=Math.trunc(o*Math.pow(10,r-3));return X(n,e.length)}};var en={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Wu={G:function(t,e,r){let o=t.getFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return r.era(o,{width:"abbreviated"});case"GGGGG":return r.era(o,{width:"narrow"});default:return r.era(o,{width:"wide"})}},y:function(t,e,r){if(e==="yo"){let o=t.getFullYear(),n=o>0?o:1-o;return r.ordinalNumber(n,{unit:"year"})}return lr.y(t,e)},Y:function(t,e,r,o){let n=Zo(t,o),s=n>0?n:1-n;if(e==="YY"){let i=s%100;return X(i,2)}return e==="Yo"?r.ordinalNumber(s,{unit:"year"}):X(s,e.length)},R:function(t,e){let r=ea(t);return X(r,e.length)},u:function(t,e){let r=t.getFullYear();return X(r,e.length)},Q:function(t,e,r){let o=Math.ceil((t.getMonth()+1)/3);switch(e){case"Q":return String(o);case"QQ":return X(o,2);case"Qo":return r.ordinalNumber(o,{unit:"quarter"});case"QQQ":return r.quarter(o,{width:"abbreviated",context:"formatting"});case"QQQQQ":return r.quarter(o,{width:"narrow",context:"formatting"});default:return r.quarter(o,{width:"wide",context:"formatting"})}},q:function(t,e,r){let o=Math.ceil((t.getMonth()+1)/3);switch(e){case"q":return String(o);case"qq":return X(o,2);case"qo":return r.ordinalNumber(o,{unit:"quarter"});case"qqq":return r.quarter(o,{width:"abbreviated",context:"standalone"});case"qqqqq":return r.quarter(o,{width:"narrow",context:"standalone"});default:return r.quarter(o,{width:"wide",context:"standalone"})}},M:function(t,e,r){let o=t.getMonth();switch(e){case"M":case"MM":return lr.M(t,e);case"Mo":return r.ordinalNumber(o+1,{unit:"month"});case"MMM":return r.month(o,{width:"abbreviated",context:"formatting"});case"MMMMM":return r.month(o,{width:"narrow",context:"formatting"});default:return r.month(o,{width:"wide",context:"formatting"})}},L:function(t,e,r){let o=t.getMonth();switch(e){case"L":return String(o+1);case"LL":return X(o+1,2);case"Lo":return r.ordinalNumber(o+1,{unit:"month"});case"LLL":return r.month(o,{width:"abbreviated",context:"standalone"});case"LLLLL":return r.month(o,{width:"narrow",context:"standalone"});default:return r.month(o,{width:"wide",context:"standalone"})}},w:function(t,e,r,o){let n=oa(t,o);return e==="wo"?r.ordinalNumber(n,{unit:"week"}):X(n,e.length)},I:function(t,e,r){let o=ra(t);return e==="Io"?r.ordinalNumber(o,{unit:"week"}):X(o,e.length)},d:function(t,e,r){return e==="do"?r.ordinalNumber(t.getDate(),{unit:"date"}):lr.d(t,e)},D:function(t,e,r){let o=Uh(t);return e==="Do"?r.ordinalNumber(o,{unit:"dayOfYear"}):X(o,e.length)},E:function(t,e,r){let o=t.getDay();switch(e){case"E":case"EE":case"EEE":return r.day(o,{width:"abbreviated",context:"formatting"});case"EEEEE":return r.day(o,{width:"narrow",context:"formatting"});case"EEEEEE":return r.day(o,{width:"short",context:"formatting"});default:return r.day(o,{width:"wide",context:"formatting"})}},e:function(t,e,r,o){let n=t.getDay(),s=(n-o.weekStartsOn+8)%7||7;switch(e){case"e":return String(s);case"ee":return X(s,2);case"eo":return r.ordinalNumber(s,{unit:"day"});case"eee":return r.day(n,{width:"abbreviated",context:"formatting"});case"eeeee":return r.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(n,{width:"short",context:"formatting"});default:return r.day(n,{width:"wide",context:"formatting"})}},c:function(t,e,r,o){let n=t.getDay(),s=(n-o.weekStartsOn+8)%7||7;switch(e){case"c":return String(s);case"cc":return X(s,e.length);case"co":return r.ordinalNumber(s,{unit:"day"});case"ccc":return r.day(n,{width:"abbreviated",context:"standalone"});case"ccccc":return r.day(n,{width:"narrow",context:"standalone"});case"cccccc":return r.day(n,{width:"short",context:"standalone"});default:return r.day(n,{width:"wide",context:"standalone"})}},i:function(t,e,r){let o=t.getDay(),n=o===0?7:o;switch(e){case"i":return String(n);case"ii":return X(n,e.length);case"io":return r.ordinalNumber(n,{unit:"day"});case"iii":return r.day(o,{width:"abbreviated",context:"formatting"});case"iiiii":return r.day(o,{width:"narrow",context:"formatting"});case"iiiiii":return r.day(o,{width:"short",context:"formatting"});default:return r.day(o,{width:"wide",context:"formatting"})}},a:function(t,e,r){let n=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"aaa":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return r.dayPeriod(n,{width:"narrow",context:"formatting"});default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},b:function(t,e,r){let o=t.getHours(),n;switch(o===12?n=en.noon:o===0?n=en.midnight:n=o/12>=1?"pm":"am",e){case"b":case"bb":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"bbb":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return r.dayPeriod(n,{width:"narrow",context:"formatting"});default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},B:function(t,e,r){let o=t.getHours(),n;switch(o>=17?n=en.evening:o>=12?n=en.afternoon:o>=4?n=en.morning:n=en.night,e){case"B":case"BB":case"BBB":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"BBBBB":return r.dayPeriod(n,{width:"narrow",context:"formatting"});default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},h:function(t,e,r){if(e==="ho"){let o=t.getHours()%12;return o===0&&(o=12),r.ordinalNumber(o,{unit:"hour"})}return lr.h(t,e)},H:function(t,e,r){return e==="Ho"?r.ordinalNumber(t.getHours(),{unit:"hour"}):lr.H(t,e)},K:function(t,e,r){let o=t.getHours()%12;return e==="Ko"?r.ordinalNumber(o,{unit:"hour"}):X(o,e.length)},k:function(t,e,r){let o=t.getHours();return o===0&&(o=24),e==="ko"?r.ordinalNumber(o,{unit:"hour"}):X(o,e.length)},m:function(t,e,r){return e==="mo"?r.ordinalNumber(t.getMinutes(),{unit:"minute"}):lr.m(t,e)},s:function(t,e,r){return e==="so"?r.ordinalNumber(t.getSeconds(),{unit:"second"}):lr.s(t,e)},S:function(t,e){return lr.S(t,e)},X:function(t,e,r){let o=t.getTimezoneOffset();if(o===0)return"Z";switch(e){case"X":return Bh(o);case"XXXX":case"XX":return lo(o);default:return lo(o,":")}},x:function(t,e,r){let o=t.getTimezoneOffset();switch(e){case"x":return Bh(o);case"xxxx":case"xx":return lo(o);default:return lo(o,":")}},O:function(t,e,r){let o=t.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+$h(o,":");default:return"GMT"+lo(o,":")}},z:function(t,e,r){let o=t.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+$h(o,":");default:return"GMT"+lo(o,":")}},t:function(t,e,r){let o=Math.trunc(+t/1e3);return X(o,e.length)},T:function(t,e,r){return X(+t,e.length)}};function $h(t,e=""){let r=t>0?"-":"+",o=Math.abs(t),n=Math.trunc(o/60),s=o%60;return s===0?r+String(n):r+String(n)+e+X(s,2)}function Bh(t,e){return t%60===0?(t>0?"-":"+")+X(Math.abs(t)/60,2):lo(t,e)}function lo(t,e=""){let r=t>0?"-":"+",o=Math.abs(t),n=X(Math.trunc(o/60),2),s=X(o%60,2);return r+n+e+s}var qh=(t,e)=>{switch(t){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});default:return e.date({width:"full"})}},Vh=(t,e)=>{switch(t){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});default:return e.time({width:"full"})}},H0=(t,e)=>{let r=t.match(/(P+)(p+)?/)||[],o=r[1],n=r[2];if(!n)return qh(t,e);let s;switch(o){case"P":s=e.dateTime({width:"short"});break;case"PP":s=e.dateTime({width:"medium"});break;case"PPP":s=e.dateTime({width:"long"});break;default:s=e.dateTime({width:"full"});break}return s.replace("{{date}}",qh(o,e)).replace("{{time}}",Vh(n,e))},vs={p:Vh,P:H0};var z0=/^D+$/,G0=/^Y+$/,K0=["D","DD","YY","YYYY"];function na(t){return z0.test(t)}function sa(t){return G0.test(t)}function Ss(t,e,r){let o=J0(t,e,r);if(console.warn(o),K0.includes(t))throw new RangeError(o)}function J0(t,e,r){let o=t[0]==="Y"?"years":"days of the month";return`Use \`${t.toLowerCase()}\` instead of \`${t}\` (in \`${e}\`) for formatting ${o} to the input \`${r}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}var Y0=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,X0=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Q0=/^'([^]*?)'?$/,Z0=/''/g,eS=/[a-zA-Z]/;function Be(t,e,r){let o=dt(),n=r?.locale??o.locale??ws,s=r?.firstWeekContainsDate??r?.locale?.options?.firstWeekContainsDate??o.firstWeekContainsDate??o.locale?.options?.firstWeekContainsDate??1,i=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??o.weekStartsOn??o.locale?.options?.weekStartsOn??0,a=R(t,r?.in);if(!ao(a))throw new RangeError("Invalid time value");let l=e.match(X0).map(c=>{let d=c[0];if(d==="p"||d==="P"){let f=vs[d];return f(c,n.formatLong)}return c}).join("").match(Y0).map(c=>{if(c==="''")return{isToken:!1,value:"'"};let d=c[0];if(d==="'")return{isToken:!1,value:tS(c)};if(Wu[d])return{isToken:!0,value:c};if(d.match(eS))throw new RangeError("Format string contains an unescaped latin alphabet character `"+d+"`");return{isToken:!1,value:c}});n.localize.preprocessor&&(l=n.localize.preprocessor(a,l));let u={firstWeekContainsDate:s,weekStartsOn:i,locale:n};return l.map(c=>{if(!c.isToken)return c.value;let d=c.value;(!r?.useAdditionalWeekYearTokens&&sa(d)||!r?.useAdditionalDayOfYearTokens&&na(d))&&Ss(d,e,String(t));let f=Wu[d[0]];return f(a,d,n.localize,u)}).join("")}function tS(t){let e=t.match(Q0);return e?e[1].replace(Z0,"'"):t}function ia(t,e){return R(t,e?.in).getDay()}function aa(){return Object.assign({},dt())}function Wh(t,e){let r=R(t,e?.in).getDay();return r===0?7:r}function $t(t,e){return+R(t)>+R(e)}function Ge(t,e){return+R(t)<+R(e)}function Hh(t,e){let r=rS(e)?new e(0):H(e,0);return r.setFullYear(t.getFullYear(),t.getMonth(),t.getDate()),r.setHours(t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()),r}function rS(t){return typeof t=="function"&&t.prototype?.constructor===t}var oS=10,la=class{subPriority=0;validate(e,r){return!0}},ua=class extends la{constructor(e,r,o,n,s){super(),this.value=e,this.validateValue=r,this.setValue=o,this.priority=n,s&&(this.subPriority=s)}validate(e,r){return this.validateValue(e,this.value,r)}set(e,r,o){return this.setValue(e,r,this.value,o)}},ca=class extends la{priority=oS;subPriority=-1;constructor(e,r){super(),this.context=e||(o=>H(r,o))}set(e,r){return r.timestampIsSet?e:H(e,Hh(e,this.context))}};var C=class{run(e,r,o,n){let s=this.parse(e,r,o,n);return s?{setter:new ua(s.value,this.validate,this.set,this.priority,this.subPriority),rest:s.rest}:null}validate(e,r,o){return!0}};var da=class extends C{priority=140;parse(e,r,o){switch(r){case"G":case"GG":case"GGG":return o.era(e,{width:"abbreviated"})||o.era(e,{width:"narrow"});case"GGGGG":return o.era(e,{width:"narrow"});default:return o.era(e,{width:"wide"})||o.era(e,{width:"abbreviated"})||o.era(e,{width:"narrow"})}}set(e,r,o){return r.era=o,e.setFullYear(o,0,1),e.setHours(0,0,0,0),e}incompatibleTokens=["R","u","t","T"]};var G={month:/^(1[0-2]|0?\d)/,date:/^(3[0-1]|[0-2]?\d)/,dayOfYear:/^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,week:/^(5[0-3]|[0-4]?\d)/,hour23h:/^(2[0-3]|[0-1]?\d)/,hour24h:/^(2[0-4]|[0-1]?\d)/,hour11h:/^(1[0-1]|0?\d)/,hour12h:/^(1[0-2]|0?\d)/,minute:/^[0-5]?\d/,second:/^[0-5]?\d/,singleDigit:/^\d/,twoDigits:/^\d{1,2}/,threeDigits:/^\d{1,3}/,fourDigits:/^\d{1,4}/,anyDigitsSigned:/^-?\d+/,singleDigitSigned:/^-?\d/,twoDigitsSigned:/^-?\d{1,2}/,threeDigitsSigned:/^-?\d{1,3}/,fourDigitsSigned:/^-?\d{1,4}/},ft={basicOptionalMinutes:/^([+-])(\d{2})(\d{2})?|Z/,basic:/^([+-])(\d{2})(\d{2})|Z/,basicOptionalSeconds:/^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,extended:/^([+-])(\d{2}):(\d{2})|Z/,extendedOptionalSeconds:/^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/};function Q(t,e){return t&&{value:e(t.value),rest:t.rest}}function z(t,e){let r=e.match(t);return r?{value:parseInt(r[0],10),rest:e.slice(r[0].length)}:null}function mt(t,e){let r=e.match(t);if(!r)return null;if(r[0]==="Z")return{value:0,rest:e.slice(1)};let o=r[1]==="+"?1:-1,n=r[2]?parseInt(r[2],10):0,s=r[3]?parseInt(r[3],10):0,i=r[5]?parseInt(r[5],10):0;return{value:o*(n*Qi+s*Xi+i*Sh),rest:e.slice(r[0].length)}}function fa(t){return z(G.anyDigitsSigned,t)}function F(t,e){switch(t){case 1:return z(G.singleDigit,e);case 2:return z(G.twoDigits,e);case 3:return z(G.threeDigits,e);case 4:return z(G.fourDigits,e);default:return z(new RegExp("^\\d{1,"+t+"}"),e)}}function tn(t,e){switch(t){case 1:return z(G.singleDigitSigned,e);case 2:return z(G.twoDigitsSigned,e);case 3:return z(G.threeDigitsSigned,e);case 4:return z(G.fourDigitsSigned,e);default:return z(new RegExp("^-?\\d{1,"+t+"}"),e)}}function rn(t){switch(t){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;default:return 0}}function ma(t,e){let r=e>0,o=r?e:1-e,n;if(o<=50)n=t||100;else{let s=o+50,i=Math.trunc(s/100)*100,a=t>=s%100;n=t+i-(a?100:0)}return r?n:1-n}function ha(t){return t%400===0||t%4===0&&t%100!==0}var pa=class extends C{priority=130;incompatibleTokens=["Y","R","u","w","I","i","e","c","t","T"];parse(e,r,o){let n=s=>({year:s,isTwoDigitYear:r==="yy"});switch(r){case"y":return Q(F(4,e),n);case"yo":return Q(o.ordinalNumber(e,{unit:"year"}),n);default:return Q(F(r.length,e),n)}}validate(e,r){return r.isTwoDigitYear||r.year>0}set(e,r,o){let n=e.getFullYear();if(o.isTwoDigitYear){let i=ma(o.year,n);return e.setFullYear(i,0,1),e.setHours(0,0,0,0),e}let s=!("era"in r)||r.era===1?o.year:1-o.year;return e.setFullYear(s,0,1),e.setHours(0,0,0,0),e}};var ga=class extends C{priority=130;parse(e,r,o){let n=s=>({year:s,isTwoDigitYear:r==="YY"});switch(r){case"Y":return Q(F(4,e),n);case"Yo":return Q(o.ordinalNumber(e,{unit:"year"}),n);default:return Q(F(r.length,e),n)}}validate(e,r){return r.isTwoDigitYear||r.year>0}set(e,r,o,n){let s=Zo(e,n);if(o.isTwoDigitYear){let a=ma(o.year,s);return e.setFullYear(a,0,n.firstWeekContainsDate),e.setHours(0,0,0,0),ze(e,n)}let i=!("era"in r)||r.era===1?o.year:1-o.year;return e.setFullYear(i,0,n.firstWeekContainsDate),e.setHours(0,0,0,0),ze(e,n)}incompatibleTokens=["y","R","u","Q","q","M","L","I","d","D","i","t","T"]};var ya=class extends C{priority=130;parse(e,r){return r==="R"?tn(4,e):tn(r.length,e)}set(e,r,o){let n=H(e,0);return n.setFullYear(o,0,4),n.setHours(0,0,0,0),Ct(n)}incompatibleTokens=["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"]};var ba=class extends C{priority=130;parse(e,r){return r==="u"?tn(4,e):tn(r.length,e)}set(e,r,o){return e.setFullYear(o,0,1),e.setHours(0,0,0,0),e}incompatibleTokens=["G","y","Y","R","w","I","i","e","c","t","T"]};var _a=class extends C{priority=120;parse(e,r,o){switch(r){case"Q":case"QQ":return F(r.length,e);case"Qo":return o.ordinalNumber(e,{unit:"quarter"});case"QQQ":return o.quarter(e,{width:"abbreviated",context:"formatting"})||o.quarter(e,{width:"narrow",context:"formatting"});case"QQQQQ":return o.quarter(e,{width:"narrow",context:"formatting"});default:return o.quarter(e,{width:"wide",context:"formatting"})||o.quarter(e,{width:"abbreviated",context:"formatting"})||o.quarter(e,{width:"narrow",context:"formatting"})}}validate(e,r){return r>=1&&r<=4}set(e,r,o){return e.setMonth((o-1)*3,1),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"]};var wa=class extends C{priority=120;parse(e,r,o){switch(r){case"q":case"qq":return F(r.length,e);case"qo":return o.ordinalNumber(e,{unit:"quarter"});case"qqq":return o.quarter(e,{width:"abbreviated",context:"standalone"})||o.quarter(e,{width:"narrow",context:"standalone"});case"qqqqq":return o.quarter(e,{width:"narrow",context:"standalone"});default:return o.quarter(e,{width:"wide",context:"standalone"})||o.quarter(e,{width:"abbreviated",context:"standalone"})||o.quarter(e,{width:"narrow",context:"standalone"})}}validate(e,r){return r>=1&&r<=4}set(e,r,o){return e.setMonth((o-1)*3,1),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"]};var va=class extends C{incompatibleTokens=["Y","R","q","Q","L","w","I","D","i","e","c","t","T"];priority=110;parse(e,r,o){let n=s=>s-1;switch(r){case"M":return Q(z(G.month,e),n);case"MM":return Q(F(2,e),n);case"Mo":return Q(o.ordinalNumber(e,{unit:"month"}),n);case"MMM":return o.month(e,{width:"abbreviated",context:"formatting"})||o.month(e,{width:"narrow",context:"formatting"});case"MMMMM":return o.month(e,{width:"narrow",context:"formatting"});default:return o.month(e,{width:"wide",context:"formatting"})||o.month(e,{width:"abbreviated",context:"formatting"})||o.month(e,{width:"narrow",context:"formatting"})}}validate(e,r){return r>=0&&r<=11}set(e,r,o){return e.setMonth(o,1),e.setHours(0,0,0,0),e}};var Sa=class extends C{priority=110;parse(e,r,o){let n=s=>s-1;switch(r){case"L":return Q(z(G.month,e),n);case"LL":return Q(F(2,e),n);case"Lo":return Q(o.ordinalNumber(e,{unit:"month"}),n);case"LLL":return o.month(e,{width:"abbreviated",context:"standalone"})||o.month(e,{width:"narrow",context:"standalone"});case"LLLLL":return o.month(e,{width:"narrow",context:"standalone"});default:return o.month(e,{width:"wide",context:"standalone"})||o.month(e,{width:"abbreviated",context:"standalone"})||o.month(e,{width:"narrow",context:"standalone"})}}validate(e,r){return r>=0&&r<=11}set(e,r,o){return e.setMonth(o,1),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","M","w","I","D","i","e","c","t","T"]};function zh(t,e,r){let o=R(t,r?.in),n=oa(o,r)-e;return o.setDate(o.getDate()-n*7),R(o,r?.in)}var xa=class extends C{priority=100;parse(e,r,o){switch(r){case"w":return z(G.week,e);case"wo":return o.ordinalNumber(e,{unit:"week"});default:return F(r.length,e)}}validate(e,r){return r>=1&&r<=53}set(e,r,o,n){return ze(zh(e,o,n),n)}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","i","t","T"]};function Gh(t,e,r){let o=R(t,r?.in),n=ra(o,r)-e;return o.setDate(o.getDate()-n*7),o}var ka=class extends C{priority=100;parse(e,r,o){switch(r){case"I":return z(G.week,e);case"Io":return o.ordinalNumber(e,{unit:"week"});default:return F(r.length,e)}}validate(e,r){return r>=1&&r<=53}set(e,r,o){return Ct(Gh(e,o))}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"]};var nS=[31,28,31,30,31,30,31,31,30,31,30,31],sS=[31,29,31,30,31,30,31,31,30,31,30,31],Ta=class extends C{priority=90;subPriority=1;parse(e,r,o){switch(r){case"d":return z(G.date,e);case"do":return o.ordinalNumber(e,{unit:"date"});default:return F(r.length,e)}}validate(e,r){let o=e.getFullYear(),n=ha(o),s=e.getMonth();return n?r>=1&&r<=sS[s]:r>=1&&r<=nS[s]}set(e,r,o){return e.setDate(o),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","w","I","D","i","e","c","t","T"]};var Ca=class extends C{priority=90;subpriority=1;parse(e,r,o){switch(r){case"D":case"DD":return z(G.dayOfYear,e);case"Do":return o.ordinalNumber(e,{unit:"date"});default:return F(r.length,e)}}validate(e,r){let o=e.getFullYear();return ha(o)?r>=1&&r<=366:r>=1&&r<=365}set(e,r,o){return e.setMonth(0,o),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"]};function on(t,e,r){let o=dt(),n=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??o.weekStartsOn??o.locale?.options?.weekStartsOn??0,s=R(t,r?.in),i=s.getDay(),l=(e%7+7)%7,u=7-n,c=e<0||e>6?e-(i+u)%7:(l+u)%7-(i+u)%7;return Zi(s,c,r)}var Ea=class extends C{priority=90;parse(e,r,o){switch(r){case"E":case"EE":case"EEE":return o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"});case"EEEEE":return o.day(e,{width:"narrow",context:"formatting"});case"EEEEEE":return o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"});default:return o.day(e,{width:"wide",context:"formatting"})||o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"})}}validate(e,r){return r>=0&&r<=6}set(e,r,o,n){return e=on(e,o,n),e.setHours(0,0,0,0),e}incompatibleTokens=["D","i","e","c","t","T"]};var Pa=class extends C{priority=90;parse(e,r,o,n){let s=i=>{let a=Math.floor((i-1)/7)*7;return(i+n.weekStartsOn+6)%7+a};switch(r){case"e":case"ee":return Q(F(r.length,e),s);case"eo":return Q(o.ordinalNumber(e,{unit:"day"}),s);case"eee":return o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"});case"eeeee":return o.day(e,{width:"narrow",context:"formatting"});case"eeeeee":return o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"});default:return o.day(e,{width:"wide",context:"formatting"})||o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"})}}validate(e,r){return r>=0&&r<=6}set(e,r,o,n){return e=on(e,o,n),e.setHours(0,0,0,0),e}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"]};var Oa=class extends C{priority=90;parse(e,r,o,n){let s=i=>{let a=Math.floor((i-1)/7)*7;return(i+n.weekStartsOn+6)%7+a};switch(r){case"c":case"cc":return Q(F(r.length,e),s);case"co":return Q(o.ordinalNumber(e,{unit:"day"}),s);case"ccc":return o.day(e,{width:"abbreviated",context:"standalone"})||o.day(e,{width:"short",context:"standalone"})||o.day(e,{width:"narrow",context:"standalone"});case"ccccc":return o.day(e,{width:"narrow",context:"standalone"});case"cccccc":return o.day(e,{width:"short",context:"standalone"})||o.day(e,{width:"narrow",context:"standalone"});default:return o.day(e,{width:"wide",context:"standalone"})||o.day(e,{width:"abbreviated",context:"standalone"})||o.day(e,{width:"short",context:"standalone"})||o.day(e,{width:"narrow",context:"standalone"})}}validate(e,r){return r>=0&&r<=6}set(e,r,o,n){return e=on(e,o,n),e.setHours(0,0,0,0),e}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"]};function Kh(t,e,r){let o=R(t,r?.in),n=Wh(o,r),s=e-n;return Zi(o,s,r)}var Aa=class extends C{priority=90;parse(e,r,o){let n=s=>s===0?7:s;switch(r){case"i":case"ii":return F(r.length,e);case"io":return o.ordinalNumber(e,{unit:"day"});case"iii":return Q(o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"}),n);case"iiiii":return Q(o.day(e,{width:"narrow",context:"formatting"}),n);case"iiiiii":return Q(o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"}),n);default:return Q(o.day(e,{width:"wide",context:"formatting"})||o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"}),n)}}validate(e,r){return r>=1&&r<=7}set(e,r,o){return e=Kh(e,o),e.setHours(0,0,0,0),e}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"]};var Ra=class extends C{priority=80;parse(e,r,o){switch(r){case"a":case"aa":case"aaa":return o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"});case"aaaaa":return o.dayPeriod(e,{width:"narrow",context:"formatting"});default:return o.dayPeriod(e,{width:"wide",context:"formatting"})||o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,r,o){return e.setHours(rn(o),0,0,0),e}incompatibleTokens=["b","B","H","k","t","T"]};var Ia=class extends C{priority=80;parse(e,r,o){switch(r){case"b":case"bb":case"bbb":return o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"});case"bbbbb":return o.dayPeriod(e,{width:"narrow",context:"formatting"});default:return o.dayPeriod(e,{width:"wide",context:"formatting"})||o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,r,o){return e.setHours(rn(o),0,0,0),e}incompatibleTokens=["a","B","H","k","t","T"]};var Da=class extends C{priority=80;parse(e,r,o){switch(r){case"B":case"BB":case"BBB":return o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"});case"BBBBB":return o.dayPeriod(e,{width:"narrow",context:"formatting"});default:return o.dayPeriod(e,{width:"wide",context:"formatting"})||o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,r,o){return e.setHours(rn(o),0,0,0),e}incompatibleTokens=["a","b","t","T"]};var La=class extends C{priority=70;parse(e,r,o){switch(r){case"h":return z(G.hour12h,e);case"ho":return o.ordinalNumber(e,{unit:"hour"});default:return F(r.length,e)}}validate(e,r){return r>=1&&r<=12}set(e,r,o){let n=e.getHours()>=12;return n&&o<12?e.setHours(o+12,0,0,0):!n&&o===12?e.setHours(0,0,0,0):e.setHours(o,0,0,0),e}incompatibleTokens=["H","K","k","t","T"]};var Na=class extends C{priority=70;parse(e,r,o){switch(r){case"H":return z(G.hour23h,e);case"Ho":return o.ordinalNumber(e,{unit:"hour"});default:return F(r.length,e)}}validate(e,r){return r>=0&&r<=23}set(e,r,o){return e.setHours(o,0,0,0),e}incompatibleTokens=["a","b","h","K","k","t","T"]};var ja=class extends C{priority=70;parse(e,r,o){switch(r){case"K":return z(G.hour11h,e);case"Ko":return o.ordinalNumber(e,{unit:"hour"});default:return F(r.length,e)}}validate(e,r){return r>=0&&r<=11}set(e,r,o){return e.getHours()>=12&&o<12?e.setHours(o+12,0,0,0):e.setHours(o,0,0,0),e}incompatibleTokens=["h","H","k","t","T"]};var Ma=class extends C{priority=70;parse(e,r,o){switch(r){case"k":return z(G.hour24h,e);case"ko":return o.ordinalNumber(e,{unit:"hour"});default:return F(r.length,e)}}validate(e,r){return r>=1&&r<=24}set(e,r,o){let n=o<=24?o%24:o;return e.setHours(n,0,0,0),e}incompatibleTokens=["a","b","h","H","K","t","T"]};var Ua=class extends C{priority=60;parse(e,r,o){switch(r){case"m":return z(G.minute,e);case"mo":return o.ordinalNumber(e,{unit:"minute"});default:return F(r.length,e)}}validate(e,r){return r>=0&&r<=59}set(e,r,o){return e.setMinutes(o,0,0),e}incompatibleTokens=["t","T"]};var Fa=class extends C{priority=50;parse(e,r,o){switch(r){case"s":return z(G.second,e);case"so":return o.ordinalNumber(e,{unit:"second"});default:return F(r.length,e)}}validate(e,r){return r>=0&&r<=59}set(e,r,o){return e.setSeconds(o,0),e}incompatibleTokens=["t","T"]};var $a=class extends C{priority=30;parse(e,r){let o=n=>Math.trunc(n*Math.pow(10,-r.length+3));return Q(F(r.length,e),o)}set(e,r,o){return e.setMilliseconds(o),e}incompatibleTokens=["t","T"]};var Ba=class extends C{priority=10;parse(e,r){switch(r){case"X":return mt(ft.basicOptionalMinutes,e);case"XX":return mt(ft.basic,e);case"XXXX":return mt(ft.basicOptionalSeconds,e);case"XXXXX":return mt(ft.extendedOptionalSeconds,e);default:return mt(ft.extended,e)}}set(e,r,o){return r.timestampIsSet?e:H(e,e.getTime()-io(e)-o)}incompatibleTokens=["t","T","x"]};var qa=class extends C{priority=10;parse(e,r){switch(r){case"x":return mt(ft.basicOptionalMinutes,e);case"xx":return mt(ft.basic,e);case"xxxx":return mt(ft.basicOptionalSeconds,e);case"xxxxx":return mt(ft.extendedOptionalSeconds,e);default:return mt(ft.extended,e)}}set(e,r,o){return r.timestampIsSet?e:H(e,e.getTime()-io(e)-o)}incompatibleTokens=["t","T","X"]};var Va=class extends C{priority=40;parse(e){return fa(e)}set(e,r,o){return[H(e,o*1e3),{timestampIsSet:!0}]}incompatibleTokens="*"};var Wa=class extends C{priority=20;parse(e){return fa(e)}set(e,r,o){return[H(e,o),{timestampIsSet:!0}]}incompatibleTokens="*"};var Jh={G:new da,y:new pa,Y:new ga,R:new ya,u:new ba,Q:new _a,q:new wa,M:new va,L:new Sa,w:new xa,I:new ka,d:new Ta,D:new Ca,E:new Ea,e:new Pa,c:new Oa,i:new Aa,a:new Ra,b:new Ia,B:new Da,h:new La,H:new Na,K:new ja,k:new Ma,m:new Ua,s:new Fa,S:new $a,X:new Ba,x:new qa,t:new Va,T:new Wa};var iS=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,aS=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,lS=/^'([^]*?)'?$/,uS=/''/g,cS=/\S/,dS=/[a-zA-Z]/;function Qe(t,e,r,o){let n=()=>H(o?.in||r,NaN),s=aa(),i=o?.locale??s.locale??ws,a=o?.firstWeekContainsDate??o?.locale?.options?.firstWeekContainsDate??s.firstWeekContainsDate??s.locale?.options?.firstWeekContainsDate??1,l=o?.weekStartsOn??o?.locale?.options?.weekStartsOn??s.weekStartsOn??s.locale?.options?.weekStartsOn??0;if(!e)return t?n():R(r,o?.in);let u={firstWeekContainsDate:a,weekStartsOn:l,locale:i},c=[new ca(o?.in,r)],d=e.match(aS).map(y=>{let p=y[0];if(p in vs){let b=vs[p];return b(y,i.formatLong)}return y}).join("").match(iS),f=[];for(let y of d){!o?.useAdditionalWeekYearTokens&&sa(y)&&Ss(y,e,t),!o?.useAdditionalDayOfYearTokens&&na(y)&&Ss(y,e,t);let p=y[0],b=Jh[p];if(b){let{incompatibleTokens:_}=b;if(Array.isArray(_)){let N=f.find(x=>_.includes(x.token)||x.token===p);if(N)throw new RangeError(`The format string mustn't contain \`${N.fullToken}\` and \`${y}\` at the same time`)}else if(b.incompatibleTokens==="*"&&f.length>0)throw new RangeError(`The format string mustn't contain \`${y}\` and any other token at the same time`);f.push({token:p,fullToken:y});let v=b.run(t,y,i.match,u);if(!v)return n();c.push(v.setter),t=v.rest}else{if(p.match(dS))throw new RangeError("Format string contains an unescaped latin alphabet character `"+p+"`");if(y==="''"?y="'":p==="'"&&(y=fS(y)),t.indexOf(y)===0)t=t.slice(y.length);else return n()}}if(t.length>0&&cS.test(t))return n();let m=c.map(y=>y.priority).sort((y,p)=>p-y).filter((y,p,b)=>b.indexOf(y)===p).map(y=>c.filter(p=>p.priority===y).sort((p,b)=>b.subPriority-p.subPriority)).map(y=>y[0]),h=R(r,o?.in);if(isNaN(+h))return n();let g={};for(let y of m){if(!y.validate(h,u))return n();let p=y.set(h,g,u);Array.isArray(p)?(h=p[0],Object.assign(g,p[1])):h=p}return h}function fS(t){return t.match(lS)[1].replace(uS,"'")}function Yh(t,e){let r=R(t,e?.in);return r.setSeconds(0,0),r}var w=require("zod");var Ha=require("zod"),Xh=["pos","kds","kiosk"],nj=Ha.z.enum(Xh),mS=[...Xh,"restaurant_site","developer_dashboard","zorgo_site","backend"],Qh=Ha.z.enum(mS),hS=["gateway","main_service","agent_service","background_workers"],sj=Ha.z.enum(hS);var Hu=w.z.object({settle_ms:w.z.number().nullable().default(null),interaction_wait_ms:w.z.number().nullable().default(null),capture_ms:w.z.number().nullable().default(null),print_ms:w.z.number().nullable().default(null)}),pS=w.z.object({global:w.z.object({font_family:w.z.enum(["sans-serif","serif","monospace"]).default("sans-serif"),base_font_size:w.z.enum(["small","medium","large"]).default("large"),text_alignment:w.z.enum(["left","center"]).default("left")}).prefault({}),header:w.z.object({show_logo:w.z.boolean().default(!0),show_customer_name:w.z.boolean().default(!0),show_time_info:w.z.boolean().default(!0),show_order_number:w.z.boolean().default(!0),order_number_style:w.z.enum(["bold","normal, small"]).default("bold")}).prefault({}),body:w.z.object({show_modifiers:w.z.boolean().default(!0),show_item_notes:w.z.boolean().default(!0),show_prices:w.z.boolean().default(!0),compact_view:w.z.boolean().default(!0)}).prefault({}),footer:w.z.object({show_tax_breakdown:w.z.boolean().default(!0),show_subtotal:w.z.boolean().default(!0),show_tax:w.z.boolean().default(!0),show_service_fee:w.z.boolean().default(!1),show_tip:w.z.boolean().default(!0),show_suggested_tips:w.z.boolean().default(!1),show_customer_signature:w.z.boolean().default(!1),show_grand_total:w.z.boolean().default(!0),total_line_label:w.z.string().max(24).default("Total"),suggested_tip_percentages:w.z.array(w.z.number().min(0).max(1)).default([.2,.15,.1]),custom_message:w.z.string().max(200).optional().default(""),customer_signature_agreement:w.z.string().max(300).default("I agree to pay the above amount per the cardholder and/or merchant agreement")}).prefault({})}),gS=w.z.enum(["kitchen","merchant","customer"]),aj=w.z.object({id:w.z.uuid().optional(),franchise_id:w.z.number().default(-1),type:gS.default("kitchen"),config:pS.prefault({})}),Zh=w.z.string().regex(/^[1-9][0-9]?\/[1-9][0-9]?$/,'portion must look like "1/2"').refine(t=>{let[e,r]=t.split("/").map(Number);return e<=r},"portion index cannot exceed its divisions"),yS=w.z.enum(["radial","grid","linear","count"]),lj=w.z.object({id:w.z.number(),franchise_id:w.z.number(),geometry:yS,name:w.z.string().min(1),min_divisions:w.z.number().int().min(1).default(1),max_divisions:w.z.number().int().min(1).max(12)}).check(t=>{let e=t.value;e.max_divisions<e.min_divisions&&t.issues.push({code:"custom",input:e,path:["max_divisions"],message:"max_divisions must be >= min_divisions"})}),bS=w.z.object({type:w.z.enum(["item","component"]),id:w.z.number(),quantity:w.z.number(),upcharge:w.z.number(),serving_price:w.z.number().optional(),name:w.z.string(),portion:Zh.nullish()}),_S=w.z.object({rule_id:w.z.number(),group_name:w.z.string(),selections:w.z.array(bS)}),wS=w.z.object({id:w.z.number(),servings_per_item:w.z.number().nullish(),is_base:w.z.boolean().nullish(),price_per_serving:w.z.number().nullish(),franchise_id:w.z.number().nullish(),component_type_id:w.z.number(),serving_weight:w.z.number().nullish(),name:w.z.string().default(""),item_id:w.z.number().nullish(),quantity_servings:w.z.number(),upcharge:w.z.number().nullish(),rule_id:w.z.number().nullish(),portion:Zh.nullish()}),vS=w.z.object({item_id:w.z.number(),name:w.z.string(),quantity:w.z.number(),price:w.z.number(),order_item_id:w.z.number().nullish(),status:w.z.enum(["removed","modified"]).nullish(),category_id:w.z.number().nullish(),category_name:w.z.string().nullish(),is_catering:w.z.boolean().nullish(),per_person:w.z.boolean().nullish(),components:w.z.array(wS).nullish(),selections:w.z.array(_S).nullish(),comments:w.z.string().nullish()}),SS=w.z.object({customer_id:w.z.number().optional(),phone:w.z.string(),first_name:w.z.string(),last_name:w.z.string().nullish(),email:w.z.string().nullish(),allow_marketing:w.z.boolean().default(!1)}),uj=w.z.object({first_name:w.z.string().min(2,"Enter at least 2 characters"),last_name:w.z.string().min(2,"Enter at least 2 characters"),phone:w.z.string().regex(/^\d{10}$/,"Enter a 10-digit phone number"),email:w.z.email().optional().or(w.z.literal("")),allow_marketing:w.z.boolean().optional().default(!1)});var xS=w.z.object({id:w.z.number(),order_id:w.z.number().nullish(),total:w.z.number(),subtotal:w.z.number(),tax:w.z.number(),tip:w.z.number().nullish(),discount:w.z.number().nullish(),service_fee:w.z.number().nullish(),charge_id:w.z.string().nullish(),charge_status:w.z.number().nullish(),created_at:w.z.coerce.date().nullish(),setup_intent_id:w.z.string().nullish(),payment_method_id:w.z.string().nullish(),stripe_customer_id:w.z.string().nullish()}),cj=w.z.object({order_id:w.z.number(),customer:SS,location_id:w.z.number(),method_id:w.z.number().nullish(),type_id:w.z.number().nullish(),time_placed:w.z.coerce.date(),time_requested:w.z.coerce.date().nullish(),items:w.z.array(vS),order_status:w.z.number().nullish(),order_code:w.z.string().optional(),promo_code:w.z.string().nullish(),charges:w.z.array(xS),subtotal:w.z.number().nullish(),delivery_address:w.z.string().optional()}),kS=w.z.enum(["guest","requested_access","action_required","pending_approval","healthy"]).default("guest"),dj=w.z.object({id:w.z.string(),user_id:w.z.string(),franchise_name:w.z.string(),number_of_locations:w.z.number(),phone:w.z.string(),email:w.z.string(),status:kS,metadata:w.z.record(w.z.string(),w.z.unknown()).default({}),created_at:w.z.coerce.date()}),fj=w.z.object({location_id:w.z.number(),table_number:w.z.number(),label:w.z.string().nullish(),capacity:w.z.number(),shape:w.z.enum(["rect","round"]),reservable:w.z.boolean(),x:w.z.number(),y:w.z.number(),w:w.z.number(),h:w.z.number()}),mj=w.z.object({salesCount:w.z.number().int().nonnegative(),grossRevenue:w.z.number().int().nonnegative(),totalRevenue:w.z.number().int().nonnegative(),totalRefunds:w.z.number().int().nonnegative(),totalDiscounts:w.z.number().int().nonnegative(),totalTips:w.z.number().int().nonnegative(),netRevenue:w.z.number().int()}),hj=w.z.object({requireTableForDineIn:w.z.boolean().default(!1)});var xs=()=>typeof globalThis.crypto?.randomUUID=="function"?globalThis.crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)});function tp(t){let e=(t||"").replace(/\D/g,"");return e.length===11?`+${e}`:`+1${e}`}var xr=typeof globalThis.document<"u"&&globalThis.navigator?.product!=="ReactNative",ep={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};function kr(){let t=globalThis;if(typeof t.window<"u"&&typeof t.window.localStorage<"u")return t.window.localStorage;if(t?.navigator?.product==="ReactNative"||typeof t?.document>"u"&&typeof process>"u")try{return(Bu(),Ol($u)).default}catch{return ep}return ep}function za(t){return`(${t.join(",")})`}var Ga=(n=>(n.Website="website",n.Kiosk="kiosk",n.Pos="pos",n.KitchenDisplay="kitchen_display",n))(Ga||{});var vj={website:"Website",kiosk:"Kiosk",pos:"POS"},Bt=class extends Error{constructor(e){super(e),this.name="VisibilityConditionError"}};function rp(t){let e=t?.date??new Date,r=["su","m","t","w","th","f","sa"],o=e.getHours().toString().padStart(2,"0"),n=e.getMinutes().toString().padStart(2,"0");return{dayOfWeek:r[e.getDay()]??"m",currentTime:`${o}:${n}`,platform:t?.platform??"website"}}function TS(t){if(t.version!==1)throw new Bt("Unsupported visibility condition version.");np(t.root)}function op(t,e){return TS(t),zu(t.root,e)}function np(t){switch(t.type){case"group":if(t.children.length===0)throw new Bt("Condition groups cannot be empty.");t.children.forEach(np);return;case"constant":return;case"rule":CS(t);return;default:throw new Bt("Unknown visibility condition node.")}}function CS(t){if(t.variable==="dayOfWeek"){if(!Array.isArray(t.value)||t.value.length===0)throw new Bt("Day-of-week rules require at least one day.");return}if(t.variable==="platform"){if((Array.isArray(t.value)?t.value:[t.value]).length===0)throw new Bt("Platform rules require at least one platform.");return}if(t.variable==="currentTime"){if(t.operator==="between"){if(typeof t.value!="object"||t.value==null||!("start"in t.value)||!("end"in t.value))throw new Bt("Between rules require a start and end time.");Ja(t.value.start),Ja(t.value.end);return}if(typeof t.value!="string")throw new Bt("Time rules require a single time value.");Ja(t.value)}}function zu(t,e){return t.type==="group"?t.operator==="and"?t.children.every(r=>zu(r,e)):t.children.some(r=>zu(r,e)):t.type==="constant"?t.value:ES(t,e)}function ES(t,e){switch(t.variable){case"dayOfWeek":{let r=t.value;return t.operator==="is_any_of"?r.includes(e.dayOfWeek):!r.includes(e.dayOfWeek)}case"platform":{let r=Array.isArray(t.value)?t.value:[t.value];switch(t.operator){case"is":return e.platform===r[0];case"is_not":return e.platform!==r[0];case"is_any_of":return r.includes(e.platform)}}case"currentTime":{let r=Ka(e.currentTime);if(t.operator==="between"){let n=t.value,s=Ka(n.start),i=Ka(n.end);return r>=s&&r<=i}let o=Ka(t.value);switch(t.operator){case"before":return r<o;case"after":return r>o;case"on_or_before":return r<=o;case"on_or_after":return r>=o;default:return!1}}default:return!1}}function Ka(t){Ja(t);let e=t.split(":"),r=Number(e[0]),o=Number(e[1]);return r*60+o}function Ja(t){if(!/^\d{2}:\d{2}$/.test(t))throw new Bt(`Invalid time "${t}". Use HH:mm format.`)}var Tr={ascending:!0,nullsFirst:!1},sp=Number.MAX_SAFE_INTEGER;function Ju(t,e){let r=(t.sort_index??sp)-(e.sort_index??sp);return r!==0?r:t.name.localeCompare(e.name)}async function ip(t,e,r=up(),o=!1){let n=await AS(t,e,r.categoryIds);if(n.length===0)return Ku([],[],[],[],[]);let s=await RS(t,e,r.baseItemIds,n);if(s.length===0)return Ku([],[],n,[],[]);let i=await DS(t,s,r.itemIds),a=await LS(t,i,o),l=await NS(t,s,n,i,o);return Ku(i,s,n,a,l)}function ap(t,e){let r=new Map,o=(i,a)=>a.promotion_type_id===1?Math.max(0,Math.floor(i*(1-a.discount_value/100))):a.promotion_type_id===2?Math.max(0,i-a.discount_value):i,n=t.items.map(i=>{let l=e.find(c=>{if(!c.is_active||c.id==null||!c.discount_target_ids?.length||!c.min_purchase_quantity)return!1;let d=c.discount_target_ids;return c.discount_target_type==="category"&&d.includes(i.category_id)||c.discount_target_type==="item"&&d.includes(i.base_item_id)})?.id,u=i.variants.map(c=>{let d,f=c.price;for(let m of e){if(!m.is_active||m.id==null||!m.discount_target_ids?.length||m.min_purchase_amount||m.min_purchase_quantity)continue;let h=m.discount_target_ids;if(!(m.discount_target_type==="category"&&h.includes(i.category_id)||m.discount_target_type==="item"&&h.includes(i.base_item_id)||m.discount_target_type==="item_variant"&&h.includes(c.item_id)))continue;let y=o(c.price,m);y<f&&(d=m,f=y)}return!d||f>=c.price?c:(l??=d.id,d.discount_target_type==="category"&&r.set(i.category_id,d.id),{...c,active_promo_id:d.id,display_price:f})});return{...i,variants:u,active_promo_id:l}}),s=t.categories.map(i=>{let{active_promo_id:a,...l}=i,u=r.get(l.category_id);return u==null?l:{...l,active_promo_id:u}});return{...t,items:n,categories:s}}async function lp(t,e,r,o){let n=await PS(t,e),s=await OS(t,e,o);if(s.length===0)return up();let i=Gu(s,p=>p.category_id),a=Gu(s,p=>p.base_item_id),l=Gu(s,p=>p.item_id),u=new Map(n.baseItems.map(p=>[p.base_item_id,p])),c=new Map(n.items.map(p=>[p.item_id,p])),d=p=>i.get(p)!=="exclude",f=p=>{let b=a.get(p);if(b==="include")return!0;if(b==="exclude")return!1;let _=u.get(p)?.category_id;return _==null||d(_)},m=p=>{let b=l.get(p);if(b==="include")return!0;if(b==="exclude")return!1;let _=c.get(p);return _?.base_item_id==null?!0:f(_.base_item_id)},h=new Set(n.items.filter(p=>m(p.item_id)).map(p=>p.item_id)),g=new Set(n.baseItems.filter(p=>f(p.base_item_id)).map(p=>p.base_item_id));for(let p of n.items)h.has(p.item_id)&&p.base_item_id!=null&&g.add(p.base_item_id);let y=new Set(n.categories.filter(p=>d(p.category_id)).map(p=>p.category_id));for(let p of n.baseItems)g.has(p.base_item_id)&&y.add(p.category_id);return{categoryIds:n.categories.map(p=>p.category_id).filter(p=>!y.has(p)),baseItemIds:n.baseItems.map(p=>p.base_item_id).filter(p=>!g.has(p)),itemIds:n.items.map(p=>p.item_id).filter(p=>!h.has(p))}}function up(){return{categoryIds:[],baseItemIds:[],itemIds:[]}}async function PS(t,e){let{data:r,error:o}=await t.from("categories").select("category_id").eq("franchise_id",e);if(o)throw o;let{data:n,error:s}=await t.from("base_items").select("base_item_id, category_id").eq("franchise_id",e);if(s)throw s;let i=(n??[]).map(u=>u.base_item_id),{data:a,error:l}=i.length>0?await t.from("items").select("item_id, base_item_id").in("base_item_id",i):{data:[],error:null};if(l)throw l;return{categories:r??[],baseItems:n??[],items:a??[]}}async function OS(t,e,r){let{data:o,error:n}=await t.from("visibility_condition_group_assignments").select("*, visibility_condition_groups (*)").eq("visibility_condition_groups.franchise_id",e).eq("visibility_condition_groups.platform",r);if(n||!o)return[];let s=rp({platform:r});return o.filter(i=>{let a=i.visibility_condition_groups;if(!a?.condition||a.platform!==s.platform)return!1;try{return op(a.condition,s)}catch{return!1}})}function Gu(t,e){let r=new Map;for(let o of t){let n=e(o);n!=null&&r.set(n,[...r.get(n)??[],o.effect])}return new Map(Array.from(r.entries()).map(([o,n])=>[o,n.includes("exclude")?"exclude":"include"]))}async function AS(t,e,r){let o=t.from("categories").select("*").eq("franchise_id",e).order("sort_index",Tr).order("name",Tr);r&&r.length>0&&(o=o.not("category_id","in",za(r)));let{data:n,error:s}=await o;if(s)throw s;return n??[]}async function RS(t,e,r,o){if(o&&o.length===0)return[];let n=t.from("base_items").select("*").eq("franchise_id",e).order("sort_index",Tr).order("name",Tr);r&&r.length>0&&(n=n.not("base_item_id","in",za(r))),o&&(n=n.in("category_id",o.map(u=>u.category_id)));let{data:s,error:i}=await n;if(i)throw i;if(!s||s.length===0)return[];let{data:a,error:l}=await t.from("base_item_images").select("*").in("base_item_id",s.map(u=>u.base_item_id)).order("sort_index",{ascending:!0}).order("image_id",{ascending:!0});if(l)throw l;return IS(s,a??[])}function IS(t,e){let r=new Map;for(let o of e){let n=r.get(o.base_item_id);n?n.push(o):r.set(o.base_item_id,[o])}return t.map(o=>({...o,images:r.get(o.base_item_id)??[]}))}async function DS(t,e,r){if(e&&e.length===0)return[];let o=t.from("items").select("*, portion_scheme:portion_schemes(*)").in("base_item_id",e.map(i=>i.base_item_id)).order("sort_index",Tr).order("price",Tr);r&&r.length>0&&(o=o.not("item_id","in",za(r)));let{data:n,error:s}=await o;if(s)throw s;return n??[]}async function LS(t,e,r=!1){let o=e.length>0&&typeof e[0]=="number"?e:e.map(i=>i.item_id);if(o.length===0)return[];let n=r?"components(*), item_id, servings_per_item, behavior_id, component_quantity_behaviors(headcount_threshold, starting_amount, step_size, step_interval, maximum)":"components(*), item_id, servings_per_item",{data:s}=await t.from("item_components").select(n).in("item_id",o).throwOnError();return s.map(i=>({servings_per_item:i.servings_per_item,is_base:i.components?.is_base,serving_weight:i.components?.serving_weight,component_type_id:i.components?.component_type_id,id:i.components?.id,name:i.components?.name,item_id:i.item_id,...r&&{behavior:i.component_quantity_behaviors??void 0}}))}function cp(t){return[...(t.components??[]).map(e=>({key:`component:${e.component_id}`,id:e.component_id,type:"component",name:e.name,basePrice:e.upcharge_price||0,description:e.description,sort_index:e.sort_index??null})),...(t.items??[]).map(e=>({key:`item:${e.item_id}`,id:e.item_id,type:"item",name:e.name,basePrice:e.upcharge_price||0,description:e.description,sort_index:e.sort_index??null}))].sort(Ju)}async function NS(t,e,r,o,n=!1,s){let i=o?.map(g=>g.item_id)??[],a=e?.map(g=>g.base_item_id)??[],l=r?.map(g=>g.category_id)??[];if(i.length===0&&a.length===0&&l.length===0&&!s?.length)return[];let u=[`item_id.in.(${i.length>0?i.join(","):-1})`,`base_item_id.in.(${a.length>0?a.join(","):-1})`,`category_id.in.(${l.length>0?l.join(","):-1})`,...s?.length?[`rule_id.in.(${s.join(",")})`]:[]].join(","),c=n?"component_quantity_behaviors(headcount_threshold, starting_amount, step_size, step_interval, maximum)":null,d=["component_id, upcharge_price, sort_index, components(name, description, serving_weight)",c].filter(Boolean).join(", "),f=["item_id, upcharge_price, sort_index, items(item_id, name, description)",c].filter(Boolean).join(", "),{data:m,error:h}=await t.from("item_rules").select(`
|
|
140
|
+
`};var sh=null;var Fu=(t,e)=>{if(!sh)return fetch(t,e);let r=new Headers(e?.headers);return r.set("Authorization",`Bearer ${sh}`),fetch(t,{...e,headers:r})};var Wu=globalThis?.navigator?.product==="ReactNative",wh=typeof process<"u"&&process.versions?.node,f0=!Wu&&!wh&&typeof globalThis?.document<"u";function _h(){if(!wh&&Wu)try{return(Vu(),Rl(qu)).default}catch{return}}function m0(){return f0?nh(Mu,Uu,{global:{fetch:Fu}}):Gf(Mu,Uu,{auth:{autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!Wu,..._h()?{storage:_h()}:{},lock:Zl},global:{fetch:Fu}})}var U=m0();var rg=require("zustand/middleware/immer"),ln=require("zustand/middleware");var h0=Math.pow(10,8)*24*60*60*1e3,lI=-h0,Qi=6048e5,vh=864e5,Zi=6e4,ea=36e5,Sh=1e3;var p0=3600;var xh=p0*24,uI=xh*7,g0=xh*365.2425,y0=g0/12,cI=y0*3,Hu=Symbol.for("constructDateFrom");function H(t,e){return typeof t=="function"?t(e):t&&typeof t=="object"&&Hu in t?t[Hu](e):t instanceof Date?new t.constructor(e):new Date(e)}function R(t,e){return H(e||t,t)}function ta(t,e,r){let o=R(t,r?.in);return isNaN(e)?H(r?.in||t,NaN):(e&&o.setDate(o.getDate()+e),o)}function kh(t,e,r){return H(r?.in||t,+R(t)+e)}function Yo(t,e,r){return kh(t,e*ea,r)}var b0={};function dt(){return b0}function ze(t,e){let r=dt(),o=e?.weekStartsOn??e?.locale?.options?.weekStartsOn??r.weekStartsOn??r.locale?.options?.weekStartsOn??0,n=R(t,e?.in),s=n.getDay(),i=(s<o?7:0)+s-o;return n.setDate(n.getDate()-i),n.setHours(0,0,0,0),n}function Ct(t,e){return ze(t,{...e,weekStartsOn:1})}function ra(t,e){let r=R(t,e?.in),o=r.getFullYear(),n=H(r,0);n.setFullYear(o+1,0,4),n.setHours(0,0,0,0);let s=Ct(n),i=H(r,0);i.setFullYear(o,0,4),i.setHours(0,0,0,0);let a=Ct(i);return r.getTime()>=s.getTime()?o+1:r.getTime()>=a.getTime()?o:o-1}function io(t){let e=R(t),r=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return r.setUTCFullYear(e.getFullYear()),+t-+r}function Th(t,...e){let r=H.bind(null,t||e.find(o=>typeof o=="object"));return e.map(r)}function Et(t,e){let r=R(t,e?.in);return r.setHours(0,0,0,0),r}function Ch(t,e,r){let[o,n]=Th(r?.in,t,e),s=Et(o),i=Et(n),a=+s-io(s),l=+i-io(i);return Math.round((a-l)/vh)}function Eh(t,e){let r=ra(t,e),o=H(e?.in||t,0);return o.setFullYear(r,0,4),o.setHours(0,0,0,0),Ct(o)}function Ph(t,e,r){let o=R(t,r?.in);return o.setTime(o.getTime()+e*Zi),o}function Oh(t){return t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"}function ao(t){return!(!Oh(t)&&typeof t!="number"||isNaN(+R(t)))}function Ah(t,e){return+R(t)-+R(e)}function Rh(t,e){let r=R(t,e?.in);return r.setFullYear(r.getFullYear(),0,1),r.setHours(0,0,0,0),r}var _0={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},Ih=(t,e,r)=>{let o,n=_0[t];return typeof n=="string"?o=n:e===1?o=n.one:o=n.other.replace("{{count}}",e.toString()),r?.addSuffix?r.comparison&&r.comparison>0?"in "+o:o+" ago":o};function oa(t){return(e={})=>{let r=e.width?String(e.width):t.defaultWidth;return t.formats[r]||t.formats[t.defaultWidth]}}var w0={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},v0={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},S0={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},Dh={date:oa({formats:w0,defaultWidth:"full"}),time:oa({formats:v0,defaultWidth:"full"}),dateTime:oa({formats:S0,defaultWidth:"full"})};var x0={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Lh=(t,e,r,o)=>x0[t];function Xo(t){return(e,r)=>{let o=r?.context?String(r.context):"standalone",n;if(o==="formatting"&&t.formattingValues){let i=t.defaultFormattingWidth||t.defaultWidth,a=r?.width?String(r.width):i;n=t.formattingValues[a]||t.formattingValues[i]}else{let i=t.defaultWidth,a=r?.width?String(r.width):t.defaultWidth;n=t.values[a]||t.values[i]}let s=t.argumentCallback?t.argumentCallback(e):e;return n[s]}}var k0={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},T0={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},C0={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},E0={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},P0={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},O0={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},A0=(t,e)=>{let r=Number(t),o=r%100;if(o>20||o<10)switch(o%10){case 1:return r+"st";case 2:return r+"nd";case 3:return r+"rd"}return r+"th"},Nh={ordinalNumber:A0,era:Xo({values:k0,defaultWidth:"wide"}),quarter:Xo({values:T0,defaultWidth:"wide",argumentCallback:t=>t-1}),month:Xo({values:C0,defaultWidth:"wide"}),day:Xo({values:E0,defaultWidth:"wide"}),dayPeriod:Xo({values:P0,defaultWidth:"wide",formattingValues:O0,defaultFormattingWidth:"wide"})};function Qo(t){return(e,r={})=>{let o=r.width,n=o&&t.matchPatterns[o]||t.matchPatterns[t.defaultMatchWidth],s=e.match(n);if(!s)return null;let i=s[0],a=o&&t.parsePatterns[o]||t.parsePatterns[t.defaultParseWidth],l=Array.isArray(a)?I0(a,d=>d.test(i)):R0(a,d=>d.test(i)),u;u=t.valueCallback?t.valueCallback(l):l,u=r.valueCallback?r.valueCallback(u):u;let c=e.slice(i.length);return{value:u,rest:c}}}function R0(t,e){for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&e(t[r]))return r}function I0(t,e){for(let r=0;r<t.length;r++)if(e(t[r]))return r}function jh(t){return(e,r={})=>{let o=e.match(t.matchPattern);if(!o)return null;let n=o[0],s=e.match(t.parsePattern);if(!s)return null;let i=t.valueCallback?t.valueCallback(s[0]):s[0];i=r.valueCallback?r.valueCallback(i):i;let a=e.slice(n.length);return{value:i,rest:a}}}var D0=/^(\d+)(th|st|nd|rd)?/i,L0=/\d+/i,N0={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},j0={any:[/^b/i,/^(a|c)/i]},M0={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},U0={any:[/1/i,/2/i,/3/i,/4/i]},F0={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},$0={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},B0={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},q0={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},V0={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},W0={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},Mh={ordinalNumber:jh({matchPattern:D0,parsePattern:L0,valueCallback:t=>parseInt(t,10)}),era:Qo({matchPatterns:N0,defaultMatchWidth:"wide",parsePatterns:j0,defaultParseWidth:"any"}),quarter:Qo({matchPatterns:M0,defaultMatchWidth:"wide",parsePatterns:U0,defaultParseWidth:"any",valueCallback:t=>t+1}),month:Qo({matchPatterns:F0,defaultMatchWidth:"wide",parsePatterns:$0,defaultParseWidth:"any"}),day:Qo({matchPatterns:B0,defaultMatchWidth:"wide",parsePatterns:q0,defaultParseWidth:"any"}),dayPeriod:Qo({matchPatterns:V0,defaultMatchWidth:"any",parsePatterns:W0,defaultParseWidth:"any"})};var ws={code:"en-US",formatDistance:Ih,formatLong:Dh,formatRelative:Lh,localize:Nh,match:Mh,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Uh(t,e){let r=R(t,e?.in);return Ch(r,Rh(r))+1}function na(t,e){let r=R(t,e?.in),o=+Ct(r)-+Eh(r);return Math.round(o/Qi)+1}function Zo(t,e){let r=R(t,e?.in),o=r.getFullYear(),n=dt(),s=e?.firstWeekContainsDate??e?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,i=H(e?.in||t,0);i.setFullYear(o+1,0,s),i.setHours(0,0,0,0);let a=ze(i,e),l=H(e?.in||t,0);l.setFullYear(o,0,s),l.setHours(0,0,0,0);let u=ze(l,e);return+r>=+a?o+1:+r>=+u?o:o-1}function Fh(t,e){let r=dt(),o=e?.firstWeekContainsDate??e?.locale?.options?.firstWeekContainsDate??r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,n=Zo(t,e),s=H(e?.in||t,0);return s.setFullYear(n,0,o),s.setHours(0,0,0,0),ze(s,e)}function sa(t,e){let r=R(t,e?.in),o=+ze(r,e)-+Fh(r,e);return Math.round(o/Qi)+1}function X(t,e){let r=t<0?"-":"",o=Math.abs(t).toString().padStart(e,"0");return r+o}var lr={y(t,e){let r=t.getFullYear(),o=r>0?r:1-r;return X(e==="yy"?o%100:o,e.length)},M(t,e){let r=t.getMonth();return e==="M"?String(r+1):X(r+1,2)},d(t,e){return X(t.getDate(),e.length)},a(t,e){let r=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return r.toUpperCase();case"aaa":return r;case"aaaaa":return r[0];default:return r==="am"?"a.m.":"p.m."}},h(t,e){return X(t.getHours()%12||12,e.length)},H(t,e){return X(t.getHours(),e.length)},m(t,e){return X(t.getMinutes(),e.length)},s(t,e){return X(t.getSeconds(),e.length)},S(t,e){let r=e.length,o=t.getMilliseconds(),n=Math.trunc(o*Math.pow(10,r-3));return X(n,e.length)}};var en={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},zu={G:function(t,e,r){let o=t.getFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return r.era(o,{width:"abbreviated"});case"GGGGG":return r.era(o,{width:"narrow"});default:return r.era(o,{width:"wide"})}},y:function(t,e,r){if(e==="yo"){let o=t.getFullYear(),n=o>0?o:1-o;return r.ordinalNumber(n,{unit:"year"})}return lr.y(t,e)},Y:function(t,e,r,o){let n=Zo(t,o),s=n>0?n:1-n;if(e==="YY"){let i=s%100;return X(i,2)}return e==="Yo"?r.ordinalNumber(s,{unit:"year"}):X(s,e.length)},R:function(t,e){let r=ra(t);return X(r,e.length)},u:function(t,e){let r=t.getFullYear();return X(r,e.length)},Q:function(t,e,r){let o=Math.ceil((t.getMonth()+1)/3);switch(e){case"Q":return String(o);case"QQ":return X(o,2);case"Qo":return r.ordinalNumber(o,{unit:"quarter"});case"QQQ":return r.quarter(o,{width:"abbreviated",context:"formatting"});case"QQQQQ":return r.quarter(o,{width:"narrow",context:"formatting"});default:return r.quarter(o,{width:"wide",context:"formatting"})}},q:function(t,e,r){let o=Math.ceil((t.getMonth()+1)/3);switch(e){case"q":return String(o);case"qq":return X(o,2);case"qo":return r.ordinalNumber(o,{unit:"quarter"});case"qqq":return r.quarter(o,{width:"abbreviated",context:"standalone"});case"qqqqq":return r.quarter(o,{width:"narrow",context:"standalone"});default:return r.quarter(o,{width:"wide",context:"standalone"})}},M:function(t,e,r){let o=t.getMonth();switch(e){case"M":case"MM":return lr.M(t,e);case"Mo":return r.ordinalNumber(o+1,{unit:"month"});case"MMM":return r.month(o,{width:"abbreviated",context:"formatting"});case"MMMMM":return r.month(o,{width:"narrow",context:"formatting"});default:return r.month(o,{width:"wide",context:"formatting"})}},L:function(t,e,r){let o=t.getMonth();switch(e){case"L":return String(o+1);case"LL":return X(o+1,2);case"Lo":return r.ordinalNumber(o+1,{unit:"month"});case"LLL":return r.month(o,{width:"abbreviated",context:"standalone"});case"LLLLL":return r.month(o,{width:"narrow",context:"standalone"});default:return r.month(o,{width:"wide",context:"standalone"})}},w:function(t,e,r,o){let n=sa(t,o);return e==="wo"?r.ordinalNumber(n,{unit:"week"}):X(n,e.length)},I:function(t,e,r){let o=na(t);return e==="Io"?r.ordinalNumber(o,{unit:"week"}):X(o,e.length)},d:function(t,e,r){return e==="do"?r.ordinalNumber(t.getDate(),{unit:"date"}):lr.d(t,e)},D:function(t,e,r){let o=Uh(t);return e==="Do"?r.ordinalNumber(o,{unit:"dayOfYear"}):X(o,e.length)},E:function(t,e,r){let o=t.getDay();switch(e){case"E":case"EE":case"EEE":return r.day(o,{width:"abbreviated",context:"formatting"});case"EEEEE":return r.day(o,{width:"narrow",context:"formatting"});case"EEEEEE":return r.day(o,{width:"short",context:"formatting"});default:return r.day(o,{width:"wide",context:"formatting"})}},e:function(t,e,r,o){let n=t.getDay(),s=(n-o.weekStartsOn+8)%7||7;switch(e){case"e":return String(s);case"ee":return X(s,2);case"eo":return r.ordinalNumber(s,{unit:"day"});case"eee":return r.day(n,{width:"abbreviated",context:"formatting"});case"eeeee":return r.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return r.day(n,{width:"short",context:"formatting"});default:return r.day(n,{width:"wide",context:"formatting"})}},c:function(t,e,r,o){let n=t.getDay(),s=(n-o.weekStartsOn+8)%7||7;switch(e){case"c":return String(s);case"cc":return X(s,e.length);case"co":return r.ordinalNumber(s,{unit:"day"});case"ccc":return r.day(n,{width:"abbreviated",context:"standalone"});case"ccccc":return r.day(n,{width:"narrow",context:"standalone"});case"cccccc":return r.day(n,{width:"short",context:"standalone"});default:return r.day(n,{width:"wide",context:"standalone"})}},i:function(t,e,r){let o=t.getDay(),n=o===0?7:o;switch(e){case"i":return String(n);case"ii":return X(n,e.length);case"io":return r.ordinalNumber(n,{unit:"day"});case"iii":return r.day(o,{width:"abbreviated",context:"formatting"});case"iiiii":return r.day(o,{width:"narrow",context:"formatting"});case"iiiiii":return r.day(o,{width:"short",context:"formatting"});default:return r.day(o,{width:"wide",context:"formatting"})}},a:function(t,e,r){let n=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"aaa":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return r.dayPeriod(n,{width:"narrow",context:"formatting"});default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},b:function(t,e,r){let o=t.getHours(),n;switch(o===12?n=en.noon:o===0?n=en.midnight:n=o/12>=1?"pm":"am",e){case"b":case"bb":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"bbb":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return r.dayPeriod(n,{width:"narrow",context:"formatting"});default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},B:function(t,e,r){let o=t.getHours(),n;switch(o>=17?n=en.evening:o>=12?n=en.afternoon:o>=4?n=en.morning:n=en.night,e){case"B":case"BB":case"BBB":return r.dayPeriod(n,{width:"abbreviated",context:"formatting"});case"BBBBB":return r.dayPeriod(n,{width:"narrow",context:"formatting"});default:return r.dayPeriod(n,{width:"wide",context:"formatting"})}},h:function(t,e,r){if(e==="ho"){let o=t.getHours()%12;return o===0&&(o=12),r.ordinalNumber(o,{unit:"hour"})}return lr.h(t,e)},H:function(t,e,r){return e==="Ho"?r.ordinalNumber(t.getHours(),{unit:"hour"}):lr.H(t,e)},K:function(t,e,r){let o=t.getHours()%12;return e==="Ko"?r.ordinalNumber(o,{unit:"hour"}):X(o,e.length)},k:function(t,e,r){let o=t.getHours();return o===0&&(o=24),e==="ko"?r.ordinalNumber(o,{unit:"hour"}):X(o,e.length)},m:function(t,e,r){return e==="mo"?r.ordinalNumber(t.getMinutes(),{unit:"minute"}):lr.m(t,e)},s:function(t,e,r){return e==="so"?r.ordinalNumber(t.getSeconds(),{unit:"second"}):lr.s(t,e)},S:function(t,e){return lr.S(t,e)},X:function(t,e,r){let o=t.getTimezoneOffset();if(o===0)return"Z";switch(e){case"X":return Bh(o);case"XXXX":case"XX":return lo(o);default:return lo(o,":")}},x:function(t,e,r){let o=t.getTimezoneOffset();switch(e){case"x":return Bh(o);case"xxxx":case"xx":return lo(o);default:return lo(o,":")}},O:function(t,e,r){let o=t.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+$h(o,":");default:return"GMT"+lo(o,":")}},z:function(t,e,r){let o=t.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+$h(o,":");default:return"GMT"+lo(o,":")}},t:function(t,e,r){let o=Math.trunc(+t/1e3);return X(o,e.length)},T:function(t,e,r){return X(+t,e.length)}};function $h(t,e=""){let r=t>0?"-":"+",o=Math.abs(t),n=Math.trunc(o/60),s=o%60;return s===0?r+String(n):r+String(n)+e+X(s,2)}function Bh(t,e){return t%60===0?(t>0?"-":"+")+X(Math.abs(t)/60,2):lo(t,e)}function lo(t,e=""){let r=t>0?"-":"+",o=Math.abs(t),n=X(Math.trunc(o/60),2),s=X(o%60,2);return r+n+e+s}var qh=(t,e)=>{switch(t){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});default:return e.date({width:"full"})}},Vh=(t,e)=>{switch(t){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});default:return e.time({width:"full"})}},H0=(t,e)=>{let r=t.match(/(P+)(p+)?/)||[],o=r[1],n=r[2];if(!n)return qh(t,e);let s;switch(o){case"P":s=e.dateTime({width:"short"});break;case"PP":s=e.dateTime({width:"medium"});break;case"PPP":s=e.dateTime({width:"long"});break;default:s=e.dateTime({width:"full"});break}return s.replace("{{date}}",qh(o,e)).replace("{{time}}",Vh(n,e))},vs={p:Vh,P:H0};var z0=/^D+$/,G0=/^Y+$/,K0=["D","DD","YY","YYYY"];function ia(t){return z0.test(t)}function aa(t){return G0.test(t)}function Ss(t,e,r){let o=J0(t,e,r);if(console.warn(o),K0.includes(t))throw new RangeError(o)}function J0(t,e,r){let o=t[0]==="Y"?"years":"days of the month";return`Use \`${t.toLowerCase()}\` instead of \`${t}\` (in \`${e}\`) for formatting ${o} to the input \`${r}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}var Y0=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,X0=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Q0=/^'([^]*?)'?$/,Z0=/''/g,eS=/[a-zA-Z]/;function Be(t,e,r){let o=dt(),n=r?.locale??o.locale??ws,s=r?.firstWeekContainsDate??r?.locale?.options?.firstWeekContainsDate??o.firstWeekContainsDate??o.locale?.options?.firstWeekContainsDate??1,i=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??o.weekStartsOn??o.locale?.options?.weekStartsOn??0,a=R(t,r?.in);if(!ao(a))throw new RangeError("Invalid time value");let l=e.match(X0).map(c=>{let d=c[0];if(d==="p"||d==="P"){let f=vs[d];return f(c,n.formatLong)}return c}).join("").match(Y0).map(c=>{if(c==="''")return{isToken:!1,value:"'"};let d=c[0];if(d==="'")return{isToken:!1,value:tS(c)};if(zu[d])return{isToken:!0,value:c};if(d.match(eS))throw new RangeError("Format string contains an unescaped latin alphabet character `"+d+"`");return{isToken:!1,value:c}});n.localize.preprocessor&&(l=n.localize.preprocessor(a,l));let u={firstWeekContainsDate:s,weekStartsOn:i,locale:n};return l.map(c=>{if(!c.isToken)return c.value;let d=c.value;(!r?.useAdditionalWeekYearTokens&&aa(d)||!r?.useAdditionalDayOfYearTokens&&ia(d))&&Ss(d,e,String(t));let f=zu[d[0]];return f(a,d,n.localize,u)}).join("")}function tS(t){let e=t.match(Q0);return e?e[1].replace(Z0,"'"):t}function la(t,e){return R(t,e?.in).getDay()}function ua(){return Object.assign({},dt())}function Wh(t,e){let r=R(t,e?.in).getDay();return r===0?7:r}function $t(t,e){return+R(t)>+R(e)}function Ge(t,e){return+R(t)<+R(e)}function Hh(t,e){let r=rS(e)?new e(0):H(e,0);return r.setFullYear(t.getFullYear(),t.getMonth(),t.getDate()),r.setHours(t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()),r}function rS(t){return typeof t=="function"&&t.prototype?.constructor===t}var oS=10,ca=class{subPriority=0;validate(e,r){return!0}},da=class extends ca{constructor(e,r,o,n,s){super(),this.value=e,this.validateValue=r,this.setValue=o,this.priority=n,s&&(this.subPriority=s)}validate(e,r){return this.validateValue(e,this.value,r)}set(e,r,o){return this.setValue(e,r,this.value,o)}},fa=class extends ca{priority=oS;subPriority=-1;constructor(e,r){super(),this.context=e||(o=>H(r,o))}set(e,r){return r.timestampIsSet?e:H(e,Hh(e,this.context))}};var C=class{run(e,r,o,n){let s=this.parse(e,r,o,n);return s?{setter:new da(s.value,this.validate,this.set,this.priority,this.subPriority),rest:s.rest}:null}validate(e,r,o){return!0}};var ma=class extends C{priority=140;parse(e,r,o){switch(r){case"G":case"GG":case"GGG":return o.era(e,{width:"abbreviated"})||o.era(e,{width:"narrow"});case"GGGGG":return o.era(e,{width:"narrow"});default:return o.era(e,{width:"wide"})||o.era(e,{width:"abbreviated"})||o.era(e,{width:"narrow"})}}set(e,r,o){return r.era=o,e.setFullYear(o,0,1),e.setHours(0,0,0,0),e}incompatibleTokens=["R","u","t","T"]};var G={month:/^(1[0-2]|0?\d)/,date:/^(3[0-1]|[0-2]?\d)/,dayOfYear:/^(36[0-6]|3[0-5]\d|[0-2]?\d?\d)/,week:/^(5[0-3]|[0-4]?\d)/,hour23h:/^(2[0-3]|[0-1]?\d)/,hour24h:/^(2[0-4]|[0-1]?\d)/,hour11h:/^(1[0-1]|0?\d)/,hour12h:/^(1[0-2]|0?\d)/,minute:/^[0-5]?\d/,second:/^[0-5]?\d/,singleDigit:/^\d/,twoDigits:/^\d{1,2}/,threeDigits:/^\d{1,3}/,fourDigits:/^\d{1,4}/,anyDigitsSigned:/^-?\d+/,singleDigitSigned:/^-?\d/,twoDigitsSigned:/^-?\d{1,2}/,threeDigitsSigned:/^-?\d{1,3}/,fourDigitsSigned:/^-?\d{1,4}/},ft={basicOptionalMinutes:/^([+-])(\d{2})(\d{2})?|Z/,basic:/^([+-])(\d{2})(\d{2})|Z/,basicOptionalSeconds:/^([+-])(\d{2})(\d{2})((\d{2}))?|Z/,extended:/^([+-])(\d{2}):(\d{2})|Z/,extendedOptionalSeconds:/^([+-])(\d{2}):(\d{2})(:(\d{2}))?|Z/};function Q(t,e){return t&&{value:e(t.value),rest:t.rest}}function z(t,e){let r=e.match(t);return r?{value:parseInt(r[0],10),rest:e.slice(r[0].length)}:null}function mt(t,e){let r=e.match(t);if(!r)return null;if(r[0]==="Z")return{value:0,rest:e.slice(1)};let o=r[1]==="+"?1:-1,n=r[2]?parseInt(r[2],10):0,s=r[3]?parseInt(r[3],10):0,i=r[5]?parseInt(r[5],10):0;return{value:o*(n*ea+s*Zi+i*Sh),rest:e.slice(r[0].length)}}function ha(t){return z(G.anyDigitsSigned,t)}function F(t,e){switch(t){case 1:return z(G.singleDigit,e);case 2:return z(G.twoDigits,e);case 3:return z(G.threeDigits,e);case 4:return z(G.fourDigits,e);default:return z(new RegExp("^\\d{1,"+t+"}"),e)}}function tn(t,e){switch(t){case 1:return z(G.singleDigitSigned,e);case 2:return z(G.twoDigitsSigned,e);case 3:return z(G.threeDigitsSigned,e);case 4:return z(G.fourDigitsSigned,e);default:return z(new RegExp("^-?\\d{1,"+t+"}"),e)}}function rn(t){switch(t){case"morning":return 4;case"evening":return 17;case"pm":case"noon":case"afternoon":return 12;default:return 0}}function pa(t,e){let r=e>0,o=r?e:1-e,n;if(o<=50)n=t||100;else{let s=o+50,i=Math.trunc(s/100)*100,a=t>=s%100;n=t+i-(a?100:0)}return r?n:1-n}function ga(t){return t%400===0||t%4===0&&t%100!==0}var ya=class extends C{priority=130;incompatibleTokens=["Y","R","u","w","I","i","e","c","t","T"];parse(e,r,o){let n=s=>({year:s,isTwoDigitYear:r==="yy"});switch(r){case"y":return Q(F(4,e),n);case"yo":return Q(o.ordinalNumber(e,{unit:"year"}),n);default:return Q(F(r.length,e),n)}}validate(e,r){return r.isTwoDigitYear||r.year>0}set(e,r,o){let n=e.getFullYear();if(o.isTwoDigitYear){let i=pa(o.year,n);return e.setFullYear(i,0,1),e.setHours(0,0,0,0),e}let s=!("era"in r)||r.era===1?o.year:1-o.year;return e.setFullYear(s,0,1),e.setHours(0,0,0,0),e}};var ba=class extends C{priority=130;parse(e,r,o){let n=s=>({year:s,isTwoDigitYear:r==="YY"});switch(r){case"Y":return Q(F(4,e),n);case"Yo":return Q(o.ordinalNumber(e,{unit:"year"}),n);default:return Q(F(r.length,e),n)}}validate(e,r){return r.isTwoDigitYear||r.year>0}set(e,r,o,n){let s=Zo(e,n);if(o.isTwoDigitYear){let a=pa(o.year,s);return e.setFullYear(a,0,n.firstWeekContainsDate),e.setHours(0,0,0,0),ze(e,n)}let i=!("era"in r)||r.era===1?o.year:1-o.year;return e.setFullYear(i,0,n.firstWeekContainsDate),e.setHours(0,0,0,0),ze(e,n)}incompatibleTokens=["y","R","u","Q","q","M","L","I","d","D","i","t","T"]};var _a=class extends C{priority=130;parse(e,r){return r==="R"?tn(4,e):tn(r.length,e)}set(e,r,o){let n=H(e,0);return n.setFullYear(o,0,4),n.setHours(0,0,0,0),Ct(n)}incompatibleTokens=["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"]};var wa=class extends C{priority=130;parse(e,r){return r==="u"?tn(4,e):tn(r.length,e)}set(e,r,o){return e.setFullYear(o,0,1),e.setHours(0,0,0,0),e}incompatibleTokens=["G","y","Y","R","w","I","i","e","c","t","T"]};var va=class extends C{priority=120;parse(e,r,o){switch(r){case"Q":case"QQ":return F(r.length,e);case"Qo":return o.ordinalNumber(e,{unit:"quarter"});case"QQQ":return o.quarter(e,{width:"abbreviated",context:"formatting"})||o.quarter(e,{width:"narrow",context:"formatting"});case"QQQQQ":return o.quarter(e,{width:"narrow",context:"formatting"});default:return o.quarter(e,{width:"wide",context:"formatting"})||o.quarter(e,{width:"abbreviated",context:"formatting"})||o.quarter(e,{width:"narrow",context:"formatting"})}}validate(e,r){return r>=1&&r<=4}set(e,r,o){return e.setMonth((o-1)*3,1),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"]};var Sa=class extends C{priority=120;parse(e,r,o){switch(r){case"q":case"qq":return F(r.length,e);case"qo":return o.ordinalNumber(e,{unit:"quarter"});case"qqq":return o.quarter(e,{width:"abbreviated",context:"standalone"})||o.quarter(e,{width:"narrow",context:"standalone"});case"qqqqq":return o.quarter(e,{width:"narrow",context:"standalone"});default:return o.quarter(e,{width:"wide",context:"standalone"})||o.quarter(e,{width:"abbreviated",context:"standalone"})||o.quarter(e,{width:"narrow",context:"standalone"})}}validate(e,r){return r>=1&&r<=4}set(e,r,o){return e.setMonth((o-1)*3,1),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"]};var xa=class extends C{incompatibleTokens=["Y","R","q","Q","L","w","I","D","i","e","c","t","T"];priority=110;parse(e,r,o){let n=s=>s-1;switch(r){case"M":return Q(z(G.month,e),n);case"MM":return Q(F(2,e),n);case"Mo":return Q(o.ordinalNumber(e,{unit:"month"}),n);case"MMM":return o.month(e,{width:"abbreviated",context:"formatting"})||o.month(e,{width:"narrow",context:"formatting"});case"MMMMM":return o.month(e,{width:"narrow",context:"formatting"});default:return o.month(e,{width:"wide",context:"formatting"})||o.month(e,{width:"abbreviated",context:"formatting"})||o.month(e,{width:"narrow",context:"formatting"})}}validate(e,r){return r>=0&&r<=11}set(e,r,o){return e.setMonth(o,1),e.setHours(0,0,0,0),e}};var ka=class extends C{priority=110;parse(e,r,o){let n=s=>s-1;switch(r){case"L":return Q(z(G.month,e),n);case"LL":return Q(F(2,e),n);case"Lo":return Q(o.ordinalNumber(e,{unit:"month"}),n);case"LLL":return o.month(e,{width:"abbreviated",context:"standalone"})||o.month(e,{width:"narrow",context:"standalone"});case"LLLLL":return o.month(e,{width:"narrow",context:"standalone"});default:return o.month(e,{width:"wide",context:"standalone"})||o.month(e,{width:"abbreviated",context:"standalone"})||o.month(e,{width:"narrow",context:"standalone"})}}validate(e,r){return r>=0&&r<=11}set(e,r,o){return e.setMonth(o,1),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","M","w","I","D","i","e","c","t","T"]};function zh(t,e,r){let o=R(t,r?.in),n=sa(o,r)-e;return o.setDate(o.getDate()-n*7),R(o,r?.in)}var Ta=class extends C{priority=100;parse(e,r,o){switch(r){case"w":return z(G.week,e);case"wo":return o.ordinalNumber(e,{unit:"week"});default:return F(r.length,e)}}validate(e,r){return r>=1&&r<=53}set(e,r,o,n){return ze(zh(e,o,n),n)}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","i","t","T"]};function Gh(t,e,r){let o=R(t,r?.in),n=na(o,r)-e;return o.setDate(o.getDate()-n*7),o}var Ca=class extends C{priority=100;parse(e,r,o){switch(r){case"I":return z(G.week,e);case"Io":return o.ordinalNumber(e,{unit:"week"});default:return F(r.length,e)}}validate(e,r){return r>=1&&r<=53}set(e,r,o){return Ct(Gh(e,o))}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"]};var nS=[31,28,31,30,31,30,31,31,30,31,30,31],sS=[31,29,31,30,31,30,31,31,30,31,30,31],Ea=class extends C{priority=90;subPriority=1;parse(e,r,o){switch(r){case"d":return z(G.date,e);case"do":return o.ordinalNumber(e,{unit:"date"});default:return F(r.length,e)}}validate(e,r){let o=e.getFullYear(),n=ga(o),s=e.getMonth();return n?r>=1&&r<=sS[s]:r>=1&&r<=nS[s]}set(e,r,o){return e.setDate(o),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","w","I","D","i","e","c","t","T"]};var Pa=class extends C{priority=90;subpriority=1;parse(e,r,o){switch(r){case"D":case"DD":return z(G.dayOfYear,e);case"Do":return o.ordinalNumber(e,{unit:"date"});default:return F(r.length,e)}}validate(e,r){let o=e.getFullYear();return ga(o)?r>=1&&r<=366:r>=1&&r<=365}set(e,r,o){return e.setMonth(0,o),e.setHours(0,0,0,0),e}incompatibleTokens=["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"]};function on(t,e,r){let o=dt(),n=r?.weekStartsOn??r?.locale?.options?.weekStartsOn??o.weekStartsOn??o.locale?.options?.weekStartsOn??0,s=R(t,r?.in),i=s.getDay(),l=(e%7+7)%7,u=7-n,c=e<0||e>6?e-(i+u)%7:(l+u)%7-(i+u)%7;return ta(s,c,r)}var Oa=class extends C{priority=90;parse(e,r,o){switch(r){case"E":case"EE":case"EEE":return o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"});case"EEEEE":return o.day(e,{width:"narrow",context:"formatting"});case"EEEEEE":return o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"});default:return o.day(e,{width:"wide",context:"formatting"})||o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"})}}validate(e,r){return r>=0&&r<=6}set(e,r,o,n){return e=on(e,o,n),e.setHours(0,0,0,0),e}incompatibleTokens=["D","i","e","c","t","T"]};var Aa=class extends C{priority=90;parse(e,r,o,n){let s=i=>{let a=Math.floor((i-1)/7)*7;return(i+n.weekStartsOn+6)%7+a};switch(r){case"e":case"ee":return Q(F(r.length,e),s);case"eo":return Q(o.ordinalNumber(e,{unit:"day"}),s);case"eee":return o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"});case"eeeee":return o.day(e,{width:"narrow",context:"formatting"});case"eeeeee":return o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"});default:return o.day(e,{width:"wide",context:"formatting"})||o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"})}}validate(e,r){return r>=0&&r<=6}set(e,r,o,n){return e=on(e,o,n),e.setHours(0,0,0,0),e}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"]};var Ra=class extends C{priority=90;parse(e,r,o,n){let s=i=>{let a=Math.floor((i-1)/7)*7;return(i+n.weekStartsOn+6)%7+a};switch(r){case"c":case"cc":return Q(F(r.length,e),s);case"co":return Q(o.ordinalNumber(e,{unit:"day"}),s);case"ccc":return o.day(e,{width:"abbreviated",context:"standalone"})||o.day(e,{width:"short",context:"standalone"})||o.day(e,{width:"narrow",context:"standalone"});case"ccccc":return o.day(e,{width:"narrow",context:"standalone"});case"cccccc":return o.day(e,{width:"short",context:"standalone"})||o.day(e,{width:"narrow",context:"standalone"});default:return o.day(e,{width:"wide",context:"standalone"})||o.day(e,{width:"abbreviated",context:"standalone"})||o.day(e,{width:"short",context:"standalone"})||o.day(e,{width:"narrow",context:"standalone"})}}validate(e,r){return r>=0&&r<=6}set(e,r,o,n){return e=on(e,o,n),e.setHours(0,0,0,0),e}incompatibleTokens=["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"]};function Kh(t,e,r){let o=R(t,r?.in),n=Wh(o,r),s=e-n;return ta(o,s,r)}var Ia=class extends C{priority=90;parse(e,r,o){let n=s=>s===0?7:s;switch(r){case"i":case"ii":return F(r.length,e);case"io":return o.ordinalNumber(e,{unit:"day"});case"iii":return Q(o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"}),n);case"iiiii":return Q(o.day(e,{width:"narrow",context:"formatting"}),n);case"iiiiii":return Q(o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"}),n);default:return Q(o.day(e,{width:"wide",context:"formatting"})||o.day(e,{width:"abbreviated",context:"formatting"})||o.day(e,{width:"short",context:"formatting"})||o.day(e,{width:"narrow",context:"formatting"}),n)}}validate(e,r){return r>=1&&r<=7}set(e,r,o){return e=Kh(e,o),e.setHours(0,0,0,0),e}incompatibleTokens=["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"]};var Da=class extends C{priority=80;parse(e,r,o){switch(r){case"a":case"aa":case"aaa":return o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"});case"aaaaa":return o.dayPeriod(e,{width:"narrow",context:"formatting"});default:return o.dayPeriod(e,{width:"wide",context:"formatting"})||o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,r,o){return e.setHours(rn(o),0,0,0),e}incompatibleTokens=["b","B","H","k","t","T"]};var La=class extends C{priority=80;parse(e,r,o){switch(r){case"b":case"bb":case"bbb":return o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"});case"bbbbb":return o.dayPeriod(e,{width:"narrow",context:"formatting"});default:return o.dayPeriod(e,{width:"wide",context:"formatting"})||o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,r,o){return e.setHours(rn(o),0,0,0),e}incompatibleTokens=["a","B","H","k","t","T"]};var Na=class extends C{priority=80;parse(e,r,o){switch(r){case"B":case"BB":case"BBB":return o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"});case"BBBBB":return o.dayPeriod(e,{width:"narrow",context:"formatting"});default:return o.dayPeriod(e,{width:"wide",context:"formatting"})||o.dayPeriod(e,{width:"abbreviated",context:"formatting"})||o.dayPeriod(e,{width:"narrow",context:"formatting"})}}set(e,r,o){return e.setHours(rn(o),0,0,0),e}incompatibleTokens=["a","b","t","T"]};var ja=class extends C{priority=70;parse(e,r,o){switch(r){case"h":return z(G.hour12h,e);case"ho":return o.ordinalNumber(e,{unit:"hour"});default:return F(r.length,e)}}validate(e,r){return r>=1&&r<=12}set(e,r,o){let n=e.getHours()>=12;return n&&o<12?e.setHours(o+12,0,0,0):!n&&o===12?e.setHours(0,0,0,0):e.setHours(o,0,0,0),e}incompatibleTokens=["H","K","k","t","T"]};var Ma=class extends C{priority=70;parse(e,r,o){switch(r){case"H":return z(G.hour23h,e);case"Ho":return o.ordinalNumber(e,{unit:"hour"});default:return F(r.length,e)}}validate(e,r){return r>=0&&r<=23}set(e,r,o){return e.setHours(o,0,0,0),e}incompatibleTokens=["a","b","h","K","k","t","T"]};var Ua=class extends C{priority=70;parse(e,r,o){switch(r){case"K":return z(G.hour11h,e);case"Ko":return o.ordinalNumber(e,{unit:"hour"});default:return F(r.length,e)}}validate(e,r){return r>=0&&r<=11}set(e,r,o){return e.getHours()>=12&&o<12?e.setHours(o+12,0,0,0):e.setHours(o,0,0,0),e}incompatibleTokens=["h","H","k","t","T"]};var Fa=class extends C{priority=70;parse(e,r,o){switch(r){case"k":return z(G.hour24h,e);case"ko":return o.ordinalNumber(e,{unit:"hour"});default:return F(r.length,e)}}validate(e,r){return r>=1&&r<=24}set(e,r,o){let n=o<=24?o%24:o;return e.setHours(n,0,0,0),e}incompatibleTokens=["a","b","h","H","K","t","T"]};var $a=class extends C{priority=60;parse(e,r,o){switch(r){case"m":return z(G.minute,e);case"mo":return o.ordinalNumber(e,{unit:"minute"});default:return F(r.length,e)}}validate(e,r){return r>=0&&r<=59}set(e,r,o){return e.setMinutes(o,0,0),e}incompatibleTokens=["t","T"]};var Ba=class extends C{priority=50;parse(e,r,o){switch(r){case"s":return z(G.second,e);case"so":return o.ordinalNumber(e,{unit:"second"});default:return F(r.length,e)}}validate(e,r){return r>=0&&r<=59}set(e,r,o){return e.setSeconds(o,0),e}incompatibleTokens=["t","T"]};var qa=class extends C{priority=30;parse(e,r){let o=n=>Math.trunc(n*Math.pow(10,-r.length+3));return Q(F(r.length,e),o)}set(e,r,o){return e.setMilliseconds(o),e}incompatibleTokens=["t","T"]};var Va=class extends C{priority=10;parse(e,r){switch(r){case"X":return mt(ft.basicOptionalMinutes,e);case"XX":return mt(ft.basic,e);case"XXXX":return mt(ft.basicOptionalSeconds,e);case"XXXXX":return mt(ft.extendedOptionalSeconds,e);default:return mt(ft.extended,e)}}set(e,r,o){return r.timestampIsSet?e:H(e,e.getTime()-io(e)-o)}incompatibleTokens=["t","T","x"]};var Wa=class extends C{priority=10;parse(e,r){switch(r){case"x":return mt(ft.basicOptionalMinutes,e);case"xx":return mt(ft.basic,e);case"xxxx":return mt(ft.basicOptionalSeconds,e);case"xxxxx":return mt(ft.extendedOptionalSeconds,e);default:return mt(ft.extended,e)}}set(e,r,o){return r.timestampIsSet?e:H(e,e.getTime()-io(e)-o)}incompatibleTokens=["t","T","X"]};var Ha=class extends C{priority=40;parse(e){return ha(e)}set(e,r,o){return[H(e,o*1e3),{timestampIsSet:!0}]}incompatibleTokens="*"};var za=class extends C{priority=20;parse(e){return ha(e)}set(e,r,o){return[H(e,o),{timestampIsSet:!0}]}incompatibleTokens="*"};var Jh={G:new ma,y:new ya,Y:new ba,R:new _a,u:new wa,Q:new va,q:new Sa,M:new xa,L:new ka,w:new Ta,I:new Ca,d:new Ea,D:new Pa,E:new Oa,e:new Aa,c:new Ra,i:new Ia,a:new Da,b:new La,B:new Na,h:new ja,H:new Ma,K:new Ua,k:new Fa,m:new $a,s:new Ba,S:new qa,X:new Va,x:new Wa,t:new Ha,T:new za};var iS=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,aS=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,lS=/^'([^]*?)'?$/,uS=/''/g,cS=/\S/,dS=/[a-zA-Z]/;function Qe(t,e,r,o){let n=()=>H(o?.in||r,NaN),s=ua(),i=o?.locale??s.locale??ws,a=o?.firstWeekContainsDate??o?.locale?.options?.firstWeekContainsDate??s.firstWeekContainsDate??s.locale?.options?.firstWeekContainsDate??1,l=o?.weekStartsOn??o?.locale?.options?.weekStartsOn??s.weekStartsOn??s.locale?.options?.weekStartsOn??0;if(!e)return t?n():R(r,o?.in);let u={firstWeekContainsDate:a,weekStartsOn:l,locale:i},c=[new fa(o?.in,r)],d=e.match(aS).map(y=>{let p=y[0];if(p in vs){let b=vs[p];return b(y,i.formatLong)}return y}).join("").match(iS),f=[];for(let y of d){!o?.useAdditionalWeekYearTokens&&aa(y)&&Ss(y,e,t),!o?.useAdditionalDayOfYearTokens&&ia(y)&&Ss(y,e,t);let p=y[0],b=Jh[p];if(b){let{incompatibleTokens:_}=b;if(Array.isArray(_)){let N=f.find(x=>_.includes(x.token)||x.token===p);if(N)throw new RangeError(`The format string mustn't contain \`${N.fullToken}\` and \`${y}\` at the same time`)}else if(b.incompatibleTokens==="*"&&f.length>0)throw new RangeError(`The format string mustn't contain \`${y}\` and any other token at the same time`);f.push({token:p,fullToken:y});let v=b.run(t,y,i.match,u);if(!v)return n();c.push(v.setter),t=v.rest}else{if(p.match(dS))throw new RangeError("Format string contains an unescaped latin alphabet character `"+p+"`");if(y==="''"?y="'":p==="'"&&(y=fS(y)),t.indexOf(y)===0)t=t.slice(y.length);else return n()}}if(t.length>0&&cS.test(t))return n();let m=c.map(y=>y.priority).sort((y,p)=>p-y).filter((y,p,b)=>b.indexOf(y)===p).map(y=>c.filter(p=>p.priority===y).sort((p,b)=>b.subPriority-p.subPriority)).map(y=>y[0]),h=R(r,o?.in);if(isNaN(+h))return n();let g={};for(let y of m){if(!y.validate(h,u))return n();let p=y.set(h,g,u);Array.isArray(p)?(h=p[0],Object.assign(g,p[1])):h=p}return h}function fS(t){return t.match(lS)[1].replace(uS,"'")}function Yh(t,e){let r=R(t,e?.in);return r.setSeconds(0,0),r}var w=require("zod");var Ga=require("zod"),Xh=["pos","kds","kiosk"],nj=Ga.z.enum(Xh),mS=[...Xh,"restaurant_site","developer_dashboard","zorgo_site","backend"],Qh=Ga.z.enum(mS),hS=["gateway","main_service","agent_service","background_workers"],sj=Ga.z.enum(hS);var Gu=w.z.object({settle_ms:w.z.number().nullable().default(null),interaction_wait_ms:w.z.number().nullable().default(null),capture_ms:w.z.number().nullable().default(null),print_ms:w.z.number().nullable().default(null)}),pS=w.z.object({global:w.z.object({font_family:w.z.enum(["sans-serif","serif","monospace"]).default("sans-serif"),base_font_size:w.z.enum(["small","medium","large"]).default("large"),text_alignment:w.z.enum(["left","center"]).default("left")}).prefault({}),header:w.z.object({show_logo:w.z.boolean().default(!0),show_customer_name:w.z.boolean().default(!0),show_time_info:w.z.boolean().default(!0),show_order_number:w.z.boolean().default(!0),order_number_style:w.z.enum(["bold","normal, small"]).default("bold")}).prefault({}),body:w.z.object({show_modifiers:w.z.boolean().default(!0),show_item_notes:w.z.boolean().default(!0),show_prices:w.z.boolean().default(!0),compact_view:w.z.boolean().default(!0)}).prefault({}),footer:w.z.object({show_tax_breakdown:w.z.boolean().default(!0),show_subtotal:w.z.boolean().default(!0),show_tax:w.z.boolean().default(!0),show_service_fee:w.z.boolean().default(!1),show_tip:w.z.boolean().default(!0),show_suggested_tips:w.z.boolean().default(!1),show_customer_signature:w.z.boolean().default(!1),show_grand_total:w.z.boolean().default(!0),total_line_label:w.z.string().max(24).default("Total"),suggested_tip_percentages:w.z.array(w.z.number().min(0).max(1)).default([.2,.15,.1]),custom_message:w.z.string().max(200).optional().default(""),customer_signature_agreement:w.z.string().max(300).default("I agree to pay the above amount per the cardholder and/or merchant agreement")}).prefault({})}),gS=w.z.enum(["kitchen","merchant","customer"]),aj=w.z.object({id:w.z.uuid().optional(),franchise_id:w.z.number().default(-1),type:gS.default("kitchen"),config:pS.prefault({})}),Zh=w.z.string().regex(/^[1-9][0-9]?\/[1-9][0-9]?$/,'portion must look like "1/2"').refine(t=>{let[e,r]=t.split("/").map(Number);return e<=r},"portion index cannot exceed its divisions"),yS=w.z.enum(["radial","grid","linear","count"]),lj=w.z.object({id:w.z.number(),franchise_id:w.z.number(),geometry:yS,name:w.z.string().min(1),min_divisions:w.z.number().int().min(1).default(1),max_divisions:w.z.number().int().min(1).max(12)}).check(t=>{let e=t.value;e.max_divisions<e.min_divisions&&t.issues.push({code:"custom",input:e,path:["max_divisions"],message:"max_divisions must be >= min_divisions"})}),bS=w.z.object({type:w.z.enum(["item","component"]),id:w.z.number(),quantity:w.z.number(),upcharge:w.z.number(),serving_price:w.z.number().optional(),name:w.z.string(),portion:Zh.nullish()}),_S=w.z.object({rule_id:w.z.number(),group_name:w.z.string(),selections:w.z.array(bS)}),wS=w.z.object({id:w.z.number(),servings_per_item:w.z.number().nullish(),is_base:w.z.boolean().nullish(),price_per_serving:w.z.number().nullish(),franchise_id:w.z.number().nullish(),component_type_id:w.z.number(),serving_weight:w.z.number().nullish(),name:w.z.string().default(""),item_id:w.z.number().nullish(),quantity_servings:w.z.number(),upcharge:w.z.number().nullish(),rule_id:w.z.number().nullish(),portion:Zh.nullish()}),vS=w.z.object({item_id:w.z.number(),name:w.z.string(),quantity:w.z.number(),price:w.z.number(),order_item_id:w.z.number().nullish(),status:w.z.enum(["removed","modified"]).nullish(),category_id:w.z.number().nullish(),category_name:w.z.string().nullish(),is_catering:w.z.boolean().nullish(),per_person:w.z.boolean().nullish(),components:w.z.array(wS).nullish(),selections:w.z.array(_S).nullish(),comments:w.z.string().nullish()}),SS=w.z.object({customer_id:w.z.number().optional(),phone:w.z.string(),first_name:w.z.string(),last_name:w.z.string().nullish(),email:w.z.string().nullish(),allow_marketing:w.z.boolean().default(!1)}),uj=w.z.object({first_name:w.z.string().min(2,"Enter at least 2 characters"),last_name:w.z.string().min(2,"Enter at least 2 characters"),phone:w.z.string().regex(/^\d{10}$/,"Enter a 10-digit phone number"),email:w.z.email().optional().or(w.z.literal("")),allow_marketing:w.z.boolean().optional().default(!1)});var xS=w.z.object({id:w.z.number(),order_id:w.z.number().nullish(),total:w.z.number(),subtotal:w.z.number(),tax:w.z.number(),tip:w.z.number().nullish(),discount:w.z.number().nullish(),service_fee:w.z.number().nullish(),charge_id:w.z.string().nullish(),charge_status:w.z.number().nullish(),created_at:w.z.coerce.date().nullish(),setup_intent_id:w.z.string().nullish(),payment_method_id:w.z.string().nullish(),stripe_customer_id:w.z.string().nullish()}),cj=w.z.object({order_id:w.z.number(),customer:SS,location_id:w.z.number(),method_id:w.z.number().nullish(),type_id:w.z.number().nullish(),time_placed:w.z.coerce.date(),time_requested:w.z.coerce.date().nullish(),items:w.z.array(vS),order_status:w.z.number().nullish(),order_code:w.z.string().optional(),promo_code:w.z.string().nullish(),charges:w.z.array(xS),subtotal:w.z.number().nullish(),delivery_address:w.z.string().optional()}),kS=w.z.enum(["guest","requested_access","action_required","pending_approval","healthy"]).default("guest"),dj=w.z.object({id:w.z.string(),user_id:w.z.string(),franchise_name:w.z.string(),number_of_locations:w.z.number(),phone:w.z.string(),email:w.z.string(),status:kS,metadata:w.z.record(w.z.string(),w.z.unknown()).default({}),created_at:w.z.coerce.date()}),fj=w.z.object({location_id:w.z.number(),table_number:w.z.number(),label:w.z.string().nullish(),capacity:w.z.number(),shape:w.z.enum(["rect","round"]),reservable:w.z.boolean(),x:w.z.number(),y:w.z.number(),w:w.z.number(),h:w.z.number()}),mj=w.z.object({salesCount:w.z.number().int().nonnegative(),grossRevenue:w.z.number().int().nonnegative(),totalRevenue:w.z.number().int().nonnegative(),totalRefunds:w.z.number().int().nonnegative(),totalDiscounts:w.z.number().int().nonnegative(),totalTips:w.z.number().int().nonnegative(),netRevenue:w.z.number().int()}),hj=w.z.object({requireTableForDineIn:w.z.boolean().default(!1)});var xs=()=>typeof globalThis.crypto?.randomUUID=="function"?globalThis.crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)});function tp(t){let e=(t||"").replace(/\D/g,"");return e.length===11?`+${e}`:`+1${e}`}var xr=typeof globalThis.document<"u"&&globalThis.navigator?.product!=="ReactNative",ep={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};function kr(){let t=globalThis;if(typeof t.window<"u"&&typeof t.window.localStorage<"u")return t.window.localStorage;if(t?.navigator?.product==="ReactNative"||typeof t?.document>"u"&&typeof process>"u")try{return(Vu(),Rl(qu)).default}catch{return ep}return ep}function Ka(t){return`(${t.join(",")})`}var Ja=(n=>(n.Website="website",n.Kiosk="kiosk",n.Pos="pos",n.KitchenDisplay="kitchen_display",n))(Ja||{});var vj={website:"Website",kiosk:"Kiosk",pos:"POS"},Bt=class extends Error{constructor(e){super(e),this.name="VisibilityConditionError"}};function rp(t){let e=t?.date??new Date,r=["su","m","t","w","th","f","sa"],o=e.getHours().toString().padStart(2,"0"),n=e.getMinutes().toString().padStart(2,"0");return{dayOfWeek:r[e.getDay()]??"m",currentTime:`${o}:${n}`,platform:t?.platform??"website"}}function TS(t){if(t.version!==1)throw new Bt("Unsupported visibility condition version.");np(t.root)}function op(t,e){return TS(t),Ku(t.root,e)}function np(t){switch(t.type){case"group":if(t.children.length===0)throw new Bt("Condition groups cannot be empty.");t.children.forEach(np);return;case"constant":return;case"rule":CS(t);return;default:throw new Bt("Unknown visibility condition node.")}}function CS(t){if(t.variable==="dayOfWeek"){if(!Array.isArray(t.value)||t.value.length===0)throw new Bt("Day-of-week rules require at least one day.");return}if(t.variable==="platform"){if((Array.isArray(t.value)?t.value:[t.value]).length===0)throw new Bt("Platform rules require at least one platform.");return}if(t.variable==="currentTime"){if(t.operator==="between"){if(typeof t.value!="object"||t.value==null||!("start"in t.value)||!("end"in t.value))throw new Bt("Between rules require a start and end time.");Xa(t.value.start),Xa(t.value.end);return}if(typeof t.value!="string")throw new Bt("Time rules require a single time value.");Xa(t.value)}}function Ku(t,e){return t.type==="group"?t.operator==="and"?t.children.every(r=>Ku(r,e)):t.children.some(r=>Ku(r,e)):t.type==="constant"?t.value:ES(t,e)}function ES(t,e){switch(t.variable){case"dayOfWeek":{let r=t.value;return t.operator==="is_any_of"?r.includes(e.dayOfWeek):!r.includes(e.dayOfWeek)}case"platform":{let r=Array.isArray(t.value)?t.value:[t.value];switch(t.operator){case"is":return e.platform===r[0];case"is_not":return e.platform!==r[0];case"is_any_of":return r.includes(e.platform)}}case"currentTime":{let r=Ya(e.currentTime);if(t.operator==="between"){let n=t.value,s=Ya(n.start),i=Ya(n.end);return r>=s&&r<=i}let o=Ya(t.value);switch(t.operator){case"before":return r<o;case"after":return r>o;case"on_or_before":return r<=o;case"on_or_after":return r>=o;default:return!1}}default:return!1}}function Ya(t){Xa(t);let e=t.split(":"),r=Number(e[0]),o=Number(e[1]);return r*60+o}function Xa(t){if(!/^\d{2}:\d{2}$/.test(t))throw new Bt(`Invalid time "${t}". Use HH:mm format.`)}var Tr={ascending:!0,nullsFirst:!1},sp=Number.MAX_SAFE_INTEGER;function Xu(t,e){let r=(t.sort_index??sp)-(e.sort_index??sp);return r!==0?r:t.name.localeCompare(e.name)}async function ip(t,e,r=up(),o=!1){let n=await AS(t,e,r.categoryIds);if(n.length===0)return Yu([],[],[],[],[]);let s=await RS(t,e,r.baseItemIds,n);if(s.length===0)return Yu([],[],n,[],[]);let i=await DS(t,s,r.itemIds),a=await LS(t,i,o),l=await NS(t,s,n,i,o);return Yu(i,s,n,a,l)}function ap(t,e){let r=new Map,o=(i,a)=>a.promotion_type_id===1?Math.max(0,Math.floor(i*(1-a.discount_value/100))):a.promotion_type_id===2?Math.max(0,i-a.discount_value):i,n=t.items.map(i=>{let l=e.find(c=>{if(!c.is_active||c.id==null||!c.discount_target_ids?.length||!c.min_purchase_quantity)return!1;let d=c.discount_target_ids;return c.discount_target_type==="category"&&d.includes(i.category_id)||c.discount_target_type==="item"&&d.includes(i.base_item_id)})?.id,u=i.variants.map(c=>{let d,f=c.price;for(let m of e){if(!m.is_active||m.id==null||!m.discount_target_ids?.length||m.min_purchase_amount||m.min_purchase_quantity)continue;let h=m.discount_target_ids;if(!(m.discount_target_type==="category"&&h.includes(i.category_id)||m.discount_target_type==="item"&&h.includes(i.base_item_id)||m.discount_target_type==="item_variant"&&h.includes(c.item_id)))continue;let y=o(c.price,m);y<f&&(d=m,f=y)}return!d||f>=c.price?c:(l??=d.id,d.discount_target_type==="category"&&r.set(i.category_id,d.id),{...c,active_promo_id:d.id,display_price:f})});return{...i,variants:u,active_promo_id:l}}),s=t.categories.map(i=>{let{active_promo_id:a,...l}=i,u=r.get(l.category_id);return u==null?l:{...l,active_promo_id:u}});return{...t,items:n,categories:s}}async function lp(t,e,r,o){let n=await PS(t,e),s=await OS(t,e,o);if(s.length===0)return up();let i=Ju(s,p=>p.category_id),a=Ju(s,p=>p.base_item_id),l=Ju(s,p=>p.item_id),u=new Map(n.baseItems.map(p=>[p.base_item_id,p])),c=new Map(n.items.map(p=>[p.item_id,p])),d=p=>i.get(p)!=="exclude",f=p=>{let b=a.get(p);if(b==="include")return!0;if(b==="exclude")return!1;let _=u.get(p)?.category_id;return _==null||d(_)},m=p=>{let b=l.get(p);if(b==="include")return!0;if(b==="exclude")return!1;let _=c.get(p);return _?.base_item_id==null?!0:f(_.base_item_id)},h=new Set(n.items.filter(p=>m(p.item_id)).map(p=>p.item_id)),g=new Set(n.baseItems.filter(p=>f(p.base_item_id)).map(p=>p.base_item_id));for(let p of n.items)h.has(p.item_id)&&p.base_item_id!=null&&g.add(p.base_item_id);let y=new Set(n.categories.filter(p=>d(p.category_id)).map(p=>p.category_id));for(let p of n.baseItems)g.has(p.base_item_id)&&y.add(p.category_id);return{categoryIds:n.categories.map(p=>p.category_id).filter(p=>!y.has(p)),baseItemIds:n.baseItems.map(p=>p.base_item_id).filter(p=>!g.has(p)),itemIds:n.items.map(p=>p.item_id).filter(p=>!h.has(p))}}function up(){return{categoryIds:[],baseItemIds:[],itemIds:[]}}async function PS(t,e){let{data:r,error:o}=await t.from("categories").select("category_id").eq("franchise_id",e);if(o)throw o;let{data:n,error:s}=await t.from("base_items").select("base_item_id, category_id").eq("franchise_id",e);if(s)throw s;let i=(n??[]).map(u=>u.base_item_id),{data:a,error:l}=i.length>0?await t.from("items").select("item_id, base_item_id").in("base_item_id",i):{data:[],error:null};if(l)throw l;return{categories:r??[],baseItems:n??[],items:a??[]}}async function OS(t,e,r){let{data:o,error:n}=await t.from("visibility_condition_group_assignments").select("*, visibility_condition_groups (*)").eq("visibility_condition_groups.franchise_id",e).eq("visibility_condition_groups.platform",r);if(n||!o)return[];let s=rp({platform:r});return o.filter(i=>{let a=i.visibility_condition_groups;if(!a?.condition||a.platform!==s.platform)return!1;try{return op(a.condition,s)}catch{return!1}})}function Ju(t,e){let r=new Map;for(let o of t){let n=e(o);n!=null&&r.set(n,[...r.get(n)??[],o.effect])}return new Map(Array.from(r.entries()).map(([o,n])=>[o,n.includes("exclude")?"exclude":"include"]))}async function AS(t,e,r){let o=t.from("categories").select("*").eq("franchise_id",e).order("sort_index",Tr).order("name",Tr);r&&r.length>0&&(o=o.not("category_id","in",Ka(r)));let{data:n,error:s}=await o;if(s)throw s;return n??[]}async function RS(t,e,r,o){if(o&&o.length===0)return[];let n=t.from("base_items").select("*").eq("franchise_id",e).order("sort_index",Tr).order("name",Tr);r&&r.length>0&&(n=n.not("base_item_id","in",Ka(r))),o&&(n=n.in("category_id",o.map(u=>u.category_id)));let{data:s,error:i}=await n;if(i)throw i;if(!s||s.length===0)return[];let{data:a,error:l}=await t.from("base_item_images").select("*").in("base_item_id",s.map(u=>u.base_item_id)).order("sort_index",{ascending:!0}).order("image_id",{ascending:!0});if(l)throw l;return IS(s,a??[])}function IS(t,e){let r=new Map;for(let o of e){let n=r.get(o.base_item_id);n?n.push(o):r.set(o.base_item_id,[o])}return t.map(o=>({...o,images:r.get(o.base_item_id)??[]}))}async function DS(t,e,r){if(e&&e.length===0)return[];let o=t.from("items").select("*, portion_scheme:portion_schemes(*)").in("base_item_id",e.map(i=>i.base_item_id)).order("sort_index",Tr).order("price",Tr);r&&r.length>0&&(o=o.not("item_id","in",Ka(r)));let{data:n,error:s}=await o;if(s)throw s;return n??[]}async function LS(t,e,r=!1){let o=e.length>0&&typeof e[0]=="number"?e:e.map(i=>i.item_id);if(o.length===0)return[];let n=r?"components(*), item_id, servings_per_item, behavior_id, component_quantity_behaviors(headcount_threshold, starting_amount, step_size, step_interval, maximum)":"components(*), item_id, servings_per_item",{data:s}=await t.from("item_components").select(n).in("item_id",o).throwOnError();return s.map(i=>({servings_per_item:i.servings_per_item,is_base:i.components?.is_base,serving_weight:i.components?.serving_weight,component_type_id:i.components?.component_type_id,id:i.components?.id,name:i.components?.name,item_id:i.item_id,...r&&{behavior:i.component_quantity_behaviors??void 0}}))}function cp(t){return[...(t.components??[]).map(e=>({key:`component:${e.component_id}`,id:e.component_id,type:"component",name:e.name,basePrice:e.upcharge_price||0,description:e.description,sort_index:e.sort_index??null})),...(t.items??[]).map(e=>({key:`item:${e.item_id}`,id:e.item_id,type:"item",name:e.name,basePrice:e.upcharge_price||0,description:e.description,sort_index:e.sort_index??null}))].sort(Xu)}async function NS(t,e,r,o,n=!1,s){let i=o?.map(g=>g.item_id)??[],a=e?.map(g=>g.base_item_id)??[],l=r?.map(g=>g.category_id)??[];if(i.length===0&&a.length===0&&l.length===0&&!s?.length)return[];let u=[`item_id.in.(${i.length>0?i.join(","):-1})`,`base_item_id.in.(${a.length>0?a.join(","):-1})`,`category_id.in.(${l.length>0?l.join(","):-1})`,...s?.length?[`rule_id.in.(${s.join(",")})`]:[]].join(","),c=n?"component_quantity_behaviors(headcount_threshold, starting_amount, step_size, step_interval, maximum)":null,d=["component_id, upcharge_price, sort_index, components(name, description, serving_weight)",c].filter(Boolean).join(", "),f=["item_id, upcharge_price, sort_index, items(item_id, name, description)",c].filter(Boolean).join(", "),{data:m,error:h}=await t.from("item_rules").select(`
|
|
141
141
|
rule_id,
|
|
142
142
|
category_id,
|
|
143
143
|
item_id,
|
|
@@ -150,12 +150,12 @@ https://supabase.com/dashboard/project/_/settings/api`);let{storage:n}=Du({...r,
|
|
|
150
150
|
sort_index,
|
|
151
151
|
rule_components (${d}),
|
|
152
152
|
rule_items (${f})
|
|
153
|
-
`).or(u).order("sort_index",Tr).order("rule_id",Tr);if(h)throw h;return(m??[]).map(g=>({rule_id:g.rule_id,group_name:g.group_name,min_selection:g.min_selection,max_selection:g.max_selection,included_quantity:g.included_quantity,is_portionable:g.is_portionable,category_id:g.category_id,item_id:g.item_id,base_item_id:g.base_item_id,sort_index:g.sort_index??null,components:(g.rule_components??[]).map(y=>({component_id:y.component_id,upcharge_price:y.upcharge_price??0,name:y.components?.name??"",description:y.components?.description??void 0,serving_weight:y.components?.serving_weight??void 0,sort_index:y.sort_index??null,...n&&{behavior:y.component_quantity_behaviors??void 0}})).sort(Ju),items:(g.rule_items??[]).map(y=>({item_id:y.item_id,name:y.items?.name??"",description:y.items?.description??void 0,upcharge_price:y.upcharge_price??0,sort_index:y.sort_index??null,...n&&{behavior:y.component_quantity_behaviors??void 0}})).sort(Ju)}))}function Ku(t,e,r,o,n){let s={items:[],categories:[],rules:n,components:o};return s.items=e.map(i=>{let a=n.filter(c=>c.category_id===i.category_id),l=n.filter(c=>c.base_item_id===i.base_item_id),u=r.find(c=>c.category_id===i.category_id);return{...i,is_catering:u?.is_catering??!1,variants:t.filter(c=>c.base_item_id===i.base_item_id).map(c=>({...c,components:o.filter(d=>d.item_id===c.item_id),rules:[...a,...l,...n.filter(d=>d.item_id===c.item_id)]})),rules:l}}),s.categories=r.map(i=>({...i,rules:n.filter(a=>a.category_id===i.category_id)})),s}function ks(t,e,r,o=new Date){return t.filter(n=>{if(n.start_date&&new Date(n.start_date)>o||n.end_date&&new Date(n.end_date)<o||n.platforms&&n.platforms.length>0&&!n.platforms.includes(e)||!n.is_automatic)return!1;if(n.location_id!=null&&r!==void 0){if(n.location_id!==r)return!1}else if(n.location_id!=null&&r===void 0)return!1;if(n.schedule_details_json){let{interval:s,days:i,start_time:a,end_time:l}=n.schedule_details_json;if(s==="weekly"&&i&&!i.includes(ia(o)+1))return!1;let u=Et(o);if(a&&Ge(o,Qe(a,"HH:mm",u))||l&&$t(o,Qe(l,"HH:mm",u)))return!1}return!0})}var Yu=null;function dp(t){Yu=t}async function jS(){if(!Yu)throw new Error("apiFetch called before registerTokenProvider");return Yu()}async function qt(t,e={}){let r=await jS(),o={...e.headers};return o["x-request-id"]||(o["x-request-id"]=xs()),fetch(`${zi}${t}`,{...e,headers:{"Content-Type":"application/json",...r&&{Authorization:`Bearer ${r}`},...o}})}function Vt(t){let[e,r]=t.split("/").map(Number);return{index:e,divisions:r}}function Ts(t){return t?1/Vt(t).divisions:1}function uo(t,e){return e?`${t}@${e}`:t}function ht(t){let e=t.indexOf("@");return e===-1?{baseKey:t,portion:null}:{baseKey:t.slice(0,e),portion:t.slice(e+1)}}function MS(t,e){return Math.ceil(t/e)}function US(t){let{min_divisions:e,max_divisions:r}=t;return Array.from({length:r-e+1},(o,n)=>e+n)}var FS={radial:{2:["Left","Right"],4:["Top left","Bottom left","Bottom right","Top right"]},grid:{2:["Left","Right"],4:["Top left","Bottom left","Top right","Bottom right"]},linear:{2:["First half","Second half"]},count:{2:["First half","Second half"]}};function $S(t,e){if(!t)return"Whole";let{index:r,divisions:o}=Vt(t);return FS[e.geometry][o]?.[r-1]??`Part ${r} of ${o}`}function Xu(t,e,r){let o=e[t]??r,n=Object.entries(e).flatMap(([a,l])=>{let u=ht(a);return u.baseKey===t&&u.portion?[{portion:u.portion,value:l}]:[]});if(!n.length)return[{portion:null,value:o}];let{divisions:s}=Vt(n[0].portion),i=Array.from({length:s},(a,l)=>{let u=`${l+1}/${s}`;return{portion:u,value:n.find(c=>c.portion===u)?.value??o}});return i.every(a=>a.value===i[0].value)?[{portion:null,value:i[0].value}]:i}function Ya(t){return t.reduce((e,r)=>e+Ts(ht(r).portion),0)}function Qu(t,e,r){let o=new Map,n=new Map;for(let s of t){let{baseKey:i,portion:a}=ht(s);n.has(i)||n.set(i,n.size),o.set(s,n.get(i)<r?0:Math.ceil(e(i)*Ts(a)))}return o}function Zu(t,e){let{index:r,divisions:o}=Vt(t);if(o===e)return[t];if(e%o===0){let n=e/o,s=(r-1)*n+1;return Array.from({length:n},(i,a)=>`${s+a}/${e}`)}return o%e===0?[`${Math.ceil(r*e/o)}/${e}`]:null}function mp(t){if(!t)return"Whole";let{index:e,divisions:r}=Vt(t);return`Section ${e} of ${r}`}var BS={radial:"\u25CF",grid:"\u25A0",linear:"\u25A0",count:null},qS={radial:{2:["\u25D0","\u25D1"]},grid:{2:["\u25E7","\u25E8"]},linear:{2:["\u25E7","\u25E8"]},count:{}};function hp(t,e){if(!e)return null;if(!t)return BS[e];let{index:r,divisions:o}=Vt(t);return qS[e][o]?.[r-1]??null}function VS(t){let e=t.portion_scheme?.geometry,r=new Map,o=s=>{let i=s??"",a=r.get(i);return a||r.set(i,a={selections:[],removals:[],additions:[]}),a};for(let s of t.selections??[])for(let i of s.selections){let{selections:a}=o(i.portion),l=a.find(u=>u.rule_id===s.rule_id);l||a.push(l={...s,selections:[]}),l.selections.push(i)}for(let s of t.components??[])s.quantity_servings<=0?o(s.portion).removals.push(s):s.portion&&o(s.portion).additions.push(s);let n=s=>s?Vt(s).index:-1;return[...r.entries()].sort(([s],[i])=>n(s)-n(i)).map(([s,i])=>({portion:s||null,label:mp(s||null),glyph:hp(s||null,e),...i}))}var fp=t=>Math.round(t*100)/100;function WS(t,e,r=48){if(e===1)return`M 50 ${50-r} A ${r} ${r} 0 1 0 49.9 ${50-r} Z`;let o=2*Math.PI/e,n=-Math.PI/2-(t-1)*o,s=n-o,i=a=>`${fp(50+r*Math.cos(a))} ${fp(50+r*Math.sin(a))}`;return`M 50 50 L ${i(n)} A ${r} ${r} 0 ${o>Math.PI?1:0} 0 ${i(s)} Z`}function pp(t,e){return t.map(r=>!e.discount_target_type||e.discount_target_type==="item"&&r.base_item_id!=null&&e.discount_target_ids?.includes(r.base_item_id)||e.discount_target_type==="item_variant"&&e.discount_target_ids?.includes(r.item_id)||e.discount_target_type==="category"&&e.discount_target_ids?.includes(r.category_id)?{...r,applied_promo_id:e.id}:r)}function gp(t){switch(t){case 1:return"Kiosk";case 2:return"Website";case 3:return"POS";default:return""}}function yp(t){let{max_selection:e,min_selection:r}=t,o=e!=null&&e!==1/0,n=t.included_quantity??0,s=o?r===e?`Choose ${r}`:r>0?`Choose ${r} to ${e}`:`Choose up to ${e}`:r>0?`Choose at least ${r}`:"Choose any";return n>0?`${s}. ${n} included`:s}function ec(t,e,r,o){let n=o/2,s=Math.log(99)/(o-n),i=1/(1+Math.exp(-s*(e-n))),a=1/(1+Math.exp(s*n)),l=(i-a)/(1-a);return t*(1-r*l)}var HS=.06;var zS=.02,GS=.015;function KS(t,e,r=!1){return e!==2?0:Math.floor(r?GS*t:zS*t)}function Cr(t,e=!1){let r=e?t.display_price||0:t.price||0,o=t.selections?.reduce((s,i)=>s+i.selections.reduce((a,l)=>a+l.upcharge,0),0)||0;return(r+o)*t.quantity}function nn({order:t}){return t.items.filter(e=>e.status!=="removed").reduce((e,r)=>e+Cr(r),0)}function JS(t,e){let r=nn({order:t}),{discount:o}=QS(t,e),n=r-o,s=ZS(n),i=KS(n,t.method_id,t.is_catering??!1),a=n+s+i;return{subtotal:r,tax:s,service_fee:i,discount:o,total:a}}function sn(t,e,r=0){let o=YS(t.charges),{subtotal:n,discount:s,tax:i,service_fee:a,total:l}=o.length?XS(o):JS(t,e);return{lines:t.items.filter(u=>u.status!=="removed").map(u=>({name:u.name,quantity:u.quantity,unitPrice:Cr({...u,quantity:1}),lineTotal:Cr(u),perPerson:u.per_person,addOns:(u.selections??[]).flatMap(c=>c.selections.map(d=>({name:d.name,groupName:c.group_name,upcharge:d.upcharge})))})),subtotal:n,discount:s??0,tax:i,serviceFee:a??0,tip:r,total:l+r}}function YS(t){return(t??[]).filter(e=>e.charge_status===1)}function XS(t){return(Array.isArray(t)?t:[]).reduce((r,o)=>({subtotal:r.subtotal+o.subtotal,tax:r.tax+o.tax,tip:(r.tip||0)+(o.tip||0),discount:(r.discount||0)+(o.discount||0),service_fee:(r.service_fee||0)+(o.service_fee||0),total:r.total+o.total}),{subtotal:0,tax:0,tip:0,discount:0,service_fee:0,total:0})}function ur(t,e,r){if(!e.method_id)throw new Error("Attach method_id to order to calculate promo discount.");if(!e.location_id)throw new Error("Attach location_id to order to calculate promo discount.");if(!t.is_active)return 0;let o=gp(e.method_id).toLowerCase();if(t.platforms&&t.platforms.length>0&&!t.platforms.includes(o)||t.location_id&&t.location_id!==e.location_id||t.start_date&&Ge(r,new Date(t.start_date))||t.end_date&&$t(r,new Date(t.end_date)))return 0;if(t.schedule_details_json){let{interval:d,days:f,start_time:m,end_time:h}=t.schedule_details_json;if(d==="weekly"&&f&&!f.includes(ia(r)+1))return 0;let g=Et(r);if(m){let y=Qe(m,"HH:mm",g);if(Ge(r,y))return 0}if(h){let y=Qe(h,"HH:mm",g);if($t(r,y))return 0}}let n=e.is_catering||e.items.some(d=>d.is_catering);if(t.is_catering_only&&!n)return 0;let s=nn({order:e});if(t.min_purchase_amount&&s<t.min_purchase_amount)return 0;let i=e.items.reduce((d,f)=>d+f.quantity,0),a=t.is_catering_only&&t.min_purchase_quantity;if(!a&&t.min_purchase_quantity&&i<t.min_purchase_quantity)return 0;let l=e.items,u=s;if(t.discount_target_type&&t.discount_target_ids?.length&&(l=e.items.filter(d=>t.discount_target_type==="category"?t.discount_target_ids.includes(d.category_id):t.discount_target_type==="item"?t.discount_target_ids.includes(d.base_item_id):t.discount_target_type==="item_variant"?t.discount_target_ids.includes(d.item_id):!1),u=l.reduce((d,f)=>d+Cr(f),0)),l.length===0)return 0;let c=0;if(a&&t.promotion_type_id===1){let d=l.reduce((m,h)=>m+h.quantity,0),f=ec(u,d,t.discount_value/100,t.min_purchase_quantity);c=u-f}else t.promotion_type_id===1?c=u*(t.discount_value/100):t.promotion_type_id===2&&(c=t.discount_value);return Math.min(Math.floor(c),u)}function Xa(t){return t.is_automatic?t.discount_target_type?"item":"order":"private"}function bp(t,e,r){if(!e.length)return{discount:0};let o,n=0;for(let u of e){if(Xa(u)!=="order")continue;let c=ur(u,t,r);c>n&&(n=c,o=u)}let s=t.items.filter(u=>u.status!=="removed"),i=e.filter(u=>Xa(u)==="item"),a=[];i.length>0&&s.forEach((u,c)=>{let d=0,f;for(let m of i){let h={...t,items:[u]},g=ur(m,h,r);g>d&&(d=g,f=m.id)}d>0&&f!==void 0&&a.push({itemIndex:c,itemId:u.item_id,promotionId:f,discount:d})});let l=a.reduce((u,c)=>u+c.discount,0);return n===0&&l===0?{discount:0}:n>=l?{discount:n,orderPromo:o}:{discount:l,itemDiscounts:a}}function QS(t,e,r=new Date){if(e)try{let n=ur(e,t,r);return{name:e.name,discount:n}}catch{return{name:e.name,discount:0}}let o=t.items.reduce((n,s)=>n+(s.discount_amount??0),0);return o>0?{name:"Item discounts",discount:o}:{discount:0}}function ZS(t){return Math.round(t*HS)}var $p=require("zustand");function tc(t,e,r){let o=aa(),n=rx(t,r.timeZone,r.locale??o.locale);return"formatToParts"in n?ex(n,e):tx(n,e)}function ex(t,e){let r=t.formatToParts(e);for(let o=r.length-1;o>=0;--o)if(r[o].type==="timeZoneName")return r[o].value}function tx(t,e){let r=t.format(e).replace(/\u200E/g,""),o=/ [\w-+ ]+$/.exec(r);return o?o[0].substr(1):""}function rx(t,e,r){return new Intl.DateTimeFormat(r?[r.code,"en-US"]:void 0,{timeZone:e,timeZoneName:t})}function wp(t,e){let r=ax(e);return"formatToParts"in r?nx(r,t):sx(r,t)}var ox={year:0,month:1,day:2,hour:3,minute:4,second:5};function nx(t,e){try{let r=t.formatToParts(e),o=[];for(let n=0;n<r.length;n++){let s=ox[r[n].type];s!==void 0&&(o[s]=parseInt(r[n].value,10))}return o}catch(r){if(r instanceof RangeError)return[NaN];throw r}}function sx(t,e){let r=t.format(e),o=/(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(r);return[parseInt(o[3],10),parseInt(o[1],10),parseInt(o[2],10),parseInt(o[4],10),parseInt(o[5],10),parseInt(o[6],10)]}var rc={},_p=new Intl.DateTimeFormat("en-US",{hourCycle:"h23",timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(new Date("2014-06-25T04:00:00.123Z")),ix=_p==="06/25/2014, 00:00:00"||_p==="\u200E06\u200E/\u200E25\u200E/\u200E2014\u200E \u200E00\u200E:\u200E00\u200E:\u200E00";function ax(t){return rc[t]||(rc[t]=ix?new Intl.DateTimeFormat("en-US",{hourCycle:"h23",timeZone:t,year:"numeric",month:"numeric",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}):new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"numeric",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})),rc[t]}function Cs(t,e,r,o,n,s,i){let a=new Date(0);return a.setUTCFullYear(t,e,r),a.setUTCHours(o,n,s,i),a}var vp=36e5,lx=6e4,oc={timezone:/([Z+-].*)$/,timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function cr(t,e,r){if(!t)return 0;let o=oc.timezoneZ.exec(t);if(o)return 0;let n,s;if(o=oc.timezoneHH.exec(t),o)return n=parseInt(o[1],10),Sp(n)?-(n*vp):NaN;if(o=oc.timezoneHHMM.exec(t),o){n=parseInt(o[2],10);let i=parseInt(o[3],10);return Sp(n,i)?(s=Math.abs(n)*vp+i*lx,o[1]==="+"?-s:s):NaN}if(dx(t)){e=new Date(e||Date.now());let i=r?e:ux(e),a=nc(i,t);return-(r?a:cx(e,a,t))}return NaN}function ux(t){return Cs(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds())}function nc(t,e){let r=wp(t,e),o=Cs(r[0],r[1]-1,r[2],r[3]%24,r[4],r[5],0).getTime(),n=t.getTime(),s=n%1e3;return n-=s>=0?s:1e3+s,o-n}function cx(t,e,r){let n=t.getTime()-e,s=nc(new Date(n),r);if(e===s)return e;n-=s-e;let i=nc(new Date(n),r);return s===i?s:Math.max(s,i)}function Sp(t,e){return-23<=t&&t<=23&&(e==null||0<=e&&e<=59)}var xp={};function dx(t){if(xp[t])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:t}),xp[t]=!0,!0}catch{return!1}}var fx=60*1e3,Tp={X:function(t,e,r){let o=sc(r.timeZone,t);if(o===0)return"Z";switch(e){case"X":return kp(o);case"XXXX":case"XX":return an(o);default:return an(o,":")}},x:function(t,e,r){let o=sc(r.timeZone,t);switch(e){case"x":return kp(o);case"xxxx":case"xx":return an(o);default:return an(o,":")}},O:function(t,e,r){let o=sc(r.timeZone,t);switch(e){case"O":case"OO":case"OOO":return"GMT"+mx(o,":");default:return"GMT"+an(o,":")}},z:function(t,e,r){switch(e){case"z":case"zz":case"zzz":return tc("short",t,r);default:return tc("long",t,r)}}};function sc(t,e){let r=t?cr(t,e,!0)/fx:e?.getTimezoneOffset()??0;if(Number.isNaN(r))throw new RangeError("Invalid time zone specified: "+t);return r}function Qa(t,e){let r=t<0?"-":"",o=Math.abs(t).toString();for(;o.length<e;)o="0"+o;return r+o}function an(t,e=""){let r=t>0?"-":"+",o=Math.abs(t),n=Qa(Math.floor(o/60),2),s=Qa(Math.floor(o%60),2);return r+n+e+s}function kp(t,e){return t%60===0?(t>0?"-":"+")+Qa(Math.abs(t)/60,2):an(t,e)}function mx(t,e=""){let r=t>0?"-":"+",o=Math.abs(t),n=Math.floor(o/60),s=o%60;return s===0?r+String(n):r+String(n)+e+Qa(s,2)}function ic(t){let e=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return e.setUTCFullYear(t.getFullYear()),+t-+e}var Za=/(Z|[+-]\d{2}(?::?\d{2})?| UTC| [a-zA-Z]+\/[a-zA-Z_]+(?:\/[a-zA-Z_]+)?)$/;var ac=36e5,Cp=6e4,hx=2,qe={dateTimePattern:/^([0-9W+-]+)(T| )(.*)/,datePattern:/^([0-9W+-]+)(.*)/,plainTime:/:/,YY:/^(\d{2})$/,YYY:[/^([+-]\d{2})$/,/^([+-]\d{3})$/,/^([+-]\d{4})$/],YYYY:/^(\d{4})/,YYYYY:[/^([+-]\d{4})/,/^([+-]\d{5})/,/^([+-]\d{6})/],MM:/^-(\d{2})$/,DDD:/^-?(\d{3})$/,MMDD:/^-?(\d{2})-?(\d{2})$/,Www:/^-?W(\d{2})$/,WwwD:/^-?W(\d{2})-?(\d{1})$/,HH:/^(\d{2}([.,]\d*)?)$/,HHMM:/^(\d{2}):?(\d{2}([.,]\d*)?)$/,HHMMSS:/^(\d{2}):?(\d{2}):?(\d{2}([.,]\d*)?)$/,timeZone:Za};function pt(t,e={}){if(arguments.length<1)throw new TypeError("1 argument required, but only "+arguments.length+" present");if(t===null)return new Date(NaN);let r=e.additionalDigits==null?hx:Number(e.additionalDigits);if(r!==2&&r!==1&&r!==0)throw new RangeError("additionalDigits must be 0, 1 or 2");if(t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]")return new Date(t.getTime());if(typeof t=="number"||Object.prototype.toString.call(t)==="[object Number]")return new Date(t);if(Object.prototype.toString.call(t)!=="[object String]")return new Date(NaN);let o=px(t),{year:n,restDateString:s}=gx(o.date,r),i=yx(s,n);if(i===null||isNaN(i.getTime()))return new Date(NaN);if(i){let a=i.getTime(),l=0,u;if(o.time&&(l=bx(o.time),l===null||isNaN(l)))return new Date(NaN);if(o.timeZone||e.timeZone){if(u=cr(o.timeZone||e.timeZone,new Date(a+l)),isNaN(u))return new Date(NaN)}else u=ic(new Date(a+l)),u=ic(new Date(a+l+u));return new Date(a+l+u)}else return new Date(NaN)}function px(t){let e={},r=qe.dateTimePattern.exec(t),o;if(r?(e.date=r[1],o=r[3]):(r=qe.datePattern.exec(t),r?(e.date=r[1],o=r[2]):(e.date=null,o=t)),o){let n=qe.timeZone.exec(o);n?(e.time=o.replace(n[1],""),e.timeZone=n[1].trim()):e.time=o}return e}function gx(t,e){if(t){let r=qe.YYY[e],o=qe.YYYYY[e],n=qe.YYYY.exec(t)||o.exec(t);if(n){let s=n[1];return{year:parseInt(s,10),restDateString:t.slice(s.length)}}if(n=qe.YY.exec(t)||r.exec(t),n){let s=n[1];return{year:parseInt(s,10)*100,restDateString:t.slice(s.length)}}}return{year:null}}function yx(t,e){if(e===null)return null;let r,o,n;if(!t||!t.length)return r=new Date(0),r.setUTCFullYear(e),r;let s=qe.MM.exec(t);if(s)return r=new Date(0),o=parseInt(s[1],10)-1,Pp(e,o)?(r.setUTCFullYear(e,o),r):new Date(NaN);if(s=qe.DDD.exec(t),s){r=new Date(0);let i=parseInt(s[1],10);return vx(e,i)?(r.setUTCFullYear(e,0,i),r):new Date(NaN)}if(s=qe.MMDD.exec(t),s){r=new Date(0),o=parseInt(s[1],10)-1;let i=parseInt(s[2],10);return Pp(e,o,i)?(r.setUTCFullYear(e,o,i),r):new Date(NaN)}if(s=qe.Www.exec(t),s)return n=parseInt(s[1],10)-1,Op(n)?Ep(e,n):new Date(NaN);if(s=qe.WwwD.exec(t),s){n=parseInt(s[1],10)-1;let i=parseInt(s[2],10)-1;return Op(n,i)?Ep(e,n,i):new Date(NaN)}return null}function bx(t){let e,r,o=qe.HH.exec(t);if(o)return e=parseFloat(o[1].replace(",",".")),lc(e)?e%24*ac:NaN;if(o=qe.HHMM.exec(t),o)return e=parseInt(o[1],10),r=parseFloat(o[2].replace(",",".")),lc(e,r)?e%24*ac+r*Cp:NaN;if(o=qe.HHMMSS.exec(t),o){e=parseInt(o[1],10),r=parseInt(o[2],10);let n=parseFloat(o[3].replace(",","."));return lc(e,r,n)?e%24*ac+r*Cp+n*1e3:NaN}return null}function Ep(t,e,r){e=e||0,r=r||0;let o=new Date(0);o.setUTCFullYear(t,0,4);let n=o.getUTCDay()||7,s=e*7+r+1-n;return o.setUTCDate(o.getUTCDate()+s),o}var _x=[31,28,31,30,31,30,31,31,30,31,30,31],wx=[31,29,31,30,31,30,31,31,30,31,30,31];function Ap(t){return t%400===0||t%4===0&&t%100!==0}function Pp(t,e,r){if(e<0||e>11)return!1;if(r!=null){if(r<1)return!1;let o=Ap(t);if(o&&r>wx[e]||!o&&r>_x[e])return!1}return!0}function vx(t,e){if(e<1)return!1;let r=Ap(t);return!(r&&e>366||!r&&e>365)}function Op(t,e){return!(t<0||t>52||e!=null&&(e<0||e>6))}function lc(t,e,r){return!(t<0||t>=25||e!=null&&(e<0||e>=60)||r!=null&&(r<0||r>=60))}var Sx=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function uc(t,e,r={}){e=String(e);let o=e.match(Sx);if(o){let n=pt(r.originalDate||t,r);e=o.reduce(function(s,i){if(i[0]==="'")return s;let a=s.indexOf(i),l=s[a-1]==="'",u=s.replace(i,"'"+Tp[i[0]](n,i,r)+"'");return l?u.substring(0,a-1)+u.substring(a+1):u},e)}return Be(t,e,r)}function Es(t,e,r){t=pt(t,r);let o=cr(e,t,!0),n=new Date(t.getTime()-o),s=new Date(0);return s.setFullYear(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate()),s.setHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),s}function el(t,e,r,o){return o={...o,timeZone:e,originalDate:t},uc(Es(t,e,{timeZone:o.timeZone}),r,o)}function cc(t,e,r){if(typeof t=="string"&&!t.match(Za))return pt(t,{...r,timeZone:e});t=pt(t,r);let o=Cs(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()).getTime(),n=cr(e,new Date(o));return new Date(o+n)}var Ps="America/New_York",xx=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];function Rp(t){return t.replace(/[+-].*$/,"").trim().slice(0,5)}function dc(t,e,r=0){let o=new Date(`${el(t,Ps,"yyyy-MM-dd")}T12:00:00Z`);o.setUTCDate(o.getUTCDate()+r);let n=o.toISOString().slice(0,10),s=xx[o.getUTCDay()],i=e[`${s}_open`],a=e[`${s}_close`];if(!i||!a)return null;let l=pt(`${n}T${Rp(i)}`,{timeZone:Ps}),u=pt(`${n}T${Rp(a)}`,{timeZone:Ps});return u<=l&&(u=new Date(u.getTime()+1440*60*1e3)),{day:s,open:l,close:u}}function tl(t,e){if(e.force_close)return!0;for(let r of[-1,0]){let o=dc(t,e,r);if(o&&!Ge(t,o.open)&&Ge(t,o.close))return!1}return!0}var Er=require("zustand/middleware");async function Ip(t,e){let r=e||U,{data:o,error:n}=await r.from("permissions").select("franchise_id, location_ids, portal_role").eq("user_id",t);if(n)throw n;if(o?.some(f=>f.portal_role==="admin")){let[f,m]=await Promise.all([r.from("franchises").select("*").throwOnError(),r.from("locations").select("*").throwOnError()]);return{franchises:f.data,locations:m.data}}let s=new Set(o?.map(f=>f.franchise_id).filter(f=>f!=null)??[]),i=new Set(o?.filter(f=>!f.location_ids?.length&&f.franchise_id!==null).map(f=>f.franchise_id)),a=o?.flatMap(f=>f.location_ids??[])??[],{data:l,error:u}=await r.from("franchises").select("*").in("franchise_id",Array.from(s));if(u)throw u;let{data:c,error:d}=await r.from("locations").select("*").or(`location_id.in.(${a.join(",")}), franchise_id.in.(${Array.from(i).join(",")})`);if(d)throw d;return{franchises:l,locations:c}}async function Dp(t,e){let r=e||U,{data:o,error:n}=await r.from("franchises").select("*").eq("franchise_id",t);if(n)throw n;let{data:s,error:i}=await r.from("locations").select("*").eq("franchise_id",t).or("status.is.null,status.neq.permanently_closed");if(i)throw i;return{franchises:o,locations:s}}async function Lp(t,e,r){let o=r||U,n={...e,...t},{data:s,error:i}=await o.from("locations").update(n).eq("location_id",e.location_id).select().single();if(i)throw i;return s}async function Np(t,e,r){let o=r||U,{data:n,error:s}=await o.from("locations").update({force_close:e}).eq("location_id",t);if(s)throw s;return n}async function jp(t,e){let r=e||U,{data:o,error:n}=await r.from("locations").insert(t).select().single();if(n)throw n;return o}async function Mp(t,e){let r=e||U,{data:o,error:n}=await r.from("locations").delete().eq("location_id",t);if(n)throw n;return o}async function Up(t,e,r){let o=r||U,n={...t,...e},{data:s,error:i}=await o.from("franchises").update(n).eq("franchise_id",t.franchise_id).select().single();if(i)throw i;return s}function Fp(t){try{let e=(t.split(".")[1]??"").replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(e.padEnd(Math.ceil(e.length/4)*4,"=")))}catch{return{}}}var Os=(0,$p.create)()((0,Er.subscribeWithSelector)((0,Er.persist)((0,Er.devtools)((t,e)=>({selectedLocation:null,franchises:[],locations:[],userId:null,navScope:"franchise",initialize:async({userId:r,token:o,locationId:n})=>{if(r&&t({userId:r}),n){let{data:a}=await U.from("locations").select("*").eq("location_id",n).throwOnError().single(),{data:l}=await U.from("franchises").select("*").eq("franchise_id",a.franchise_id).throwOnError().single();t({selectedLocation:a,franchiseId:a.franchise_id,locations:[a],franchises:[l]});return}else if(o){let l=Fp(o).franchise_ids?.[0],{locations:u,franchises:c}=await Dp(l),d=e().selectedLocation,f=d?u.find(m=>m.location_id===d.location_id)??null:null;t({locations:u,franchises:c,franchiseId:l,selectedLocation:f});return}else if(r){let{locations:a,franchises:l}=await Ip(r);t({locations:a,franchises:l})}let i=e().locations[0];t({selectedLocation:i,...i&&{franchiseId:i.franchise_id}})},hydrate:({franchises:r,locations:o})=>t({franchises:r??[],locations:o??[]},!1,"hydrate"),getCurrentLocation:()=>e().selectedLocation,getIsCurrentLocationOpen:()=>{let r=e().selectedLocation;return r?!tl(new Date,r):!1},getAllLocations:()=>e().locations,setForceClose:async(r,o)=>{await Np(o,r),t(n=>({locations:n.locations.map(s=>s.location_id===o?{...s,force_close:r}:s),selectedLocation:n.selectedLocation?.location_id===o?{...n.selectedLocation,force_close:r}:n.selectedLocation}))},setSelectedLocation:r=>{t({selectedLocation:r}),t({franchiseId:r.franchise_id})},setFranchiseId:r=>{if(t({franchiseId:r}),e().selectedLocation?.franchise_id!==r){let o=e().locations.find(n=>n.franchise_id===r&&n.location_id!==0)??e().locations.find(n=>n.franchise_id===r)??null;t({selectedLocation:o})}},enterFranchise:r=>{let o=e();if(t({franchiseId:r,navScope:"franchise"}),o.selectedLocation?.franchise_id!==r){let n=o.locations.find(s=>s.franchise_id===r&&s.location_id!==0)??o.locations.find(s=>s.franchise_id===r)??null;t({selectedLocation:n})}},enterLocation:r=>{t({selectedLocation:r,franchiseId:r.franchise_id,navScope:"location"})},exitToFranchise:()=>{t({navScope:"franchise"})},exitToAccount:()=>{t({navScope:"account"})},updateLocation:async(r,o)=>{await Lp(r,o),t(n=>({locations:n.locations.map(s=>s.location_id===o.location_id?{...s,...r}:s)}))},createLocation:async r=>{let o=await jp(r);return t(n=>({locations:[...n.locations,o]})),o},deleteLocation:async r=>{await Mp(r),t(o=>({locations:o.locations.filter(n=>n.location_id!==r)}))},updateFranchise:async(r,o)=>{let n=await Up(r,o);return t(s=>({franchises:s.franchises.map(i=>i.franchise_id===r.franchise_id?n:i)})),n}})),{name:"location",version:3,migrate:(t,e)=>{let r=t??{};return e<3?{...r,navScope:r.navScope??"franchise",franchiseId:r.franchiseId??r.selectedLocation?.franchise_id}:r},storage:(0,Er.createJSONStorage)(()=>kr()),skipHydration:xr,partialize:t=>({selectedLocation:t.selectedLocation,franchises:t.franchises,locations:t.locations,userId:t.userId,franchiseId:t.franchiseId,navScope:t.navScope})}))),Y=Os;var Yp=require("zustand");var Xp=require("zustand/middleware/immer"),Qp=require("zustand/middleware");async function Bp(t){let{data:e,error:r}=await U.from("promotions").select("*").eq("franchise_id",t);if(r)throw r;return e}async function qp(t,e="website",r){let{data:o,error:n}=await U.from("promotions").select("*").eq("is_active",!0).eq("franchise_id",t);if(n)throw n;let s=ks(o,e,r);return{all:o,active:s}}async function Vp(t,e){let{data:r,error:o}=await U.from("promotions").select("*").eq("promo_code",t).eq("franchise_id",e).eq("is_active",!0).single();return o||!r?null:r}async function Wp(t){let{data:e,error:r}=await U.from("promotions").insert(t).select("*").single();if(r)throw r;return e}async function Hp(t){let{data:e,error:r}=await U.from("promotions").update(t).eq("id",t.id).select("*").single();if(r)throw r;return e}async function zp(t){let{data:e,error:r}=await U.from("promotions").delete().eq("id",t).select("*").single();if(r)throw r;e||console.log("No promotion deleted")}async function Gp(t){let{data:e,error:r}=await U.from("franchise_marketing").select("personal_marketer").eq("franchise_id",t).maybeSingle();if(r)throw r;return e?.personal_marketer??!1}async function Kp(t,e){let{error:r}=await U.from("franchise_marketing").upsert({franchise_id:t,personal_marketer:e},{onConflict:"franchise_id"});if(r)throw r;let{error:o}=await U.from("agent_skill_config").upsert({franchise_id:t,skill_id:"personal-marketer",enabled:e,updated_at:new Date().toISOString()},{onConflict:"franchise_id,skill_id"});if(o)throw o}async function Jp(t,e=10){let{data:r,error:o}=await U.from("personal_marketer_runs").select("*").eq("franchise_id",t).order("created_at",{ascending:!1}).limit(e);if(o)throw o;return r}var kx=(0,Yp.create)()((0,Qp.devtools)((0,Xp.immer)((t,e)=>({logLevel:1,promotions:[],allPromotions:[],activePromotions:[],personalMarketerEnabled:!1,recentRuns:[],recentOutboundMessages:[],getPromotions:async r=>{let o=await Bp(r);return t({promotions:o},!1,"getPromotions"),o},getActivePromotions:async(r,o,n="website")=>{let{active:s,all:i}=await qp(r,n,o);return t({allPromotions:i,activePromotions:s},!1,"getActivePromotions"),s},getPromotionByCode:async(r,o)=>await Vp(r,o),addPromotion:async r=>{let o=await Wp(r);t(n=>{n.promotions.push(o)})},updatePromotion:async r=>{let o=await Hp(r);t(n=>{n.promotions=n.promotions.map(s=>s.id===o.id?o:s)})},deletePromotion:async r=>{await zp(r),t(o=>{o.promotions=o.promotions.filter(n=>n.id!==r)})},getPersonalMarketerSettings:async()=>{let r=Os.getState().franchiseId;if(!r){e().logLevel<=2&&console.warn("[PROMOTION STORE] No franchise ID found");return}let o=await Gp(r);t({personalMarketerEnabled:o},!1,"getPersonalMarketerSettings")},setPersonalMarketerEnabled:async r=>{let o=Os.getState().selectedLocation?.franchise_id;if(!o){e().logLevel<=2&&console.warn("[PROMOTION STORE] No franchise ID found");return}await Kp(o,r),t({personalMarketerEnabled:r},!1,"setPersonalMarketerEnabled")},getRecentRuns:async(r=10)=>{let o=Os.getState().franchiseId;if(!o)return e().logLevel<=2&&console.warn("[PROMOTION STORE] No franchise ID found"),[];let n=await Jp(o,r);return t({recentRuns:n},!1,"getRecentRuns"),n},createBlastRun:async(r,o)=>{let n=await qt("/marketing/create-run",{method:"POST",body:JSON.stringify({franchiseId:r,source:"blast",strategyId:"promotionalBlast",promotionId:o,dryRun:!1})});if(!n.ok){let i=await n.json().catch(()=>({}));throw new Error(i?.error??`HTTP ${n.status}`)}let{run:s}=await n.json();return await e().getRecentRuns(),s}})),{name:"PromotionStore"})),Ce=kx;var og=Le(eg(),1),ng=require("react");function rl(t){return t===2?2:1}var sg=!1;function ig(){sg=!0}var ol=(0,tg.create)()((0,ln.persist)((0,ln.devtools)((0,rg.immer)((t,e)=>({deliveryFeeCents:0,workingOrder:{time_placed:new Date,time_requested:void 0,customer:{first_name:"",last_name:"",phone:"",email:"",allow_marketing:!1},location_id:Y.getState().selectedLocation?.location_id||0,order_status:1,method_id:1,order_id:0,type_id:1,items:[],promo_code:void 0,charges:[],table_number:void 0},status:"idle",editingSourceOrder:null,promoOverrideActive:!1,addItem:(r,o)=>{let n=r;if(o){t(a=>{a.promoOverrideActive=!0,a.selectedPromotion=void 0,a.workingOrder.promo_code=void 0});let s=e().workingOrder.location_id,i=ur(o,{items:[r],location_id:s,method_id:3},new Date);n={...r,applied_promo_id:o.id,discount_amount:i>0?i:void 0}}t(s=>{s.workingOrder.items.push(n),n.is_catering&&(s.workingOrder.is_catering=!0),s.status!=="editing"&&(s.workingOrder.order_id=0)}),e().checkBestPromo()},setTip:r=>t(o=>{o.selectedTip=r}),removeItem:r=>{t(o=>{o.workingOrder.items.splice(r,1),o.status!=="editing"&&(o.workingOrder.order_id=0)}),e().checkBestPromo()},updateItem:(r,o,n)=>{let s=r;if(n!==void 0)if(t(i=>{i.promoOverrideActive=!0,n&&(i.selectedPromotion=void 0,i.workingOrder.promo_code=void 0)}),n){let i=e().workingOrder.location_id,a=ur(n,{items:[r],location_id:i,method_id:3},new Date);s={...r,applied_promo_id:n.id,discount_amount:a>0?a:void 0}}else s={...r,applied_promo_id:void 0,discount_amount:void 0};t(i=>{i.workingOrder.items[o]=s,i.status!=="editing"&&(i.workingOrder.order_id=0)}),e().checkBestPromo()},setCustomer:r=>t(o=>{o.workingOrder.customer=r}),getAnonCustomer:()=>({customer_id:0,first_name:"Customer",last_name:"Customer",phone:"0"}),setCart:r=>t(o=>{o.workingOrder=r}),createCustomer:async()=>{let r=e().workingOrder.customer,{data:o,error:n}=await U.from("customers").insert({first_name:r.first_name,last_name:r.last_name,email:r.email,phone_number:parseInt(r.phone)}).select("*").single();return n?(console.log("Error creating customer:",n),null):(console.log("customer created",o),o)},setLocationId:r=>t(o=>{o.workingOrder.location_id=r}),setOrderType:r=>t(o=>{o.workingOrder.type_id=rl(r)}),setTableNumber:r=>t(o=>{o.workingOrder.table_number=r}),setTimeRequested:r=>t(o=>{o.workingOrder.time_requested=r}),applyCateringPreflight:r=>t(o=>{if(o.workingOrder.type_id=r.type_id,o.workingOrder.location_id=r.location_id,o.workingOrder.time_requested=r.time_requested,r.type_id===bs.ORDER_TYPE.DELIVERY){let n=r.delivery_address?.trim();o.workingOrder.delivery_address=n&&n.length>0?n:void 0}else o.workingOrder.delivery_address=void 0}),clearCateringSchedule:()=>t(r=>{r.workingOrder.time_requested=void 0}),setDeliveryFee:r=>t(o=>{o.deliveryFeeCents=r}),setPromoCode:r=>t(o=>{o.workingOrder.promo_code=r}),resetOrder:()=>t(r=>({workingOrder:{...r.workingOrder,order_id:0,location_id:Y.getState().selectedLocation?.location_id??0,customer:{first_name:"",last_name:"",phone:"",email:"",allow_marketing:!1},items:[],promo_code:void 0,type_id:1,is_catering:!1,time_requested:void 0,delivery_address:void 0,table_number:void 0},selectedTip:void 0,deliveryFeeCents:0})),setOrder:r=>t(o=>{o.workingOrder={...r,type_id:rl(r.type_id)}}),startEdit:r=>t(o=>{let n={...r,type_id:rl(r.type_id),charges:r.charges??[]};o.workingOrder=n,o.editingSourceOrder=n,o.status="editing",o.selectedTip=void 0;let s=Number(r.promo_code);o.selectedPromotion=s?Ce.getState().activePromotions.find(i=>i.id===s):void 0,o.promoOverrideActive=!!o.selectedPromotion}),cancelEdit:(r=!0)=>t(o=>{o.status="idle",o.editingSourceOrder=null,o.selectedTip=void 0,o.selectedPromotion=void 0,o.promoOverrideActive=!1,r&&(o.workingOrder={...o.workingOrder,location_id:Y.getState().selectedLocation?.location_id??0,type_id:1,customer:{first_name:"",last_name:"",phone:"",email:"",allow_marketing:!1},order_status:1,order_id:0,items:[],promo_code:void 0,charges:[],revision:void 0,updated_at:void 0,table_number:void 0})}),finishEdit:()=>t(r=>({workingOrder:{...r.workingOrder,location_id:Y.getState().selectedLocation?.location_id??0,type_id:1,customer:{first_name:"",last_name:"",phone:"",email:"",allow_marketing:!1},order_status:1,order_id:0,items:[],promo_code:void 0,charges:[],revision:void 0,updated_at:void 0,table_number:void 0},status:"idle",editingSourceOrder:null,selectedTip:void 0,selectedPromotion:void 0,promoOverrideActive:!1})),hasMeaningfulEditChanges:()=>{let{status:r,editingSourceOrder:o,workingOrder:n}=e();return r!=="editing"||!o?!1:!(0,og.default)(o.items,n.items)},getOrderTotal:()=>nn({order:e().workingOrder}),setCartFromURL:async(r,o)=>{try{let n={"Content-Type":"application/json",...o?{"X-Zorgo-Api-Key":o}:{}},s=await fetch(`${zi}/s/${r}`,{headers:n});if(!s.ok)return!1;let{cart_data:i,promotion_id:a}=await s.json();return i?(t(l=>{if(l.workingOrder={...l.workingOrder,...i,type_id:rl(i.type_id),order_id:0,order_status:1},l.workingOrder.time_requested=void 0,!a||i?.promo_code||i?.items?.some(d=>d.applied_promo_id))return;let c=Ce.getState().activePromotions.find(d=>d.id===a);if(!c){l.workingOrder.promo_code=String(a);return}if(c.promo_code){l.workingOrder.promo_code=c.promo_code;return}l.workingOrder.items=pp(l.workingOrder.items,c)}),e().checkBestPromo(),!0):!1}catch(n){return console.error("[CartStore] setCartFromURL failed:",n),!1}},dismissPromo:r=>{t(o=>{o.dismissedPromoIds=[...o.dismissedPromoIds||[],r]})},checkBestPromo:()=>{if(e().promoOverrideActive)return;let{workingOrder:r}=e();if(!r.location_id||!r.method_id)return;let o=Ce.getState().activePromotions,n=new Date,s=e().selectedPromotion;if(s&&Xa(s)==="private")return;let i=s?ur(s,r,n):0;if(s&&i===0){e().removeOrderPromotion();return}let a=bp(r,o,n);if(s){a.orderPromo&&a.orderPromo.id!==s.id&&a.discount>i&&!e().dismissedPromoIds?.includes(a.orderPromo.id)&&e().onBestPromoChange?.(a.orderPromo);return}if(a.itemDiscounts?.length?t(u=>{for(let c of u.workingOrder.items)c.display_price=void 0,c.applied_promo_id=void 0,c.discount_amount=void 0;for(let c of a.itemDiscounts){let d=u.workingOrder.items[c.itemIndex];d&&(d.applied_promo_id=c.promotionId,d.discount_amount=c.discount,d.display_price=d.price-Math.round(c.discount/d.quantity))}}):e().wipeItemPromos(),a.discount===0||!a.orderPromo)return;let l=e().workingOrder.items.reduce((u,c)=>u+(c.discount_amount??0),0);l===0?e().applyOrderPromotion(a.orderPromo):a.discount>l&&!e().dismissedPromoIds?.includes(a.orderPromo.id)&&e().onBestPromoChange?.(a.orderPromo)},setOnBestPromoChange:r=>{t(o=>(o.onBestPromoChange=r,o))},wipeItemPromos:()=>{t(r=>{r.workingOrder.items=r.workingOrder.items.map(o=>({...o,display_price:void 0,applied_promo_id:void 0,discount_amount:void 0}))})},applyOrderPromotion:r=>{t(o=>{o.selectedPromotion=r,o.workingOrder.promo_code=String(r.id)}),e().wipeItemPromos()},removeOrderPromotion:()=>{t(r=>{r.selectedPromotion=void 0,r.workingOrder.promo_code=void 0}),e().checkBestPromo()},overrideOrderPromotion:r=>{t(o=>{o.promoOverrideActive=!0}),r?e().applyOrderPromotion(r):(t(o=>{o.selectedPromotion=void 0,o.workingOrder.promo_code=void 0}),e().wipeItemPromos())}}))),{name:"cart",version:1,storage:(0,ln.createJSONStorage)(()=>kr()),skipHydration:xr,partialize:t=>({editingSourceOrder:t.editingSourceOrder,...sg&&{workingOrder:t.workingOrder,selectedTip:t.selectedTip,deliveryFeeCents:t.deliveryFeeCents}})})),te=ol;function ag(){let t=ol(o=>o.workingOrder),e=ol(o=>o.selectedPromotion),r=ol(o=>o.selectedTip??0);return(0,ng.useMemo)(()=>{let{subtotal:o,discount:n,tax:s,serviceFee:i,total:a}=sn(t,e,r);return{subtotal:o,discount:n,tax:s,serviceFee:i,total:a}},[t,e,r])}var ug=require("zustand");var $=require("zod");function Wt(t){return(t/100).toLocaleString("en-US",{style:"currency",currency:"USD"})}var Tx=$.z.object({email:$.z.email(),location_id:$.z.number().int().nullish()}),Cx=$.z.object({notification_emails:$.z.array(Tx).nullish(),minimum_notice_hours:$.z.number().int().nullish(),minimum_people_required:$.z.number().int().positive().nullish(),minimum_price:$.z.number().nonnegative().nullish(),does_cater:$.z.boolean().nullish(),preferred_time:$.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d:[0-5]\d$/,"expected HH:mm:ss").nullish()}),Ex=$.z.preprocess(t=>{if(t&&typeof t=="object"&&!Array.isArray(t)){let e=t;if(e.notification_email&&e.notification_emails==null){let{notification_email:r,...o}=e;return{...o,notification_emails:[{email:r,location_id:null}]}}}return t},Cx),Px=$.z.object({does_deliver:$.z.boolean().nullish(),delivery_fee_cents:$.z.number().int().nullish(),max_delivery_radius_miles:$.z.number().nullish(),cents_per_mile:$.z.number().int().nullish()}),Ox=$.z.object({key:$.z.string().min(1),enabled:$.z.boolean().default(!0),email:$.z.email().nullish(),label:$.z.string().nullish()}),Ax=$.z.object({forms:$.z.array(Ox).nullish()}),Rx=$.z.object({is_active:$.z.boolean().nullish(),full_discount_at:$.z.number().int().positive().nullish(),maximum_percent_off:$.z.number().min(0).max(1).nullish()}),Ix=$.z.object({key:$.z.string().min(1),label:$.z.string().min(1),description:$.z.string().nullish(),price_per_person_cents:$.z.number().int().nonnegative()}),Dx=$.z.object({base_price_per_person_cents:$.z.number().int().nonnegative(),default_service_hours:$.z.number().int().positive(),additional_hour_rate_cents:$.z.number().int().nonnegative(),service_fee_percent:$.z.number().min(0).max(100),sales_tax_percent:$.z.number().min(0).max(100),minimum_booking_fee_cents:$.z.number().int().nonnegative(),date_hold_deposit_cents:$.z.number().int().nonnegative(),add_ons:$.z.array(Ix).default([])}).refine(t=>new Set(t.add_ons.map(e=>e.key)).size===t.add_ons.length,{message:"add_on keys must be unique"}),Lx={catering:Ex,delivery:Px,contact:Ax,catering_bulk_discount:Rx,food_truck:Dx};async function fc(t,e,r=U){let{data:o}=await r.from("franchise_feature_config").select("config").eq("franchise_id",t).eq("feature",e).maybeSingle();return o?Lx[e].parse(o.config):null}var un=require("zustand/middleware");var gt=null,dr=null,fr=null,As=null;function Nx(t){return typeof t=="number"?{franchiseId:t}:t??{}}function lg(){return mc.getState().platform??"website"}var mc=(0,ug.create)()((0,un.persist)((0,un.devtools)((t,e)=>({logLevel:3,location_id:void 0,franchiseId:void 0,franchiseCateringConfig:{does_cater:null,minimum_notice_hours:null,minimum_people_required:null,minimum_price:null},franchiseDeliveryConfig:{does_deliver:null,delivery_fee_cents:null,max_delivery_radius_miles:null,cents_per_mile:null},platform:"website",visibilityMode:"editor",lastUpdatedAt:new Date(0),setFranchiseId:r=>t({franchiseId:r}),remoteMenuLastUpdated:async()=>{let{data:r,error:o}=await U.from("items").select("updated_at").order("updated_at",{ascending:!1}).limit(1).single();if(o)throw e().logLevel<=2&&console.warn(o,"error getting menu last updated"),new Error("error getting menu last updated");return!r||!r.updated_at?new Date(0):new Date(r.updated_at)},start:async r=>{let o=Nx(r),n=o.franchiseId??e().franchiseId??Y.getState().franchiseId;if(e().logLevel<=1&&console.debug("starting menu manager"),!n){e().logLevel<=3&&console.warn("franchise id is not set, cannot start menu manager");return}t({franchiseId:n}),o.platform&&t({platform:o.platform}),e().refreshLocalMenu(),e().menuChangeListener(),e().promotionsChangeListener()},items:[],hydrate:({items:r,categories:o,rules:n,components:s})=>t({items:r??[],categories:o??[],rules:n??[],components:s??[]},!1,"hydrate"),setItems:r=>{t({items:r})},addItem:r=>{t({items:[...e().items,r]})},updateItem:r=>{t({items:e().items.map(o=>o.base_item_id===r.base_item_id?r:o)})},deleteItem:r=>{t({items:e().items.filter(o=>o.base_item_id!==r)})},addVariant:(r,o)=>{t({items:e().items.map(n=>n.base_item_id===o?{...n,variants:[...n.variants,r]}:n)})},updateVariant:(r,o)=>{t({items:e().items.map(n=>n.base_item_id===o?{...n,variants:n.variants.map(s=>s.item_id===r.item_id?r:s)}:n)})},deleteVariant:(r,o)=>{t({items:e().items.map(n=>n.base_item_id===o?{...n,variants:n.variants.filter(s=>s.item_id!==r)}:n)})},categories:[],setCategories:r=>t({categories:r}),addCategory:r=>{t({categories:[...e().categories,r]})},updateCategory:r=>{t({categories:e().categories.map(o=>o.category_id===r.category_id?r:o)})},deleteCategory:r=>{t({categories:e().categories.filter(o=>o.category_id!==r)})},rules:[],setRules:r=>{t({rules:r})},addRule:r=>{t({rules:[...e().rules,r]})},updateRule:r=>{t({rules:e().rules.map(o=>o.rule_id===r.rule_id?r:o)})},deleteRule:r=>{t({rules:e().rules.filter(o=>o.rule_id!==r)})},components:[],setComponents:r=>{t({components:r})},addComponent:r=>{t({components:[...e().components,r]})},updateComponent:r=>{t({components:e().components.map(o=>o.id===r.id?r:o)})},deleteComponent:r=>{t({components:e().components.filter(o=>o.id!==r)})},isLocalMenuFresh:async()=>{let r=await e().remoteMenuLastUpdated(),o=e().lastUpdatedAt;return r>=o},refreshLocalMenu:async()=>{let r=e().franchiseId;if(!r){e().logLevel<=2&&console.warn("franchise id is not set, cannot refresh menu");return}let o=lg(),n=Y.getState().selectedLocation?.location_id||0;e().logLevel<=1&&console.log("[MenuStore] refreshing menu:",{franchiseId:r,locationId:n,platform:o});let s=await lp(U,r,n,o),i=ks(Ce.getState().allPromotions,o,n||void 0,new Date);Ce.setState({activePromotions:i});let[a,l,u]=await Promise.all([ip(U,r,s),fc(r,"catering"),fc(r,"delivery")]),{items:c,categories:d,rules:f,components:m}=ap(a,i);t({items:c,categories:d,rules:f,components:m,franchiseCateringConfig:l??{},franchiseDeliveryConfig:u??{}},!1,"refreshLocalMenu"),As||(As=setInterval(()=>{let h=Ce.getState().allPromotions;if(!h.length)return;let g=lg(),y=Y.getState().selectedLocation?.location_id??void 0,p=ks(h,g,y,new Date),b=Ce.getState().activePromotions;(p.length!==b.length||p.some((v,N)=>v.id!==b[N]?.id))&&e().refreshLocalMenu()},6e4)),t({lastUpdatedAt:new Date})},menuChangeListener:async()=>{let r=e().franchiseId;if(!r){e().logLevel<=2&&console.warn("[MenuStore] Cannot subscribe to menu changes without franchiseId");return}if(dr&&(clearTimeout(dr),dr=null),gt){try{gt.unsubscribe?.()}catch{}try{U.removeChannel?.(gt)}catch{}gt=null}let o=U.channel(`menu-changes-${r}`).on("postgres_changes",{event:"*",schema:"public",table:"items",filter:`franchise_id=eq.${r}`},()=>{e().refreshLocalMenu()});gt=o,o.subscribe(n=>{if(n==="SUBSCRIBED"){e().logLevel<=1&&console.log("[MenuStore] Subscribed to menu changes");return}if(n==="CLOSED"){e().logLevel<=1&&console.log(`[MenuStore] Subscription status: ${n}`);return}if(n!=="CHANNEL_ERROR"&&n!=="TIMED_OUT"){e().logLevel<=2&&console.warn(`[MenuStore] Subscription status: ${n}`);return}console.warn(`[MenuStore] Subscription status: ${n}. Reconnecting in 5s...`);try{gt?.unsubscribe?.()}catch{}try{U.removeChannel?.(gt)}catch{}gt=null,dr&&clearTimeout(dr),dr=setTimeout(()=>{e().menuChangeListener()},5e3)})},promotionsChangeListener:()=>{let r=e().franchiseId;if(!r)return;if(fr){try{fr.unsubscribe?.()}catch{}try{U.removeChannel?.(fr)}catch{}fr=null}fr=U.channel(`promotions-changes-${r}`).on("postgres_changes",{event:"*",schema:"public",table:"promotions",filter:`franchise_id=eq.${r}`},async()=>{let{data:n}=await U.from("promotions").select("*").eq("is_active",!0).eq("franchise_id",r);Ce.setState({allPromotions:n||[]}),e().refreshLocalMenu()}).subscribe()},cleanup:()=>{if(dr&&(clearTimeout(dr),dr=null),gt){try{gt.unsubscribe?.()}catch{}try{U.removeChannel?.(gt)}catch{}gt=null}if(fr){try{fr.unsubscribe?.()}catch{}try{U.removeChannel?.(fr)}catch{}fr=null}As&&(clearInterval(As),As=null)},setLastUpdatedAt:r=>t({lastUpdatedAt:r}),uploadMenuImage:async r=>{let o=Y.getState().franchiseId;if(!o)throw e().logLevel<=2&&console.warn("[MenuStore] Cannot upload menu image without franchiseId"),new Error("franchise id is not set");let n=`franchise_id_${o}/menu-${Date.now()}`,{error:s}=await U.storage.from("menu-images").upload(n,r);if(s)throw s;return n}}),{name:"MenuStore"}),{name:"menu",onRehydrateStorage:()=>(t,e)=>{if(e||!t)return;let r=t.items;mc.setState({items:r??[]})},storage:(0,un.createJSONStorage)(()=>kr()),skipHydration:xr}));var Ht=mc;var be=require("zod");var Pr=require("zod"),Pt=t=>({schema:t,actionable:!0}),jx=t=>typeof t=="object"&&t!==null&&t.actionable===!0;function Fe(t,e){let r={};for(let[o,n]of Object.entries(e)){let s=`${t}.${o}`;r[o]=n instanceof Pr.z.ZodType?{name:s,schema:n,actionable:!1}:jx(n)?{name:s,schema:n.schema,actionable:!0}:Fe(s,n)}return r}var Mx=t=>typeof t=="object"&&t!==null&&"name"in t&&t.schema instanceof Pr.z.ZodType;function nl(t,e=[]){if(Mx(t))return e.push(t),e;if(t&&typeof t=="object")for(let r of Object.values(t))nl(r,e);return e}if(process.env.NODE_ENV!=="production"){let t=Fe("order",{placed:Pr.z.object({orderId:Pr.z.number()}),catering:{placed:Pt(Pr.z.object({orderId:Pr.z.number(),headcount:Pr.z.number()}))}}),e=(r,o)=>{if(!r)throw new Error(`define.ts assert: ${o}`)};e(t.placed.name==="order.placed","leaf name"),e(t.catering.placed.name==="order.catering.placed","nested name"),e(t.placed.schema.safeParse({orderId:1}).success,"leaf schema parses"),e(t.catering.placed.schema.safeParse({orderId:1,headcount:2}).success,"marked schema parses"),e(t.placed.actionable===!1,"bare leaf is not actionable"),e(t.catering.placed.actionable===!0,"marked leaf is actionable"),e(nl(t).length===2,"descriptorsIn walks nested"),console.log("define.ts ok")}var W=require("zod");var co={franchiseId:W.z.number(),locationId:W.z.number()},cn={placed:W.z.object({orderId:W.z.number(),...co,total:W.z.number(),itemCount:W.z.number().int()}),requested:W.z.object({orderId:W.z.number(),...co}),confirmed:W.z.object({orderId:W.z.number(),...co,via:W.z.enum(["pos","email_link","dashboard"]),userId:W.z.string().optional(),deviceId:W.z.number().optional()}),paid:W.z.object({orderId:W.z.number(),...co,paymentMethod:W.z.string()}),completed:W.z.object({orderId:W.z.number(),...co}),canceled:W.z.object({orderId:W.z.number(),...co,reason:W.z.string().nullable()})},cg=Fe("order",{...cn,placed:Pt(cn.placed),completed:Pt(cn.completed),failed:W.z.object({orderId:W.z.number().nullable(),total:W.z.number(),reason:W.z.string(),phase:W.z.enum(["create","modify","refund","complete","kitchen_complete"]).optional()}),confirmation_email_sent:W.z.object({orderId:W.z.number(),recipient:W.z.string()}),realtime_disconnected:W.z.object({status:W.z.string(),location_id:W.z.number().nullable()}),catering:{...cn,requested:Pt(cn.requested),confirmed:Pt(cn.confirmed),charge_failed:Pt(W.z.object({orderId:W.z.number(),...co,chargeId:W.z.number()}))}});var zt=require("zod");var hc={franchiseId:zt.z.number(),locationId:zt.z.number()},dg=Fe("inventory",{stock_changed:Pt(zt.z.object(hc)),ingredient_added:Pt(zt.z.object({...hc,locationIngredientId:zt.z.number(),ingredientName:zt.z.string()})),component_added:Pt(zt.z.object({...hc,locationComponentId:zt.z.number(),componentName:zt.z.string()}))});var Ae=require("zod");var fg=Fe("payment",{captured:Ae.z.object({orderId:Ae.z.number(),amount:Ae.z.number(),method:Ae.z.string()}),failed:Ae.z.object({orderId:Ae.z.number(),amount:Ae.z.number(),method:Ae.z.string(),reason:Ae.z.string(),phase:Ae.z.enum(["create_payment_intent","retrieve_payment_intent","collect_payment_method","confirm_payment_intent","unexpected"]).optional(),code:Ae.z.string().nullable().optional(),decline_code:Ae.z.string().nullable().optional(),payment_intent_id:Ae.z.string().nullable().optional()}),refunded:Ae.z.object({orderId:Ae.z.number(),amount:Ae.z.number(),method:Ae.z.string()})});var B=require("zod");var Re=require("zod"),mg=["healthy","degraded","unhealthy","offline"];function Ze(t,e){return{severity:t,detail:e}}function pc(t){let e=Object.fromEntries(Object.entries(t).map(([r,o])=>[r,Re.z.object({healthy:Re.z.boolean(),detail:(o.detail??Re.z.unknown()).optional()})]));return Re.z.object(e)}var gc={pos:{authenticated:Ze("critical"),menu_loaded:Ze("critical"),reader_connected:Ze("critical"),printer_connected:Ze("critical"),order_listener:Ze("critical"),battery_healthy:Ze("warning",Re.z.object({percentage:Re.z.number()}))},kiosk:{authenticated:Ze("critical"),menu_loaded:Ze("critical"),reader_connected:Ze("critical"),battery_healthy:Ze("warning",Re.z.object({percentage:Re.z.number()}))},kitchen_display:{authenticated:Ze("critical"),order_listener:Ze("critical"),battery_healthy:Ze("warning",Re.z.object({percentage:Re.z.number()}))}},OU=Re.z.discriminatedUnion("platform",[Re.z.object({platform:Re.z.literal("pos"),checks:pc(gc.pos)}),Re.z.object({platform:Re.z.literal("kiosk"),checks:pc(gc.kiosk)}),Re.z.object({platform:Re.z.literal("kitchen_display"),checks:pc(gc.kitchen_display)})]);var hg=B.z.enum(mg),pg=Fe("device",{status_changed:B.z.object({from:hg.nullable(),to:hg,reason:B.z.string().nullable()}),check_failed:B.z.object({check_key:B.z.string(),reason:B.z.string()}),check_recovered:B.z.object({check_key:B.z.string()}),auth_failed:B.z.object({phase:B.z.enum(["init","verify_403"]),reason:B.z.string()}),connection_error:B.z.object({reason:B.z.string()}),verified:B.z.object({device_id:B.z.number()}),printer_disconnected:B.z.object({printer_id:B.z.string(),reason:B.z.string()}),print_failed:B.z.object({printer_id:B.z.string().nullable(),job_type:B.z.string(),reason:B.z.string(),order_id:B.z.number().nullable(),timings:Hu}),print_succeeded:B.z.object({printer_id:B.z.string().nullable(),job_type:B.z.string(),order_id:B.z.number().nullable(),timings:Hu}),reader_connected:B.z.object({reader_serial:B.z.string().nullable()}),reader_disconnected:B.z.object({reader_serial:B.z.string().nullable(),reason:B.z.string()}),reader_connect_failed:B.z.object({reader_serial:B.z.string().nullable(),reason:B.z.string()}),order_received:B.z.object({orderId:B.z.number(),method_id:B.z.number().nullable()}),order_acknowledged:B.z.object({orderId:B.z.number(),method_id:B.z.number().nullable()})});var ce=require("zod");var dn=Fe("api",{supabase_failed:ce.z.object({table:ce.z.string(),op:ce.z.string(),code:ce.z.string().nullable(),message:ce.z.string()}),unhandled:ce.z.object({message:ce.z.string(),where:ce.z.string().nullable()}),rate_limited:ce.z.object({path:ce.z.string(),method:ce.z.string(),retryAfterMs:ce.z.number().nullable()}),timeout:ce.z.object({path:ce.z.string(),method:ce.z.string(),durationMs:ce.z.number()}),log_invalid_payload:ce.z.object({event:ce.z.string(),issues:ce.z.string()}),log_enqueue_failed:ce.z.object({event:ce.z.string(),message:ce.z.string()})});var se=require("zod");var gg=se.z.object({source:se.z.string().optional(),medium:se.z.string().optional(),campaign:se.z.string().optional()}),mr=Fe("website",{session_started:se.z.object({landing_page:se.z.string(),referrer:se.z.string().optional(),utm:gg.optional()}),session_ended:se.z.object({duration_ms:se.z.number(),pages_visited:se.z.number()}),page_viewed:se.z.object({path:se.z.string(),referrer:se.z.string().optional(),utm:gg.optional()}),page_exited:se.z.object({path:se.z.string(),duration_ms:se.z.number()}),short_url_clicked:se.z.object({slug:se.z.string(),referrer:se.z.string().optional(),run_id:se.z.string().uuid().optional(),outbound_message_id:se.z.string().uuid().optional(),strategy_id:se.z.string().optional(),strategy_variant_id:se.z.string().optional(),dry_run:se.z.boolean().optional()})});var hr=require("zod");var yg=Fe("integration",{pushed:hr.z.object({orderId:hr.z.number(),provider:hr.z.string(),externalId:hr.z.string()}),failed:hr.z.object({orderId:hr.z.number(),provider:hr.z.string(),reason:hr.z.string()})});var JU=new Set(nl([cg,dg,fg,pg,dn,mr,yg]).filter(t=>t.actionable).map(t=>t.name));var rF=be.z.object({id:be.z.number(),created_at:be.z.string(),severity:be.z.enum(["debug","info","warn","error"]),event_name:be.z.string(),source:Qh,service:be.z.string().nullable(),device_id:be.z.number().nullable(),session_id:be.z.string().nullable(),request_id:be.z.string().nullable(),franchise_id:be.z.number().nullable(),location_id:be.z.number().nullable(),user_id:be.z.string().nullable(),anonymous_id:be.z.string().nullable(),customer_id:be.z.number().nullable(),order_id:be.z.number().nullable(),payload:be.z.record(be.z.string(),be.z.unknown()),stack_trace:be.z.string().nullable()}),Ux=()=>({}),bg=null,oF=new Proxy({},{get(t,e){return bg?.[e]??(()=>{})}});function _g(t){let{source:e,getContext:r=Ux,dev:o=!1}=t,n=(i,a,l,u,c)=>{let d=a.schema.safeParse(l);if(!d.success){console.error(`[log] invalid payload for ${a.name}:`,d.error.issues),a.name!==dn.log_invalid_payload.name&&n("error",dn.log_invalid_payload,{event:a.name,issues:JSON.stringify(d.error.issues)});return}let f=r(),m=i==="error"?(u instanceof Error?u.stack:null)??new Error().stack??null:null;if(o){console.log(`[${i}] ${a.name}`,d.data);return}qt("/events",{method:"POST",body:JSON.stringify({severity:i,event_name:a.name,source:e,session_id:f.session_id??null,request_id:c?.request_id??f.request_id??null,location_id:f.location_id??null,franchise_id:f.franchise_id??null,anonymous_id:f.anonymous_id??null,customer_id:f.customer_id??null,payload:d.data,stack_trace:m})}).then(h=>{h.ok||h.text().then(g=>console.error(`[log] POST /events ${h.status} for ${a.name}:`,g))}).catch(h=>{console.error(`[log] POST /events failed for ${a.name}:`,h)})},s={info:(i,a,l)=>n("info",i,a,void 0,l),warn:(i,a,l)=>n("warn",i,a,void 0,l),error:(i,a,l,u)=>n("error",i,a,l,u)};return bg=s,s}var fo=class{diff(e,r,o={}){let n;typeof o=="function"?(n=o,o={}):"callback"in o&&(n=o.callback);let s=this.castInput(e,o),i=this.castInput(r,o),a=this.removeEmpty(this.tokenize(s,o)),l=this.removeEmpty(this.tokenize(i,o));return this.diffWithOptionsObj(a,l,o,n)}diffWithOptionsObj(e,r,o,n){var s;let i=b=>{if(b=this.postProcess(b,o),n){setTimeout(function(){n(b)},0);return}else return b},a=r.length,l=e.length,u=1,c=a+l;o.maxEditLength!=null&&(c=Math.min(c,o.maxEditLength));let d=(s=o.timeout)!==null&&s!==void 0?s:1/0,f=Date.now()+d,m=[{oldPos:-1,lastComponent:void 0}],h=this.extractCommon(m[0],r,e,0,o);if(m[0].oldPos+1>=l&&h+1>=a)return i(this.buildValues(m[0].lastComponent,r,e));let g=-1/0,y=1/0,p=()=>{for(let b=Math.max(g,-u);b<=Math.min(y,u);b+=2){let _,v=m[b-1],N=m[b+1];v&&(m[b-1]=void 0);let x=!1;if(N){let Z=N.oldPos-b;x=N&&0<=Z&&Z<a}let P=v&&v.oldPos+1<l;if(!x&&!P){m[b]=void 0;continue}if(!P||x&&v.oldPos<N.oldPos?_=this.addToPath(N,!0,!1,0,o):_=this.addToPath(v,!1,!0,1,o),h=this.extractCommon(_,r,e,b,o),_.oldPos+1>=l&&h+1>=a)return i(this.buildValues(_.lastComponent,r,e))||!0;m[b]=_,_.oldPos+1>=l&&(y=Math.min(y,b-1)),h+1>=a&&(g=Math.max(g,b+1))}u++};if(n)(function b(){setTimeout(function(){if(u>c||Date.now()>f)return n(void 0);p()||b()},0)})();else for(;u<=c&&Date.now()<=f;){let b=p();if(b)return b}}addToPath(e,r,o,n,s){let i=e.lastComponent;return i&&!s.oneChangePerToken&&i.added===r&&i.removed===o?{oldPos:e.oldPos+n,lastComponent:{count:i.count+1,added:r,removed:o,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+n,lastComponent:{count:1,added:r,removed:o,previousComponent:i}}}extractCommon(e,r,o,n,s){let i=r.length,a=o.length,l=e.oldPos,u=l-n,c=0;for(;u+1<i&&l+1<a&&this.equals(o[l+1],r[u+1],s);)u++,l++,c++,s.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return c&&!s.oneChangePerToken&&(e.lastComponent={count:c,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=l,u}equals(e,r,o){return o.comparator?o.comparator(e,r):e===r||!!o.ignoreCase&&e.toLowerCase()===r.toLowerCase()}removeEmpty(e){let r=[];for(let o=0;o<e.length;o++)e[o]&&r.push(e[o]);return r}castInput(e,r){return e}tokenize(e,r){return Array.from(e)}join(e){return e.join("")}postProcess(e,r){return e}get useLongestToken(){return!1}buildValues(e,r,o){let n=[],s;for(;e;)n.push(e),s=e.previousComponent,delete e.previousComponent,e=s;n.reverse();let i=n.length,a=0,l=0,u=0;for(;a<i;a++){let c=n[a];if(c.removed)c.value=this.join(o.slice(u,u+c.count)),u+=c.count;else{if(!c.added&&this.useLongestToken){let d=r.slice(l,l+c.count);d=d.map(function(f,m){let h=o[u+m];return h.length>f.length?h:f}),c.value=this.join(d)}else c.value=this.join(r.slice(l,l+c.count));l+=c.count,c.added||(u+=c.count)}}return n}};var yc=class extends fo{constructor(){super(...arguments),this.tokenize=bc}equals(e,r,o){return o.ignoreWhitespace?((!o.newlineIsToken||!e.includes(`
|
|
153
|
+
`).or(u).order("sort_index",Tr).order("rule_id",Tr);if(h)throw h;return(m??[]).map(g=>({rule_id:g.rule_id,group_name:g.group_name,min_selection:g.min_selection,max_selection:g.max_selection,included_quantity:g.included_quantity,is_portionable:g.is_portionable,category_id:g.category_id,item_id:g.item_id,base_item_id:g.base_item_id,sort_index:g.sort_index??null,components:(g.rule_components??[]).map(y=>({component_id:y.component_id,upcharge_price:y.upcharge_price??0,name:y.components?.name??"",description:y.components?.description??void 0,serving_weight:y.components?.serving_weight??void 0,sort_index:y.sort_index??null,...n&&{behavior:y.component_quantity_behaviors??void 0}})).sort(Xu),items:(g.rule_items??[]).map(y=>({item_id:y.item_id,name:y.items?.name??"",description:y.items?.description??void 0,upcharge_price:y.upcharge_price??0,sort_index:y.sort_index??null,...n&&{behavior:y.component_quantity_behaviors??void 0}})).sort(Xu)}))}function Yu(t,e,r,o,n){let s={items:[],categories:[],rules:n,components:o};return s.items=e.map(i=>{let a=n.filter(c=>c.category_id===i.category_id),l=n.filter(c=>c.base_item_id===i.base_item_id),u=r.find(c=>c.category_id===i.category_id);return{...i,is_catering:u?.is_catering??!1,variants:t.filter(c=>c.base_item_id===i.base_item_id).map(c=>({...c,components:o.filter(d=>d.item_id===c.item_id),rules:[...a,...l,...n.filter(d=>d.item_id===c.item_id)]})),rules:l}}),s.categories=r.map(i=>({...i,rules:n.filter(a=>a.category_id===i.category_id)})),s}function ks(t,e,r,o=new Date){return t.filter(n=>{if(n.start_date&&new Date(n.start_date)>o||n.end_date&&new Date(n.end_date)<o||n.platforms&&n.platforms.length>0&&!n.platforms.includes(e)||!n.is_automatic)return!1;if(n.location_id!=null&&r!==void 0){if(n.location_id!==r)return!1}else if(n.location_id!=null&&r===void 0)return!1;if(n.schedule_details_json){let{interval:s,days:i,start_time:a,end_time:l}=n.schedule_details_json;if(s==="weekly"&&i&&!i.includes(la(o)+1))return!1;let u=Et(o);if(a&&Ge(o,Qe(a,"HH:mm",u))||l&&$t(o,Qe(l,"HH:mm",u)))return!1}return!0})}var Qu=null;function dp(t){Qu=t}async function jS(){if(!Qu)throw new Error("apiFetch called before registerTokenProvider");return Qu()}async function qt(t,e={}){let r=await jS(),o={...e.headers};return o["x-request-id"]||(o["x-request-id"]=xs()),fetch(`${Ki}${t}`,{...e,headers:{"Content-Type":"application/json",...r&&{Authorization:`Bearer ${r}`},...o}})}function Vt(t){let[e,r]=t.split("/").map(Number);return{index:e,divisions:r}}function Ts(t){return t?1/Vt(t).divisions:1}function uo(t,e){return e?`${t}@${e}`:t}function ht(t){let e=t.indexOf("@");return e===-1?{baseKey:t,portion:null}:{baseKey:t.slice(0,e),portion:t.slice(e+1)}}function MS(t,e){return Math.ceil(t/e)}function US(t){let{min_divisions:e,max_divisions:r}=t;return Array.from({length:r-e+1},(o,n)=>e+n)}var FS={radial:{2:["Left","Right"],4:["Top left","Bottom left","Bottom right","Top right"]},grid:{2:["Left","Right"],4:["Top left","Bottom left","Top right","Bottom right"]},linear:{2:["First half","Second half"]},count:{2:["First half","Second half"]}};function $S(t,e){if(!t)return"Whole";let{index:r,divisions:o}=Vt(t);return FS[e.geometry][o]?.[r-1]??`Part ${r} of ${o}`}function Zu(t,e,r){let o=e[t]??r,n=Object.entries(e).flatMap(([a,l])=>{let u=ht(a);return u.baseKey===t&&u.portion?[{portion:u.portion,value:l}]:[]});if(!n.length)return[{portion:null,value:o}];let{divisions:s}=Vt(n[0].portion),i=Array.from({length:s},(a,l)=>{let u=`${l+1}/${s}`;return{portion:u,value:n.find(c=>c.portion===u)?.value??o}});return i.every(a=>a.value===i[0].value)?[{portion:null,value:i[0].value}]:i}function Qa(t){return t.reduce((e,r)=>e+Ts(ht(r).portion),0)}function ec(t,e,r){let o=new Map,n=new Map;for(let s of t){let{baseKey:i,portion:a}=ht(s);n.has(i)||n.set(i,n.size),o.set(s,n.get(i)<r?0:Math.ceil(e(i)*Ts(a)))}return o}function tc(t,e){let{index:r,divisions:o}=Vt(t);if(o===e)return[t];if(e%o===0){let n=e/o,s=(r-1)*n+1;return Array.from({length:n},(i,a)=>`${s+a}/${e}`)}return o%e===0?[`${Math.ceil(r*e/o)}/${e}`]:null}function mp(t){if(!t)return"Whole";let{index:e,divisions:r}=Vt(t);return`Section ${e} of ${r}`}var BS={radial:"\u25CF",grid:"\u25A0",linear:"\u25A0",count:null},qS={radial:{2:["\u25D0","\u25D1"]},grid:{2:["\u25E7","\u25E8"]},linear:{2:["\u25E7","\u25E8"]},count:{}};function hp(t,e){if(!e)return null;if(!t)return BS[e];let{index:r,divisions:o}=Vt(t);return qS[e][o]?.[r-1]??null}function VS(t){let e=t.portion_scheme?.geometry,r=new Map,o=s=>{let i=s??"",a=r.get(i);return a||r.set(i,a={selections:[],removals:[],additions:[]}),a};for(let s of t.selections??[])for(let i of s.selections){let{selections:a}=o(i.portion),l=a.find(u=>u.rule_id===s.rule_id);l||a.push(l={...s,selections:[]}),l.selections.push(i)}for(let s of t.components??[])s.quantity_servings<=0?o(s.portion).removals.push(s):s.portion&&o(s.portion).additions.push(s);let n=s=>s?Vt(s).index:-1;return[...r.entries()].sort(([s],[i])=>n(s)-n(i)).map(([s,i])=>({portion:s||null,label:mp(s||null),glyph:hp(s||null,e),...i}))}var fp=t=>Math.round(t*100)/100;function WS(t,e,r=48){if(e===1)return`M 50 ${50-r} A ${r} ${r} 0 1 0 49.9 ${50-r} Z`;let o=2*Math.PI/e,n=-Math.PI/2-(t-1)*o,s=n-o,i=a=>`${fp(50+r*Math.cos(a))} ${fp(50+r*Math.sin(a))}`;return`M 50 50 L ${i(n)} A ${r} ${r} 0 ${o>Math.PI?1:0} 0 ${i(s)} Z`}function pp(t,e){return t.map(r=>!e.discount_target_type||e.discount_target_type==="item"&&r.base_item_id!=null&&e.discount_target_ids?.includes(r.base_item_id)||e.discount_target_type==="item_variant"&&e.discount_target_ids?.includes(r.item_id)||e.discount_target_type==="category"&&e.discount_target_ids?.includes(r.category_id)?{...r,applied_promo_id:e.id}:r)}function gp(t){switch(t){case 1:return"Kiosk";case 2:return"Website";case 3:return"POS";default:return""}}function yp(t){let{max_selection:e,min_selection:r}=t,o=e!=null&&e!==1/0,n=t.included_quantity??0,s=o?r===e?`Choose ${r}`:r>0?`Choose ${r} to ${e}`:`Choose up to ${e}`:r>0?`Choose at least ${r}`:"Choose any";return n>0?`${s}. ${n} included`:s}function rc(t,e,r,o){let n=o/2,s=Math.log(99)/(o-n),i=1/(1+Math.exp(-s*(e-n))),a=1/(1+Math.exp(s*n)),l=(i-a)/(1-a);return t*(1-r*l)}var HS=.06;var zS=.02,GS=.015;function KS(t,e,r=!1){return e!==2?0:Math.floor(r?GS*t:zS*t)}function Cr(t,e=!1){let r=e?t.display_price||0:t.price||0,o=t.selections?.reduce((s,i)=>s+i.selections.reduce((a,l)=>a+l.upcharge,0),0)||0;return(r+o)*t.quantity}function nn({order:t}){return t.items.filter(e=>e.status!=="removed").reduce((e,r)=>e+Cr(r),0)}function JS(t,e){let r=nn({order:t}),{discount:o}=QS(t,e),n=r-o,s=ZS(n),i=KS(n,t.method_id,t.is_catering??!1),a=n+s+i;return{subtotal:r,tax:s,service_fee:i,discount:o,total:a}}function sn(t,e,r=0){let o=YS(t.charges),{subtotal:n,discount:s,tax:i,service_fee:a,total:l}=o.length?XS(o):JS(t,e);return{lines:t.items.filter(u=>u.status!=="removed").map(u=>({name:u.name,quantity:u.quantity,basePrice:u.price||0,unitPrice:Cr({...u,quantity:1}),lineTotal:Cr(u),perPerson:u.per_person,addOns:(u.selections??[]).flatMap(c=>c.selections.map(d=>({name:d.name,groupName:c.group_name,upcharge:d.upcharge})))})),subtotal:n,discount:s??0,tax:i,serviceFee:a??0,tip:r,total:l+r}}function YS(t){return(t??[]).filter(e=>e.charge_status===1)}function XS(t){return(Array.isArray(t)?t:[]).reduce((r,o)=>({subtotal:r.subtotal+o.subtotal,tax:r.tax+o.tax,tip:(r.tip||0)+(o.tip||0),discount:(r.discount||0)+(o.discount||0),service_fee:(r.service_fee||0)+(o.service_fee||0),total:r.total+o.total}),{subtotal:0,tax:0,tip:0,discount:0,service_fee:0,total:0})}function ur(t,e,r){if(!e.method_id)throw new Error("Attach method_id to order to calculate promo discount.");if(!e.location_id)throw new Error("Attach location_id to order to calculate promo discount.");if(!t.is_active)return 0;let o=gp(e.method_id).toLowerCase();if(t.platforms&&t.platforms.length>0&&!t.platforms.includes(o)||t.location_id&&t.location_id!==e.location_id||t.start_date&&Ge(r,new Date(t.start_date))||t.end_date&&$t(r,new Date(t.end_date)))return 0;if(t.schedule_details_json){let{interval:d,days:f,start_time:m,end_time:h}=t.schedule_details_json;if(d==="weekly"&&f&&!f.includes(la(r)+1))return 0;let g=Et(r);if(m){let y=Qe(m,"HH:mm",g);if(Ge(r,y))return 0}if(h){let y=Qe(h,"HH:mm",g);if($t(r,y))return 0}}let n=e.is_catering||e.items.some(d=>d.is_catering);if(t.is_catering_only&&!n)return 0;let s=nn({order:e});if(t.min_purchase_amount&&s<t.min_purchase_amount)return 0;let i=e.items.reduce((d,f)=>d+f.quantity,0),a=t.is_catering_only&&t.min_purchase_quantity;if(!a&&t.min_purchase_quantity&&i<t.min_purchase_quantity)return 0;let l=e.items,u=s;if(t.discount_target_type&&t.discount_target_ids?.length&&(l=e.items.filter(d=>t.discount_target_type==="category"?t.discount_target_ids.includes(d.category_id):t.discount_target_type==="item"?t.discount_target_ids.includes(d.base_item_id):t.discount_target_type==="item_variant"?t.discount_target_ids.includes(d.item_id):!1),u=l.reduce((d,f)=>d+Cr(f),0)),l.length===0)return 0;let c=0;if(a&&t.promotion_type_id===1){let d=l.reduce((m,h)=>m+h.quantity,0),f=rc(u,d,t.discount_value/100,t.min_purchase_quantity);c=u-f}else t.promotion_type_id===1?c=u*(t.discount_value/100):t.promotion_type_id===2&&(c=t.discount_value);return Math.min(Math.floor(c),u)}function Za(t){return t.is_automatic?t.discount_target_type?"item":"order":"private"}function bp(t,e,r){if(!e.length)return{discount:0};let o,n=0;for(let u of e){if(Za(u)!=="order")continue;let c=ur(u,t,r);c>n&&(n=c,o=u)}let s=t.items.filter(u=>u.status!=="removed"),i=e.filter(u=>Za(u)==="item"),a=[];i.length>0&&s.forEach((u,c)=>{let d=0,f;for(let m of i){let h={...t,items:[u]},g=ur(m,h,r);g>d&&(d=g,f=m.id)}d>0&&f!==void 0&&a.push({itemIndex:c,itemId:u.item_id,promotionId:f,discount:d})});let l=a.reduce((u,c)=>u+c.discount,0);return n===0&&l===0?{discount:0}:n>=l?{discount:n,orderPromo:o}:{discount:l,itemDiscounts:a}}function QS(t,e,r=new Date){if(e)try{let n=ur(e,t,r);return{name:e.name,discount:n}}catch{return{name:e.name,discount:0}}let o=t.items.reduce((n,s)=>n+(s.discount_amount??0),0);return o>0?{name:"Item discounts",discount:o}:{discount:0}}function ZS(t){return Math.round(t*HS)}var $p=require("zustand");function oc(t,e,r){let o=ua(),n=rx(t,r.timeZone,r.locale??o.locale);return"formatToParts"in n?ex(n,e):tx(n,e)}function ex(t,e){let r=t.formatToParts(e);for(let o=r.length-1;o>=0;--o)if(r[o].type==="timeZoneName")return r[o].value}function tx(t,e){let r=t.format(e).replace(/\u200E/g,""),o=/ [\w-+ ]+$/.exec(r);return o?o[0].substr(1):""}function rx(t,e,r){return new Intl.DateTimeFormat(r?[r.code,"en-US"]:void 0,{timeZone:e,timeZoneName:t})}function wp(t,e){let r=ax(e);return"formatToParts"in r?nx(r,t):sx(r,t)}var ox={year:0,month:1,day:2,hour:3,minute:4,second:5};function nx(t,e){try{let r=t.formatToParts(e),o=[];for(let n=0;n<r.length;n++){let s=ox[r[n].type];s!==void 0&&(o[s]=parseInt(r[n].value,10))}return o}catch(r){if(r instanceof RangeError)return[NaN];throw r}}function sx(t,e){let r=t.format(e),o=/(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(r);return[parseInt(o[3],10),parseInt(o[1],10),parseInt(o[2],10),parseInt(o[4],10),parseInt(o[5],10),parseInt(o[6],10)]}var nc={},_p=new Intl.DateTimeFormat("en-US",{hourCycle:"h23",timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).format(new Date("2014-06-25T04:00:00.123Z")),ix=_p==="06/25/2014, 00:00:00"||_p==="\u200E06\u200E/\u200E25\u200E/\u200E2014\u200E \u200E00\u200E:\u200E00\u200E:\u200E00";function ax(t){return nc[t]||(nc[t]=ix?new Intl.DateTimeFormat("en-US",{hourCycle:"h23",timeZone:t,year:"numeric",month:"numeric",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}):new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:t,year:"numeric",month:"numeric",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})),nc[t]}function Cs(t,e,r,o,n,s,i){let a=new Date(0);return a.setUTCFullYear(t,e,r),a.setUTCHours(o,n,s,i),a}var vp=36e5,lx=6e4,sc={timezone:/([Z+-].*)$/,timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function cr(t,e,r){if(!t)return 0;let o=sc.timezoneZ.exec(t);if(o)return 0;let n,s;if(o=sc.timezoneHH.exec(t),o)return n=parseInt(o[1],10),Sp(n)?-(n*vp):NaN;if(o=sc.timezoneHHMM.exec(t),o){n=parseInt(o[2],10);let i=parseInt(o[3],10);return Sp(n,i)?(s=Math.abs(n)*vp+i*lx,o[1]==="+"?-s:s):NaN}if(dx(t)){e=new Date(e||Date.now());let i=r?e:ux(e),a=ic(i,t);return-(r?a:cx(e,a,t))}return NaN}function ux(t){return Cs(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds())}function ic(t,e){let r=wp(t,e),o=Cs(r[0],r[1]-1,r[2],r[3]%24,r[4],r[5],0).getTime(),n=t.getTime(),s=n%1e3;return n-=s>=0?s:1e3+s,o-n}function cx(t,e,r){let n=t.getTime()-e,s=ic(new Date(n),r);if(e===s)return e;n-=s-e;let i=ic(new Date(n),r);return s===i?s:Math.max(s,i)}function Sp(t,e){return-23<=t&&t<=23&&(e==null||0<=e&&e<=59)}var xp={};function dx(t){if(xp[t])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:t}),xp[t]=!0,!0}catch{return!1}}var fx=60*1e3,Tp={X:function(t,e,r){let o=ac(r.timeZone,t);if(o===0)return"Z";switch(e){case"X":return kp(o);case"XXXX":case"XX":return an(o);default:return an(o,":")}},x:function(t,e,r){let o=ac(r.timeZone,t);switch(e){case"x":return kp(o);case"xxxx":case"xx":return an(o);default:return an(o,":")}},O:function(t,e,r){let o=ac(r.timeZone,t);switch(e){case"O":case"OO":case"OOO":return"GMT"+mx(o,":");default:return"GMT"+an(o,":")}},z:function(t,e,r){switch(e){case"z":case"zz":case"zzz":return oc("short",t,r);default:return oc("long",t,r)}}};function ac(t,e){let r=t?cr(t,e,!0)/fx:e?.getTimezoneOffset()??0;if(Number.isNaN(r))throw new RangeError("Invalid time zone specified: "+t);return r}function el(t,e){let r=t<0?"-":"",o=Math.abs(t).toString();for(;o.length<e;)o="0"+o;return r+o}function an(t,e=""){let r=t>0?"-":"+",o=Math.abs(t),n=el(Math.floor(o/60),2),s=el(Math.floor(o%60),2);return r+n+e+s}function kp(t,e){return t%60===0?(t>0?"-":"+")+el(Math.abs(t)/60,2):an(t,e)}function mx(t,e=""){let r=t>0?"-":"+",o=Math.abs(t),n=Math.floor(o/60),s=o%60;return s===0?r+String(n):r+String(n)+e+el(s,2)}function lc(t){let e=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return e.setUTCFullYear(t.getFullYear()),+t-+e}var tl=/(Z|[+-]\d{2}(?::?\d{2})?| UTC| [a-zA-Z]+\/[a-zA-Z_]+(?:\/[a-zA-Z_]+)?)$/;var uc=36e5,Cp=6e4,hx=2,qe={dateTimePattern:/^([0-9W+-]+)(T| )(.*)/,datePattern:/^([0-9W+-]+)(.*)/,plainTime:/:/,YY:/^(\d{2})$/,YYY:[/^([+-]\d{2})$/,/^([+-]\d{3})$/,/^([+-]\d{4})$/],YYYY:/^(\d{4})/,YYYYY:[/^([+-]\d{4})/,/^([+-]\d{5})/,/^([+-]\d{6})/],MM:/^-(\d{2})$/,DDD:/^-?(\d{3})$/,MMDD:/^-?(\d{2})-?(\d{2})$/,Www:/^-?W(\d{2})$/,WwwD:/^-?W(\d{2})-?(\d{1})$/,HH:/^(\d{2}([.,]\d*)?)$/,HHMM:/^(\d{2}):?(\d{2}([.,]\d*)?)$/,HHMMSS:/^(\d{2}):?(\d{2}):?(\d{2}([.,]\d*)?)$/,timeZone:tl};function pt(t,e={}){if(arguments.length<1)throw new TypeError("1 argument required, but only "+arguments.length+" present");if(t===null)return new Date(NaN);let r=e.additionalDigits==null?hx:Number(e.additionalDigits);if(r!==2&&r!==1&&r!==0)throw new RangeError("additionalDigits must be 0, 1 or 2");if(t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]")return new Date(t.getTime());if(typeof t=="number"||Object.prototype.toString.call(t)==="[object Number]")return new Date(t);if(Object.prototype.toString.call(t)!=="[object String]")return new Date(NaN);let o=px(t),{year:n,restDateString:s}=gx(o.date,r),i=yx(s,n);if(i===null||isNaN(i.getTime()))return new Date(NaN);if(i){let a=i.getTime(),l=0,u;if(o.time&&(l=bx(o.time),l===null||isNaN(l)))return new Date(NaN);if(o.timeZone||e.timeZone){if(u=cr(o.timeZone||e.timeZone,new Date(a+l)),isNaN(u))return new Date(NaN)}else u=lc(new Date(a+l)),u=lc(new Date(a+l+u));return new Date(a+l+u)}else return new Date(NaN)}function px(t){let e={},r=qe.dateTimePattern.exec(t),o;if(r?(e.date=r[1],o=r[3]):(r=qe.datePattern.exec(t),r?(e.date=r[1],o=r[2]):(e.date=null,o=t)),o){let n=qe.timeZone.exec(o);n?(e.time=o.replace(n[1],""),e.timeZone=n[1].trim()):e.time=o}return e}function gx(t,e){if(t){let r=qe.YYY[e],o=qe.YYYYY[e],n=qe.YYYY.exec(t)||o.exec(t);if(n){let s=n[1];return{year:parseInt(s,10),restDateString:t.slice(s.length)}}if(n=qe.YY.exec(t)||r.exec(t),n){let s=n[1];return{year:parseInt(s,10)*100,restDateString:t.slice(s.length)}}}return{year:null}}function yx(t,e){if(e===null)return null;let r,o,n;if(!t||!t.length)return r=new Date(0),r.setUTCFullYear(e),r;let s=qe.MM.exec(t);if(s)return r=new Date(0),o=parseInt(s[1],10)-1,Pp(e,o)?(r.setUTCFullYear(e,o),r):new Date(NaN);if(s=qe.DDD.exec(t),s){r=new Date(0);let i=parseInt(s[1],10);return vx(e,i)?(r.setUTCFullYear(e,0,i),r):new Date(NaN)}if(s=qe.MMDD.exec(t),s){r=new Date(0),o=parseInt(s[1],10)-1;let i=parseInt(s[2],10);return Pp(e,o,i)?(r.setUTCFullYear(e,o,i),r):new Date(NaN)}if(s=qe.Www.exec(t),s)return n=parseInt(s[1],10)-1,Op(n)?Ep(e,n):new Date(NaN);if(s=qe.WwwD.exec(t),s){n=parseInt(s[1],10)-1;let i=parseInt(s[2],10)-1;return Op(n,i)?Ep(e,n,i):new Date(NaN)}return null}function bx(t){let e,r,o=qe.HH.exec(t);if(o)return e=parseFloat(o[1].replace(",",".")),cc(e)?e%24*uc:NaN;if(o=qe.HHMM.exec(t),o)return e=parseInt(o[1],10),r=parseFloat(o[2].replace(",",".")),cc(e,r)?e%24*uc+r*Cp:NaN;if(o=qe.HHMMSS.exec(t),o){e=parseInt(o[1],10),r=parseInt(o[2],10);let n=parseFloat(o[3].replace(",","."));return cc(e,r,n)?e%24*uc+r*Cp+n*1e3:NaN}return null}function Ep(t,e,r){e=e||0,r=r||0;let o=new Date(0);o.setUTCFullYear(t,0,4);let n=o.getUTCDay()||7,s=e*7+r+1-n;return o.setUTCDate(o.getUTCDate()+s),o}var _x=[31,28,31,30,31,30,31,31,30,31,30,31],wx=[31,29,31,30,31,30,31,31,30,31,30,31];function Ap(t){return t%400===0||t%4===0&&t%100!==0}function Pp(t,e,r){if(e<0||e>11)return!1;if(r!=null){if(r<1)return!1;let o=Ap(t);if(o&&r>wx[e]||!o&&r>_x[e])return!1}return!0}function vx(t,e){if(e<1)return!1;let r=Ap(t);return!(r&&e>366||!r&&e>365)}function Op(t,e){return!(t<0||t>52||e!=null&&(e<0||e>6))}function cc(t,e,r){return!(t<0||t>=25||e!=null&&(e<0||e>=60)||r!=null&&(r<0||r>=60))}var Sx=/([xXOz]+)|''|'(''|[^'])+('|$)/g;function dc(t,e,r={}){e=String(e);let o=e.match(Sx);if(o){let n=pt(r.originalDate||t,r);e=o.reduce(function(s,i){if(i[0]==="'")return s;let a=s.indexOf(i),l=s[a-1]==="'",u=s.replace(i,"'"+Tp[i[0]](n,i,r)+"'");return l?u.substring(0,a-1)+u.substring(a+1):u},e)}return Be(t,e,r)}function Es(t,e,r){t=pt(t,r);let o=cr(e,t,!0),n=new Date(t.getTime()-o),s=new Date(0);return s.setFullYear(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate()),s.setHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),s}function rl(t,e,r,o){return o={...o,timeZone:e,originalDate:t},dc(Es(t,e,{timeZone:o.timeZone}),r,o)}function fc(t,e,r){if(typeof t=="string"&&!t.match(tl))return pt(t,{...r,timeZone:e});t=pt(t,r);let o=Cs(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()).getTime(),n=cr(e,new Date(o));return new Date(o+n)}var Ps="America/New_York",xx=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];function Rp(t){return t.replace(/[+-].*$/,"").trim().slice(0,5)}function mc(t,e,r=0){let o=new Date(`${rl(t,Ps,"yyyy-MM-dd")}T12:00:00Z`);o.setUTCDate(o.getUTCDate()+r);let n=o.toISOString().slice(0,10),s=xx[o.getUTCDay()],i=e[`${s}_open`],a=e[`${s}_close`];if(!i||!a)return null;let l=pt(`${n}T${Rp(i)}`,{timeZone:Ps}),u=pt(`${n}T${Rp(a)}`,{timeZone:Ps});return u<=l&&(u=new Date(u.getTime()+1440*60*1e3)),{day:s,open:l,close:u}}function ol(t,e){if(e.force_close)return!0;for(let r of[-1,0]){let o=mc(t,e,r);if(o&&!Ge(t,o.open)&&Ge(t,o.close))return!1}return!0}var Er=require("zustand/middleware");async function Ip(t,e){let r=e||U,{data:o,error:n}=await r.from("permissions").select("franchise_id, location_ids, portal_role").eq("user_id",t);if(n)throw n;if(o?.some(f=>f.portal_role==="admin")){let[f,m]=await Promise.all([r.from("franchises").select("*").throwOnError(),r.from("locations").select("*").throwOnError()]);return{franchises:f.data,locations:m.data}}let s=new Set(o?.map(f=>f.franchise_id).filter(f=>f!=null)??[]),i=new Set(o?.filter(f=>!f.location_ids?.length&&f.franchise_id!==null).map(f=>f.franchise_id)),a=o?.flatMap(f=>f.location_ids??[])??[],{data:l,error:u}=await r.from("franchises").select("*").in("franchise_id",Array.from(s));if(u)throw u;let{data:c,error:d}=await r.from("locations").select("*").or(`location_id.in.(${a.join(",")}), franchise_id.in.(${Array.from(i).join(",")})`);if(d)throw d;return{franchises:l,locations:c}}async function Dp(t,e){let r=e||U,{data:o,error:n}=await r.from("franchises").select("*").eq("franchise_id",t);if(n)throw n;let{data:s,error:i}=await r.from("locations").select("*").eq("franchise_id",t).or("status.is.null,status.neq.permanently_closed");if(i)throw i;return{franchises:o,locations:s}}async function Lp(t,e,r){let o=r||U,n={...e,...t},{data:s,error:i}=await o.from("locations").update(n).eq("location_id",e.location_id).select().single();if(i)throw i;return s}async function Np(t,e,r){let o=r||U,{data:n,error:s}=await o.from("locations").update({force_close:e}).eq("location_id",t);if(s)throw s;return n}async function jp(t,e){let r=e||U,{data:o,error:n}=await r.from("locations").insert(t).select().single();if(n)throw n;return o}async function Mp(t,e){let r=e||U,{data:o,error:n}=await r.from("locations").delete().eq("location_id",t);if(n)throw n;return o}async function Up(t,e,r){let o=r||U,n={...t,...e},{data:s,error:i}=await o.from("franchises").update(n).eq("franchise_id",t.franchise_id).select().single();if(i)throw i;return s}function Fp(t){try{let e=(t.split(".")[1]??"").replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(e.padEnd(Math.ceil(e.length/4)*4,"=")))}catch{return{}}}var Os=(0,$p.create)()((0,Er.subscribeWithSelector)((0,Er.persist)((0,Er.devtools)((t,e)=>({selectedLocation:null,franchises:[],locations:[],userId:null,navScope:"franchise",initialize:async({userId:r,token:o,locationId:n})=>{if(r&&t({userId:r}),n){let{data:a}=await U.from("locations").select("*").eq("location_id",n).throwOnError().single(),{data:l}=await U.from("franchises").select("*").eq("franchise_id",a.franchise_id).throwOnError().single();t({selectedLocation:a,franchiseId:a.franchise_id,locations:[a],franchises:[l]});return}else if(o){let l=Fp(o).franchise_ids?.[0],{locations:u,franchises:c}=await Dp(l),d=e().selectedLocation,f=d?u.find(m=>m.location_id===d.location_id)??null:null;t({locations:u,franchises:c,franchiseId:l,selectedLocation:f});return}else if(r){let{locations:a,franchises:l}=await Ip(r);t({locations:a,franchises:l})}let i=e().locations[0];t({selectedLocation:i,...i&&{franchiseId:i.franchise_id}})},hydrate:({franchises:r,locations:o})=>t({franchises:r??[],locations:o??[]},!1,"hydrate"),getCurrentLocation:()=>e().selectedLocation,getIsCurrentLocationOpen:()=>{let r=e().selectedLocation;return r?!ol(new Date,r):!1},getAllLocations:()=>e().locations,setForceClose:async(r,o)=>{await Np(o,r),t(n=>({locations:n.locations.map(s=>s.location_id===o?{...s,force_close:r}:s),selectedLocation:n.selectedLocation?.location_id===o?{...n.selectedLocation,force_close:r}:n.selectedLocation}))},setSelectedLocation:r=>{t({selectedLocation:r}),t({franchiseId:r.franchise_id})},setFranchiseId:r=>{if(t({franchiseId:r}),e().selectedLocation?.franchise_id!==r){let o=e().locations.find(n=>n.franchise_id===r&&n.location_id!==0)??e().locations.find(n=>n.franchise_id===r)??null;t({selectedLocation:o})}},enterFranchise:r=>{let o=e();if(t({franchiseId:r,navScope:"franchise"}),o.selectedLocation?.franchise_id!==r){let n=o.locations.find(s=>s.franchise_id===r&&s.location_id!==0)??o.locations.find(s=>s.franchise_id===r)??null;t({selectedLocation:n})}},enterLocation:r=>{t({selectedLocation:r,franchiseId:r.franchise_id,navScope:"location"})},exitToFranchise:()=>{t({navScope:"franchise"})},exitToAccount:()=>{t({navScope:"account"})},updateLocation:async(r,o)=>{await Lp(r,o),t(n=>({locations:n.locations.map(s=>s.location_id===o.location_id?{...s,...r}:s)}))},createLocation:async r=>{let o=await jp(r);return t(n=>({locations:[...n.locations,o]})),o},deleteLocation:async r=>{await Mp(r),t(o=>({locations:o.locations.filter(n=>n.location_id!==r)}))},updateFranchise:async(r,o)=>{let n=await Up(r,o);return t(s=>({franchises:s.franchises.map(i=>i.franchise_id===r.franchise_id?n:i)})),n}})),{name:"location",version:3,migrate:(t,e)=>{let r=t??{};return e<3?{...r,navScope:r.navScope??"franchise",franchiseId:r.franchiseId??r.selectedLocation?.franchise_id}:r},storage:(0,Er.createJSONStorage)(()=>kr()),skipHydration:xr,partialize:t=>({selectedLocation:t.selectedLocation,franchises:t.franchises,locations:t.locations,userId:t.userId,franchiseId:t.franchiseId,navScope:t.navScope})}))),Y=Os;var Yp=require("zustand");var Xp=require("zustand/middleware/immer"),Qp=require("zustand/middleware");async function Bp(t){let{data:e,error:r}=await U.from("promotions").select("*").eq("franchise_id",t);if(r)throw r;return e}async function qp(t,e="website",r){let{data:o,error:n}=await U.from("promotions").select("*").eq("is_active",!0).eq("franchise_id",t);if(n)throw n;let s=ks(o,e,r);return{all:o,active:s}}async function Vp(t,e){let{data:r,error:o}=await U.from("promotions").select("*").eq("promo_code",t).eq("franchise_id",e).eq("is_active",!0).single();return o||!r?null:r}async function Wp(t){let{data:e,error:r}=await U.from("promotions").insert(t).select("*").single();if(r)throw r;return e}async function Hp(t){let{data:e,error:r}=await U.from("promotions").update(t).eq("id",t.id).select("*").single();if(r)throw r;return e}async function zp(t){let{data:e,error:r}=await U.from("promotions").delete().eq("id",t).select("*").single();if(r)throw r;e||console.log("No promotion deleted")}async function Gp(t){let{data:e,error:r}=await U.from("franchise_marketing").select("personal_marketer").eq("franchise_id",t).maybeSingle();if(r)throw r;return e?.personal_marketer??!1}async function Kp(t,e){let{error:r}=await U.from("franchise_marketing").upsert({franchise_id:t,personal_marketer:e},{onConflict:"franchise_id"});if(r)throw r;let{error:o}=await U.from("agent_skill_config").upsert({franchise_id:t,skill_id:"personal-marketer",enabled:e,updated_at:new Date().toISOString()},{onConflict:"franchise_id,skill_id"});if(o)throw o}async function Jp(t,e=10){let{data:r,error:o}=await U.from("personal_marketer_runs").select("*").eq("franchise_id",t).order("created_at",{ascending:!1}).limit(e);if(o)throw o;return r}var kx=(0,Yp.create)()((0,Qp.devtools)((0,Xp.immer)((t,e)=>({logLevel:1,promotions:[],allPromotions:[],activePromotions:[],personalMarketerEnabled:!1,recentRuns:[],recentOutboundMessages:[],getPromotions:async r=>{let o=await Bp(r);return t({promotions:o},!1,"getPromotions"),o},getActivePromotions:async(r,o,n="website")=>{let{active:s,all:i}=await qp(r,n,o);return t({allPromotions:i,activePromotions:s},!1,"getActivePromotions"),s},getPromotionByCode:async(r,o)=>await Vp(r,o),addPromotion:async r=>{let o=await Wp(r);t(n=>{n.promotions.push(o)})},updatePromotion:async r=>{let o=await Hp(r);t(n=>{n.promotions=n.promotions.map(s=>s.id===o.id?o:s)})},deletePromotion:async r=>{await zp(r),t(o=>{o.promotions=o.promotions.filter(n=>n.id!==r)})},getPersonalMarketerSettings:async()=>{let r=Os.getState().franchiseId;if(!r){e().logLevel<=2&&console.warn("[PROMOTION STORE] No franchise ID found");return}let o=await Gp(r);t({personalMarketerEnabled:o},!1,"getPersonalMarketerSettings")},setPersonalMarketerEnabled:async r=>{let o=Os.getState().selectedLocation?.franchise_id;if(!o){e().logLevel<=2&&console.warn("[PROMOTION STORE] No franchise ID found");return}await Kp(o,r),t({personalMarketerEnabled:r},!1,"setPersonalMarketerEnabled")},getRecentRuns:async(r=10)=>{let o=Os.getState().franchiseId;if(!o)return e().logLevel<=2&&console.warn("[PROMOTION STORE] No franchise ID found"),[];let n=await Jp(o,r);return t({recentRuns:n},!1,"getRecentRuns"),n},createBlastRun:async(r,o)=>{let n=await qt("/marketing/create-run",{method:"POST",body:JSON.stringify({franchiseId:r,source:"blast",strategyId:"promotionalBlast",promotionId:o,dryRun:!1})});if(!n.ok){let i=await n.json().catch(()=>({}));throw new Error(i?.error??`HTTP ${n.status}`)}let{run:s}=await n.json();return await e().getRecentRuns(),s}})),{name:"PromotionStore"})),Ce=kx;var og=Le(eg(),1),ng=require("react");function nl(t){return t===2?2:1}var sg=!1;function ig(){sg=!0}var sl=(0,tg.create)()((0,ln.persist)((0,ln.devtools)((0,rg.immer)((t,e)=>({deliveryFeeCents:0,workingOrder:{time_placed:new Date,time_requested:void 0,customer:{first_name:"",last_name:"",phone:"",email:"",allow_marketing:!1},location_id:Y.getState().selectedLocation?.location_id||0,order_status:1,method_id:1,order_id:0,type_id:1,items:[],promo_code:void 0,charges:[],table_number:void 0},status:"idle",editingSourceOrder:null,promoOverrideActive:!1,addItem:(r,o)=>{let n=r;if(o){t(a=>{a.promoOverrideActive=!0,a.selectedPromotion=void 0,a.workingOrder.promo_code=void 0});let s=e().workingOrder.location_id,i=ur(o,{items:[r],location_id:s,method_id:3},new Date);n={...r,applied_promo_id:o.id,discount_amount:i>0?i:void 0}}t(s=>{s.workingOrder.items.push(n),n.is_catering&&(s.workingOrder.is_catering=!0),s.status!=="editing"&&(s.workingOrder.order_id=0)}),e().checkBestPromo()},setTip:r=>t(o=>{o.selectedTip=r}),removeItem:r=>{t(o=>{o.workingOrder.items.splice(r,1),o.status!=="editing"&&(o.workingOrder.order_id=0)}),e().checkBestPromo()},updateItem:(r,o,n)=>{let s=r;if(n!==void 0)if(t(i=>{i.promoOverrideActive=!0,n&&(i.selectedPromotion=void 0,i.workingOrder.promo_code=void 0)}),n){let i=e().workingOrder.location_id,a=ur(n,{items:[r],location_id:i,method_id:3},new Date);s={...r,applied_promo_id:n.id,discount_amount:a>0?a:void 0}}else s={...r,applied_promo_id:void 0,discount_amount:void 0};t(i=>{i.workingOrder.items[o]=s,i.status!=="editing"&&(i.workingOrder.order_id=0)}),e().checkBestPromo()},setCustomer:r=>t(o=>{o.workingOrder.customer=r}),getAnonCustomer:()=>({customer_id:0,first_name:"Customer",last_name:"Customer",phone:"0"}),setCart:r=>t(o=>{o.workingOrder=r}),createCustomer:async()=>{let r=e().workingOrder.customer,{data:o,error:n}=await U.from("customers").insert({first_name:r.first_name,last_name:r.last_name,email:r.email,phone_number:parseInt(r.phone)}).select("*").single();return n?(console.log("Error creating customer:",n),null):(console.log("customer created",o),o)},setLocationId:r=>t(o=>{o.workingOrder.location_id=r}),setOrderType:r=>t(o=>{o.workingOrder.type_id=nl(r)}),setTableNumber:r=>t(o=>{o.workingOrder.table_number=r}),setTimeRequested:r=>t(o=>{o.workingOrder.time_requested=r}),applyCateringPreflight:r=>t(o=>{if(o.workingOrder.type_id=r.type_id,o.workingOrder.location_id=r.location_id,o.workingOrder.time_requested=r.time_requested,r.type_id===bs.ORDER_TYPE.DELIVERY){let n=r.delivery_address?.trim();o.workingOrder.delivery_address=n&&n.length>0?n:void 0}else o.workingOrder.delivery_address=void 0}),clearCateringSchedule:()=>t(r=>{r.workingOrder.time_requested=void 0}),setDeliveryFee:r=>t(o=>{o.deliveryFeeCents=r}),setPromoCode:r=>t(o=>{o.workingOrder.promo_code=r}),resetOrder:()=>t(r=>({workingOrder:{...r.workingOrder,order_id:0,location_id:Y.getState().selectedLocation?.location_id??0,customer:{first_name:"",last_name:"",phone:"",email:"",allow_marketing:!1},items:[],promo_code:void 0,type_id:1,is_catering:!1,time_requested:void 0,delivery_address:void 0,table_number:void 0},selectedTip:void 0,deliveryFeeCents:0})),setOrder:r=>t(o=>{o.workingOrder={...r,type_id:nl(r.type_id)}}),startEdit:r=>t(o=>{let n={...r,type_id:nl(r.type_id),charges:r.charges??[]};o.workingOrder=n,o.editingSourceOrder=n,o.status="editing",o.selectedTip=void 0;let s=Number(r.promo_code);o.selectedPromotion=s?Ce.getState().activePromotions.find(i=>i.id===s):void 0,o.promoOverrideActive=!!o.selectedPromotion}),cancelEdit:(r=!0)=>t(o=>{o.status="idle",o.editingSourceOrder=null,o.selectedTip=void 0,o.selectedPromotion=void 0,o.promoOverrideActive=!1,r&&(o.workingOrder={...o.workingOrder,location_id:Y.getState().selectedLocation?.location_id??0,type_id:1,customer:{first_name:"",last_name:"",phone:"",email:"",allow_marketing:!1},order_status:1,order_id:0,items:[],promo_code:void 0,charges:[],revision:void 0,updated_at:void 0,table_number:void 0})}),finishEdit:()=>t(r=>({workingOrder:{...r.workingOrder,location_id:Y.getState().selectedLocation?.location_id??0,type_id:1,customer:{first_name:"",last_name:"",phone:"",email:"",allow_marketing:!1},order_status:1,order_id:0,items:[],promo_code:void 0,charges:[],revision:void 0,updated_at:void 0,table_number:void 0},status:"idle",editingSourceOrder:null,selectedTip:void 0,selectedPromotion:void 0,promoOverrideActive:!1})),hasMeaningfulEditChanges:()=>{let{status:r,editingSourceOrder:o,workingOrder:n}=e();return r!=="editing"||!o?!1:!(0,og.default)(o.items,n.items)},getOrderTotal:()=>nn({order:e().workingOrder}),setCartFromURL:async(r,o)=>{try{let n={"Content-Type":"application/json",...o?{"X-Zorgo-Api-Key":o}:{}},s=await fetch(`${Ki}/s/${r}`,{headers:n});if(!s.ok)return!1;let{cart_data:i,promotion_id:a}=await s.json();return i?(t(l=>{if(l.workingOrder={...l.workingOrder,...i,type_id:nl(i.type_id),order_id:0,order_status:1},l.workingOrder.time_requested=void 0,!a||i?.promo_code||i?.items?.some(d=>d.applied_promo_id))return;let c=Ce.getState().activePromotions.find(d=>d.id===a);if(!c){l.workingOrder.promo_code=String(a);return}if(c.promo_code){l.workingOrder.promo_code=c.promo_code;return}l.workingOrder.items=pp(l.workingOrder.items,c)}),e().checkBestPromo(),!0):!1}catch(n){return console.error("[CartStore] setCartFromURL failed:",n),!1}},dismissPromo:r=>{t(o=>{o.dismissedPromoIds=[...o.dismissedPromoIds||[],r]})},checkBestPromo:()=>{if(e().promoOverrideActive)return;let{workingOrder:r}=e();if(!r.location_id||!r.method_id)return;let o=Ce.getState().activePromotions,n=new Date,s=e().selectedPromotion;if(s&&Za(s)==="private")return;let i=s?ur(s,r,n):0;if(s&&i===0){e().removeOrderPromotion();return}let a=bp(r,o,n);if(s){a.orderPromo&&a.orderPromo.id!==s.id&&a.discount>i&&!e().dismissedPromoIds?.includes(a.orderPromo.id)&&e().onBestPromoChange?.(a.orderPromo);return}if(a.itemDiscounts?.length?t(u=>{for(let c of u.workingOrder.items)c.display_price=void 0,c.applied_promo_id=void 0,c.discount_amount=void 0;for(let c of a.itemDiscounts){let d=u.workingOrder.items[c.itemIndex];d&&(d.applied_promo_id=c.promotionId,d.discount_amount=c.discount,d.display_price=d.price-Math.round(c.discount/d.quantity))}}):e().wipeItemPromos(),a.discount===0||!a.orderPromo)return;let l=e().workingOrder.items.reduce((u,c)=>u+(c.discount_amount??0),0);l===0?e().applyOrderPromotion(a.orderPromo):a.discount>l&&!e().dismissedPromoIds?.includes(a.orderPromo.id)&&e().onBestPromoChange?.(a.orderPromo)},setOnBestPromoChange:r=>{t(o=>(o.onBestPromoChange=r,o))},wipeItemPromos:()=>{t(r=>{r.workingOrder.items=r.workingOrder.items.map(o=>({...o,display_price:void 0,applied_promo_id:void 0,discount_amount:void 0}))})},applyOrderPromotion:r=>{t(o=>{o.selectedPromotion=r,o.workingOrder.promo_code=String(r.id)}),e().wipeItemPromos()},removeOrderPromotion:()=>{t(r=>{r.selectedPromotion=void 0,r.workingOrder.promo_code=void 0}),e().checkBestPromo()},overrideOrderPromotion:r=>{t(o=>{o.promoOverrideActive=!0}),r?e().applyOrderPromotion(r):(t(o=>{o.selectedPromotion=void 0,o.workingOrder.promo_code=void 0}),e().wipeItemPromos())}}))),{name:"cart",version:1,storage:(0,ln.createJSONStorage)(()=>kr()),skipHydration:xr,partialize:t=>({editingSourceOrder:t.editingSourceOrder,...sg&&{workingOrder:t.workingOrder,selectedTip:t.selectedTip,deliveryFeeCents:t.deliveryFeeCents}})})),te=sl;function ag(){let t=sl(o=>o.workingOrder),e=sl(o=>o.selectedPromotion),r=sl(o=>o.selectedTip??0);return(0,ng.useMemo)(()=>{let{subtotal:o,discount:n,tax:s,serviceFee:i,total:a}=sn(t,e,r);return{subtotal:o,discount:n,tax:s,serviceFee:i,total:a}},[t,e,r])}var ug=require("zustand");var $=require("zod");function Wt(t){return(t/100).toLocaleString("en-US",{style:"currency",currency:"USD"})}function As(t){return`${t.quantity} guests \xD7 ${Wt(t.unitPrice)}/person`}function Rs(t,e){return t.upcharge<=0?"included":`+${Wt(t.upcharge)}${e?"/person":""}`}var Tx=$.z.object({email:$.z.email(),location_id:$.z.number().int().nullish()}),Cx=$.z.object({notification_emails:$.z.array(Tx).nullish(),minimum_notice_hours:$.z.number().int().nullish(),minimum_people_required:$.z.number().int().positive().nullish(),minimum_price:$.z.number().nonnegative().nullish(),does_cater:$.z.boolean().nullish(),preferred_time:$.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d:[0-5]\d$/,"expected HH:mm:ss").nullish()}),Ex=$.z.preprocess(t=>{if(t&&typeof t=="object"&&!Array.isArray(t)){let e=t;if(e.notification_email&&e.notification_emails==null){let{notification_email:r,...o}=e;return{...o,notification_emails:[{email:r,location_id:null}]}}}return t},Cx),Px=$.z.object({does_deliver:$.z.boolean().nullish(),delivery_fee_cents:$.z.number().int().nullish(),max_delivery_radius_miles:$.z.number().nullish(),cents_per_mile:$.z.number().int().nullish()}),Ox=$.z.object({key:$.z.string().min(1),enabled:$.z.boolean().default(!0),email:$.z.email().nullish(),label:$.z.string().nullish()}),Ax=$.z.object({forms:$.z.array(Ox).nullish()}),Rx=$.z.object({is_active:$.z.boolean().nullish(),full_discount_at:$.z.number().int().positive().nullish(),maximum_percent_off:$.z.number().min(0).max(1).nullish()}),Ix=$.z.object({key:$.z.string().min(1),label:$.z.string().min(1),description:$.z.string().nullish(),price_per_person_cents:$.z.number().int().nonnegative()}),Dx=$.z.object({base_price_per_person_cents:$.z.number().int().nonnegative(),default_service_hours:$.z.number().int().positive(),additional_hour_rate_cents:$.z.number().int().nonnegative(),service_fee_percent:$.z.number().min(0).max(100),sales_tax_percent:$.z.number().min(0).max(100),minimum_booking_fee_cents:$.z.number().int().nonnegative(),date_hold_deposit_cents:$.z.number().int().nonnegative(),add_ons:$.z.array(Ix).default([])}).refine(t=>new Set(t.add_ons.map(e=>e.key)).size===t.add_ons.length,{message:"add_on keys must be unique"}),Lx={catering:Ex,delivery:Px,contact:Ax,catering_bulk_discount:Rx,food_truck:Dx};async function hc(t,e,r=U){let{data:o}=await r.from("franchise_feature_config").select("config").eq("franchise_id",t).eq("feature",e).maybeSingle();return o?Lx[e].parse(o.config):null}var un=require("zustand/middleware");var gt=null,dr=null,fr=null,Is=null;function Nx(t){return typeof t=="number"?{franchiseId:t}:t??{}}function lg(){return pc.getState().platform??"website"}var pc=(0,ug.create)()((0,un.persist)((0,un.devtools)((t,e)=>({logLevel:3,location_id:void 0,franchiseId:void 0,franchiseCateringConfig:{does_cater:null,minimum_notice_hours:null,minimum_people_required:null,minimum_price:null},franchiseDeliveryConfig:{does_deliver:null,delivery_fee_cents:null,max_delivery_radius_miles:null,cents_per_mile:null},platform:"website",visibilityMode:"editor",lastUpdatedAt:new Date(0),setFranchiseId:r=>t({franchiseId:r}),remoteMenuLastUpdated:async()=>{let{data:r,error:o}=await U.from("items").select("updated_at").order("updated_at",{ascending:!1}).limit(1).single();if(o)throw e().logLevel<=2&&console.warn(o,"error getting menu last updated"),new Error("error getting menu last updated");return!r||!r.updated_at?new Date(0):new Date(r.updated_at)},start:async r=>{let o=Nx(r),n=o.franchiseId??e().franchiseId??Y.getState().franchiseId;if(e().logLevel<=1&&console.debug("starting menu manager"),!n){e().logLevel<=3&&console.warn("franchise id is not set, cannot start menu manager");return}t({franchiseId:n}),o.platform&&t({platform:o.platform}),e().refreshLocalMenu(),e().menuChangeListener(),e().promotionsChangeListener()},items:[],hydrate:({items:r,categories:o,rules:n,components:s})=>t({items:r??[],categories:o??[],rules:n??[],components:s??[]},!1,"hydrate"),setItems:r=>{t({items:r})},addItem:r=>{t({items:[...e().items,r]})},updateItem:r=>{t({items:e().items.map(o=>o.base_item_id===r.base_item_id?r:o)})},deleteItem:r=>{t({items:e().items.filter(o=>o.base_item_id!==r)})},addVariant:(r,o)=>{t({items:e().items.map(n=>n.base_item_id===o?{...n,variants:[...n.variants,r]}:n)})},updateVariant:(r,o)=>{t({items:e().items.map(n=>n.base_item_id===o?{...n,variants:n.variants.map(s=>s.item_id===r.item_id?r:s)}:n)})},deleteVariant:(r,o)=>{t({items:e().items.map(n=>n.base_item_id===o?{...n,variants:n.variants.filter(s=>s.item_id!==r)}:n)})},categories:[],setCategories:r=>t({categories:r}),addCategory:r=>{t({categories:[...e().categories,r]})},updateCategory:r=>{t({categories:e().categories.map(o=>o.category_id===r.category_id?r:o)})},deleteCategory:r=>{t({categories:e().categories.filter(o=>o.category_id!==r)})},rules:[],setRules:r=>{t({rules:r})},addRule:r=>{t({rules:[...e().rules,r]})},updateRule:r=>{t({rules:e().rules.map(o=>o.rule_id===r.rule_id?r:o)})},deleteRule:r=>{t({rules:e().rules.filter(o=>o.rule_id!==r)})},components:[],setComponents:r=>{t({components:r})},addComponent:r=>{t({components:[...e().components,r]})},updateComponent:r=>{t({components:e().components.map(o=>o.id===r.id?r:o)})},deleteComponent:r=>{t({components:e().components.filter(o=>o.id!==r)})},isLocalMenuFresh:async()=>{let r=await e().remoteMenuLastUpdated(),o=e().lastUpdatedAt;return r>=o},refreshLocalMenu:async()=>{let r=e().franchiseId;if(!r){e().logLevel<=2&&console.warn("franchise id is not set, cannot refresh menu");return}let o=lg(),n=Y.getState().selectedLocation?.location_id||0;e().logLevel<=1&&console.log("[MenuStore] refreshing menu:",{franchiseId:r,locationId:n,platform:o});let s=await lp(U,r,n,o),i=ks(Ce.getState().allPromotions,o,n||void 0,new Date);Ce.setState({activePromotions:i});let[a,l,u]=await Promise.all([ip(U,r,s),hc(r,"catering"),hc(r,"delivery")]),{items:c,categories:d,rules:f,components:m}=ap(a,i);t({items:c,categories:d,rules:f,components:m,franchiseCateringConfig:l??{},franchiseDeliveryConfig:u??{}},!1,"refreshLocalMenu"),Is||(Is=setInterval(()=>{let h=Ce.getState().allPromotions;if(!h.length)return;let g=lg(),y=Y.getState().selectedLocation?.location_id??void 0,p=ks(h,g,y,new Date),b=Ce.getState().activePromotions;(p.length!==b.length||p.some((v,N)=>v.id!==b[N]?.id))&&e().refreshLocalMenu()},6e4)),t({lastUpdatedAt:new Date})},menuChangeListener:async()=>{let r=e().franchiseId;if(!r){e().logLevel<=2&&console.warn("[MenuStore] Cannot subscribe to menu changes without franchiseId");return}if(dr&&(clearTimeout(dr),dr=null),gt){try{gt.unsubscribe?.()}catch{}try{U.removeChannel?.(gt)}catch{}gt=null}let o=U.channel(`menu-changes-${r}`).on("postgres_changes",{event:"*",schema:"public",table:"items",filter:`franchise_id=eq.${r}`},()=>{e().refreshLocalMenu()});gt=o,o.subscribe(n=>{if(n==="SUBSCRIBED"){e().logLevel<=1&&console.log("[MenuStore] Subscribed to menu changes");return}if(n==="CLOSED"){e().logLevel<=1&&console.log(`[MenuStore] Subscription status: ${n}`);return}if(n!=="CHANNEL_ERROR"&&n!=="TIMED_OUT"){e().logLevel<=2&&console.warn(`[MenuStore] Subscription status: ${n}`);return}console.warn(`[MenuStore] Subscription status: ${n}. Reconnecting in 5s...`);try{gt?.unsubscribe?.()}catch{}try{U.removeChannel?.(gt)}catch{}gt=null,dr&&clearTimeout(dr),dr=setTimeout(()=>{e().menuChangeListener()},5e3)})},promotionsChangeListener:()=>{let r=e().franchiseId;if(!r)return;if(fr){try{fr.unsubscribe?.()}catch{}try{U.removeChannel?.(fr)}catch{}fr=null}fr=U.channel(`promotions-changes-${r}`).on("postgres_changes",{event:"*",schema:"public",table:"promotions",filter:`franchise_id=eq.${r}`},async()=>{let{data:n}=await U.from("promotions").select("*").eq("is_active",!0).eq("franchise_id",r);Ce.setState({allPromotions:n||[]}),e().refreshLocalMenu()}).subscribe()},cleanup:()=>{if(dr&&(clearTimeout(dr),dr=null),gt){try{gt.unsubscribe?.()}catch{}try{U.removeChannel?.(gt)}catch{}gt=null}if(fr){try{fr.unsubscribe?.()}catch{}try{U.removeChannel?.(fr)}catch{}fr=null}Is&&(clearInterval(Is),Is=null)},setLastUpdatedAt:r=>t({lastUpdatedAt:r}),uploadMenuImage:async r=>{let o=Y.getState().franchiseId;if(!o)throw e().logLevel<=2&&console.warn("[MenuStore] Cannot upload menu image without franchiseId"),new Error("franchise id is not set");let n=`franchise_id_${o}/menu-${Date.now()}`,{error:s}=await U.storage.from("menu-images").upload(n,r);if(s)throw s;return n}}),{name:"MenuStore"}),{name:"menu",onRehydrateStorage:()=>(t,e)=>{if(e||!t)return;let r=t.items;pc.setState({items:r??[]})},storage:(0,un.createJSONStorage)(()=>kr()),skipHydration:xr}));var Ht=pc;var be=require("zod");var Pr=require("zod"),Pt=t=>({schema:t,actionable:!0}),jx=t=>typeof t=="object"&&t!==null&&t.actionable===!0;function Fe(t,e){let r={};for(let[o,n]of Object.entries(e)){let s=`${t}.${o}`;r[o]=n instanceof Pr.z.ZodType?{name:s,schema:n,actionable:!1}:jx(n)?{name:s,schema:n.schema,actionable:!0}:Fe(s,n)}return r}var Mx=t=>typeof t=="object"&&t!==null&&"name"in t&&t.schema instanceof Pr.z.ZodType;function il(t,e=[]){if(Mx(t))return e.push(t),e;if(t&&typeof t=="object")for(let r of Object.values(t))il(r,e);return e}if(process.env.NODE_ENV!=="production"){let t=Fe("order",{placed:Pr.z.object({orderId:Pr.z.number()}),catering:{placed:Pt(Pr.z.object({orderId:Pr.z.number(),headcount:Pr.z.number()}))}}),e=(r,o)=>{if(!r)throw new Error(`define.ts assert: ${o}`)};e(t.placed.name==="order.placed","leaf name"),e(t.catering.placed.name==="order.catering.placed","nested name"),e(t.placed.schema.safeParse({orderId:1}).success,"leaf schema parses"),e(t.catering.placed.schema.safeParse({orderId:1,headcount:2}).success,"marked schema parses"),e(t.placed.actionable===!1,"bare leaf is not actionable"),e(t.catering.placed.actionable===!0,"marked leaf is actionable"),e(il(t).length===2,"descriptorsIn walks nested"),console.log("define.ts ok")}var W=require("zod");var co={franchiseId:W.z.number(),locationId:W.z.number()},cn={placed:W.z.object({orderId:W.z.number(),...co,total:W.z.number(),itemCount:W.z.number().int()}),requested:W.z.object({orderId:W.z.number(),...co}),confirmed:W.z.object({orderId:W.z.number(),...co,via:W.z.enum(["pos","email_link","dashboard"]),userId:W.z.string().optional(),deviceId:W.z.number().optional()}),paid:W.z.object({orderId:W.z.number(),...co,paymentMethod:W.z.string()}),completed:W.z.object({orderId:W.z.number(),...co}),canceled:W.z.object({orderId:W.z.number(),...co,reason:W.z.string().nullable()})},cg=Fe("order",{...cn,placed:Pt(cn.placed),completed:Pt(cn.completed),failed:W.z.object({orderId:W.z.number().nullable(),total:W.z.number(),reason:W.z.string(),phase:W.z.enum(["create","modify","refund","complete","kitchen_complete"]).optional()}),confirmation_email_sent:W.z.object({orderId:W.z.number(),recipient:W.z.string()}),realtime_disconnected:W.z.object({status:W.z.string(),location_id:W.z.number().nullable()}),catering:{...cn,requested:Pt(cn.requested),confirmed:Pt(cn.confirmed),charge_failed:Pt(W.z.object({orderId:W.z.number(),...co,chargeId:W.z.number()}))}});var zt=require("zod");var gc={franchiseId:zt.z.number(),locationId:zt.z.number()},dg=Fe("inventory",{stock_changed:Pt(zt.z.object(gc)),ingredient_added:Pt(zt.z.object({...gc,locationIngredientId:zt.z.number(),ingredientName:zt.z.string()})),component_added:Pt(zt.z.object({...gc,locationComponentId:zt.z.number(),componentName:zt.z.string()}))});var Ae=require("zod");var fg=Fe("payment",{captured:Ae.z.object({orderId:Ae.z.number(),amount:Ae.z.number(),method:Ae.z.string()}),failed:Ae.z.object({orderId:Ae.z.number(),amount:Ae.z.number(),method:Ae.z.string(),reason:Ae.z.string(),phase:Ae.z.enum(["create_payment_intent","retrieve_payment_intent","collect_payment_method","confirm_payment_intent","unexpected"]).optional(),code:Ae.z.string().nullable().optional(),decline_code:Ae.z.string().nullable().optional(),payment_intent_id:Ae.z.string().nullable().optional()}),refunded:Ae.z.object({orderId:Ae.z.number(),amount:Ae.z.number(),method:Ae.z.string()})});var B=require("zod");var Re=require("zod"),mg=["healthy","degraded","unhealthy","offline"];function Ze(t,e){return{severity:t,detail:e}}function yc(t){let e=Object.fromEntries(Object.entries(t).map(([r,o])=>[r,Re.z.object({healthy:Re.z.boolean(),detail:(o.detail??Re.z.unknown()).optional()})]));return Re.z.object(e)}var bc={pos:{authenticated:Ze("critical"),menu_loaded:Ze("critical"),reader_connected:Ze("critical"),printer_connected:Ze("critical"),order_listener:Ze("critical"),battery_healthy:Ze("warning",Re.z.object({percentage:Re.z.number()}))},kiosk:{authenticated:Ze("critical"),menu_loaded:Ze("critical"),reader_connected:Ze("critical"),battery_healthy:Ze("warning",Re.z.object({percentage:Re.z.number()}))},kitchen_display:{authenticated:Ze("critical"),order_listener:Ze("critical"),battery_healthy:Ze("warning",Re.z.object({percentage:Re.z.number()}))}},OU=Re.z.discriminatedUnion("platform",[Re.z.object({platform:Re.z.literal("pos"),checks:yc(bc.pos)}),Re.z.object({platform:Re.z.literal("kiosk"),checks:yc(bc.kiosk)}),Re.z.object({platform:Re.z.literal("kitchen_display"),checks:yc(bc.kitchen_display)})]);var hg=B.z.enum(mg),pg=Fe("device",{status_changed:B.z.object({from:hg.nullable(),to:hg,reason:B.z.string().nullable()}),check_failed:B.z.object({check_key:B.z.string(),reason:B.z.string()}),check_recovered:B.z.object({check_key:B.z.string()}),auth_failed:B.z.object({phase:B.z.enum(["init","verify_403"]),reason:B.z.string()}),connection_error:B.z.object({reason:B.z.string()}),verified:B.z.object({device_id:B.z.number()}),printer_disconnected:B.z.object({printer_id:B.z.string(),reason:B.z.string()}),print_failed:B.z.object({printer_id:B.z.string().nullable(),job_type:B.z.string(),reason:B.z.string(),order_id:B.z.number().nullable(),timings:Gu}),print_succeeded:B.z.object({printer_id:B.z.string().nullable(),job_type:B.z.string(),order_id:B.z.number().nullable(),timings:Gu}),reader_connected:B.z.object({reader_serial:B.z.string().nullable()}),reader_disconnected:B.z.object({reader_serial:B.z.string().nullable(),reason:B.z.string()}),reader_connect_failed:B.z.object({reader_serial:B.z.string().nullable(),reason:B.z.string()}),order_received:B.z.object({orderId:B.z.number(),method_id:B.z.number().nullable()}),order_acknowledged:B.z.object({orderId:B.z.number(),method_id:B.z.number().nullable()})});var ce=require("zod");var dn=Fe("api",{supabase_failed:ce.z.object({table:ce.z.string(),op:ce.z.string(),code:ce.z.string().nullable(),message:ce.z.string()}),unhandled:ce.z.object({message:ce.z.string(),where:ce.z.string().nullable()}),rate_limited:ce.z.object({path:ce.z.string(),method:ce.z.string(),retryAfterMs:ce.z.number().nullable()}),timeout:ce.z.object({path:ce.z.string(),method:ce.z.string(),durationMs:ce.z.number()}),log_invalid_payload:ce.z.object({event:ce.z.string(),issues:ce.z.string()}),log_enqueue_failed:ce.z.object({event:ce.z.string(),message:ce.z.string()})});var se=require("zod");var gg=se.z.object({source:se.z.string().optional(),medium:se.z.string().optional(),campaign:se.z.string().optional()}),mr=Fe("website",{session_started:se.z.object({landing_page:se.z.string(),referrer:se.z.string().optional(),utm:gg.optional()}),session_ended:se.z.object({duration_ms:se.z.number(),pages_visited:se.z.number()}),page_viewed:se.z.object({path:se.z.string(),referrer:se.z.string().optional(),utm:gg.optional()}),page_exited:se.z.object({path:se.z.string(),duration_ms:se.z.number()}),short_url_clicked:se.z.object({slug:se.z.string(),referrer:se.z.string().optional(),run_id:se.z.string().uuid().optional(),outbound_message_id:se.z.string().uuid().optional(),strategy_id:se.z.string().optional(),strategy_variant_id:se.z.string().optional(),dry_run:se.z.boolean().optional()})});var hr=require("zod");var yg=Fe("integration",{pushed:hr.z.object({orderId:hr.z.number(),provider:hr.z.string(),externalId:hr.z.string()}),failed:hr.z.object({orderId:hr.z.number(),provider:hr.z.string(),reason:hr.z.string()})});var JU=new Set(il([cg,dg,fg,pg,dn,mr,yg]).filter(t=>t.actionable).map(t=>t.name));var rF=be.z.object({id:be.z.number(),created_at:be.z.string(),severity:be.z.enum(["debug","info","warn","error"]),event_name:be.z.string(),source:Qh,service:be.z.string().nullable(),device_id:be.z.number().nullable(),session_id:be.z.string().nullable(),request_id:be.z.string().nullable(),franchise_id:be.z.number().nullable(),location_id:be.z.number().nullable(),user_id:be.z.string().nullable(),anonymous_id:be.z.string().nullable(),customer_id:be.z.number().nullable(),order_id:be.z.number().nullable(),payload:be.z.record(be.z.string(),be.z.unknown()),stack_trace:be.z.string().nullable()}),Ux=()=>({}),bg=null,oF=new Proxy({},{get(t,e){return bg?.[e]??(()=>{})}});function _g(t){let{source:e,getContext:r=Ux,dev:o=!1}=t,n=(i,a,l,u,c)=>{let d=a.schema.safeParse(l);if(!d.success){console.error(`[log] invalid payload for ${a.name}:`,d.error.issues),a.name!==dn.log_invalid_payload.name&&n("error",dn.log_invalid_payload,{event:a.name,issues:JSON.stringify(d.error.issues)});return}let f=r(),m=i==="error"?(u instanceof Error?u.stack:null)??new Error().stack??null:null;if(o){console.log(`[${i}] ${a.name}`,d.data);return}qt("/events",{method:"POST",body:JSON.stringify({severity:i,event_name:a.name,source:e,session_id:f.session_id??null,request_id:c?.request_id??f.request_id??null,location_id:f.location_id??null,franchise_id:f.franchise_id??null,anonymous_id:f.anonymous_id??null,customer_id:f.customer_id??null,payload:d.data,stack_trace:m})}).then(h=>{h.ok||h.text().then(g=>console.error(`[log] POST /events ${h.status} for ${a.name}:`,g))}).catch(h=>{console.error(`[log] POST /events failed for ${a.name}:`,h)})},s={info:(i,a,l)=>n("info",i,a,void 0,l),warn:(i,a,l)=>n("warn",i,a,void 0,l),error:(i,a,l,u)=>n("error",i,a,l,u)};return bg=s,s}var fo=class{diff(e,r,o={}){let n;typeof o=="function"?(n=o,o={}):"callback"in o&&(n=o.callback);let s=this.castInput(e,o),i=this.castInput(r,o),a=this.removeEmpty(this.tokenize(s,o)),l=this.removeEmpty(this.tokenize(i,o));return this.diffWithOptionsObj(a,l,o,n)}diffWithOptionsObj(e,r,o,n){var s;let i=b=>{if(b=this.postProcess(b,o),n){setTimeout(function(){n(b)},0);return}else return b},a=r.length,l=e.length,u=1,c=a+l;o.maxEditLength!=null&&(c=Math.min(c,o.maxEditLength));let d=(s=o.timeout)!==null&&s!==void 0?s:1/0,f=Date.now()+d,m=[{oldPos:-1,lastComponent:void 0}],h=this.extractCommon(m[0],r,e,0,o);if(m[0].oldPos+1>=l&&h+1>=a)return i(this.buildValues(m[0].lastComponent,r,e));let g=-1/0,y=1/0,p=()=>{for(let b=Math.max(g,-u);b<=Math.min(y,u);b+=2){let _,v=m[b-1],N=m[b+1];v&&(m[b-1]=void 0);let x=!1;if(N){let Z=N.oldPos-b;x=N&&0<=Z&&Z<a}let P=v&&v.oldPos+1<l;if(!x&&!P){m[b]=void 0;continue}if(!P||x&&v.oldPos<N.oldPos?_=this.addToPath(N,!0,!1,0,o):_=this.addToPath(v,!1,!0,1,o),h=this.extractCommon(_,r,e,b,o),_.oldPos+1>=l&&h+1>=a)return i(this.buildValues(_.lastComponent,r,e))||!0;m[b]=_,_.oldPos+1>=l&&(y=Math.min(y,b-1)),h+1>=a&&(g=Math.max(g,b+1))}u++};if(n)(function b(){setTimeout(function(){if(u>c||Date.now()>f)return n(void 0);p()||b()},0)})();else for(;u<=c&&Date.now()<=f;){let b=p();if(b)return b}}addToPath(e,r,o,n,s){let i=e.lastComponent;return i&&!s.oneChangePerToken&&i.added===r&&i.removed===o?{oldPos:e.oldPos+n,lastComponent:{count:i.count+1,added:r,removed:o,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+n,lastComponent:{count:1,added:r,removed:o,previousComponent:i}}}extractCommon(e,r,o,n,s){let i=r.length,a=o.length,l=e.oldPos,u=l-n,c=0;for(;u+1<i&&l+1<a&&this.equals(o[l+1],r[u+1],s);)u++,l++,c++,s.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return c&&!s.oneChangePerToken&&(e.lastComponent={count:c,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=l,u}equals(e,r,o){return o.comparator?o.comparator(e,r):e===r||!!o.ignoreCase&&e.toLowerCase()===r.toLowerCase()}removeEmpty(e){let r=[];for(let o=0;o<e.length;o++)e[o]&&r.push(e[o]);return r}castInput(e,r){return e}tokenize(e,r){return Array.from(e)}join(e){return e.join("")}postProcess(e,r){return e}get useLongestToken(){return!1}buildValues(e,r,o){let n=[],s;for(;e;)n.push(e),s=e.previousComponent,delete e.previousComponent,e=s;n.reverse();let i=n.length,a=0,l=0,u=0;for(;a<i;a++){let c=n[a];if(c.removed)c.value=this.join(o.slice(u,u+c.count)),u+=c.count;else{if(!c.added&&this.useLongestToken){let d=r.slice(l,l+c.count);d=d.map(function(f,m){let h=o[u+m];return h.length>f.length?h:f}),c.value=this.join(d)}else c.value=this.join(r.slice(l,l+c.count));l+=c.count,c.added||(u+=c.count)}}return n}};var _c=class extends fo{constructor(){super(...arguments),this.tokenize=wc}equals(e,r,o){return o.ignoreWhitespace?((!o.newlineIsToken||!e.includes(`
|
|
154
154
|
`))&&(e=e.trim()),(!o.newlineIsToken||!r.includes(`
|
|
155
155
|
`))&&(r=r.trim())):o.ignoreNewlineAtEof&&!o.newlineIsToken&&(e.endsWith(`
|
|
156
156
|
`)&&(e=e.slice(0,-1)),r.endsWith(`
|
|
157
|
-
`)&&(r=r.slice(0,-1))),super.equals(e,r,o)}},uF=new
|
|
158
|
-
`));let r=[],o=t.split(/(\n|\r\n)/);o[o.length-1]||o.pop();for(let n=0;n<o.length;n++){let s=o[n];n%2&&!e.newlineIsToken?r[r.length-1]+=s:r.push(s)}return r}var _c=class extends fo{constructor(){super(...arguments),this.tokenize=bc}get useLongestToken(){return!0}castInput(e,r){let{undefinedReplacement:o,stringifyReplacer:n=(s,i)=>typeof i>"u"?o:i}=r;return typeof e=="string"?e:JSON.stringify(sl(e,null,null,n),null," ")}equals(e,r,o){return super.equals(e.replace(/,([\r\n])/g,"$1"),r.replace(/,([\r\n])/g,"$1"),o)}},wg=new _c;function wc(t,e,r){return wg.diff(t,e,r)}function sl(t,e,r,o,n){e=e||[],r=r||[],o&&(t=o(n===void 0?"":n,t));let s;for(s=0;s<e.length;s+=1)if(e[s]===t)return r[s];let i;if(Object.prototype.toString.call(t)==="[object Array]"){for(e.push(t),i=new Array(t.length),r.push(i),s=0;s<t.length;s+=1)i[s]=sl(t[s],e,r,o,String(s));return e.pop(),r.pop(),i}if(t&&t.toJSON&&(t=t.toJSON()),typeof t=="object"&&t!==null){e.push(t),i={},r.push(i);let a=[],l;for(l in t)Object.prototype.hasOwnProperty.call(t,l)&&a.push(l);for(a.sort(),s=0;s<a.length;s+=1)l=a[s],i[l]=sl(t[l],e,r,o,l);e.pop(),r.pop()}else i=t;return i}var vg=require("zustand"),Sg=require("zustand/middleware"),Or=(0,vg.create)()((0,Sg.devtools)((t,e)=>({logLevel:4,stack:[],openModal:r=>t({stack:[...e().stack,r]}),goBack:()=>{let r=e().stack;if(r.length>1){let o=r[r.length-1];if(!o)return;let n=r.slice(0,-1),s=n[n.length-1];o.displayStyle!=="dialog"&&s&&(n[n.length-1]={...s,workingData:null}),t({stack:n})}else t({stack:[]})},close:()=>t({stack:[]}),setWorkingData:(r,o=0)=>{if(e().logLevel<=1&&e().stack.length>1){let a=e().getWorkingData(),l=wc(a,r);console.log("[MODAL STORE] working data diff from old:",l)}let n=e().stack,s=n.length-1-o;if(s<0)return;let i=[...n];i[s]={...i[s],workingData:r},t({stack:i})},getWorkingData:(r=0)=>{let o=e().stack;if(o.length!==0)return o[o.length-1-r]?.workingData}}),{name:"ModalStore"}));var Fx="v3",$x=function(e){return e===3?"v3":e},Tg="https://js.stripe.com",Bx="".concat(Tg,"/v3"),qx=/^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/,Vx=/^https:\/\/js\.stripe\.com\/(v3|[a-z]+)\/stripe\.js(\?.*)?$/,xg="loadStripe.setLoadParameters was called but an existing Stripe.js script already exists in the document; existing script parameters will be used",Wx=function(e){return qx.test(e)||Vx.test(e)},Hx=function(){for(var e=document.querySelectorAll('script[src^="'.concat(Tg,'"]')),r=0;r<e.length;r++){var o=e[r];if(Wx(o.src))return o}return null},kg=function(e){var r=e&&!e.advancedFraudSignals?"?advancedFraudSignals=false":"",o=document.createElement("script");o.src="".concat(Bx).concat(r);var n=document.head||document.body;if(!n)throw new Error("Expected document.body not to be null. Stripe.js requires a <body> element.");return n.appendChild(o),o},zx=function(e,r){!e||!e._registerWrapper||e._registerWrapper({name:"stripe-js",version:"5.10.0",startTime:r})},Rs=null,il=null,al=null,Gx=function(e){return function(r){e(new Error("Failed to load Stripe.js",{cause:r}))}},Kx=function(e,r){return function(){window.Stripe?e(window.Stripe):r(new Error("Stripe.js not available"))}},Jx=function(e){return Rs!==null?Rs:(Rs=new Promise(function(r,o){if(typeof window>"u"||typeof document>"u"){r(null);return}if(window.Stripe&&e&&console.warn(xg),window.Stripe){r(window.Stripe);return}try{var n=Hx();if(n&&e)console.warn(xg);else if(!n)n=kg(e);else if(n&&al!==null&&il!==null){var s;n.removeEventListener("load",al),n.removeEventListener("error",il),(s=n.parentNode)===null||s===void 0||s.removeChild(n),n=kg(e)}al=Kx(r,o),il=Gx(o),n.addEventListener("load",al),n.addEventListener("error",il)}catch(i){o(i);return}}),Rs.catch(function(r){return Rs=null,Promise.reject(r)}))},Yx=function(e,r,o){if(e===null)return null;var n=r[0],s=n.match(/^pk_test/),i=$x(e.version),a=Fx;s&&i!==a&&console.warn("Stripe.js@".concat(i," was loaded on the page, but @stripe/stripe-js@").concat("5.10.0"," expected Stripe.js@").concat(a,". This may result in unexpected behavior. For more information, see https://docs.stripe.com/sdks/stripejs-versioning"));var l=e.apply(void 0,r);return zx(l,o),l},Is,Cg=!1,Eg=function(){return Is||(Is=Jx(null).catch(function(e){return Is=null,Promise.reject(e)}),Is)};Promise.resolve().then(function(){return Eg()}).catch(function(t){Cg||console.warn(t)});var Pg=function(){for(var e=arguments.length,r=new Array(e),o=0;o<e;o++)r[o]=arguments[o];Cg=!0;var n=Date.now();return Eg().then(function(s){return Yx(s,r,n)})};var Dg=require("zustand"),Lg=require("zustand/middleware");var Gt=Le(require("zod"),1),Ag=require("zustand"),Rg=require("zustand/middleware");var ll=globalThis;function mo(t){if(!ll.document)return null;let e=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=ll.document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return r?decodeURIComponent(r[1]):null}function vc(t,e,r=365){ll.document&&(ll.document.cookie=`${t}=${encodeURIComponent(e)}; path=/; max-age=${r*86400}; SameSite=Lax`)}var Og=Gt.default.object({shortUrlPath:Gt.default.string().optional().default("/s"),siteUrl:Gt.default.url().optional(),franchiseId:Gt.default.union([Gt.default.string(),Gt.default.number()]).optional(),locationId:Gt.default.union([Gt.default.string(),Gt.default.number()]).optional()});var Xx=(0,Ag.create)()((0,Rg.devtools)((t,e)=>({logLevel:1,config:Og.parse({}),sessionData:{},sessionId:xs(),consentGiven:mo("zorgo_consent")==="1",consentAnswered:mo("zorgo_consent")!==null,anonymousId:mo("zorgo_anon_id"),getSiteUrl:()=>{let r=e().config.siteUrl,o=typeof process<"u"?process.env.NEXT_PUBLIC_SITE_URL||process.env.NEXT_PUBLIC_BASE_URL:void 0,n=typeof globalThis<"u"&&"location"in globalThis&&globalThis.location?.origin?globalThis.location.origin:void 0,s=r||o||n;if(!s){e().logLevel<=3&&console.error("No site url found.");return}return s},getAnonymousId:()=>e().anonymousId,mergeSessionData:r=>{t(o=>{let n={...o.sessionData};for(let[s,i]of Object.entries(r))i===void 0?delete n[s]:n[s]=i;return{sessionData:n}})},setConsent:r=>{if(vc("zorgo_consent",r?"1":"0"),r&&!e().anonymousId){let o=`anon_${xs()}`;vc("zorgo_anon_id",o),t({consentGiven:!0,consentAnswered:!0,anonymousId:o})}else t({consentGiven:r,consentAnswered:!0})},initialize:({token:r,config:o})=>{let n=Og.parse(o||{});t({token:r,config:n,consentGiven:mo("zorgo_consent")==="1",consentAnswered:mo("zorgo_consent")!==null,anonymousId:mo("zorgo_anon_id")})}}),{name:"websiteCoreStore"})),Me=Xx;var Ig={logLevel:1,clientSecret:null,intentType:null,isLoading:!1,error:null,orderId:null,finalAmount:null},Sc=!1,Qx=(0,Dg.create)()((0,Lg.devtools)((t,e)=>({...Ig,start:async()=>{let r=Y.getState().selectedLocation,o=process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY,n=process.env.NEXT_PUBLIC_STRIPE_ACCOUNT_OVERRIDE||r?.stripe_account_id;if(!o||!n)return null;let s=await Pg(o,{stripeAccount:n});if(!s){e().logLevel<=3&&console.error("Failed to load Stripe");return}t({stripe:s})},createOrder:async(r,o)=>{if(!r?.items?.length||!o?.location_id)throw new Error("Order, location, and time_requested are required");let n={...r,method_id:2,location_id:o.location_id},{franchiseId:s}=Me.getState().config,i=await qt("/create-order",{method:"POST",body:JSON.stringify({order:n,anonymous_id:Me.getState().getAnonymousId(),franchise_id:s?String(s):void 0})});if(!i.ok){let l=await i.json();throw new Error(l.error||`Server error: ${i.status}`)}return(await i.json()).orderId},createPaymentIntentForOrder:async(r,o,n)=>{let s=await qt("/create-payment-intent",{method:"POST",body:JSON.stringify({orderId:r,tipAmount:o,deliveryFeeCents:n||0})});if(!s.ok){let u=await s.json();throw new Error(u.error||`Server error: ${s.status}`)}let i=await s.json(),a=i.charges?.total??i.amount??0,l=i.type==="setup_intent"?"setup_intent":"payment_intent";return{clientSecret:i.clientSecret,amount:a,intentType:l}},confirmPayment:async(r,o,n,s,i)=>{let a=r,l={name:`${i.first_name} ${i.last_name}`.trim()||void 0,email:i.email,phone:tp(i.phone)},u=e().intentType,c={return_url:s,payment_method_data:{billing_details:l}},d;return u==="setup_intent"?{error:d}=await a.confirmSetup({elements:o,clientSecret:n,confirmParams:c}):{error:d}=await a.confirmPayment({elements:o,clientSecret:n,confirmParams:c}),d?{success:!1,error:d.message}:u!=="setup_intent"?{success:!0,paymentIntentId:(await a.retrievePaymentIntent(n)).paymentIntent?.id}:{success:!0}},getReturnStatus:r=>{let o=typeof r=="string"?new URL(r):r,n=o.searchParams.get("redirect_status"),s=o.searchParams.get("setup_intent"),i=o.searchParams.get("payment_intent")??s??void 0,a=!!s,l=o.searchParams.get("amount"),u=Number(o.searchParams.get("order")),c=Number.isSafeInteger(u)&&u>0?u:void 0,d=o.searchParams.get("order_token")??void 0;return n?n==="succeeded"?{succeeded:!0,amount:l?parseFloat(l):void 0,paymentIntentId:i,isHold:a,orderId:c,orderToken:c?d:void 0}:{succeeded:!1,error:`Payment ${n}`,paymentIntentId:i,isHold:a}:{succeeded:!1,error:"No payment status found in URL",isHold:a}},mintOrderLinkToken:async(r,o)=>{if(!r||!o)return null;try{let n=await qt(`/catering/order/${r}/link`,{method:"POST",body:JSON.stringify({email:o}),signal:AbortSignal.timeout(3e3)});if(!n.ok)return null;let s=await n.json();return typeof s?.token=="string"?s.token:null}catch{return null}},beginCheckout:async()=>{if(!(e().isLoading||Sc)){Sc=!0,t({isLoading:!0,error:null});try{let r=te.getState().workingOrder,o=Y.getState().selectedLocation,n=te.getState().selectedTip??0,s=te.getState().deliveryFeeCents??0;if(!o)throw new Error("Cannot start checkout without a selected location");if(!r)throw new Error("Cannot start checkout without a working order");let i=e().orderId;i||(i=await e().createOrder(r,o),t({orderId:i}));let{clientSecret:a,amount:l,intentType:u}=await e().createPaymentIntentForOrder(i,n,s);t({clientSecret:a,intentType:u,orderId:i,finalAmount:l,isLoading:!1,error:null})}catch(r){let o=r instanceof Error?r.message:"Failed to setup payment";throw t({isLoading:!1,error:o}),r}finally{Sc=!1}}},reset:()=>t(Ig)}),{name:"PaymentStore"})),$e=Qx;var sy=require("zustand");var hn=require("zod"),ty=Le(Zg(),1),Pc=t=>(0,ty.default)(t).isLight()?"#000000":"#FFFFFF",ml=t=>hn.z.string().nullish().transform(e=>e??t),ey=t=>hn.z.number().nullish().transform(e=>e??t),ry=hn.z.object({design_id:ey(0),franchise_id:ey(0),primary:ml("#9943E9"),accent:ml("#6636BF"),backgroundBase:ml("#EBEBEB"),fontFamily:ml("Inter"),created_at:hn.z.string().optional(),updated_at:hn.z.string().optional()}).transform(t=>({...t,foreground:Pc(t.backgroundBase),primaryForeground:Pc(t.primary),accentForeground:Pc(t.accent)})),oy=ry.parse({});function ny(t){return ry.parse(t??{})}var pn=require("zustand/middleware");var hk="branding-assets",pk=3600,gk=(0,sy.create)()((0,pn.persist)((0,pn.devtools)((t,e)=>({branding:oy,logoUrl:null,fetchFranchiseLogoUrl:async r=>{let o=[`franchises/${r}/logo.png`,`franchises/${r}/logo.jpg`];for(let n of o){let{data:s,error:i}=await U.storage.from(hk).createSignedUrl(n,pk);if(!i&&s?.signedUrl)return t({logoUrl:s.signedUrl}),console.log("logoUrl",s.signedUrl),s.signedUrl;console.log("error",i)}return t({logoUrl:null}),null},initialize:async()=>{let r=Y.getState().franchiseId,{data:o,error:n}=await U.from("franchise_branding").select("*").eq("franchise_id",r).single();n||o&&t({branding:ny(o)})}})),{name:"branding",storage:(0,pn.createJSONStorage)(()=>kr()),skipHydration:xr,partialize:t=>({branding:t.branding})})),Oc=gk;var iy=require("zustand"),ay=require("zustand/middleware"),ly=require("zustand/middleware/immer");var yk=(0,iy.create)()((0,ay.devtools)((0,ly.immer)(t=>({recommendations:[],isLoading:!1,error:null,strategy:"top_items",lastFetchedAt:null,fetchRecommendations:async e=>{t(r=>{r.isLoading=!0,r.error=null});try{let r=await qt("/recommendations",{method:"POST",body:JSON.stringify(e)});if(!r.ok){let n=await r.json().catch(()=>null);throw new Error(n?.error??`Server error: ${r.status}`)}let o=await r.json();t(n=>{n.recommendations=o.recommendations??[],n.strategy=e.strategy??"top_items",n.isLoading=!1,n.lastFetchedAt=new Date})}catch(r){let o=r?.message??"Failed to fetch recommendations";t(n=>{n.error=o,n.isLoading=!1})}},setStrategy:e=>{t(r=>{r.strategy=e})},clear:()=>{t(e=>{e.recommendations=[],e.error=null,e.lastFetchedAt=null})}})),{name:"RecommendationStore"})),Kt=yk;function uy(){let t=()=>`ses_${crypto.randomUUID()}`;if(typeof sessionStorage>"u")return t();let e="zorgo_session_id",r=sessionStorage.getItem(e);return r||(r=t(),sessionStorage.setItem(e,r)),r}function cy(t){if(!t)return;let e=new URLSearchParams(t),r=e.get("utm_source")||void 0,o=e.get("utm_medium")||void 0,n=e.get("utm_campaign")||void 0;if(!(!r&&!o&&!n))return{source:r,medium:o,campaign:n}}var dy=()=>Promise.resolve();function Ic(t){dy=t}function Jt(){(0,L.useEffect)(()=>{dy().catch(console.error)},[])}var fy=()=>typeof window>"u"?"/":window.location.pathname;function Dc(t){fy=t}function bk(){let t=Or(r=>r.stack);return{current:t[t.length-1]??null,isOpen:t.length>0,depth:t.length,open:(r,o,n)=>Or.getState().openModal({type:r,props:o,displayStyle:n}),close:Or.getState().close,back:Or.getState().goBack,setWorkingData:Or.getState().setWorkingData,getWorkingData:Or.getState().getWorkingData}}function _k(){Jt();let t=te.getState(),e=te(u=>u.workingOrder),r=te(u=>u.selectedTip),{subtotal:o,discount:n,tax:s,serviceFee:i,total:a}=ag(),l=(0,L.useMemo)(()=>e.items.reduce((u,c)=>u+c.quantity,0),[e.items]);return{items:e.items,itemCount:l,isEmpty:l===0,customer:e.customer,promoCode:e.promo_code,tip:r,subtotal:o,discount:n,tax:s,serviceFee:i,total:a,addItem:t.addItem,removeItem:t.removeItem,updateItem:t.updateItem,resetCart:()=>{t.resetOrder(),t.setOrderType(2)},setCustomer:t.setCustomer,setLocationId:t.setLocationId,setOrderType:t.setOrderType,setTimeRequested:t.setTimeRequested,setTip:t.setTip,getItemTotal:u=>Cr(u),getOrder:()=>te.getState().workingOrder,resolveShortUrl:u=>t.setCartFromURL(u,Me.getState().token)}}function wk(t){Jt();let e=Y(u=>u.locations),r=Y(u=>u.franchises),o=Y(u=>u.selectedLocation),n=Y(u=>u.setSelectedLocation),s=Y(u=>u.getIsCurrentLocationOpen),i=(0,L.useMemo)(()=>e.filter(u=>r.some(c=>c.franchise_id===u.franchise_id)),[e,r]),a=t?.autoSelectLocationId;(0,L.useEffect)(()=>{if(a==null||o)return;let u=i.find(c=>c.location_id===a);u&&n(u)},[a,o,i,n]);let l=!!t?.promptLocationSelection&&!o&&i.length>0;return{availableLocations:i,currentLocation:o,setLocation:n,getIsCurrentLocationOpen:s,needsLocationSelection:l}}function my(){Jt();let t=Ht(o=>o.items),e=Ht(o=>o.categories);return{items:(0,L.useMemo)(()=>t.filter(o=>!e.find(s=>s.category_id===o.category_id)?.is_catering),[t,e]),allItems:t,categories:e}}function hy(t,e,r,o){let n=t.getState();o(n)&&r(n)(e)}function vk(t){hy(Ht,t,e=>e.hydrate,e=>!e.items?.length)}function Sk(t,e,r){Jt();let o=r!=null,{allItems:n}=my(),s=(0,L.useMemo)(()=>n.find(S=>S.base_item_id===t),[n,t]),[i,a]=(0,L.useState)(e?.item_id??null),[l,u]=(0,L.useState)(()=>{let S={};for(let V of e?.selections??[])S[V.rule_id]=V.selections.map(j=>uo(`${j.type}:${j.id}`,j.portion));return S}),[c,d]=(0,L.useState)(()=>{let S={};for(let V of e?.components??[])S[uo(String(V.id),V.portion)]=V.quantity_servings;return S}),[f,m]=(0,L.useState)(e?.quantity??1),h=(0,L.useCallback)(S=>m(V=>Math.max(1,typeof S=="function"?S(V):S)),[]),[g,y]=(0,L.useState)(e?.comments??""),p=s?.variants.find(S=>S.item_id===i)??s?.variants[0],b=p?.portion_scheme??null,_=(0,L.useCallback)(S=>{a(S.item_id),u({}),d({})},[]),v=(0,L.useMemo)(()=>(p?.rules??s?.rules??[]).filter(S=>S.rule_id!=null),[p,s]),N=(0,L.useCallback)((S,V,j,re=1/0)=>{u(ee=>{let J=ee[S]??[],Se=uo(V,j),ye=J.findIndex(xe=>ht(xe).baseKey===V);return ye!==-1?{...ee,[S]:J[ye]===Se?J.filter(xe=>xe!==Se):J.map((xe,At)=>At===ye?Se:xe)}:re===1?{...ee,[S]:[Se]}:Ya(J)+Ts(j)>re?ee:{...ee,[S]:[...J,Se]}})},[]),x=(0,L.useCallback)(S=>{u(V=>{let j={};for(let[re,ee]of Object.entries(V))j[Number(re)]=ee.flatMap(J=>{let{baseKey:Se,portion:ye}=ht(J);if(!ye)return[J];let xe=Zu(ye,S);return xe?[uo(Se,xe[0])]:[]});return j})},[]),P=(0,L.useCallback)((S,V)=>{u(j=>({...j,[S]:(j[S]??[]).filter(re=>ht(re).baseKey!==V)}))},[]),Z=(0,L.useMemo)(()=>v.map(S=>{let V=S.rule_id,j=l[V]??[],re=cp(S),ee=new Map(re.map(J=>[J.key,J]));return{rule:S,ruleId:V,keys:j,defs:re,byKey:ee,charged:Qu(j,J=>ee.get(J)?.basePrice??0,S.included_quantity??0)}}),[v,l]),q=(0,L.useMemo)(()=>Z.map(({rule:S,ruleId:V,keys:j,defs:re,charged:ee})=>{let J=S.max_selection??1/0,Se=Ya(j),ye=Se>=J;return{...S,rule_id:V,max:J,selectedCount:Se,portionable:!!b&&!!S.is_portionable,subtext:yp(S),satisfied:Se>=S.min_selection&&Se<=J,message:()=>Se<S.min_selection?`Choose at least ${S.min_selection} option${S.min_selection>1?"s":""}`:Se>J?`Choose no more than ${J} option${J>1?"s":""}`:null,options:re.map(({basePrice:xe,...At})=>{let Rt=j.find(bb=>ht(bb).baseKey===At.key),_o=Rt?ht(Rt).portion:null;return{...At,key:Rt??At.key,portion:_o,coveredSections:_o?[Vt(_o).index]:[],coveredWhole:!!Rt&&!_o,upcharge:Rt?ee.get(Rt):xe,selected:!!Rt,disabled:ye&&!Rt&&J!==1,toggle:()=>N(V,At.key,null,J)}})}}),[Z,b,N]),nt=(0,L.useMemo)(()=>Z.map(({rule:S,ruleId:V,keys:j,byKey:re,charged:ee})=>({rule_id:V,group_name:S.group_name,selections:j.flatMap(J=>{let{baseKey:Se,portion:ye}=ht(J),xe=re.get(Se);return xe?[{id:xe.id,type:xe.type,quantity:1,upcharge:ee.get(J)??0,name:xe.name,portion:ye}]:[]})})).filter(S=>S.selections.length>0),[Z]),ge=(0,L.useMemo)(()=>!s||!p?null:{item_id:p.item_id,base_item_id:s.base_item_id,category_id:s.category_id,name:p.name,quantity:f,price:p.price,components:(p.components??[]).flatMap(S=>Xu(String(S.id),c,S.servings_per_item??1).map(({portion:V,value:j})=>({...S,portion:V,quantity_servings:j}))),selections:nt,comments:g},[s,p,f,c,nt,g]),st=q.find(S=>!S.satisfied)??null,er=!!ge&&!st,tr=(0,L.useCallback)(()=>!ge||q.some(S=>!S.satisfied)?null:(o?te.getState().updateItem(ge,r):te.getState().addItem(ge),ge),[ge,q,o,r]),rr=ge?Cr(ge):0,Ue=!!p?.display_price&&p.display_price<p.price;return{item:s,variant:p,variants:s?.variants??[],setVariant:_,ruleGroups:q,unmetRule:st,canSubmit:er,submit:tr,portionScheme:b,placeOption:N,clearOption:P,recutSelections:x,quantity:f,setQuantity:h,comments:g,setComments:y,setComponentServings:(S,V,j=null)=>d(re=>{let ee={...re};if(!j)for(let J of Object.keys(ee))ht(J).baseKey===String(S)&&delete ee[J];return ee[uo(String(S),j)]=Math.max(0,V),ee}),price:rr,salePrice:Ue&&ge?Cr({...ge,display_price:p.display_price},!0):void 0,isEditMode:o,draft:ge}}function xk(){Jt();let t=Y(p=>p.selectedLocation),e=Ce(p=>p.activePromotions),r=te(p=>p.workingOrder),o=te(p=>p.selectedPromotion),n=r.promo_code,[s,i]=(0,L.useState)(null),[a,l]=(0,L.useState)(!1),u=(0,L.useRef)(null),c=(0,L.useMemo)(()=>r.items.reduce((p,b)=>p+(b.discount_amount??0),0),[r.items]),d=(0,L.useMemo)(()=>nn({order:r}),[r]),f=(0,L.useMemo)(()=>{if(!o)return c;try{return ur(o,r,new Date)}catch{return 0}},[c,o,r]),m=(0,L.useMemo)(()=>{if(o||c<=0)return null;let p=new Map;for(let _ of r.items)!_.applied_promo_id||!_.discount_amount||p.set(_.applied_promo_id,(p.get(_.applied_promo_id)??0)+_.discount_amount);let b=Array.from(p.entries()).sort((_,v)=>v[1]-_[1])[0]?.[0];return e.find(_=>_.id===b)??null},[e,c,o,r.items]),h=o??m;(0,L.useEffect)(()=>{if(!t?.franchise_id)return;let p=!1;return l(!0),Ce.getState().getActivePromotions(t.franchise_id,t.location_id).finally(()=>{p||l(!1)}),()=>{p=!0}},[t?.franchise_id,t?.location_id]),(0,L.useEffect)(()=>{if(!n){i(null);return}if(o&&f>0){i(null);return}if(o?.min_purchase_amount&&d<o.min_purchase_amount){i(`Minimum purchase of $${(o.min_purchase_amount/100).toFixed(2)} required`);return}o&&i("Promotion not applicable")},[d,f,n,o]);let g=(0,L.useCallback)(async p=>{let b=p.trim();if(b){if(!t?.franchise_id||!t?.location_id){i("Please select a location first");return}l(!0),i(null);try{let _=await Ce.getState().getPromotionByCode(b,t.franchise_id);if(!_){te.getState().removeOrderPromotion(),i("Invalid promotion code");return}te.getState().applyOrderPromotion(_)}catch{i("Unable to apply promotion")}finally{l(!1)}}},[t?.franchise_id,t?.location_id]);(0,L.useEffect)(()=>{te.getState().workingOrder.promo_code||te.getState().checkBestPromo()},[e]),(0,L.useEffect)(()=>{if(typeof window>"u")return;let b=new URLSearchParams(window.location.search).get("promo");!b||b===n||u.current===b||(u.current=b,g(b))},[g,n,t?.location_id]);let y=(0,L.useCallback)(()=>{if(i(null),u.current=null,te.getState().overrideOrderPromotion(null),typeof window<"u"){let p=new URL(window.location.href);p.searchParams.has("promo")&&(p.searchParams.delete("promo"),window.history.replaceState({},"",p.toString()))}},[]);return{promoCode:n??"",setPromoCode:p=>{p?g(p):y()},appliedPromo:h,discountAmount:f,error:s,loading:a,applyPromo:g,removePromo:y,activePromotions:e}}function kk(t={}){Jt();let e=$e(d=>d.clientSecret),r=$e(d=>d.intentType),o=$e(d=>d.isLoading),n=$e(d=>d.error),s=$e(d=>d.stripe),i=$e(d=>d.finalAmount),a=$e(d=>d.orderId),l=te(d=>d.workingOrder),u=e?{clientSecret:e,...t.appearance&&{appearance:t.appearance},defaultValues:{billingDetails:{name:(l.customer.first_name??"")+" "+(l.customer.last_name??""),email:l.customer.email,phone:l.customer.phone}}}:null,c=$e.getState().confirmPayment;return{clientSecret:e,intentType:r,stripe:s,elementOptions:u,total:i,orderId:a,isLoading:o,error:n,isReady:!!(e&&s),startCheckout:$e.getState().beginCheckout,resetCheckout:$e.getState().reset,submitPayment:c,paymentElementOptions:{layout:"accordion",fields:{billingDetails:{name:"never",email:"never",phone:"never",address:"auto"}}},getReturnStatus:$e.getState().getReturnStatus,mintOrderLinkToken:$e.getState().mintOrderLinkToken,getReturnUrl:Me.getState().getSiteUrl}}function Tk(){Jt();let t=Ht(r=>r.franchiseCateringConfig),e=Ht(r=>r.franchiseDeliveryConfig);return{minimum_notice_hours:t.minimum_notice_hours,minimum_people_required:t.minimum_people_required,minimum_price:t.minimum_price,does_cater:t.does_cater,does_deliver:e.does_deliver,delivery_fee_cents:e.delivery_fee_cents,max_delivery_radius_miles:e.max_delivery_radius_miles,cents_per_mile:e.cents_per_mile}}function Ck(){Jt();let t=Kt(s=>s.recommendations),e=Kt(s=>s.isLoading),r=Kt(s=>s.error),o=Kt(s=>s.strategy),n=Kt(s=>s.lastFetchedAt);return{recommendations:t,isLoading:e,error:r,strategy:o,lastFetchedAt:n,refresh:s=>Kt.getState().fetchRecommendations(s),setStrategy:s=>Kt.getState().setStrategy(s),clear:()=>Kt.getState().clear()}}var hl=null,Ac=null,py={};function Rc(){return Ac||(Ac=_g({source:"restaurant_site",getContext:()=>py})),Ac}function Ek(){Jt();let t=Me(g=>g.consentGiven),e=Me(g=>g.anonymousId),r=Me(g=>g.config),o=Y(g=>g.franchiseId),n=fy(),s=(0,L.useRef)(null);s.current||(s.current=Symbol("zorgo-tracking"));let[i,a]=(0,L.useState)(!1),l=(0,L.useRef)(null),u=(0,L.useRef)(Date.now()),c=(0,L.useRef)(Date.now()),d=(0,L.useRef)(0),f=(0,L.useRef)(!1),m=(0,L.useRef)(!1),h=(0,L.useRef)(typeof window>"u"?void 0:cy(window.location.search));(0,L.useEffect)(()=>(hl===null&&(hl=s.current,a(!0)),()=>{hl===s.current&&(hl=null)}),[]),(0,L.useEffect)(()=>{if(!i)return;if(!t){f.current=!1;return}let g=uy(),y=typeof document<"u"&&document.referrer||void 0,p=r.franchiseId??o;py={session_id:g,anonymous_id:e||null,franchise_id:p!=null?Number(p):null,location_id:r.locationId!=null?Number(r.locationId):null};let b=Rc();f.current||(f.current=!0,m.current=!1,b.info(mr.session_started,{landing_page:n,referrer:y,utm:h.current}),d.current=1,c.current=Date.now());let _=()=>{m.current||(m.current=!0,l.current&&b.info(mr.page_exited,{path:l.current,duration_ms:Date.now()-u.current}),b.info(mr.session_ended,{duration_ms:Date.now()-c.current,pages_visited:d.current}))},v=()=>{document.visibilityState==="hidden"&&_()};return window.addEventListener("beforeunload",_),document.addEventListener("visibilitychange",v),()=>{window.removeEventListener("beforeunload",_),document.removeEventListener("visibilitychange",v)}},[i,t,e,o]),(0,L.useEffect)(()=>{if(!(!i||!t||!f.current)){if(l.current&&l.current!==n&&Rc().info(mr.page_exited,{path:l.current,duration_ms:Date.now()-u.current}),l.current!==n){let g=l.current===null;Rc().info(mr.page_viewed,{path:n,referrer:typeof document<"u"&&document.referrer||void 0,utm:g?h.current:void 0}),g||(d.current+=1)}l.current=n,u.current=Date.now()}},[n,t,i])}function Pk(){Jt(),Ek();let t=te(s=>s.workingOrder.customer),e=te.getState().setCustomer,r=Me(s=>s.consentGiven),o=Me(s=>s.consentAnswered),n=Me(s=>s.anonymousId);return{customer:t,consentGiven:r,setCustomer:e,consentAnswered:o,setConsent:Me.getState().setConsent,anonymousId:n}}function gy(t){return typeof window>"u"?Promise.reject(new Error("Google Maps can only load in the browser")):window.google?.maps?.places?Promise.resolve():new Promise((r,o)=>{let n=document.querySelector('script[src^="https://maps.googleapis.com/maps/api/js"]');if(n){n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>o(new Error("Maps script failed")),{once:!0});return}let s=document.createElement("script");s.src=`https://maps.googleapis.com/maps/api/js?key=${encodeURIComponent(t)}&libraries=places`,s.async=!0,s.defer=!0,s.onload=()=>r(),s.onerror=()=>o(new Error("Failed to load Google Maps")),document.head.appendChild(s)})}var pl=null;async function Ok(){try{let t=await fetch("/api/zorgo-token");if(!t.ok)return;let{token:e}=await t.json();return e}catch{return}}function yy(){return typeof window>"u"?Promise.resolve():pl||(pl=(async()=>{ig();let t,e=new Promise(o=>t=o);dp(async()=>Me.getState().token??await e),await Promise.all([Y,Ht,te,Oc].map(o=>o.persist.rehydrate())),te.setState(o=>({workingOrder:{...o.workingOrder,method_id:2,type_id:2}}));let r=await Ok();if(t(r??null),!r)throw new Error("Zorgo: missing token. Ensure app/api/zorgo-token exists and ZORGO_SITE_SECRET is set.");Me.getState().initialize({token:r}),Ak(),await Y.getState().initialize({token:r})})(),pl)}function Ak(){let t=n=>{n&&$e.getState().start()},e=async n=>{let s=Y.getState().franchiseId;s&&(await Ce.getState().getActivePromotions(s,n,"website").catch(console.error),te.getState().checkBestPromo())},r=async n=>{n&&(await e(Y.getState().selectedLocation?.location_id),Ht.getState().start({franchiseId:n,platform:"website",visibilityMode:"runtime"}))},o={fireImmediately:!0};Y.subscribe(n=>n.franchiseId,r,o),Y.subscribe(n=>n.selectedLocation?.stripe_account_id,t,o),Y.subscribe(n=>n.selectedLocation?.location_id,(n,s)=>{n&&te.getState().setLocationId(n),n!==s&&e(n)},o)}var by=require("zustand"),_y=require("zustand/middleware"),wy=require("zustand/middleware/immer"),gl=require("react"),Lc=(0,gl.createContext)(null);function yt(){let t=(0,gl.useContext)(Lc);if(!t)throw new Error("Must be used inside DynamicFormShell");return t}function Nc({onSubmit:t}){return(0,by.createStore)()((0,_y.devtools)((0,wy.immer)((e,r)=>({values:{},fieldConfigs:{},fieldErrors:{},status:"idle",registerField:(o,n)=>(e(s=>{s.fieldConfigs[o]=n,o in s.values||(s.values[o]=n.defaultValue??"")}),()=>{e(s=>{delete s.fieldConfigs[o],delete s.fieldErrors[o]})}),setValue:(o,n)=>{e(s=>{s.values[o]=n})},clearError:o=>{e(n=>{delete n.fieldErrors[o],n.status="idle"})},validateField:o=>{let n=r().fieldConfigs[o];if(!n)return null;let s=r().values[o],i=n.required&&!s?"Required.":n.validate(s);return e(a=>{i?a.fieldErrors[o]=i:delete a.fieldErrors[o]}),i??null},setFieldError:(o,n)=>{r().fieldConfigs[o]&&e(i=>{i.fieldErrors[o]=n})},validateAll:()=>{let o={};return Object.keys(r().fieldConfigs).forEach(n=>{let s=r().validateField(n);s&&(o[n]=s)}),o},handleSubmit:async o=>{o.preventDefault();let n=r().validateAll();if(Object.keys(n).length>0){e(s=>{s.fieldErrors=n,s.status="error"});return}e(s=>{s.status="sending"});try{await t(r().values),e(s=>{s.status="sent"})}catch{e(s=>{s.status="error"})}}}))))}var yl=require("react");var jc=require("react/jsx-runtime");function Mc({className:t,onSubmit:e,children:r}){let o=(0,yl.useRef)(e);o.current=e;let n=(0,yl.useMemo)(()=>Nc({onSubmit:(...s)=>o.current(...s)}),[]);return(0,jc.jsx)(Lc.Provider,{value:n,children:(0,jc.jsx)("form",{onSubmit:n.getState().handleSubmit,className:t,children:r})})}var ky=require("react"),Us=require("zod");var vy=require("zustand");function js(){let t=yt(),e=(0,vy.useStore)(t,r=>r.status);return{status:e,isIdle:e==="idle",isSubmitting:e==="sending",isSubmitted:e==="sent",isError:e==="error"}}var Sy=require("zustand");function Rk(t,e){return t.required&&(e==null||e==="")?"Required.":t.validate(e)}function Ms(){let t=yt();return(0,Sy.useStore)(t,e=>Object.entries(e.fieldConfigs).every(([r,o])=>Rk(o,e.values[r])===null))}var xy=require("zustand");function Ve(){let t=yt();return(0,xy.useStore)(t,e=>e.values)}var Fs=require("react/jsx-runtime"),Ik=Us.z.object({label:Us.z.string().default("Submit"),loadingLabel:Us.z.string().default("Submitting..."),className:Us.z.string().default("")});function Uc(t){let{labelFn:e,...r}=t,{label:o,loadingLabel:n,className:s}=Ik.parse(r),i=Ms(),{isSubmitting:a,isSubmitted:l}=js(),u=Ve(),c=yt(),d=(0,ky.useRef)(null),f=!i||a||l,m=e?e(u):o;function h(){c.getState().validateAll(),setTimeout(()=>{d.current?.form?.querySelector("[data-field-error]")?.scrollIntoView({behavior:"smooth",block:"center"})},50)}return(0,Fs.jsxs)("div",{style:{position:"relative"},children:[(0,Fs.jsx)("button",{ref:d,type:"submit",disabled:f,className:s,children:a?n:m}),f&&(0,Fs.jsx)("div",{onClick:h,style:{position:"absolute",inset:0,cursor:"pointer"}})]})}var Fc=require("zustand");function ie(t){let e=yt(),r=(0,Fc.useStore)(e,l=>l.values[t]),o=(0,Fc.useStore)(e,l=>l.fieldErrors[t])??null;return{value:r,error:o,setValue:l=>e.getState().setValue(t,l),clearError:()=>e.getState().clearError(t),validate:()=>e.getState().validateField(t),setError:l=>e.getState().setFieldError(t,l)}}var Ty=require("react/jsx-runtime");function _e({name:t,className:e}){let{error:r}=ie(t);return r?(0,Ty.jsx)("span",{"data-field-error":t,className:e,children:r}):null}var $s=require("react/jsx-runtime");function $c({className:t,title:e,titleClassName:r,subtitle:o,subtitleClassName:n}){return(0,$s.jsxs)("div",{className:t,children:[(0,$s.jsx)("h1",{className:r,children:e}),(0,$s.jsx)("p",{className:n,children:o})]})}var Vc=require("react"),Ke=require("react/jsx-runtime");function Dk(t,e){return e.flatMap(r=>{let o=t[`rule_${r.ruleId}`]??[];return r.options.filter(n=>o.includes(n.value)&&n.upcharge>0).map(n=>({id:`rule_${r.ruleId}_${n.value}`,name:n.label,priceCents:n.upcharge}))})}function Bc({label:t,value:e,isTotal:r,isDiscount:o}){return r?(0,Ke.jsx)("div",{className:"flex items-center justify-between pt-3 mt-1 border-t-2 border-zestia-red-500",children:(0,Ke.jsx)("span",{className:"font-extrabold text-end text-zestia-red-500 text-xl",children:e})}):o?(0,Ke.jsxs)("div",{className:"flex items-center justify-between py-1.5 border-b border-stone-100",children:[(0,Ke.jsx)("span",{className:"text-xs text-emerald-600 font-medium",children:t}),(0,Ke.jsx)("span",{className:"text-xs font-semibold text-emerald-600",children:e})]}):(0,Ke.jsxs)("div",{className:"flex items-center justify-between py-1.5 border-b border-stone-100",children:[(0,Ke.jsx)("span",{className:"text-xs text-stone-500",children:t}),(0,Ke.jsx)("span",{className:"text-xs font-semibold text-stone-700",children:e})]})}function qc(t){return`$${(t/100).toFixed(2)}`}function Wc({items:t,ruleGroups:e=[],guestCountFieldId:r="guestCount",className:o}){let n=Ve(),{value:s}=ie(r),i=Number(s)||0,a=Ce(h=>h.allPromotions),l=[...t,...Dk(n,e)],u=l.reduce((h,g)=>h+g.priceCents,0),c=(0,Vc.useMemo)(()=>{let h=t.find(g=>g.isBase);if(h?.active_promo_id)return a.find(g=>g.id===h.active_promo_id&&g.min_purchase_quantity)},[t,a]),d=(0,Vc.useMemo)(()=>!c||i<=0?u:Math.round(ec(u,i,c.discount_value/100,c.min_purchase_quantity)),[c,i,u]),f=d*i,m=u>0&&d<u?((u-d)/u*100).toFixed(1):null;return(0,Ke.jsxs)("div",{className:o,children:[l.map(h=>(0,Ke.jsx)(Bc,{label:h.name,value:`${qc(h.priceCents)}/person`},h.id)),m&&(0,Ke.jsx)(Bc,{isDiscount:!0,label:`Bulk discount (${m}% off)`,value:`-${qc(u-d)}/person`}),(0,Ke.jsx)(Bc,{isTotal:!0,label:"Per-Person Cost",value:`${qc(d)}/person`})]})}var Cy=require("react/jsx-runtime");function Hc({label:t,className:e}){return(0,Cy.jsx)("h2",{className:e,children:t})}var Ey=require("react/jsx-runtime");function zc({children:t,className:e}){return(0,Ey.jsx)("p",{className:e,children:t})}var _l=require("react");function bl(t){let e={};for(let[r,o]of Object.entries(t))Array.isArray(o)&&o.every(n=>typeof n=="string")?e[r]=o.length===1?o[0]:o.length===0?void 0:o:e[r]=o;return e}var wl=require("react/jsx-runtime");function Gc({whenFormVal:t,whenFunction:e,whenMediaQuery:r,children:o}){let n=Ve(),[s,i]=(0,_l.useState)(()=>r&&typeof window<"u"?window.matchMedia(r).matches:!1);return(0,_l.useEffect)(()=>{if(!r)return;let l=window.matchMedia(r);i(l.matches);let u=c=>i(c.matches);return l.addEventListener("change",u),()=>l.removeEventListener("change",u)},[r]),(t?t(bl(n)):!1)||(e?e():!1)||(r?s:!1)?(0,wl.jsx)(wl.Fragment,{children:o}):null}var M=require("zod"),ae=M.z.object({inputType:M.z.enum(["text","number","date","time"]).default("text"),fieldId:M.z.string(),label:M.z.string().optional(),placeholder:M.z.string().optional(),autoCompleteType:M.z.string().optional(),requiredText:M.z.string().default("Required."),required:M.z.boolean().default(!0),showLabel:M.z.boolean().default(!0),showError:M.z.boolean().default(!0),disabled:M.z.boolean().default(!1),fieldClassName:M.z.string().default("flex-1"),containerClassName:M.z.string().default("flex flex-col"),fieldLabelClassName:M.z.string().default("flex-1"),fieldErrorClassName:M.z.string().default("flex-1"),fieldAsteriskClassName:M.z.string().default("text-red-500"),initialValue:M.z.unknown().optional()}),_B=ae.extend({min:M.z.number().optional(),max:M.z.number().optional(),step:M.z.number().default(1)}),wB=ae.extend({min:M.z.string().optional(),max:M.z.string().default("23:59")}),gn=ae.extend({maxLength:M.z.number().default(256),validate:M.z.any(),sanitize:M.z.any(),min:M.z.string().optional(),max:M.z.string().optional(),multiline:M.z.boolean().default(!1),rows:M.z.number().default(5)}),Py=ae.extend({minSelections:M.z.number().default(1),maxSelections:M.z.union([M.z.number(),M.z.literal(1/0)]).default(1),tooFewText:M.z.string().optional(),tooManyText:M.z.string().optional(),options:M.z.array(M.z.object({label:M.z.string(),value:M.z.string(),sublabel:M.z.string().optional(),description:M.z.string().optional(),disabled:M.z.boolean().optional().default(!1)})).min(1),optionClassName:M.z.string().default("flex items-center gap-3 px-4 py-3 rounded-lg border border-stone-200 cursor-pointer select-none transition-colors duration-150 hover:border-stone-300"),optionActiveClassName:M.z.string().default("border-blue-500 bg-blue-50"),optionLabelClassName:M.z.string().default("text-sm font-semibold text-stone-600"),optionActiveLabelClassName:M.z.string().default("text-sm font-semibold text-blue-500"),optionSublabelClassName:M.z.string().default("text-sm text-stone-400 shrink-0 ml-auto"),inputClassName:M.z.string().default("w-4 h-4 shrink-0 accent-blue-500")});var vl=require("react/jsx-runtime");function rt({children:t,required:e,className:r,asteriskClassName:o}){return(0,vl.jsxs)("label",{className:r,children:[t,e&&(0,vl.jsx)("span",{className:o,children:"*"})]})}var Bs=require("react");function ot({name:t,required:e=!1,validate:r,initialValue:o}){let n=yt(),s=(0,Bs.useRef)(r);(0,Bs.useEffect)(()=>{s.current=r},[r]),(0,Bs.useEffect)(()=>n.getState().registerField(t,{required:e,validate:i=>s.current?.(i)??null,defaultValue:o}),[])}var ho=require("react/jsx-runtime"),Lk=t=>t?/^[\n\x20-\x7E]*$/:/^[\x20-\x7E]*$/;function Nk(t,e,r=!1){return t.replace(r?/[^\n\x20-\x7E]/g:/[^\x20-\x7E]/g,"").slice(0,e)}function jk(t,e,r,o,n=!1){return s=>s.trim().length?o?o(s):s.length>e?`Must be ${e} characters or fewer.`:Lk(n).test(s)?null:"Only standard characters are allowed.":t?r:null}function De(t){let{inputRef:e}=t,{fieldId:r,label:o,placeholder:n,initialValue:s,required:i,showLabel:a,showError:l,autoCompleteType:u,fieldClassName:c,containerClassName:d,fieldLabelClassName:f,fieldErrorClassName:m,fieldAsteriskClassName:h,requiredText:g,disabled:y,maxLength:p,validate:b,sanitize:_,inputType:v,min:N,max:x,multiline:P,rows:Z}=gn.parse(t),q=_??(Ue=>Nk(Ue,p,P)),nt=jk(i,p,g,b,P);ot({name:r,required:i,validate:nt,initialValue:s});let{value:ge,setValue:st,error:er,clearError:tr,validate:rr}=ie(r);return(0,ho.jsxs)("div",{className:d,children:[a&&(0,ho.jsx)(rt,{required:i,className:f,asteriskClassName:h,children:o}),P?(0,ho.jsx)("textarea",{name:r,rows:Z,autoComplete:u,placeholder:n,value:ge??"",onChange:Ue=>{st(q(Ue.target.value)),tr()},onBlur:rr,"data-error":!!er||void 0,className:c,disabled:y,maxLength:p}):(0,ho.jsx)("input",{type:v,ref:e,name:r,autoComplete:u,placeholder:n,value:ge??"",onChange:Ue=>{st(q(Ue.target.value)),tr()},onBlur:rr,"data-error":!!er||void 0,className:c,disabled:y,maxLength:p,min:N,max:x}),l&&(0,ho.jsx)(_e,{name:r,className:m})]})}var Sl=require("zod");var Oy=require("react/jsx-runtime");function Mk(t){let e=t.replace(/\D/g,""),r=/^\d{10}$/.test(e),o=/^1\d{10}$/.test(e);return r||o?null:"Please enter a valid 10-digit phone number."}function Uk(t){let e=t.replace(/\D/g,"");if(e.startsWith("1")&&e.length>10){e=e.slice(0,11);let r=e.slice(1);return`+1 (${r.slice(0,3)}) ${r.slice(3,6)}-${r.slice(6,10)}`}return e=e.slice(0,10),e.length<=3?e:e.length<=6?`(${e.slice(0,3)}) ${e.slice(3)}`:`(${e.slice(0,3)}) ${e.slice(3,6)}-${e.slice(6)}`}var Fk=ae.extend({fieldId:Sl.z.string().default("phone"),placeholder:Sl.z.string().default("(586) 313-2480"),label:Sl.z.string().default("Phone number")});function Kc(t){let e=Fk.parse(t);return(0,Oy.jsx)(De,{...e,validate:Mk,sanitize:Uk})}var qs=require("zod");var Ay=require("react/jsx-runtime");function $k(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.trim())?null:"Please enter a valid email address."}var Bk=ae.extend({fieldId:qs.z.string().default("email"),placeholder:qs.z.string().default("Email"),label:qs.z.string().default("Email"),autoCompleteType:qs.z.string().default("email")});function Jc(t){let e=Bk.parse(t);return(0,Ay.jsx)(De,{...e,validate:$k})}var bt=require("react/jsx-runtime");function Yc(t){let{fieldId:e,label:r,required:o,showLabel:n,showError:s,containerClassName:i,fieldLabelClassName:a,fieldErrorClassName:l,fieldAsteriskClassName:u,requiredText:c,disabled:d,options:f,minSelections:m,maxSelections:h,initialValue:g,tooFewText:y,tooManyText:p,optionClassName:b,optionActiveClassName:_,optionLabelClassName:v,optionActiveLabelClassName:N,optionSublabelClassName:x,inputClassName:P}=Py.parse(t),Z=h===1,q=Z&&m===0;function nt(j){return o&&j.length===0?c:j.length<m?y??`Please select at least ${m}.`:j.length>h?p??`Please select at most ${h}.`:null}ot({name:e,required:o,initialValue:g??[],validate:nt});let{value:ge,error:st,setValue:er,setError:tr,validate:rr}=ie(e),Ue=ge??[];function S(j){let re=Z?Ue.includes(j)&&q?[]:[j]:Ue.includes(j)?Ue.filter(ee=>ee!==j):[...Ue,j];if(re.length>h){tr(p??`Please select at most ${h}.`);return}er(re),rr()}function V(j){j.currentTarget.contains(j.relatedTarget)||rr()}return(0,bt.jsxs)("div",{className:i,children:[n&&(0,bt.jsx)(rt,{required:o,className:a,asteriskClassName:u,children:r}),(0,bt.jsx)("div",{className:"space-y-2",onBlur:V,tabIndex:-1,"data-error":!!st||void 0,"aria-invalid":!!st||void 0,children:f.map(j=>{let re=Ue.includes(j.value),ee=d||j.disabled;return(0,bt.jsxs)("label",{className:`flex items-center gap-3 ${b} ${re?_:""} ${ee?"opacity-50 cursor-not-allowed":""}`,children:[(0,bt.jsx)("input",{type:q?"checkbox":Z?"radio":"checkbox",name:e,checked:re,disabled:ee,onChange:()=>S(j.value),className:P}),(0,bt.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,bt.jsx)("span",{className:re?N:v,children:j.label}),j.description&&(0,bt.jsx)("p",{className:"text-xs text-stone-400 mt-0.5 leading-snug",children:j.description})]}),j.sublabel&&(0,bt.jsx)("span",{className:x,children:j.sublabel})]},j.value)})}),s&&(0,bt.jsx)(_e,{name:e,className:l})]})}var Ry=require("react");function Xc({locationInputRef:t,isApplyingAutocompleteRef:e,setEventLocation:r,onCoordsResolved:o}){(0,Ry.useEffect)(()=>{let n=window;function s(){if(!t.current||!n.google)return;let i=new n.google.maps.places.Autocomplete(t.current,{types:["establishment","geocode"],componentRestrictions:{country:"us"},fields:["formatted_address","name","geometry"]});i.addListener("place_changed",()=>{let a=i.getPlace(),l=a.formatted_address?.trim()??"",u=a.name?.trim()??"",c=u.toLowerCase(),d=l.toLowerCase(),f=u&&l&&!d.startsWith(c)?`${u}, ${l}`:l||u;e.current=!0,t.current&&(t.current.value=f),r(f),a.geometry?.location&&o?.({lat:a.geometry.location.lat(),lng:a.geometry.location.lng()}),requestAnimationFrame(()=>{e.current=!1})})}n.google?s():window.addEventListener("google-maps-loaded",s,{once:!0})},[e,t,r,o])}var Zc=require("react");var Iy=require("react");function Qc(){return(0,Iy.useEffect)(()=>{let t=process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY;t&&gy(t).then(()=>window.dispatchEvent(new Event("google-maps-loaded"))).catch(()=>{})},[]),null}var xl=require("zod"),po=require("react/jsx-runtime"),qk=gn.extend({fieldId:xl.z.string().default("eventLocation"),label:xl.z.string().default("Event location"),placeholder:xl.z.string().default("Search for a venue or enter an address\u2026")});function ed(t){let e=(0,Zc.useRef)(null),r=(0,Zc.useRef)(!1),o=qk.parse(t),{setValue:n,clearError:s}=ie(o.fieldId);function i(a){return a.replace(/<[^>]*>/g,"").trimStart().slice(0,255)}return Xc({locationInputRef:e,isApplyingAutocompleteRef:r,setEventLocation:a=>{n(i(a)),s()}}),(0,po.jsxs)(po.Fragment,{children:[(0,po.jsx)(Qc,{}),(0,po.jsx)(De,{...o,inputRef:e})]})}var kl=require("react"),Je=require("zod");var Ly=require("react/jsx-runtime"),Vk="yyyy-MM-dd",td="HH:mm",Wk=ae.extend({fieldId:Je.z.string().default("time"),label:Je.z.string().default("Start time"),autoCompleteType:Je.z.string().default("off"),inputType:Je.z.literal("time").default("time"),minTime:Je.z.string().optional(),maxTime:Je.z.string().optional(),closedSpans:Je.z.array(Je.z.object({from:Je.z.string(),to:Je.z.string()})).optional(),minimumNoticeHours:Je.z.number().nullable().optional(),dateFieldId:Je.z.string().default("date"),timezone:Je.z.string().default(Intl.DateTimeFormat().resolvedOptions().timeZone)});function Yt(t){return Qe(t,td,new Date)}function Dy(t){return Be(Yt(t),"h:mm a")}function Hk(t){return t.replace(/[^\d:]/g,"").slice(0,5)}function Rr(t){let{minTime:e,maxTime:r,closedSpans:o,minimumNoticeHours:n,dateFieldId:s,timezone:i,...a}=Wk.parse(t),u=Ve()[s],{value:c,validate:d}=ie(a.fieldId),f=(0,kl.useRef)(!0);(0,kl.useEffect)(()=>{if(f.current){f.current=!1;return}c&&d()},[u,n,e,r]);function m(g){if(!/^\d{2}:\d{2}$/.test(g)||!ao(Yt(g)))return"Please enter a valid time.";if(e&&Ge(Yt(g),Yt(e)))return`Please choose a time after ${Dy(e)}.`;if(r&&$t(Yt(g),Yt(r)))return`Please choose a time before ${Dy(r)}.`;if(o?.some(y=>!Ge(Yt(g),Yt(y.from))&&!$t(Yt(g),Yt(y.to))))return"This time is unavailable.";if(n&&u){let y=Qe(`${u} ${g}`,`${Vk} ${td}`,new Date);if(!ao(y))return"Please enter a valid date and time.";let p=cc(y,i),b=Yh(Yo(new Date,n));if(Ge(p,b)){let _=Es(b,i),v=Be(_,"MMM d 'at' h:mm a");return`Please select a time at least ${n} hours from now (after ${v}).`}}return null}let h=a.initialValue??(n?Be(Ph(Yo(new Date,n),5),td):void 0);return(0,Ly.jsx)(De,{...a,initialValue:h,validate:m,sanitize:Hk})}var Xt=require("zod");var Ny=require("react/jsx-runtime"),Ir="yyyy-MM-dd";function zk(t,e,r,o){let n=Qe(t,Ir,new Date);return!ao(n)||Be(n,Ir)!==t?"Please enter a valid date.":e&&Ge(n,Qe(e,Ir,new Date))?`Please choose ${e} or later.`:r&&$t(n,Qe(r,Ir,new Date))?`Please choose ${r} or earlier.`:o?.includes(t)?"This date is unavailable. Please choose another.":null}function Gk(t){return t.replace(/[^\d-]/g,"").slice(0,10)}var Kk=ae.extend({fieldId:Xt.z.string().default("date"),label:Xt.z.string().default("Event date"),autoCompleteType:Xt.z.string().default("off"),inputType:Xt.z.literal("date").default("date"),minimumNoticeHours:Xt.z.number().nullable().optional(),minDate:Xt.z.date().optional(),maxDate:Xt.z.date().optional(),unavailableDates:Xt.z.array(Xt.z.date()).optional()});function go(t){let{minDate:e,maxDate:r,unavailableDates:o,minimumNoticeHours:n,...s}=Kk.parse(t),i=e??(n?Et(Yo(new Date,n)):Et(new Date)),a=Be(i,Ir),l=r?Be(r,Ir):void 0,u=o?.map(f=>Be(f,Ir));function c(f){return zk(f,a,l,u)}let d=s.initialValue??(n?Be(Et(Yo(new Date,n)),Ir):a);return(0,Ny.jsx)(De,{...s,initialValue:d,min:a,max:l,validate:c,sanitize:Gk})}var pr=require("zod");var jy=require("react/jsx-runtime");function Jk(t){return t.replace(/[^0-9]/g,"").slice(0,255)}var Yk=ae.extend({fieldId:pr.z.string().default("discreteNumber"),placeholder:pr.z.string().default("10"),label:pr.z.string().default("Number of guests"),min:pr.z.number().default(10),max:pr.z.number().default(5e3),minErrorText:pr.z.string().optional(),maxErrorText:pr.z.string().optional(),step:pr.z.number().default(1)});function Xk(t,e,r,o){return n=>{let s=Number(n);return Number.isNaN(s)?"Please enter a valid number.":s<t?r??`Must be at least ${t}.`:s>e?o??`Must be ${e} or fewer.`:null}}function rd(t){let e=Yk.parse(t),{min:r,max:o,minErrorText:n,maxErrorText:s,...i}=e;return(0,jy.jsx)(De,{...i,validate:Xk(r,o,n,s),sanitize:Jk})}var Vs=require("zod");var yn=require("react/jsx-runtime"),Qk=ae.extend({min:Vs.z.number().default(0),max:Vs.z.number().default(100),step:Vs.z.number().default(1),onChange:Vs.z.any().optional()});function od(t){let{fieldId:e,label:r,min:o,max:n,step:s,required:i,showLabel:a,showError:l,fieldClassName:u,containerClassName:c,fieldLabelClassName:d,fieldAsteriskClassName:f,fieldErrorClassName:m,initialValue:h,requiredText:g,disabled:y,onChange:p}=Qk.parse(t);function b(Z){return i&&Z==null?g:Z<o?`Must be at least ${o}.`:Z>n?`Must be ${n} or fewer.`:null}ot({name:e,required:i,validate:b,initialValue:h??o});let{value:_,setValue:v,error:N,clearError:x,validate:P}=ie(e);return(0,yn.jsxs)("div",{className:c,children:[a&&(0,yn.jsx)(rt,{required:i,className:d,asteriskClassName:f,children:r}),(0,yn.jsx)("input",{type:"range",min:o,max:n,step:s,value:_??o,disabled:y,onChange:Z=>{let q=Number(Z.target.value);v(q),x(),p?.(q)},onBlur:P,"data-error":!!N||void 0,className:u}),l&&(0,yn.jsx)(_e,{name:e,className:m})]})}var nd=require("zod");var yo=require("react/jsx-runtime"),Zk=ae.extend({checkboxClassName:nd.z.string().default("mt-0.5 h-5 w-5 shrink-0 rounded"),labelClassName:nd.z.string().default("pt-0.5 text-sm leading-snug")});function sd({children:t,...e}){let{fieldId:r,required:o,requiredText:n,showError:s,disabled:i,containerClassName:a,fieldErrorClassName:l,checkboxClassName:u,labelClassName:c,initialValue:d}=Zk.parse(e);ot({name:r,required:!1,validate:o?g=>g?null:n:void 0,initialValue:d??!1});let{value:f,setValue:m,validate:h}=ie(r);return(0,yo.jsxs)("div",{className:a,children:[(0,yo.jsxs)("div",{className:"flex items-start gap-3 px-1 py-2 min-h-[44px]",children:[(0,yo.jsx)("input",{type:"checkbox",id:r,checked:f??!1,onChange:g=>{m(g.target.checked),o&&h()},disabled:i,className:u}),(0,yo.jsx)("label",{htmlFor:r,className:c,children:t})]}),s&&(0,yo.jsx)(_e,{name:r,className:l})]})}var id=require("react/jsx-runtime");function ad({name:t,label:e="Quantity",initalVal:r=0,showLabel:o=!0,showError:n=!0,showIncrement:s=!0,showDecrement:i=!0}){return(0,id.jsx)("div",{children:(0,id.jsx)(rt,{required:!0,children:e})})}var Dr=require("zod");var Lr=require("react/jsx-runtime"),eT=gn.extend({fieldId:Dr.z.string().default("nameFields"),outerClassName:Dr.z.string().default("flex flex-col md:flex-row w-full gap-4"),firstNamePlaceholder:Dr.z.string().default("First name"),lastNamePlaceholder:Dr.z.string().default("Last name"),firstNameInitialValue:Dr.z.string().default(""),lastNameInitialValue:Dr.z.string().default(""),childClassName:Dr.z.string().default("flex flex-col w-full md:flex-1 md:min-w-0")});function tT({className:t}){let{error:e}=ie("firstName"),{error:r}=ie("lastName"),o=e??r;return o?(0,Lr.jsx)("span",{className:t,children:o}):null}function ld(t){let e=eT.parse({...t}),{outerClassName:r,firstNamePlaceholder:o,lastNamePlaceholder:n,firstNameInitialValue:s,lastNameInitialValue:i,childClassName:a,...l}=e;return(0,Lr.jsxs)("div",{className:"flex flex-col w-full gap-1",children:[(0,Lr.jsxs)("div",{className:r,children:[(0,Lr.jsx)(De,{...l,fieldId:"firstName",label:"First name",placeholder:o,initialValue:s,autoCompleteType:"given-name",containerClassName:a,showError:!1}),(0,Lr.jsx)(De,{...l,fieldId:"lastName",label:"Last name",placeholder:n,initialValue:i,autoCompleteType:"family-name",containerClassName:a,showError:!1})]}),(0,Lr.jsx)(tT,{className:l.fieldErrorClassName})]})}var we=require("zod");var Nr=require("react/jsx-runtime"),rT=ae.extend({fieldId:we.z.string().default("dateTime"),outerClassName:we.z.string().default("flex flex-col md:flex-row w-full gap-4"),childClassName:we.z.string().default("flex flex-col w-full md:flex-1 md:min-w-0"),dateLabel:we.z.string().default("Event date"),dateFieldId:we.z.string().default("date"),minDate:we.z.date().optional(),maxDate:we.z.date().optional(),unavailableDates:we.z.array(we.z.date()).optional(),minimumNoticeHours:we.z.number().nullable().optional(),timeLabel:we.z.string().default("Start time"),timeFieldId:we.z.string().default("time"),closedSpans:we.z.array(we.z.object({from:we.z.string(),to:we.z.string()})).optional(),timezone:we.z.string().default(Intl.DateTimeFormat().resolvedOptions().timeZone),dateInitialValue:we.z.string().optional(),timeInitialValue:we.z.string().optional()});function ud(t){let{minTime:e,maxTime:r,timeBounds:o,...n}=t,{fieldId:s,outerClassName:i,childClassName:a,inputType:l,dateLabel:u,dateFieldId:c,minDate:d,maxDate:f,unavailableDates:m,minimumNoticeHours:h,timeLabel:g,timeFieldId:y,closedSpans:p,timezone:b,dateInitialValue:_,timeInitialValue:v,...N}=rT.parse(n),x=bl(Ve()),P=o?o(x):void 0,Z=P?.min??(typeof e=="function"?e(x):e),q=P?.max??(typeof r=="function"?r(x):r);return(0,Nr.jsxs)("div",{className:"flex flex-col w-full gap-1",children:[(0,Nr.jsxs)("div",{className:i,children:[(0,Nr.jsx)(go,{...N,inputType:"date",fieldId:c,label:u,minDate:d,maxDate:f,unavailableDates:m,minimumNoticeHours:h,containerClassName:a,showError:!1,initialValue:_??N.initialValue}),(0,Nr.jsx)(Rr,{...N,inputType:"time",fieldId:y,label:g,minTime:Z,maxTime:q,closedSpans:p,minimumNoticeHours:h,dateFieldId:c,timezone:b,containerClassName:a,showError:!1,initialValue:v??N.initialValue})]}),(0,Nr.jsx)(_e,{name:c,className:N.fieldErrorClassName}),(0,Nr.jsx)(_e,{name:y,className:N.fieldErrorClassName})]})}var pe=require("zod");var Ot=require("react/jsx-runtime"),oT=ae.extend({fieldId:pe.z.string().default("dateTimeRange"),dateLabel:pe.z.string().default("Event date"),dateFieldId:pe.z.string().default("date"),minDate:pe.z.date().optional(),maxDate:pe.z.date().optional(),unavailableDates:pe.z.array(pe.z.date()).optional(),minimumNoticeHours:pe.z.number().nullable().optional(),startTimeLabel:pe.z.string().default("Start time"),startTimeFieldId:pe.z.string().default("startTime"),endTimeLabel:pe.z.string().default("End time"),endTimeFieldId:pe.z.string().default("endTime"),closedSpans:pe.z.array(pe.z.object({from:pe.z.string(),to:pe.z.string()})).optional(),timezone:pe.z.string().default(Intl.DateTimeFormat().resolvedOptions().timeZone),dateInitialValue:pe.z.string().optional(),startTimeInitialValue:pe.z.string().optional(),endTimeInitialValue:pe.z.string().optional()});function cd(t){let{fieldId:e,inputType:r,dateLabel:o,dateFieldId:n,minDate:s,maxDate:i,unavailableDates:a,minimumNoticeHours:l,startTimeLabel:u,startTimeFieldId:c,endTimeLabel:d,endTimeFieldId:f,closedSpans:m,timezone:h,dateInitialValue:g,startTimeInitialValue:y,endTimeInitialValue:p,...b}=oT.parse(t),v=Ve()[c];return(0,Ot.jsxs)("div",{className:"flex flex-col w-full gap-1",children:[(0,Ot.jsxs)("div",{className:"flex flex-col md:flex-row w-full gap-4",children:[(0,Ot.jsx)(go,{...b,inputType:"date",fieldId:n,label:o,minDate:s,maxDate:i,unavailableDates:a,minimumNoticeHours:l,containerClassName:"flex flex-col w-full md:flex-1 md:min-w-0",showError:!1,initialValue:g??b.initialValue}),(0,Ot.jsxs)("div",{className:"flex flex-row gap-4 md:contents",children:[(0,Ot.jsx)(Rr,{...b,inputType:"time",fieldId:c,label:u,closedSpans:m,minimumNoticeHours:l,dateFieldId:n,timezone:h,containerClassName:"flex flex-col flex-1 min-w-0 md:flex-1",showError:!1,initialValue:y??b.initialValue}),(0,Ot.jsx)(Rr,{...b,inputType:"time",fieldId:f,label:d,minTime:v,closedSpans:m,dateFieldId:n,timezone:h,containerClassName:"flex flex-col flex-1 min-w-0 md:flex-1",showError:!1,initialValue:p??b.initialValue})]})]}),(0,Ot.jsx)(_e,{name:n,className:b.fieldErrorClassName}),(0,Ot.jsx)(_e,{name:c,className:b.fieldErrorClassName}),(0,Ot.jsx)(_e,{name:f,className:b.fieldErrorClassName})]})}var Qt=require("zod");var Zt=require("react"),_t=require("react/jsx-runtime"),nT=ae.extend({fieldId:Qt.z.string().default("guestCount"),label:Qt.z.string().default("Number of guests"),placeholder:Qt.z.string().default("10"),min:Qt.z.number().default(10),max:Qt.z.number().default(5e3),step:Qt.z.number().default(1),minErrorText:Qt.z.string().optional(),maxErrorText:Qt.z.string().optional(),sliderClassName:Qt.z.string().default("flex-[3]")});function dd(t){let{fieldId:e,label:r,placeholder:o,min:n,max:s,step:i,required:a,showLabel:l,showError:u,fieldClassName:c,containerClassName:d,fieldLabelClassName:f,fieldAsteriskClassName:m,fieldErrorClassName:h,initialValue:g,requiredText:y,minErrorText:p,maxErrorText:b,disabled:_,sliderClassName:v}=nT.parse(t);function N(S){if(!S?.trim())return a?y:null;let V=Number(S);return Number.isNaN(V)?"Please enter a valid number.":V<n?p??`Must be at least ${n}.`:V>s?b??`Must be ${s} or fewer.`:null}ot({name:e,required:a,validate:N,initialValue:g??String(n)});let{value:x,setValue:P,error:Z,clearError:q,validate:nt}=ie(e),ge=(0,Zt.useRef)(P),st=(0,Zt.useRef)(q),er=(0,Zt.useRef)(nt);(0,Zt.useEffect)(()=>{ge.current=P},[P]),(0,Zt.useEffect)(()=>{st.current=q},[q]),(0,Zt.useEffect)(()=>{er.current=nt},[nt]);let tr=Number(x)||n,rr=Math.max(0,Math.min(100,(tr-n)/(s-n)*100)),Ue=(0,Zt.useRef)(null);return(0,Zt.useEffect)(()=>{let S=Ue.current;if(!S)return;let V=0,j=0;function re(ye){let{left:xe,width:At}=S.getBoundingClientRect(),Rt=Math.max(0,Math.min(1,(ye-xe)/At)),_o=n+(s-n)*Rt;return String(Math.max(n,Math.min(s,Math.round(_o/i)*i)))}function ee(ye){V=ye.changedTouches[0].clientX,j=ye.changedTouches[0].clientY,ge.current(re(V)),st.current()}function J(ye){let xe=Math.abs(ye.changedTouches[0].clientX-V),At=Math.abs(ye.changedTouches[0].clientY-j);xe>At&&ye.preventDefault(),ge.current(re(ye.changedTouches[0].clientX)),st.current()}function Se(){er.current()}return S.addEventListener("touchstart",ee,{passive:!0}),S.addEventListener("touchmove",J,{passive:!1}),S.addEventListener("touchend",Se,{passive:!0}),()=>{S.removeEventListener("touchstart",ee),S.removeEventListener("touchmove",J),S.removeEventListener("touchend",Se)}},[]),(0,_t.jsxs)("div",{className:d,children:[l&&(0,_t.jsx)(rt,{required:a,className:f,asteriskClassName:m,children:r}),(0,_t.jsxs)("div",{className:"flex items-center gap-4",children:[(0,_t.jsxs)("div",{className:`flex flex-[6] flex-col ${v}`,children:[(0,_t.jsx)("input",{ref:Ue,type:"range",min:n,max:s,step:i,value:tr,disabled:_,onChange:S=>{P(S.target.value),q()},onBlur:nt,className:`w-full ${v}`,style:{"--slider-fill":`${rr}%`}}),(0,_t.jsxs)("div",{className:"flex justify-between text-xs text-stone-400 mt-2 px-0.5",children:[(0,_t.jsx)("span",{children:n}),(0,_t.jsx)("span",{children:s})]})]}),(0,_t.jsx)("input",{type:"text",inputMode:"numeric",placeholder:o,value:x??"",disabled:_,onChange:S=>{P(S.target.value.replace(/[^0-9]/g,"").slice(0,5)),q()},onBlur:nt,"data-error":!!Z||void 0,className:`flex-1 text-center ${c}`})]}),u&&(0,_t.jsx)(_e,{name:e,className:h})]})}var My=Le(require("react"),1),ve=My.default.createContext({});var bn=Le(require("react"),1),$y=require("react");var sT=Object.defineProperty,Uy=Object.getOwnPropertySymbols,iT=Object.prototype.hasOwnProperty,aT=Object.prototype.propertyIsEnumerable,Fy=(t,e,r)=>e in t?sT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fd=(t,e)=>{for(var r in e||(e={}))iT.call(e,r)&&Fy(t,r,e[r]);if(Uy)for(var r of Uy(e))aT.call(e,r)&&Fy(t,r,e[r]);return t},lT=(t,e)=>{let r=bn.useContext(ve),o=fd(fd({},r),t);return bn.createElement("svg",fd({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),bn.createElement("path",{d:"M10.5213 2.62368C11.3147 1.75255 12.6853 1.75255 13.4787 2.62368L14.4989 3.74391C14.8998 4.18418 15.4761 4.42288 16.071 4.39508L17.5845 4.32435C18.7614 4.26934 19.7307 5.23857 19.6757 6.41554L19.6049 7.92905C19.5771 8.52388 19.8158 9.10016 20.2561 9.50111L21.3763 10.5213C22.2475 11.3147 22.2475 12.6853 21.3763 13.4787L20.2561 14.4989C19.8158 14.8998 19.5771 15.4761 19.6049 16.071L19.6757 17.5845C19.7307 18.7614 18.7614 19.7307 17.5845 19.6757L16.071 19.6049C15.4761 19.5771 14.8998 19.8158 14.4989 20.2561L13.4787 21.3763C12.6853 22.2475 11.3147 22.2475 10.5213 21.3763L9.50111 20.2561C9.10016 19.8158 8.52388 19.5771 7.92905 19.6049L6.41553 19.6757C5.23857 19.7307 4.26934 18.7614 4.32435 17.5845L4.39508 16.071C4.42288 15.4761 4.18418 14.8998 3.74391 14.4989L2.62368 13.4787C1.75255 12.6853 1.75255 11.3147 2.62368 10.5213L3.74391 9.50111C4.18418 9.10016 4.42288 8.52388 4.39508 7.92905L4.32435 6.41553C4.26934 5.23857 5.23857 4.26934 6.41554 4.32435L7.92905 4.39508C8.52388 4.42288 9.10016 4.18418 9.50111 3.74391L10.5213 2.62368Z",stroke:"currentColor"}),bn.createElement("path",{d:"M9 12L11 14L15 10",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},uT=(0,$y.forwardRef)(lT),md=uT;var _n=Le(require("react"),1),Vy=require("react");var cT=Object.defineProperty,By=Object.getOwnPropertySymbols,dT=Object.prototype.hasOwnProperty,fT=Object.prototype.propertyIsEnumerable,qy=(t,e,r)=>e in t?cT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,hd=(t,e)=>{for(var r in e||(e={}))dT.call(e,r)&&qy(t,r,e[r]);if(By)for(var r of By(e))fT.call(e,r)&&qy(t,r,e[r]);return t},mT=(t,e)=>{let r=_n.useContext(ve),o=hd(hd({},r),t);return _n.createElement("svg",hd({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),_n.createElement("path",{d:"M7 12.5L10 15.5L17 8.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),_n.createElement("path",{d:"M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},hT=(0,Vy.forwardRef)(mT),Tl=hT;var wn=Le(require("react"),1),zy=require("react");var pT=Object.defineProperty,Wy=Object.getOwnPropertySymbols,gT=Object.prototype.hasOwnProperty,yT=Object.prototype.propertyIsEnumerable,Hy=(t,e,r)=>e in t?pT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,pd=(t,e)=>{for(var r in e||(e={}))gT.call(e,r)&&Hy(t,r,e[r]);if(Wy)for(var r of Wy(e))yT.call(e,r)&&Hy(t,r,e[r]);return t},bT=(t,e)=>{let r=wn.useContext(ve),o=pd(pd({},r),t);return wn.createElement("svg",pd({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),wn.createElement("path",{d:"M12 6L12 12L18 12",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),wn.createElement("path",{d:"M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},_T=(0,zy.forwardRef)(bT),Cl=_T;var Ws=Le(require("react"),1),Jy=require("react");var wT=Object.defineProperty,Gy=Object.getOwnPropertySymbols,vT=Object.prototype.hasOwnProperty,ST=Object.prototype.propertyIsEnumerable,Ky=(t,e,r)=>e in t?wT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,gd=(t,e)=>{for(var r in e||(e={}))vT.call(e,r)&&Ky(t,r,e[r]);if(Gy)for(var r of Gy(e))ST.call(e,r)&&Ky(t,r,e[r]);return t},xT=(t,e)=>{let r=Ws.useContext(ve),o=gd(gd({},r),t);return Ws.createElement("svg",gd({width:"1.5em",height:"1.5em",viewBox:"0 0 24 24",strokeWidth:1.5,fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),Ws.createElement("path",{d:"M22 9V17C22 18.1046 21.1046 19 20 19H4C2.89543 19 2 18.1046 2 17V7C2 5.89543 2.89543 5 4 5H20C21.1046 5 22 5.89543 22 7V9ZM22 9H6",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},kT=(0,Jy.forwardRef)(xT),yd=kT;var bo=Le(require("react"),1),Qy=require("react");var TT=Object.defineProperty,Yy=Object.getOwnPropertySymbols,CT=Object.prototype.hasOwnProperty,ET=Object.prototype.propertyIsEnumerable,Xy=(t,e,r)=>e in t?TT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,bd=(t,e)=>{for(var r in e||(e={}))CT.call(e,r)&&Xy(t,r,e[r]);if(Yy)for(var r of Yy(e))ET.call(e,r)&&Xy(t,r,e[r]);return t},PT=(t,e)=>{let r=bo.useContext(ve),o=bd(bd({},r),t);return bo.createElement("svg",bd({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),bo.createElement("path",{d:"M1.5 12.5L5.57574 16.5757C5.81005 16.8101 6.18995 16.8101 6.42426 16.5757L9 14",stroke:"currentColor",strokeLinecap:"round"}),bo.createElement("path",{d:"M16 7L12 11",stroke:"currentColor",strokeLinecap:"round"}),bo.createElement("path",{d:"M7 12L11.5757 16.5757C11.8101 16.8101 12.1899 16.8101 12.4243 16.5757L22 7",stroke:"currentColor",strokeLinecap:"round"}))},OT=(0,Qy.forwardRef)(PT),_d=OT;var vn=Le(require("react"),1),tb=require("react");var AT=Object.defineProperty,Zy=Object.getOwnPropertySymbols,RT=Object.prototype.hasOwnProperty,IT=Object.prototype.propertyIsEnumerable,eb=(t,e,r)=>e in t?AT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wd=(t,e)=>{for(var r in e||(e={}))RT.call(e,r)&&eb(t,r,e[r]);if(Zy)for(var r of Zy(e))IT.call(e,r)&&eb(t,r,e[r]);return t},DT=(t,e)=>{let r=vn.useContext(ve),o=wd(wd({},r),t);return vn.createElement("svg",wd({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),vn.createElement("path",{d:"M7 9L12 12.5L17 9",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),vn.createElement("path",{d:"M2 17V7C2 5.89543 2.89543 5 4 5H20C21.1046 5 22 5.89543 22 7V17C22 18.1046 21.1046 19 20 19H4C2.89543 19 2 18.1046 2 17Z",stroke:"currentColor"}))},LT=(0,tb.forwardRef)(DT),vd=LT;var Sn=Le(require("react"),1),nb=require("react");var NT=Object.defineProperty,rb=Object.getOwnPropertySymbols,jT=Object.prototype.hasOwnProperty,MT=Object.prototype.propertyIsEnumerable,ob=(t,e,r)=>e in t?NT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Sd=(t,e)=>{for(var r in e||(e={}))jT.call(e,r)&&ob(t,r,e[r]);if(rb)for(var r of rb(e))MT.call(e,r)&&ob(t,r,e[r]);return t},UT=(t,e)=>{let r=Sn.useContext(ve),o=Sd(Sd({},r),t);return Sn.createElement("svg",Sd({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),Sn.createElement("path",{d:"M20 5.99999L20 18C20 19.1046 19.1046 20 18 20H6C4.89543 20 4 19.1046 4 18V6C4 4.89543 4.89543 4 6 4H18C19.1045 4 19.9999 4.89543 20 5.99999Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),Sn.createElement("path",{d:"M12 9V4",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},FT=(0,nb.forwardRef)(UT),xd=FT;var xn=Le(require("react"),1),ab=require("react");var $T=Object.defineProperty,sb=Object.getOwnPropertySymbols,BT=Object.prototype.hasOwnProperty,qT=Object.prototype.propertyIsEnumerable,ib=(t,e,r)=>e in t?$T(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,kd=(t,e)=>{for(var r in e||(e={}))BT.call(e,r)&&ib(t,r,e[r]);if(sb)for(var r of sb(e))qT.call(e,r)&&ib(t,r,e[r]);return t},VT=(t,e)=>{let r=xn.useContext(ve),o=kd(kd({},r),t);return xn.createElement("svg",kd({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),xn.createElement("path",{d:"M19.2609 9.69589L20.6455 18.6959C20.8319 19.9074 19.8945 21 18.6688 21H5.33122C4.10545 21 3.16809 19.9074 3.35448 18.6959L4.73909 9.69589C4.8892 8.72022 5.7287 8 6.71584 8H17.2842C18.2713 8 19.1108 8.72022 19.2609 9.69589Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),xn.createElement("path",{d:"M14 5C14 3.89543 13.1046 3 12 3C10.8954 3 10 3.89543 10 5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},WT=(0,ab.forwardRef)(VT),Td=WT;var Hs=Le(require("react"),1),cb=require("react");var HT=Object.defineProperty,lb=Object.getOwnPropertySymbols,zT=Object.prototype.hasOwnProperty,GT=Object.prototype.propertyIsEnumerable,ub=(t,e,r)=>e in t?HT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Cd=(t,e)=>{for(var r in e||(e={}))zT.call(e,r)&&ub(t,r,e[r]);if(lb)for(var r of lb(e))GT.call(e,r)&&ub(t,r,e[r]);return t},KT=(t,e)=>{let r=Hs.useContext(ve),o=Cd(Cd({},r),t);return Hs.createElement("svg",Cd({width:"1.5em",height:"1.5em",viewBox:"0 0 24 24",strokeWidth:1.5,fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),Hs.createElement("path",{d:"M15 4L8 20",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},JT=(0,cb.forwardRef)(KT),El=JT;var kn=Le(require("react"),1),mb=require("react");var YT=Object.defineProperty,db=Object.getOwnPropertySymbols,XT=Object.prototype.hasOwnProperty,QT=Object.prototype.propertyIsEnumerable,fb=(t,e,r)=>e in t?YT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ed=(t,e)=>{for(var r in e||(e={}))XT.call(e,r)&&fb(t,r,e[r]);if(db)for(var r of db(e))QT.call(e,r)&&fb(t,r,e[r]);return t},ZT=(t,e)=>{let r=kn.useContext(ve),o=Ed(Ed({},r),t);return kn.createElement("svg",Ed({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),kn.createElement("path",{d:"M9.17218 14.8284L12.0006 12M14.829 9.17157L12.0006 12M12.0006 12L9.17218 9.17157M12.0006 12L14.829 14.8284",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),kn.createElement("path",{d:"M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},eC=(0,mb.forwardRef)(ZT),Pl=eC;function hb(t){return{label:(t.split(".").at(-1)??t).replace(/_/g," "),color:"gray"}}var de=require("react/jsx-runtime"),tC={"order.placed":{label:"Order placed",color:"blue",icon:Td},"device.order_received":{label:"Received",color:"blue",icon:xd},"order.requested":{label:"Requested",color:"blue",icon:Cl},"order.paid":{label:"Paid",color:"green",icon:yd},"device.order_acknowledged":{label:"Acknowledged",color:"blue",icon:_d},"order.confirmed":{label:"Confirmed",color:"green",icon:Tl},"order.confirmation_email_sent":{label:"Confirmation email sent",color:"green",icon:vd},"order.completed":{label:"Completed",color:"green",icon:md},"order.failed":{label:"Failed",color:"red",icon:Pl},"order.canceled":{label:"Cancelled",color:"red",icon:El},"order.cancelled":{label:"Cancelled",color:"red",icon:El},"order.catering.requested":{label:"Requested",color:"blue",icon:Cl},"order.catering.confirmed":{label:"Confirmed",color:"green",icon:Tl},"order.catering.charge_failed":{label:"Charge failed",color:"red",icon:Pl}};function Pd(t){return tC[t]??hb(t)}var rC=new Set(["order.catering.requested","order.catering.confirmed","order.catering.charge_failed","order.canceled","order.cancelled"]);function Od(t){let e=t.events.filter(i=>rC.has(i.event_name));if(!e.length)return null;let r=e[e.length-1],o=r.payload,n=r.event_name==="order.catering.confirmed"?"confirmed":r.event_name==="order.catering.requested"?"requested":"rejected",s=typeof o.userId=="string"?t.actorNames?.[o.userId]??o.userId:typeof o.deviceId=="number"?`Device #${o.deviceId}`:null;return{status:n,via:o.via??null,when:r.created_at,actorName:s}}function Ad(t){let e=bs.ORDER_STATUS;switch(t.order_status){case e.REQUESTED:return{label:"Awaiting approval",color:"blue"};case e.CONFIRMED:return{label:"Confirmed",color:"green"};case e.CANCELLED:return t.is_catering?{label:"Rejected",color:"red"}:{label:"Cancelled",color:"red"};case e.PAID:case e.PARTIALLY_PAID:return{label:"Paid",color:"green"};case e.PREPARING:return{label:"Preparing",color:"blue"};case e.KITCHEN_DONE:case e.COMPLETED:return{label:"Completed",color:"green"};default:return{label:"Pending",color:"gray"}}}function Rd(t){let e=bs.ORDER_STATUS;return t.order_status===(t.is_catering?e.REQUESTED:e.STAGING)}function oC(t){return t<1e3?`${t}ms`:t<6e4?`${Math.round(t/1e3)}s`:t<36e5?`${Math.round(t/6e4)}m`:`${Math.round(t/36e5)}h`}var Id={root:"flex flex-col gap-6 min-w-0 text-white",statusPill:"text-sm font-semibold px-3 py-1 rounded-full",approval:"text-white/60 text-sm",approvalEmpty:"text-white/40 text-sm",timeline:"flex items-start overflow-x-auto pb-2",eventIcon:"w-10 h-10 rounded-xl shrink-0 flex items-center justify-center",eventLabel:"text-xs font-medium text-center",eventTime:"text-white/30 text-xs text-center",connectorLine:"h-px w-8 bg-white/20",connectorDelta:"text-white/30 text-xs",confirmButton:"w-full py-4 rounded-lg text-base font-bold text-white bg-green-600 hover:bg-green-500 disabled:opacity-60 transition-colors",confirmError:"text-red-400 text-xs text-center",colors:{blue:{bg:"bg-blue-500/20",text:"text-blue-400",dot:"bg-blue-500/60"},green:{bg:"bg-green-500/20",text:"text-green-400",dot:"bg-green-500/60"},red:{bg:"bg-red-500/20",text:"text-red-400",dot:"bg-red-500/60"},gray:{bg:"bg-white/10",text:"text-white/50",dot:"bg-white/60"}}};function Dd(t){let e=Id,{colors:r,...o}=t??{},n=Object.fromEntries(Object.keys(e.colors).map(i=>[i,{...e.colors[i],...r?.[i]}])),s=Object.fromEntries(Object.entries(o).filter(([,i])=>i!==void 0));return{...e,...s,colors:n}}var nC={pos:"at the POS",dashboard:"from the dashboard",email_link:"via an emailed link"};function pb({order:t,can:e,onConfirm:r,confirming:o,confirmError:n,itemClasses:s}){let i=Dd(s),a=Ad(t),l=Od(t),u=t.events,c=!!r&&e("catering.confirm")&&Rd(t);return(0,de.jsxs)("div",{className:i.root,children:[(0,de.jsx)("div",{className:"flex items-center gap-2",children:(0,de.jsx)("span",{className:`${i.statusPill} ${i.colors[a.color].bg} ${i.colors[a.color].text}`,children:a.label})}),(0,de.jsx)("div",{className:"flex flex-col gap-1",children:l===null?(0,de.jsx)("span",{className:i.approvalEmpty,children:"No approval recorded."}):l.status==="requested"?(0,de.jsx)("span",{className:i.approval,children:"Awaiting approval."}):(0,de.jsxs)("span",{className:i.approval,children:[l.status==="confirmed"?"Confirmed":"Rejected",l.actorName&&` by ${l.actorName}`,l.via&&` ${nC[l.via]}`," on ",Be(new Date(l.when),"MMM d, h:mm a")]})}),u.length>0&&(0,de.jsx)("div",{className:i.timeline,children:u.map((d,f)=>{let m=Pd(d.event_name),h=i.colors[m.color],g=f===u.length-1,y=m.icon;return(0,de.jsxs)("div",{className:"flex items-start shrink-0",children:[(0,de.jsxs)("div",{className:"flex flex-col items-center gap-2 min-w-20",children:[(0,de.jsx)("div",{className:`${i.eventIcon} ${h.bg}`,children:y?(0,de.jsx)(y,{width:18,height:18,className:h.text}):(0,de.jsx)("div",{className:`w-2 h-2 rounded-full ${h.dot}`})}),(0,de.jsx)("span",{className:`${i.eventLabel} ${h.text}`,children:m.label}),(0,de.jsx)("span",{className:i.eventTime,children:Be(new Date(d.created_at),"h:mm a")})]}),!g&&(0,de.jsxs)("div",{className:"flex flex-col items-center gap-1 mt-4 shrink-0",children:[(0,de.jsx)("div",{className:i.connectorLine}),(0,de.jsx)("span",{className:i.connectorDelta,children:oC(Ah(new Date(u[f+1].created_at),new Date(d.created_at)))})]})]},d.id)})}),c&&(0,de.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,de.jsx)("button",{onClick:r,disabled:o,className:i.confirmButton,children:o?"Confirming\u2026":"Confirm This Order"}),n&&(0,de.jsx)("span",{className:i.confirmError,children:n})]})]})}var K=require("react/jsx-runtime"),Ld={root:"flex flex-col gap-1 min-w-0 text-white",line:"flex flex-col gap-1 py-2 border-b border-white/10 last:border-b-0",lineName:"text-sm font-semibold text-white",lineSublabel:"text-xs text-white/50",linePrice:"text-sm font-semibold text-white tabular-nums",addOn:"flex justify-between items-baseline gap-2 text-xs",addOnName:"text-white/60",addOnPrice:"text-white/40",totalsRow:"flex justify-between text-sm text-white/70",discountRow:"flex justify-between text-sm text-green-400",totalRow:"flex justify-between text-base font-bold text-white mt-2"};function Nd(t){let e=Object.fromEntries(Object.entries(t??{}).filter(([,r])=>r!==void 0));return{...Ld,...e}}function jd(t){return`${t.quantity} guests \xD7 ${Wt(t.unitPrice)}/person`}function Md(t,e){return t.upcharge<=0?"included":`+${Wt(t.upcharge)}${e?"/person":""}`}function gb({order:t,promotion:e,tip:r=0,itemClasses:o}){let n=Nd(o),s=sn(t,e,r);return(0,K.jsxs)("div",{className:n.root,children:[s.lines.map((i,a)=>(0,K.jsxs)("div",{className:n.line,children:[(0,K.jsxs)("div",{className:"flex justify-between items-start gap-2",children:[(0,K.jsxs)("div",{className:"min-w-0",children:[(0,K.jsx)("p",{className:n.lineName,children:i.name}),i.perPerson?(0,K.jsx)("p",{className:n.lineSublabel,children:jd(i)}):i.quantity>1&&(0,K.jsxs)("p",{className:n.lineSublabel,children:["\xD7",i.quantity]})]}),(0,K.jsx)("span",{className:n.linePrice,children:Wt(i.lineTotal)})]}),i.addOns.length>0&&(0,K.jsx)("div",{className:"flex flex-col gap-0.5 mt-1",children:i.addOns.map((l,u)=>(0,K.jsxs)("div",{className:n.addOn,children:[(0,K.jsx)("span",{className:n.addOnName,children:l.name}),(0,K.jsx)("span",{className:n.addOnPrice,children:Md(l,i.perPerson)})]},u))})]},a)),(0,K.jsxs)("div",{className:"flex flex-col gap-1 mt-2",children:[(0,K.jsxs)("div",{className:n.totalsRow,children:[(0,K.jsx)("span",{children:"Subtotal"}),(0,K.jsx)("span",{children:Wt(s.subtotal)})]}),s.discount>0&&(0,K.jsxs)("div",{className:n.discountRow,children:[(0,K.jsx)("span",{children:"Discount"}),(0,K.jsxs)("span",{children:["-",Wt(s.discount)]})]}),(0,K.jsxs)("div",{className:n.totalsRow,children:[(0,K.jsx)("span",{children:"Tax"}),(0,K.jsx)("span",{children:Wt(s.tax)})]}),s.serviceFee>0&&(0,K.jsxs)("div",{className:n.totalsRow,children:[(0,K.jsx)("span",{children:"Service fee"}),(0,K.jsx)("span",{children:Wt(s.serviceFee)})]}),s.tip>0&&(0,K.jsxs)("div",{className:n.totalsRow,children:[(0,K.jsx)("span",{children:"Tip"}),(0,K.jsx)("span",{children:Wt(s.tip)})]}),(0,K.jsxs)("div",{className:n.totalRow,children:[(0,K.jsx)("span",{children:"Total"}),(0,K.jsx)("span",{children:Wt(s.total)})]})]})]})}Ic(yy);Dc(yb.usePathname);0&&(module.exports={CheckboxField,ClickableField,ConditionalRenderer,DateField,DateTime,DateTimeRange,DisclaimerText,DiscreteNumberField,DynamicFormShell,EmailField,FieldError,FieldLabel,GuestCountField,Header,IncrementField,LOCATION_ORDERING_TIMEZONE,LocationField,NameFields,ORDER_ITEMIZED_DEFAULT_ITEM_CLASSES,ORDER_STATUS_DEFAULT_ITEM_CLASSES,OrderItemized,OrderStatus,PhoneField,Platforms,PricePreview,SectionLabel,SliderField,SubmitButton,TextField,TimeField,deriveApproval,deriveOrderStatus,divisionsFor,formatAddOnPrice,formatCateringLineLabel,groupItemPortions,isConfirmable,isLocationClosedByWeeklySchedule,itemizeOrder,locationWindowOn,mergeOrderItemizedItemClasses,mergeOrderStatusItemClasses,parsePortion,parsePortionKey,portionGlyph,portionKey,portionLabel,portionRows,portionWeight,radialSectionPath,remapPortion,resolveEventDisplay,sectionLabel,selectionWeight,setZorgoBoot,setZorgoPathnameHook,splitUpcharge,useCart,useCateringConfig,useCustomer,useField,useFormStatus,useFormValidity,useFormValues,useHydrateMenu,useHydrateStore,useItemCustomization,useLocation,useMenu,useModal,usePayment,usePromotions,useRecommendations,useRegisterField,weightedUpcharges});
|
|
157
|
+
`)&&(r=r.slice(0,-1))),super.equals(e,r,o)}},uF=new _c;function wc(t,e){e.stripTrailingCr&&(t=t.replace(/\r\n/g,`
|
|
158
|
+
`));let r=[],o=t.split(/(\n|\r\n)/);o[o.length-1]||o.pop();for(let n=0;n<o.length;n++){let s=o[n];n%2&&!e.newlineIsToken?r[r.length-1]+=s:r.push(s)}return r}var vc=class extends fo{constructor(){super(...arguments),this.tokenize=wc}get useLongestToken(){return!0}castInput(e,r){let{undefinedReplacement:o,stringifyReplacer:n=(s,i)=>typeof i>"u"?o:i}=r;return typeof e=="string"?e:JSON.stringify(al(e,null,null,n),null," ")}equals(e,r,o){return super.equals(e.replace(/,([\r\n])/g,"$1"),r.replace(/,([\r\n])/g,"$1"),o)}},wg=new vc;function Sc(t,e,r){return wg.diff(t,e,r)}function al(t,e,r,o,n){e=e||[],r=r||[],o&&(t=o(n===void 0?"":n,t));let s;for(s=0;s<e.length;s+=1)if(e[s]===t)return r[s];let i;if(Object.prototype.toString.call(t)==="[object Array]"){for(e.push(t),i=new Array(t.length),r.push(i),s=0;s<t.length;s+=1)i[s]=al(t[s],e,r,o,String(s));return e.pop(),r.pop(),i}if(t&&t.toJSON&&(t=t.toJSON()),typeof t=="object"&&t!==null){e.push(t),i={},r.push(i);let a=[],l;for(l in t)Object.prototype.hasOwnProperty.call(t,l)&&a.push(l);for(a.sort(),s=0;s<a.length;s+=1)l=a[s],i[l]=al(t[l],e,r,o,l);e.pop(),r.pop()}else i=t;return i}var vg=require("zustand"),Sg=require("zustand/middleware"),Or=(0,vg.create)()((0,Sg.devtools)((t,e)=>({logLevel:4,stack:[],openModal:r=>t({stack:[...e().stack,r]}),goBack:()=>{let r=e().stack;if(r.length>1){let o=r[r.length-1];if(!o)return;let n=r.slice(0,-1),s=n[n.length-1];o.displayStyle!=="dialog"&&s&&(n[n.length-1]={...s,workingData:null}),t({stack:n})}else t({stack:[]})},close:()=>t({stack:[]}),setWorkingData:(r,o=0)=>{if(e().logLevel<=1&&e().stack.length>1){let a=e().getWorkingData(),l=Sc(a,r);console.log("[MODAL STORE] working data diff from old:",l)}let n=e().stack,s=n.length-1-o;if(s<0)return;let i=[...n];i[s]={...i[s],workingData:r},t({stack:i})},getWorkingData:(r=0)=>{let o=e().stack;if(o.length!==0)return o[o.length-1-r]?.workingData}}),{name:"ModalStore"}));var Fx="v3",$x=function(e){return e===3?"v3":e},Tg="https://js.stripe.com",Bx="".concat(Tg,"/v3"),qx=/^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/,Vx=/^https:\/\/js\.stripe\.com\/(v3|[a-z]+)\/stripe\.js(\?.*)?$/,xg="loadStripe.setLoadParameters was called but an existing Stripe.js script already exists in the document; existing script parameters will be used",Wx=function(e){return qx.test(e)||Vx.test(e)},Hx=function(){for(var e=document.querySelectorAll('script[src^="'.concat(Tg,'"]')),r=0;r<e.length;r++){var o=e[r];if(Wx(o.src))return o}return null},kg=function(e){var r=e&&!e.advancedFraudSignals?"?advancedFraudSignals=false":"",o=document.createElement("script");o.src="".concat(Bx).concat(r);var n=document.head||document.body;if(!n)throw new Error("Expected document.body not to be null. Stripe.js requires a <body> element.");return n.appendChild(o),o},zx=function(e,r){!e||!e._registerWrapper||e._registerWrapper({name:"stripe-js",version:"5.10.0",startTime:r})},Ds=null,ll=null,ul=null,Gx=function(e){return function(r){e(new Error("Failed to load Stripe.js",{cause:r}))}},Kx=function(e,r){return function(){window.Stripe?e(window.Stripe):r(new Error("Stripe.js not available"))}},Jx=function(e){return Ds!==null?Ds:(Ds=new Promise(function(r,o){if(typeof window>"u"||typeof document>"u"){r(null);return}if(window.Stripe&&e&&console.warn(xg),window.Stripe){r(window.Stripe);return}try{var n=Hx();if(n&&e)console.warn(xg);else if(!n)n=kg(e);else if(n&&ul!==null&&ll!==null){var s;n.removeEventListener("load",ul),n.removeEventListener("error",ll),(s=n.parentNode)===null||s===void 0||s.removeChild(n),n=kg(e)}ul=Kx(r,o),ll=Gx(o),n.addEventListener("load",ul),n.addEventListener("error",ll)}catch(i){o(i);return}}),Ds.catch(function(r){return Ds=null,Promise.reject(r)}))},Yx=function(e,r,o){if(e===null)return null;var n=r[0],s=n.match(/^pk_test/),i=$x(e.version),a=Fx;s&&i!==a&&console.warn("Stripe.js@".concat(i," was loaded on the page, but @stripe/stripe-js@").concat("5.10.0"," expected Stripe.js@").concat(a,". This may result in unexpected behavior. For more information, see https://docs.stripe.com/sdks/stripejs-versioning"));var l=e.apply(void 0,r);return zx(l,o),l},Ls,Cg=!1,Eg=function(){return Ls||(Ls=Jx(null).catch(function(e){return Ls=null,Promise.reject(e)}),Ls)};Promise.resolve().then(function(){return Eg()}).catch(function(t){Cg||console.warn(t)});var Pg=function(){for(var e=arguments.length,r=new Array(e),o=0;o<e;o++)r[o]=arguments[o];Cg=!0;var n=Date.now();return Eg().then(function(s){return Yx(s,r,n)})};var Dg=require("zustand"),Lg=require("zustand/middleware");var Gt=Le(require("zod"),1),Ag=require("zustand"),Rg=require("zustand/middleware");var cl=globalThis;function mo(t){if(!cl.document)return null;let e=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=cl.document.cookie.match(new RegExp(`(?:^|; )${e}=([^;]*)`));return r?decodeURIComponent(r[1]):null}function xc(t,e,r=365){cl.document&&(cl.document.cookie=`${t}=${encodeURIComponent(e)}; path=/; max-age=${r*86400}; SameSite=Lax`)}var Og=Gt.default.object({shortUrlPath:Gt.default.string().optional().default("/s"),siteUrl:Gt.default.url().optional(),franchiseId:Gt.default.union([Gt.default.string(),Gt.default.number()]).optional(),locationId:Gt.default.union([Gt.default.string(),Gt.default.number()]).optional()});var Xx=(0,Ag.create)()((0,Rg.devtools)((t,e)=>({logLevel:1,config:Og.parse({}),sessionData:{},sessionId:xs(),consentGiven:mo("zorgo_consent")==="1",consentAnswered:mo("zorgo_consent")!==null,anonymousId:mo("zorgo_anon_id"),getSiteUrl:()=>{let r=e().config.siteUrl,o=typeof process<"u"?process.env.NEXT_PUBLIC_SITE_URL||process.env.NEXT_PUBLIC_BASE_URL:void 0,n=typeof globalThis<"u"&&"location"in globalThis&&globalThis.location?.origin?globalThis.location.origin:void 0,s=r||o||n;if(!s){e().logLevel<=3&&console.error("No site url found.");return}return s},getAnonymousId:()=>e().anonymousId,mergeSessionData:r=>{t(o=>{let n={...o.sessionData};for(let[s,i]of Object.entries(r))i===void 0?delete n[s]:n[s]=i;return{sessionData:n}})},setConsent:r=>{if(xc("zorgo_consent",r?"1":"0"),r&&!e().anonymousId){let o=`anon_${xs()}`;xc("zorgo_anon_id",o),t({consentGiven:!0,consentAnswered:!0,anonymousId:o})}else t({consentGiven:r,consentAnswered:!0})},initialize:({token:r,config:o})=>{let n=Og.parse(o||{});t({token:r,config:n,consentGiven:mo("zorgo_consent")==="1",consentAnswered:mo("zorgo_consent")!==null,anonymousId:mo("zorgo_anon_id")})}}),{name:"websiteCoreStore"})),Me=Xx;var Ig={logLevel:1,clientSecret:null,intentType:null,isLoading:!1,error:null,orderId:null,finalAmount:null},kc=!1,Qx=(0,Dg.create)()((0,Lg.devtools)((t,e)=>({...Ig,start:async()=>{let r=Y.getState().selectedLocation,o=process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY,n=process.env.NEXT_PUBLIC_STRIPE_ACCOUNT_OVERRIDE||r?.stripe_account_id;if(!o||!n)return null;let s=await Pg(o,{stripeAccount:n});if(!s){e().logLevel<=3&&console.error("Failed to load Stripe");return}t({stripe:s})},createOrder:async(r,o)=>{if(!r?.items?.length||!o?.location_id)throw new Error("Order, location, and time_requested are required");let n={...r,method_id:2,location_id:o.location_id},{franchiseId:s}=Me.getState().config,i=await qt("/create-order",{method:"POST",body:JSON.stringify({order:n,anonymous_id:Me.getState().getAnonymousId(),franchise_id:s?String(s):void 0})});if(!i.ok){let l=await i.json();throw new Error(l.error||`Server error: ${i.status}`)}return(await i.json()).orderId},createPaymentIntentForOrder:async(r,o,n)=>{let s=await qt("/create-payment-intent",{method:"POST",body:JSON.stringify({orderId:r,tipAmount:o,deliveryFeeCents:n||0})});if(!s.ok){let u=await s.json();throw new Error(u.error||`Server error: ${s.status}`)}let i=await s.json(),a=i.charges?.total??i.amount??0,l=i.type==="setup_intent"?"setup_intent":"payment_intent";return{clientSecret:i.clientSecret,amount:a,intentType:l}},confirmPayment:async(r,o,n,s,i)=>{let a=r,l={name:`${i.first_name} ${i.last_name}`.trim()||void 0,email:i.email,phone:tp(i.phone)},u=e().intentType,c={return_url:s,payment_method_data:{billing_details:l}},d;return u==="setup_intent"?{error:d}=await a.confirmSetup({elements:o,clientSecret:n,confirmParams:c}):{error:d}=await a.confirmPayment({elements:o,clientSecret:n,confirmParams:c}),d?{success:!1,error:d.message}:u!=="setup_intent"?{success:!0,paymentIntentId:(await a.retrievePaymentIntent(n)).paymentIntent?.id}:{success:!0}},getReturnStatus:r=>{let o=typeof r=="string"?new URL(r):r,n=o.searchParams.get("redirect_status"),s=o.searchParams.get("setup_intent"),i=o.searchParams.get("payment_intent")??s??void 0,a=!!s,l=o.searchParams.get("amount"),u=Number(o.searchParams.get("order")),c=Number.isSafeInteger(u)&&u>0?u:void 0,d=o.searchParams.get("order_token")??void 0;return n?n==="succeeded"?{succeeded:!0,amount:l?parseFloat(l):void 0,paymentIntentId:i,isHold:a,orderId:c,orderToken:c?d:void 0}:{succeeded:!1,error:`Payment ${n}`,paymentIntentId:i,isHold:a}:{succeeded:!1,error:"No payment status found in URL",isHold:a}},mintOrderLinkToken:async(r,o)=>{if(!r||!o)return null;try{let n=await qt(`/catering/order/${r}/link`,{method:"POST",body:JSON.stringify({email:o}),signal:AbortSignal.timeout(3e3)});if(!n.ok)return null;let s=await n.json();return typeof s?.token=="string"?s.token:null}catch{return null}},beginCheckout:async()=>{if(!(e().isLoading||kc)){kc=!0,t({isLoading:!0,error:null});try{let r=te.getState().workingOrder,o=Y.getState().selectedLocation,n=te.getState().selectedTip??0,s=te.getState().deliveryFeeCents??0;if(!o)throw new Error("Cannot start checkout without a selected location");if(!r)throw new Error("Cannot start checkout without a working order");let i=e().orderId;i||(i=await e().createOrder(r,o),t({orderId:i}));let{clientSecret:a,amount:l,intentType:u}=await e().createPaymentIntentForOrder(i,n,s);t({clientSecret:a,intentType:u,orderId:i,finalAmount:l,isLoading:!1,error:null})}catch(r){let o=r instanceof Error?r.message:"Failed to setup payment";throw t({isLoading:!1,error:o}),r}finally{kc=!1}}},reset:()=>t(Ig)}),{name:"PaymentStore"})),$e=Qx;var sy=require("zustand");var hn=require("zod"),ty=Le(Zg(),1),Ac=t=>(0,ty.default)(t).isLight()?"#000000":"#FFFFFF",pl=t=>hn.z.string().nullish().transform(e=>e??t),ey=t=>hn.z.number().nullish().transform(e=>e??t),ry=hn.z.object({design_id:ey(0),franchise_id:ey(0),primary:pl("#9943E9"),accent:pl("#6636BF"),backgroundBase:pl("#EBEBEB"),fontFamily:pl("Inter"),created_at:hn.z.string().optional(),updated_at:hn.z.string().optional()}).transform(t=>({...t,foreground:Ac(t.backgroundBase),primaryForeground:Ac(t.primary),accentForeground:Ac(t.accent)})),oy=ry.parse({});function ny(t){return ry.parse(t??{})}var pn=require("zustand/middleware");var hk="branding-assets",pk=3600,gk=(0,sy.create)()((0,pn.persist)((0,pn.devtools)((t,e)=>({branding:oy,logoUrl:null,fetchFranchiseLogoUrl:async r=>{let o=[`franchises/${r}/logo.png`,`franchises/${r}/logo.jpg`];for(let n of o){let{data:s,error:i}=await U.storage.from(hk).createSignedUrl(n,pk);if(!i&&s?.signedUrl)return t({logoUrl:s.signedUrl}),console.log("logoUrl",s.signedUrl),s.signedUrl;console.log("error",i)}return t({logoUrl:null}),null},initialize:async()=>{let r=Y.getState().franchiseId,{data:o,error:n}=await U.from("franchise_branding").select("*").eq("franchise_id",r).single();n||o&&t({branding:ny(o)})}})),{name:"branding",storage:(0,pn.createJSONStorage)(()=>kr()),skipHydration:xr,partialize:t=>({branding:t.branding})})),Rc=gk;var iy=require("zustand"),ay=require("zustand/middleware"),ly=require("zustand/middleware/immer");var yk=(0,iy.create)()((0,ay.devtools)((0,ly.immer)(t=>({recommendations:[],isLoading:!1,error:null,strategy:"top_items",lastFetchedAt:null,fetchRecommendations:async e=>{t(r=>{r.isLoading=!0,r.error=null});try{let r=await qt("/recommendations",{method:"POST",body:JSON.stringify(e)});if(!r.ok){let n=await r.json().catch(()=>null);throw new Error(n?.error??`Server error: ${r.status}`)}let o=await r.json();t(n=>{n.recommendations=o.recommendations??[],n.strategy=e.strategy??"top_items",n.isLoading=!1,n.lastFetchedAt=new Date})}catch(r){let o=r?.message??"Failed to fetch recommendations";t(n=>{n.error=o,n.isLoading=!1})}},setStrategy:e=>{t(r=>{r.strategy=e})},clear:()=>{t(e=>{e.recommendations=[],e.error=null,e.lastFetchedAt=null})}})),{name:"RecommendationStore"})),Kt=yk;function uy(){let t=()=>`ses_${crypto.randomUUID()}`;if(typeof sessionStorage>"u")return t();let e="zorgo_session_id",r=sessionStorage.getItem(e);return r||(r=t(),sessionStorage.setItem(e,r)),r}function cy(t){if(!t)return;let e=new URLSearchParams(t),r=e.get("utm_source")||void 0,o=e.get("utm_medium")||void 0,n=e.get("utm_campaign")||void 0;if(!(!r&&!o&&!n))return{source:r,medium:o,campaign:n}}var dy=()=>Promise.resolve();function Lc(t){dy=t}function Jt(){(0,L.useEffect)(()=>{dy().catch(console.error)},[])}var fy=()=>typeof window>"u"?"/":window.location.pathname;function Nc(t){fy=t}function bk(){let t=Or(r=>r.stack);return{current:t[t.length-1]??null,isOpen:t.length>0,depth:t.length,open:(r,o,n)=>Or.getState().openModal({type:r,props:o,displayStyle:n}),close:Or.getState().close,back:Or.getState().goBack,setWorkingData:Or.getState().setWorkingData,getWorkingData:Or.getState().getWorkingData}}function _k(){Jt();let t=te.getState(),e=te(u=>u.workingOrder),r=te(u=>u.selectedTip),{subtotal:o,discount:n,tax:s,serviceFee:i,total:a}=ag(),l=(0,L.useMemo)(()=>e.items.reduce((u,c)=>u+c.quantity,0),[e.items]);return{items:e.items,itemCount:l,isEmpty:l===0,customer:e.customer,promoCode:e.promo_code,tip:r,subtotal:o,discount:n,tax:s,serviceFee:i,total:a,addItem:t.addItem,removeItem:t.removeItem,updateItem:t.updateItem,resetCart:()=>{t.resetOrder(),t.setOrderType(2)},setCustomer:t.setCustomer,setLocationId:t.setLocationId,setOrderType:t.setOrderType,setTimeRequested:t.setTimeRequested,setTip:t.setTip,getItemTotal:u=>Cr(u),getOrder:()=>te.getState().workingOrder,resolveShortUrl:u=>t.setCartFromURL(u,Me.getState().token)}}function wk(t){Jt();let e=Y(u=>u.locations),r=Y(u=>u.franchises),o=Y(u=>u.selectedLocation),n=Y(u=>u.setSelectedLocation),s=Y(u=>u.getIsCurrentLocationOpen),i=(0,L.useMemo)(()=>e.filter(u=>r.some(c=>c.franchise_id===u.franchise_id)),[e,r]),a=t?.autoSelectLocationId;(0,L.useEffect)(()=>{if(a==null||o)return;let u=i.find(c=>c.location_id===a);u&&n(u)},[a,o,i,n]);let l=!!t?.promptLocationSelection&&!o&&i.length>0;return{availableLocations:i,currentLocation:o,setLocation:n,getIsCurrentLocationOpen:s,needsLocationSelection:l}}function my(){Jt();let t=Ht(o=>o.items),e=Ht(o=>o.categories);return{items:(0,L.useMemo)(()=>t.filter(o=>!e.find(s=>s.category_id===o.category_id)?.is_catering),[t,e]),allItems:t,categories:e}}function hy(t,e,r,o){let n=t.getState();o(n)&&r(n)(e)}function vk(t){hy(Ht,t,e=>e.hydrate,e=>!e.items?.length)}function Sk(t,e,r){Jt();let o=r!=null,{allItems:n}=my(),s=(0,L.useMemo)(()=>n.find(S=>S.base_item_id===t),[n,t]),[i,a]=(0,L.useState)(e?.item_id??null),[l,u]=(0,L.useState)(()=>{let S={};for(let V of e?.selections??[])S[V.rule_id]=V.selections.map(j=>uo(`${j.type}:${j.id}`,j.portion));return S}),[c,d]=(0,L.useState)(()=>{let S={};for(let V of e?.components??[])S[uo(String(V.id),V.portion)]=V.quantity_servings;return S}),[f,m]=(0,L.useState)(e?.quantity??1),h=(0,L.useCallback)(S=>m(V=>Math.max(1,typeof S=="function"?S(V):S)),[]),[g,y]=(0,L.useState)(e?.comments??""),p=s?.variants.find(S=>S.item_id===i)??s?.variants[0],b=p?.portion_scheme??null,_=(0,L.useCallback)(S=>{a(S.item_id),u({}),d({})},[]),v=(0,L.useMemo)(()=>(p?.rules??s?.rules??[]).filter(S=>S.rule_id!=null),[p,s]),N=(0,L.useCallback)((S,V,j,re=1/0)=>{u(ee=>{let J=ee[S]??[],Se=uo(V,j),ye=J.findIndex(xe=>ht(xe).baseKey===V);return ye!==-1?{...ee,[S]:J[ye]===Se?J.filter(xe=>xe!==Se):J.map((xe,At)=>At===ye?Se:xe)}:re===1?{...ee,[S]:[Se]}:Qa(J)+Ts(j)>re?ee:{...ee,[S]:[...J,Se]}})},[]),x=(0,L.useCallback)(S=>{u(V=>{let j={};for(let[re,ee]of Object.entries(V))j[Number(re)]=ee.flatMap(J=>{let{baseKey:Se,portion:ye}=ht(J);if(!ye)return[J];let xe=tc(ye,S);return xe?[uo(Se,xe[0])]:[]});return j})},[]),P=(0,L.useCallback)((S,V)=>{u(j=>({...j,[S]:(j[S]??[]).filter(re=>ht(re).baseKey!==V)}))},[]),Z=(0,L.useMemo)(()=>v.map(S=>{let V=S.rule_id,j=l[V]??[],re=cp(S),ee=new Map(re.map(J=>[J.key,J]));return{rule:S,ruleId:V,keys:j,defs:re,byKey:ee,charged:ec(j,J=>ee.get(J)?.basePrice??0,S.included_quantity??0)}}),[v,l]),q=(0,L.useMemo)(()=>Z.map(({rule:S,ruleId:V,keys:j,defs:re,charged:ee})=>{let J=S.max_selection??1/0,Se=Qa(j),ye=Se>=J;return{...S,rule_id:V,max:J,selectedCount:Se,portionable:!!b&&!!S.is_portionable,subtext:yp(S),satisfied:Se>=S.min_selection&&Se<=J,message:()=>Se<S.min_selection?`Choose at least ${S.min_selection} option${S.min_selection>1?"s":""}`:Se>J?`Choose no more than ${J} option${J>1?"s":""}`:null,options:re.map(({basePrice:xe,...At})=>{let Rt=j.find(bb=>ht(bb).baseKey===At.key),_o=Rt?ht(Rt).portion:null;return{...At,key:Rt??At.key,portion:_o,coveredSections:_o?[Vt(_o).index]:[],coveredWhole:!!Rt&&!_o,upcharge:Rt?ee.get(Rt):xe,selected:!!Rt,disabled:ye&&!Rt&&J!==1,toggle:()=>N(V,At.key,null,J)}})}}),[Z,b,N]),nt=(0,L.useMemo)(()=>Z.map(({rule:S,ruleId:V,keys:j,byKey:re,charged:ee})=>({rule_id:V,group_name:S.group_name,selections:j.flatMap(J=>{let{baseKey:Se,portion:ye}=ht(J),xe=re.get(Se);return xe?[{id:xe.id,type:xe.type,quantity:1,upcharge:ee.get(J)??0,name:xe.name,portion:ye}]:[]})})).filter(S=>S.selections.length>0),[Z]),ge=(0,L.useMemo)(()=>!s||!p?null:{item_id:p.item_id,base_item_id:s.base_item_id,category_id:s.category_id,name:p.name,quantity:f,price:p.price,components:(p.components??[]).flatMap(S=>Zu(String(S.id),c,S.servings_per_item??1).map(({portion:V,value:j})=>({...S,portion:V,quantity_servings:j}))),selections:nt,comments:g},[s,p,f,c,nt,g]),st=q.find(S=>!S.satisfied)??null,er=!!ge&&!st,tr=(0,L.useCallback)(()=>!ge||q.some(S=>!S.satisfied)?null:(o?te.getState().updateItem(ge,r):te.getState().addItem(ge),ge),[ge,q,o,r]),rr=ge?Cr(ge):0,Ue=!!p?.display_price&&p.display_price<p.price;return{item:s,variant:p,variants:s?.variants??[],setVariant:_,ruleGroups:q,unmetRule:st,canSubmit:er,submit:tr,portionScheme:b,placeOption:N,clearOption:P,recutSelections:x,quantity:f,setQuantity:h,comments:g,setComments:y,setComponentServings:(S,V,j=null)=>d(re=>{let ee={...re};if(!j)for(let J of Object.keys(ee))ht(J).baseKey===String(S)&&delete ee[J];return ee[uo(String(S),j)]=Math.max(0,V),ee}),price:rr,salePrice:Ue&&ge?Cr({...ge,display_price:p.display_price},!0):void 0,isEditMode:o,draft:ge}}function xk(){Jt();let t=Y(p=>p.selectedLocation),e=Ce(p=>p.activePromotions),r=te(p=>p.workingOrder),o=te(p=>p.selectedPromotion),n=r.promo_code,[s,i]=(0,L.useState)(null),[a,l]=(0,L.useState)(!1),u=(0,L.useRef)(null),c=(0,L.useMemo)(()=>r.items.reduce((p,b)=>p+(b.discount_amount??0),0),[r.items]),d=(0,L.useMemo)(()=>nn({order:r}),[r]),f=(0,L.useMemo)(()=>{if(!o)return c;try{return ur(o,r,new Date)}catch{return 0}},[c,o,r]),m=(0,L.useMemo)(()=>{if(o||c<=0)return null;let p=new Map;for(let _ of r.items)!_.applied_promo_id||!_.discount_amount||p.set(_.applied_promo_id,(p.get(_.applied_promo_id)??0)+_.discount_amount);let b=Array.from(p.entries()).sort((_,v)=>v[1]-_[1])[0]?.[0];return e.find(_=>_.id===b)??null},[e,c,o,r.items]),h=o??m;(0,L.useEffect)(()=>{if(!t?.franchise_id)return;let p=!1;return l(!0),Ce.getState().getActivePromotions(t.franchise_id,t.location_id).finally(()=>{p||l(!1)}),()=>{p=!0}},[t?.franchise_id,t?.location_id]),(0,L.useEffect)(()=>{if(!n){i(null);return}if(o&&f>0){i(null);return}if(o?.min_purchase_amount&&d<o.min_purchase_amount){i(`Minimum purchase of $${(o.min_purchase_amount/100).toFixed(2)} required`);return}o&&i("Promotion not applicable")},[d,f,n,o]);let g=(0,L.useCallback)(async p=>{let b=p.trim();if(b){if(!t?.franchise_id||!t?.location_id){i("Please select a location first");return}l(!0),i(null);try{let _=await Ce.getState().getPromotionByCode(b,t.franchise_id);if(!_){te.getState().removeOrderPromotion(),i("Invalid promotion code");return}te.getState().applyOrderPromotion(_)}catch{i("Unable to apply promotion")}finally{l(!1)}}},[t?.franchise_id,t?.location_id]);(0,L.useEffect)(()=>{te.getState().workingOrder.promo_code||te.getState().checkBestPromo()},[e]),(0,L.useEffect)(()=>{if(typeof window>"u")return;let b=new URLSearchParams(window.location.search).get("promo");!b||b===n||u.current===b||(u.current=b,g(b))},[g,n,t?.location_id]);let y=(0,L.useCallback)(()=>{if(i(null),u.current=null,te.getState().overrideOrderPromotion(null),typeof window<"u"){let p=new URL(window.location.href);p.searchParams.has("promo")&&(p.searchParams.delete("promo"),window.history.replaceState({},"",p.toString()))}},[]);return{promoCode:n??"",setPromoCode:p=>{p?g(p):y()},appliedPromo:h,discountAmount:f,error:s,loading:a,applyPromo:g,removePromo:y,activePromotions:e}}function kk(t={}){Jt();let e=$e(d=>d.clientSecret),r=$e(d=>d.intentType),o=$e(d=>d.isLoading),n=$e(d=>d.error),s=$e(d=>d.stripe),i=$e(d=>d.finalAmount),a=$e(d=>d.orderId),l=te(d=>d.workingOrder),u=e?{clientSecret:e,...t.appearance&&{appearance:t.appearance},defaultValues:{billingDetails:{name:(l.customer.first_name??"")+" "+(l.customer.last_name??""),email:l.customer.email,phone:l.customer.phone}}}:null,c=$e.getState().confirmPayment;return{clientSecret:e,intentType:r,stripe:s,elementOptions:u,total:i,orderId:a,isLoading:o,error:n,isReady:!!(e&&s),startCheckout:$e.getState().beginCheckout,resetCheckout:$e.getState().reset,submitPayment:c,paymentElementOptions:{layout:"accordion",fields:{billingDetails:{name:"never",email:"never",phone:"never",address:"auto"}}},getReturnStatus:$e.getState().getReturnStatus,mintOrderLinkToken:$e.getState().mintOrderLinkToken,getReturnUrl:Me.getState().getSiteUrl}}function Tk(){Jt();let t=Ht(r=>r.franchiseCateringConfig),e=Ht(r=>r.franchiseDeliveryConfig);return{minimum_notice_hours:t.minimum_notice_hours,minimum_people_required:t.minimum_people_required,minimum_price:t.minimum_price,does_cater:t.does_cater,does_deliver:e.does_deliver,delivery_fee_cents:e.delivery_fee_cents,max_delivery_radius_miles:e.max_delivery_radius_miles,cents_per_mile:e.cents_per_mile}}function Ck(){Jt();let t=Kt(s=>s.recommendations),e=Kt(s=>s.isLoading),r=Kt(s=>s.error),o=Kt(s=>s.strategy),n=Kt(s=>s.lastFetchedAt);return{recommendations:t,isLoading:e,error:r,strategy:o,lastFetchedAt:n,refresh:s=>Kt.getState().fetchRecommendations(s),setStrategy:s=>Kt.getState().setStrategy(s),clear:()=>Kt.getState().clear()}}var gl=null,Ic=null,py={};function Dc(){return Ic||(Ic=_g({source:"restaurant_site",getContext:()=>py})),Ic}function Ek(){Jt();let t=Me(g=>g.consentGiven),e=Me(g=>g.anonymousId),r=Me(g=>g.config),o=Y(g=>g.franchiseId),n=fy(),s=(0,L.useRef)(null);s.current||(s.current=Symbol("zorgo-tracking"));let[i,a]=(0,L.useState)(!1),l=(0,L.useRef)(null),u=(0,L.useRef)(Date.now()),c=(0,L.useRef)(Date.now()),d=(0,L.useRef)(0),f=(0,L.useRef)(!1),m=(0,L.useRef)(!1),h=(0,L.useRef)(typeof window>"u"?void 0:cy(window.location.search));(0,L.useEffect)(()=>(gl===null&&(gl=s.current,a(!0)),()=>{gl===s.current&&(gl=null)}),[]),(0,L.useEffect)(()=>{if(!i)return;if(!t){f.current=!1;return}let g=uy(),y=typeof document<"u"&&document.referrer||void 0,p=r.franchiseId??o;py={session_id:g,anonymous_id:e||null,franchise_id:p!=null?Number(p):null,location_id:r.locationId!=null?Number(r.locationId):null};let b=Dc();f.current||(f.current=!0,m.current=!1,b.info(mr.session_started,{landing_page:n,referrer:y,utm:h.current}),d.current=1,c.current=Date.now());let _=()=>{m.current||(m.current=!0,l.current&&b.info(mr.page_exited,{path:l.current,duration_ms:Date.now()-u.current}),b.info(mr.session_ended,{duration_ms:Date.now()-c.current,pages_visited:d.current}))},v=()=>{document.visibilityState==="hidden"&&_()};return window.addEventListener("beforeunload",_),document.addEventListener("visibilitychange",v),()=>{window.removeEventListener("beforeunload",_),document.removeEventListener("visibilitychange",v)}},[i,t,e,o]),(0,L.useEffect)(()=>{if(!(!i||!t||!f.current)){if(l.current&&l.current!==n&&Dc().info(mr.page_exited,{path:l.current,duration_ms:Date.now()-u.current}),l.current!==n){let g=l.current===null;Dc().info(mr.page_viewed,{path:n,referrer:typeof document<"u"&&document.referrer||void 0,utm:g?h.current:void 0}),g||(d.current+=1)}l.current=n,u.current=Date.now()}},[n,t,i])}function Pk(){Jt(),Ek();let t=te(s=>s.workingOrder.customer),e=te.getState().setCustomer,r=Me(s=>s.consentGiven),o=Me(s=>s.consentAnswered),n=Me(s=>s.anonymousId);return{customer:t,consentGiven:r,setCustomer:e,consentAnswered:o,setConsent:Me.getState().setConsent,anonymousId:n}}function gy(t){return typeof window>"u"?Promise.reject(new Error("Google Maps can only load in the browser")):window.google?.maps?.places?Promise.resolve():new Promise((r,o)=>{let n=document.querySelector('script[src^="https://maps.googleapis.com/maps/api/js"]');if(n){n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>o(new Error("Maps script failed")),{once:!0});return}let s=document.createElement("script");s.src=`https://maps.googleapis.com/maps/api/js?key=${encodeURIComponent(t)}&libraries=places`,s.async=!0,s.defer=!0,s.onload=()=>r(),s.onerror=()=>o(new Error("Failed to load Google Maps")),document.head.appendChild(s)})}var yl=null;async function Ok(){try{let t=await fetch("/api/zorgo-token");if(!t.ok)return;let{token:e}=await t.json();return e}catch{return}}function yy(){return typeof window>"u"?Promise.resolve():yl||(yl=(async()=>{ig();let t,e=new Promise(o=>t=o);dp(async()=>Me.getState().token??await e),await Promise.all([Y,Ht,te,Rc].map(o=>o.persist.rehydrate())),te.setState(o=>({workingOrder:{...o.workingOrder,method_id:2,type_id:2}}));let r=await Ok();if(t(r??null),!r)throw new Error("Zorgo: missing token. Ensure app/api/zorgo-token exists and ZORGO_SITE_SECRET is set.");Me.getState().initialize({token:r}),Ak(),await Y.getState().initialize({token:r})})(),yl)}function Ak(){let t=n=>{n&&$e.getState().start()},e=async n=>{let s=Y.getState().franchiseId;s&&(await Ce.getState().getActivePromotions(s,n,"website").catch(console.error),te.getState().checkBestPromo())},r=async n=>{n&&(await e(Y.getState().selectedLocation?.location_id),Ht.getState().start({franchiseId:n,platform:"website",visibilityMode:"runtime"}))},o={fireImmediately:!0};Y.subscribe(n=>n.franchiseId,r,o),Y.subscribe(n=>n.selectedLocation?.stripe_account_id,t,o),Y.subscribe(n=>n.selectedLocation?.location_id,(n,s)=>{n&&te.getState().setLocationId(n),n!==s&&e(n)},o)}var by=require("zustand"),_y=require("zustand/middleware"),wy=require("zustand/middleware/immer"),bl=require("react"),jc=(0,bl.createContext)(null);function yt(){let t=(0,bl.useContext)(jc);if(!t)throw new Error("Must be used inside DynamicFormShell");return t}function Mc({onSubmit:t}){return(0,by.createStore)()((0,_y.devtools)((0,wy.immer)((e,r)=>({values:{},fieldConfigs:{},fieldErrors:{},status:"idle",registerField:(o,n)=>(e(s=>{s.fieldConfigs[o]=n,o in s.values||(s.values[o]=n.defaultValue??"")}),()=>{e(s=>{delete s.fieldConfigs[o],delete s.fieldErrors[o]})}),setValue:(o,n)=>{e(s=>{s.values[o]=n})},clearError:o=>{e(n=>{delete n.fieldErrors[o],n.status="idle"})},validateField:o=>{let n=r().fieldConfigs[o];if(!n)return null;let s=r().values[o],i=n.required&&!s?"Required.":n.validate(s);return e(a=>{i?a.fieldErrors[o]=i:delete a.fieldErrors[o]}),i??null},setFieldError:(o,n)=>{r().fieldConfigs[o]&&e(i=>{i.fieldErrors[o]=n})},validateAll:()=>{let o={};return Object.keys(r().fieldConfigs).forEach(n=>{let s=r().validateField(n);s&&(o[n]=s)}),o},handleSubmit:async o=>{o.preventDefault();let n=r().validateAll();if(Object.keys(n).length>0){e(s=>{s.fieldErrors=n,s.status="error"});return}e(s=>{s.status="sending"});try{await t(r().values),e(s=>{s.status="sent"})}catch{e(s=>{s.status="error"})}}}))))}var _l=require("react");var Uc=require("react/jsx-runtime");function Fc({className:t,onSubmit:e,children:r}){let o=(0,_l.useRef)(e);o.current=e;let n=(0,_l.useMemo)(()=>Mc({onSubmit:(...s)=>o.current(...s)}),[]);return(0,Uc.jsx)(jc.Provider,{value:n,children:(0,Uc.jsx)("form",{onSubmit:n.getState().handleSubmit,className:t,children:r})})}var ky=require("react"),$s=require("zod");var vy=require("zustand");function Us(){let t=yt(),e=(0,vy.useStore)(t,r=>r.status);return{status:e,isIdle:e==="idle",isSubmitting:e==="sending",isSubmitted:e==="sent",isError:e==="error"}}var Sy=require("zustand");function Rk(t,e){return t.required&&(e==null||e==="")?"Required.":t.validate(e)}function Fs(){let t=yt();return(0,Sy.useStore)(t,e=>Object.entries(e.fieldConfigs).every(([r,o])=>Rk(o,e.values[r])===null))}var xy=require("zustand");function Ve(){let t=yt();return(0,xy.useStore)(t,e=>e.values)}var Bs=require("react/jsx-runtime"),Ik=$s.z.object({label:$s.z.string().default("Submit"),loadingLabel:$s.z.string().default("Submitting..."),className:$s.z.string().default("")});function $c(t){let{labelFn:e,...r}=t,{label:o,loadingLabel:n,className:s}=Ik.parse(r),i=Fs(),{isSubmitting:a,isSubmitted:l}=Us(),u=Ve(),c=yt(),d=(0,ky.useRef)(null),f=!i||a||l,m=e?e(u):o;function h(){c.getState().validateAll(),setTimeout(()=>{d.current?.form?.querySelector("[data-field-error]")?.scrollIntoView({behavior:"smooth",block:"center"})},50)}return(0,Bs.jsxs)("div",{style:{position:"relative"},children:[(0,Bs.jsx)("button",{ref:d,type:"submit",disabled:f,className:s,children:a?n:m}),f&&(0,Bs.jsx)("div",{onClick:h,style:{position:"absolute",inset:0,cursor:"pointer"}})]})}var Bc=require("zustand");function ie(t){let e=yt(),r=(0,Bc.useStore)(e,l=>l.values[t]),o=(0,Bc.useStore)(e,l=>l.fieldErrors[t])??null;return{value:r,error:o,setValue:l=>e.getState().setValue(t,l),clearError:()=>e.getState().clearError(t),validate:()=>e.getState().validateField(t),setError:l=>e.getState().setFieldError(t,l)}}var Ty=require("react/jsx-runtime");function _e({name:t,className:e}){let{error:r}=ie(t);return r?(0,Ty.jsx)("span",{"data-field-error":t,className:e,children:r}):null}var qs=require("react/jsx-runtime");function qc({className:t,title:e,titleClassName:r,subtitle:o,subtitleClassName:n}){return(0,qs.jsxs)("div",{className:t,children:[(0,qs.jsx)("h1",{className:r,children:e}),(0,qs.jsx)("p",{className:n,children:o})]})}var Hc=require("react"),Ke=require("react/jsx-runtime");function Dk(t,e){return e.flatMap(r=>{let o=t[`rule_${r.ruleId}`]??[];return r.options.filter(n=>o.includes(n.value)&&n.upcharge>0).map(n=>({id:`rule_${r.ruleId}_${n.value}`,name:n.label,priceCents:n.upcharge}))})}function Vc({label:t,value:e,isTotal:r,isDiscount:o}){return r?(0,Ke.jsx)("div",{className:"flex items-center justify-between pt-3 mt-1 border-t-2 border-zestia-red-500",children:(0,Ke.jsx)("span",{className:"font-extrabold text-end text-zestia-red-500 text-xl",children:e})}):o?(0,Ke.jsxs)("div",{className:"flex items-center justify-between py-1.5 border-b border-stone-100",children:[(0,Ke.jsx)("span",{className:"text-xs text-emerald-600 font-medium",children:t}),(0,Ke.jsx)("span",{className:"text-xs font-semibold text-emerald-600",children:e})]}):(0,Ke.jsxs)("div",{className:"flex items-center justify-between py-1.5 border-b border-stone-100",children:[(0,Ke.jsx)("span",{className:"text-xs text-stone-500",children:t}),(0,Ke.jsx)("span",{className:"text-xs font-semibold text-stone-700",children:e})]})}function Wc(t){return`$${(t/100).toFixed(2)}`}function zc({items:t,ruleGroups:e=[],guestCountFieldId:r="guestCount",className:o}){let n=Ve(),{value:s}=ie(r),i=Number(s)||0,a=Ce(h=>h.allPromotions),l=[...t,...Dk(n,e)],u=l.reduce((h,g)=>h+g.priceCents,0),c=(0,Hc.useMemo)(()=>{let h=t.find(g=>g.isBase);if(h?.active_promo_id)return a.find(g=>g.id===h.active_promo_id&&g.min_purchase_quantity)},[t,a]),d=(0,Hc.useMemo)(()=>!c||i<=0?u:Math.round(rc(u,i,c.discount_value/100,c.min_purchase_quantity)),[c,i,u]),f=d*i,m=u>0&&d<u?((u-d)/u*100).toFixed(1):null;return(0,Ke.jsxs)("div",{className:o,children:[l.map(h=>(0,Ke.jsx)(Vc,{label:h.name,value:`${Wc(h.priceCents)}/person`},h.id)),m&&(0,Ke.jsx)(Vc,{isDiscount:!0,label:`Bulk discount (${m}% off)`,value:`-${Wc(u-d)}/person`}),(0,Ke.jsx)(Vc,{isTotal:!0,label:"Per-Person Cost",value:`${Wc(d)}/person`})]})}var Cy=require("react/jsx-runtime");function Gc({label:t,className:e}){return(0,Cy.jsx)("h2",{className:e,children:t})}var Ey=require("react/jsx-runtime");function Kc({children:t,className:e}){return(0,Ey.jsx)("p",{className:e,children:t})}var vl=require("react");function wl(t){let e={};for(let[r,o]of Object.entries(t))Array.isArray(o)&&o.every(n=>typeof n=="string")?e[r]=o.length===1?o[0]:o.length===0?void 0:o:e[r]=o;return e}var Sl=require("react/jsx-runtime");function Jc({whenFormVal:t,whenFunction:e,whenMediaQuery:r,children:o}){let n=Ve(),[s,i]=(0,vl.useState)(()=>r&&typeof window<"u"?window.matchMedia(r).matches:!1);return(0,vl.useEffect)(()=>{if(!r)return;let l=window.matchMedia(r);i(l.matches);let u=c=>i(c.matches);return l.addEventListener("change",u),()=>l.removeEventListener("change",u)},[r]),(t?t(wl(n)):!1)||(e?e():!1)||(r?s:!1)?(0,Sl.jsx)(Sl.Fragment,{children:o}):null}var M=require("zod"),ae=M.z.object({inputType:M.z.enum(["text","number","date","time"]).default("text"),fieldId:M.z.string(),label:M.z.string().optional(),placeholder:M.z.string().optional(),autoCompleteType:M.z.string().optional(),requiredText:M.z.string().default("Required."),required:M.z.boolean().default(!0),showLabel:M.z.boolean().default(!0),showError:M.z.boolean().default(!0),disabled:M.z.boolean().default(!1),fieldClassName:M.z.string().default("flex-1"),containerClassName:M.z.string().default("flex flex-col"),fieldLabelClassName:M.z.string().default("flex-1"),fieldErrorClassName:M.z.string().default("flex-1"),fieldAsteriskClassName:M.z.string().default("text-red-500"),initialValue:M.z.unknown().optional()}),_B=ae.extend({min:M.z.number().optional(),max:M.z.number().optional(),step:M.z.number().default(1)}),wB=ae.extend({min:M.z.string().optional(),max:M.z.string().default("23:59")}),gn=ae.extend({maxLength:M.z.number().default(256),validate:M.z.any(),sanitize:M.z.any(),min:M.z.string().optional(),max:M.z.string().optional(),multiline:M.z.boolean().default(!1),rows:M.z.number().default(5)}),Py=ae.extend({minSelections:M.z.number().default(1),maxSelections:M.z.union([M.z.number(),M.z.literal(1/0)]).default(1),tooFewText:M.z.string().optional(),tooManyText:M.z.string().optional(),options:M.z.array(M.z.object({label:M.z.string(),value:M.z.string(),sublabel:M.z.string().optional(),description:M.z.string().optional(),disabled:M.z.boolean().optional().default(!1)})).min(1),optionClassName:M.z.string().default("flex items-center gap-3 px-4 py-3 rounded-lg border border-stone-200 cursor-pointer select-none transition-colors duration-150 hover:border-stone-300"),optionActiveClassName:M.z.string().default("border-blue-500 bg-blue-50"),optionLabelClassName:M.z.string().default("text-sm font-semibold text-stone-600"),optionActiveLabelClassName:M.z.string().default("text-sm font-semibold text-blue-500"),optionSublabelClassName:M.z.string().default("text-sm text-stone-400 shrink-0 ml-auto"),inputClassName:M.z.string().default("w-4 h-4 shrink-0 accent-blue-500")});var xl=require("react/jsx-runtime");function rt({children:t,required:e,className:r,asteriskClassName:o}){return(0,xl.jsxs)("label",{className:r,children:[t,e&&(0,xl.jsx)("span",{className:o,children:"*"})]})}var Vs=require("react");function ot({name:t,required:e=!1,validate:r,initialValue:o}){let n=yt(),s=(0,Vs.useRef)(r);(0,Vs.useEffect)(()=>{s.current=r},[r]),(0,Vs.useEffect)(()=>n.getState().registerField(t,{required:e,validate:i=>s.current?.(i)??null,defaultValue:o}),[])}var ho=require("react/jsx-runtime"),Lk=t=>t?/^[\n\x20-\x7E]*$/:/^[\x20-\x7E]*$/;function Nk(t,e,r=!1){return t.replace(r?/[^\n\x20-\x7E]/g:/[^\x20-\x7E]/g,"").slice(0,e)}function jk(t,e,r,o,n=!1){return s=>s.trim().length?o?o(s):s.length>e?`Must be ${e} characters or fewer.`:Lk(n).test(s)?null:"Only standard characters are allowed.":t?r:null}function De(t){let{inputRef:e}=t,{fieldId:r,label:o,placeholder:n,initialValue:s,required:i,showLabel:a,showError:l,autoCompleteType:u,fieldClassName:c,containerClassName:d,fieldLabelClassName:f,fieldErrorClassName:m,fieldAsteriskClassName:h,requiredText:g,disabled:y,maxLength:p,validate:b,sanitize:_,inputType:v,min:N,max:x,multiline:P,rows:Z}=gn.parse(t),q=_??(Ue=>Nk(Ue,p,P)),nt=jk(i,p,g,b,P);ot({name:r,required:i,validate:nt,initialValue:s});let{value:ge,setValue:st,error:er,clearError:tr,validate:rr}=ie(r);return(0,ho.jsxs)("div",{className:d,children:[a&&(0,ho.jsx)(rt,{required:i,className:f,asteriskClassName:h,children:o}),P?(0,ho.jsx)("textarea",{name:r,rows:Z,autoComplete:u,placeholder:n,value:ge??"",onChange:Ue=>{st(q(Ue.target.value)),tr()},onBlur:rr,"data-error":!!er||void 0,className:c,disabled:y,maxLength:p}):(0,ho.jsx)("input",{type:v,ref:e,name:r,autoComplete:u,placeholder:n,value:ge??"",onChange:Ue=>{st(q(Ue.target.value)),tr()},onBlur:rr,"data-error":!!er||void 0,className:c,disabled:y,maxLength:p,min:N,max:x}),l&&(0,ho.jsx)(_e,{name:r,className:m})]})}var kl=require("zod");var Oy=require("react/jsx-runtime");function Mk(t){let e=t.replace(/\D/g,""),r=/^\d{10}$/.test(e),o=/^1\d{10}$/.test(e);return r||o?null:"Please enter a valid 10-digit phone number."}function Uk(t){let e=t.replace(/\D/g,"");if(e.startsWith("1")&&e.length>10){e=e.slice(0,11);let r=e.slice(1);return`+1 (${r.slice(0,3)}) ${r.slice(3,6)}-${r.slice(6,10)}`}return e=e.slice(0,10),e.length<=3?e:e.length<=6?`(${e.slice(0,3)}) ${e.slice(3)}`:`(${e.slice(0,3)}) ${e.slice(3,6)}-${e.slice(6)}`}var Fk=ae.extend({fieldId:kl.z.string().default("phone"),placeholder:kl.z.string().default("(586) 313-2480"),label:kl.z.string().default("Phone number")});function Yc(t){let e=Fk.parse(t);return(0,Oy.jsx)(De,{...e,validate:Mk,sanitize:Uk})}var Ws=require("zod");var Ay=require("react/jsx-runtime");function $k(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.trim())?null:"Please enter a valid email address."}var Bk=ae.extend({fieldId:Ws.z.string().default("email"),placeholder:Ws.z.string().default("Email"),label:Ws.z.string().default("Email"),autoCompleteType:Ws.z.string().default("email")});function Xc(t){let e=Bk.parse(t);return(0,Ay.jsx)(De,{...e,validate:$k})}var bt=require("react/jsx-runtime");function Qc(t){let{fieldId:e,label:r,required:o,showLabel:n,showError:s,containerClassName:i,fieldLabelClassName:a,fieldErrorClassName:l,fieldAsteriskClassName:u,requiredText:c,disabled:d,options:f,minSelections:m,maxSelections:h,initialValue:g,tooFewText:y,tooManyText:p,optionClassName:b,optionActiveClassName:_,optionLabelClassName:v,optionActiveLabelClassName:N,optionSublabelClassName:x,inputClassName:P}=Py.parse(t),Z=h===1,q=Z&&m===0;function nt(j){return o&&j.length===0?c:j.length<m?y??`Please select at least ${m}.`:j.length>h?p??`Please select at most ${h}.`:null}ot({name:e,required:o,initialValue:g??[],validate:nt});let{value:ge,error:st,setValue:er,setError:tr,validate:rr}=ie(e),Ue=ge??[];function S(j){let re=Z?Ue.includes(j)&&q?[]:[j]:Ue.includes(j)?Ue.filter(ee=>ee!==j):[...Ue,j];if(re.length>h){tr(p??`Please select at most ${h}.`);return}er(re),rr()}function V(j){j.currentTarget.contains(j.relatedTarget)||rr()}return(0,bt.jsxs)("div",{className:i,children:[n&&(0,bt.jsx)(rt,{required:o,className:a,asteriskClassName:u,children:r}),(0,bt.jsx)("div",{className:"space-y-2",onBlur:V,tabIndex:-1,"data-error":!!st||void 0,"aria-invalid":!!st||void 0,children:f.map(j=>{let re=Ue.includes(j.value),ee=d||j.disabled;return(0,bt.jsxs)("label",{className:`flex items-center gap-3 ${b} ${re?_:""} ${ee?"opacity-50 cursor-not-allowed":""}`,children:[(0,bt.jsx)("input",{type:q?"checkbox":Z?"radio":"checkbox",name:e,checked:re,disabled:ee,onChange:()=>S(j.value),className:P}),(0,bt.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,bt.jsx)("span",{className:re?N:v,children:j.label}),j.description&&(0,bt.jsx)("p",{className:"text-xs text-stone-400 mt-0.5 leading-snug",children:j.description})]}),j.sublabel&&(0,bt.jsx)("span",{className:x,children:j.sublabel})]},j.value)})}),s&&(0,bt.jsx)(_e,{name:e,className:l})]})}var Ry=require("react");function Zc({locationInputRef:t,isApplyingAutocompleteRef:e,setEventLocation:r,onCoordsResolved:o}){(0,Ry.useEffect)(()=>{let n=window;function s(){if(!t.current||!n.google)return;let i=new n.google.maps.places.Autocomplete(t.current,{types:["establishment","geocode"],componentRestrictions:{country:"us"},fields:["formatted_address","name","geometry"]});i.addListener("place_changed",()=>{let a=i.getPlace(),l=a.formatted_address?.trim()??"",u=a.name?.trim()??"",c=u.toLowerCase(),d=l.toLowerCase(),f=u&&l&&!d.startsWith(c)?`${u}, ${l}`:l||u;e.current=!0,t.current&&(t.current.value=f),r(f),a.geometry?.location&&o?.({lat:a.geometry.location.lat(),lng:a.geometry.location.lng()}),requestAnimationFrame(()=>{e.current=!1})})}n.google?s():window.addEventListener("google-maps-loaded",s,{once:!0})},[e,t,r,o])}var td=require("react");var Iy=require("react");function ed(){return(0,Iy.useEffect)(()=>{let t=process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY;t&&gy(t).then(()=>window.dispatchEvent(new Event("google-maps-loaded"))).catch(()=>{})},[]),null}var Tl=require("zod"),po=require("react/jsx-runtime"),qk=gn.extend({fieldId:Tl.z.string().default("eventLocation"),label:Tl.z.string().default("Event location"),placeholder:Tl.z.string().default("Search for a venue or enter an address\u2026")});function rd(t){let e=(0,td.useRef)(null),r=(0,td.useRef)(!1),o=qk.parse(t),{setValue:n,clearError:s}=ie(o.fieldId);function i(a){return a.replace(/<[^>]*>/g,"").trimStart().slice(0,255)}return Zc({locationInputRef:e,isApplyingAutocompleteRef:r,setEventLocation:a=>{n(i(a)),s()}}),(0,po.jsxs)(po.Fragment,{children:[(0,po.jsx)(ed,{}),(0,po.jsx)(De,{...o,inputRef:e})]})}var Cl=require("react"),Je=require("zod");var Ly=require("react/jsx-runtime"),Vk="yyyy-MM-dd",od="HH:mm",Wk=ae.extend({fieldId:Je.z.string().default("time"),label:Je.z.string().default("Start time"),autoCompleteType:Je.z.string().default("off"),inputType:Je.z.literal("time").default("time"),minTime:Je.z.string().optional(),maxTime:Je.z.string().optional(),closedSpans:Je.z.array(Je.z.object({from:Je.z.string(),to:Je.z.string()})).optional(),minimumNoticeHours:Je.z.number().nullable().optional(),dateFieldId:Je.z.string().default("date"),timezone:Je.z.string().default(Intl.DateTimeFormat().resolvedOptions().timeZone)});function Yt(t){return Qe(t,od,new Date)}function Dy(t){return Be(Yt(t),"h:mm a")}function Hk(t){return t.replace(/[^\d:]/g,"").slice(0,5)}function Rr(t){let{minTime:e,maxTime:r,closedSpans:o,minimumNoticeHours:n,dateFieldId:s,timezone:i,...a}=Wk.parse(t),u=Ve()[s],{value:c,validate:d}=ie(a.fieldId),f=(0,Cl.useRef)(!0);(0,Cl.useEffect)(()=>{if(f.current){f.current=!1;return}c&&d()},[u,n,e,r]);function m(g){if(!/^\d{2}:\d{2}$/.test(g)||!ao(Yt(g)))return"Please enter a valid time.";if(e&&Ge(Yt(g),Yt(e)))return`Please choose a time after ${Dy(e)}.`;if(r&&$t(Yt(g),Yt(r)))return`Please choose a time before ${Dy(r)}.`;if(o?.some(y=>!Ge(Yt(g),Yt(y.from))&&!$t(Yt(g),Yt(y.to))))return"This time is unavailable.";if(n&&u){let y=Qe(`${u} ${g}`,`${Vk} ${od}`,new Date);if(!ao(y))return"Please enter a valid date and time.";let p=fc(y,i),b=Yh(Yo(new Date,n));if(Ge(p,b)){let _=Es(b,i),v=Be(_,"MMM d 'at' h:mm a");return`Please select a time at least ${n} hours from now (after ${v}).`}}return null}let h=a.initialValue??(n?Be(Ph(Yo(new Date,n),5),od):void 0);return(0,Ly.jsx)(De,{...a,initialValue:h,validate:m,sanitize:Hk})}var Xt=require("zod");var Ny=require("react/jsx-runtime"),Ir="yyyy-MM-dd";function zk(t,e,r,o){let n=Qe(t,Ir,new Date);return!ao(n)||Be(n,Ir)!==t?"Please enter a valid date.":e&&Ge(n,Qe(e,Ir,new Date))?`Please choose ${e} or later.`:r&&$t(n,Qe(r,Ir,new Date))?`Please choose ${r} or earlier.`:o?.includes(t)?"This date is unavailable. Please choose another.":null}function Gk(t){return t.replace(/[^\d-]/g,"").slice(0,10)}var Kk=ae.extend({fieldId:Xt.z.string().default("date"),label:Xt.z.string().default("Event date"),autoCompleteType:Xt.z.string().default("off"),inputType:Xt.z.literal("date").default("date"),minimumNoticeHours:Xt.z.number().nullable().optional(),minDate:Xt.z.date().optional(),maxDate:Xt.z.date().optional(),unavailableDates:Xt.z.array(Xt.z.date()).optional()});function go(t){let{minDate:e,maxDate:r,unavailableDates:o,minimumNoticeHours:n,...s}=Kk.parse(t),i=e??(n?Et(Yo(new Date,n)):Et(new Date)),a=Be(i,Ir),l=r?Be(r,Ir):void 0,u=o?.map(f=>Be(f,Ir));function c(f){return zk(f,a,l,u)}let d=s.initialValue??(n?Be(Et(Yo(new Date,n)),Ir):a);return(0,Ny.jsx)(De,{...s,initialValue:d,min:a,max:l,validate:c,sanitize:Gk})}var pr=require("zod");var jy=require("react/jsx-runtime");function Jk(t){return t.replace(/[^0-9]/g,"").slice(0,255)}var Yk=ae.extend({fieldId:pr.z.string().default("discreteNumber"),placeholder:pr.z.string().default("10"),label:pr.z.string().default("Number of guests"),min:pr.z.number().default(10),max:pr.z.number().default(5e3),minErrorText:pr.z.string().optional(),maxErrorText:pr.z.string().optional(),step:pr.z.number().default(1)});function Xk(t,e,r,o){return n=>{let s=Number(n);return Number.isNaN(s)?"Please enter a valid number.":s<t?r??`Must be at least ${t}.`:s>e?o??`Must be ${e} or fewer.`:null}}function nd(t){let e=Yk.parse(t),{min:r,max:o,minErrorText:n,maxErrorText:s,...i}=e;return(0,jy.jsx)(De,{...i,validate:Xk(r,o,n,s),sanitize:Jk})}var Hs=require("zod");var yn=require("react/jsx-runtime"),Qk=ae.extend({min:Hs.z.number().default(0),max:Hs.z.number().default(100),step:Hs.z.number().default(1),onChange:Hs.z.any().optional()});function sd(t){let{fieldId:e,label:r,min:o,max:n,step:s,required:i,showLabel:a,showError:l,fieldClassName:u,containerClassName:c,fieldLabelClassName:d,fieldAsteriskClassName:f,fieldErrorClassName:m,initialValue:h,requiredText:g,disabled:y,onChange:p}=Qk.parse(t);function b(Z){return i&&Z==null?g:Z<o?`Must be at least ${o}.`:Z>n?`Must be ${n} or fewer.`:null}ot({name:e,required:i,validate:b,initialValue:h??o});let{value:_,setValue:v,error:N,clearError:x,validate:P}=ie(e);return(0,yn.jsxs)("div",{className:c,children:[a&&(0,yn.jsx)(rt,{required:i,className:d,asteriskClassName:f,children:r}),(0,yn.jsx)("input",{type:"range",min:o,max:n,step:s,value:_??o,disabled:y,onChange:Z=>{let q=Number(Z.target.value);v(q),x(),p?.(q)},onBlur:P,"data-error":!!N||void 0,className:u}),l&&(0,yn.jsx)(_e,{name:e,className:m})]})}var id=require("zod");var yo=require("react/jsx-runtime"),Zk=ae.extend({checkboxClassName:id.z.string().default("mt-0.5 h-5 w-5 shrink-0 rounded"),labelClassName:id.z.string().default("pt-0.5 text-sm leading-snug")});function ad({children:t,...e}){let{fieldId:r,required:o,requiredText:n,showError:s,disabled:i,containerClassName:a,fieldErrorClassName:l,checkboxClassName:u,labelClassName:c,initialValue:d}=Zk.parse(e);ot({name:r,required:!1,validate:o?g=>g?null:n:void 0,initialValue:d??!1});let{value:f,setValue:m,validate:h}=ie(r);return(0,yo.jsxs)("div",{className:a,children:[(0,yo.jsxs)("div",{className:"flex items-start gap-3 px-1 py-2 min-h-[44px]",children:[(0,yo.jsx)("input",{type:"checkbox",id:r,checked:f??!1,onChange:g=>{m(g.target.checked),o&&h()},disabled:i,className:u}),(0,yo.jsx)("label",{htmlFor:r,className:c,children:t})]}),s&&(0,yo.jsx)(_e,{name:r,className:l})]})}var ld=require("react/jsx-runtime");function ud({name:t,label:e="Quantity",initalVal:r=0,showLabel:o=!0,showError:n=!0,showIncrement:s=!0,showDecrement:i=!0}){return(0,ld.jsx)("div",{children:(0,ld.jsx)(rt,{required:!0,children:e})})}var Dr=require("zod");var Lr=require("react/jsx-runtime"),eT=gn.extend({fieldId:Dr.z.string().default("nameFields"),outerClassName:Dr.z.string().default("flex flex-col md:flex-row w-full gap-4"),firstNamePlaceholder:Dr.z.string().default("First name"),lastNamePlaceholder:Dr.z.string().default("Last name"),firstNameInitialValue:Dr.z.string().default(""),lastNameInitialValue:Dr.z.string().default(""),childClassName:Dr.z.string().default("flex flex-col w-full md:flex-1 md:min-w-0")});function tT({className:t}){let{error:e}=ie("firstName"),{error:r}=ie("lastName"),o=e??r;return o?(0,Lr.jsx)("span",{className:t,children:o}):null}function cd(t){let e=eT.parse({...t}),{outerClassName:r,firstNamePlaceholder:o,lastNamePlaceholder:n,firstNameInitialValue:s,lastNameInitialValue:i,childClassName:a,...l}=e;return(0,Lr.jsxs)("div",{className:"flex flex-col w-full gap-1",children:[(0,Lr.jsxs)("div",{className:r,children:[(0,Lr.jsx)(De,{...l,fieldId:"firstName",label:"First name",placeholder:o,initialValue:s,autoCompleteType:"given-name",containerClassName:a,showError:!1}),(0,Lr.jsx)(De,{...l,fieldId:"lastName",label:"Last name",placeholder:n,initialValue:i,autoCompleteType:"family-name",containerClassName:a,showError:!1})]}),(0,Lr.jsx)(tT,{className:l.fieldErrorClassName})]})}var we=require("zod");var Nr=require("react/jsx-runtime"),rT=ae.extend({fieldId:we.z.string().default("dateTime"),outerClassName:we.z.string().default("flex flex-col md:flex-row w-full gap-4"),childClassName:we.z.string().default("flex flex-col w-full md:flex-1 md:min-w-0"),dateLabel:we.z.string().default("Event date"),dateFieldId:we.z.string().default("date"),minDate:we.z.date().optional(),maxDate:we.z.date().optional(),unavailableDates:we.z.array(we.z.date()).optional(),minimumNoticeHours:we.z.number().nullable().optional(),timeLabel:we.z.string().default("Start time"),timeFieldId:we.z.string().default("time"),closedSpans:we.z.array(we.z.object({from:we.z.string(),to:we.z.string()})).optional(),timezone:we.z.string().default(Intl.DateTimeFormat().resolvedOptions().timeZone),dateInitialValue:we.z.string().optional(),timeInitialValue:we.z.string().optional()});function dd(t){let{minTime:e,maxTime:r,timeBounds:o,...n}=t,{fieldId:s,outerClassName:i,childClassName:a,inputType:l,dateLabel:u,dateFieldId:c,minDate:d,maxDate:f,unavailableDates:m,minimumNoticeHours:h,timeLabel:g,timeFieldId:y,closedSpans:p,timezone:b,dateInitialValue:_,timeInitialValue:v,...N}=rT.parse(n),x=wl(Ve()),P=o?o(x):void 0,Z=P?.min??(typeof e=="function"?e(x):e),q=P?.max??(typeof r=="function"?r(x):r);return(0,Nr.jsxs)("div",{className:"flex flex-col w-full gap-1",children:[(0,Nr.jsxs)("div",{className:i,children:[(0,Nr.jsx)(go,{...N,inputType:"date",fieldId:c,label:u,minDate:d,maxDate:f,unavailableDates:m,minimumNoticeHours:h,containerClassName:a,showError:!1,initialValue:_??N.initialValue}),(0,Nr.jsx)(Rr,{...N,inputType:"time",fieldId:y,label:g,minTime:Z,maxTime:q,closedSpans:p,minimumNoticeHours:h,dateFieldId:c,timezone:b,containerClassName:a,showError:!1,initialValue:v??N.initialValue})]}),(0,Nr.jsx)(_e,{name:c,className:N.fieldErrorClassName}),(0,Nr.jsx)(_e,{name:y,className:N.fieldErrorClassName})]})}var pe=require("zod");var Ot=require("react/jsx-runtime"),oT=ae.extend({fieldId:pe.z.string().default("dateTimeRange"),dateLabel:pe.z.string().default("Event date"),dateFieldId:pe.z.string().default("date"),minDate:pe.z.date().optional(),maxDate:pe.z.date().optional(),unavailableDates:pe.z.array(pe.z.date()).optional(),minimumNoticeHours:pe.z.number().nullable().optional(),startTimeLabel:pe.z.string().default("Start time"),startTimeFieldId:pe.z.string().default("startTime"),endTimeLabel:pe.z.string().default("End time"),endTimeFieldId:pe.z.string().default("endTime"),closedSpans:pe.z.array(pe.z.object({from:pe.z.string(),to:pe.z.string()})).optional(),timezone:pe.z.string().default(Intl.DateTimeFormat().resolvedOptions().timeZone),dateInitialValue:pe.z.string().optional(),startTimeInitialValue:pe.z.string().optional(),endTimeInitialValue:pe.z.string().optional()});function fd(t){let{fieldId:e,inputType:r,dateLabel:o,dateFieldId:n,minDate:s,maxDate:i,unavailableDates:a,minimumNoticeHours:l,startTimeLabel:u,startTimeFieldId:c,endTimeLabel:d,endTimeFieldId:f,closedSpans:m,timezone:h,dateInitialValue:g,startTimeInitialValue:y,endTimeInitialValue:p,...b}=oT.parse(t),v=Ve()[c];return(0,Ot.jsxs)("div",{className:"flex flex-col w-full gap-1",children:[(0,Ot.jsxs)("div",{className:"flex flex-col md:flex-row w-full gap-4",children:[(0,Ot.jsx)(go,{...b,inputType:"date",fieldId:n,label:o,minDate:s,maxDate:i,unavailableDates:a,minimumNoticeHours:l,containerClassName:"flex flex-col w-full md:flex-1 md:min-w-0",showError:!1,initialValue:g??b.initialValue}),(0,Ot.jsxs)("div",{className:"flex flex-row gap-4 md:contents",children:[(0,Ot.jsx)(Rr,{...b,inputType:"time",fieldId:c,label:u,closedSpans:m,minimumNoticeHours:l,dateFieldId:n,timezone:h,containerClassName:"flex flex-col flex-1 min-w-0 md:flex-1",showError:!1,initialValue:y??b.initialValue}),(0,Ot.jsx)(Rr,{...b,inputType:"time",fieldId:f,label:d,minTime:v,closedSpans:m,dateFieldId:n,timezone:h,containerClassName:"flex flex-col flex-1 min-w-0 md:flex-1",showError:!1,initialValue:p??b.initialValue})]})]}),(0,Ot.jsx)(_e,{name:n,className:b.fieldErrorClassName}),(0,Ot.jsx)(_e,{name:c,className:b.fieldErrorClassName}),(0,Ot.jsx)(_e,{name:f,className:b.fieldErrorClassName})]})}var Qt=require("zod");var Zt=require("react"),_t=require("react/jsx-runtime"),nT=ae.extend({fieldId:Qt.z.string().default("guestCount"),label:Qt.z.string().default("Number of guests"),placeholder:Qt.z.string().default("10"),min:Qt.z.number().default(10),max:Qt.z.number().default(5e3),step:Qt.z.number().default(1),minErrorText:Qt.z.string().optional(),maxErrorText:Qt.z.string().optional(),sliderClassName:Qt.z.string().default("flex-[3]")});function md(t){let{fieldId:e,label:r,placeholder:o,min:n,max:s,step:i,required:a,showLabel:l,showError:u,fieldClassName:c,containerClassName:d,fieldLabelClassName:f,fieldAsteriskClassName:m,fieldErrorClassName:h,initialValue:g,requiredText:y,minErrorText:p,maxErrorText:b,disabled:_,sliderClassName:v}=nT.parse(t);function N(S){if(!S?.trim())return a?y:null;let V=Number(S);return Number.isNaN(V)?"Please enter a valid number.":V<n?p??`Must be at least ${n}.`:V>s?b??`Must be ${s} or fewer.`:null}ot({name:e,required:a,validate:N,initialValue:g??String(n)});let{value:x,setValue:P,error:Z,clearError:q,validate:nt}=ie(e),ge=(0,Zt.useRef)(P),st=(0,Zt.useRef)(q),er=(0,Zt.useRef)(nt);(0,Zt.useEffect)(()=>{ge.current=P},[P]),(0,Zt.useEffect)(()=>{st.current=q},[q]),(0,Zt.useEffect)(()=>{er.current=nt},[nt]);let tr=Number(x)||n,rr=Math.max(0,Math.min(100,(tr-n)/(s-n)*100)),Ue=(0,Zt.useRef)(null);return(0,Zt.useEffect)(()=>{let S=Ue.current;if(!S)return;let V=0,j=0;function re(ye){let{left:xe,width:At}=S.getBoundingClientRect(),Rt=Math.max(0,Math.min(1,(ye-xe)/At)),_o=n+(s-n)*Rt;return String(Math.max(n,Math.min(s,Math.round(_o/i)*i)))}function ee(ye){V=ye.changedTouches[0].clientX,j=ye.changedTouches[0].clientY,ge.current(re(V)),st.current()}function J(ye){let xe=Math.abs(ye.changedTouches[0].clientX-V),At=Math.abs(ye.changedTouches[0].clientY-j);xe>At&&ye.preventDefault(),ge.current(re(ye.changedTouches[0].clientX)),st.current()}function Se(){er.current()}return S.addEventListener("touchstart",ee,{passive:!0}),S.addEventListener("touchmove",J,{passive:!1}),S.addEventListener("touchend",Se,{passive:!0}),()=>{S.removeEventListener("touchstart",ee),S.removeEventListener("touchmove",J),S.removeEventListener("touchend",Se)}},[]),(0,_t.jsxs)("div",{className:d,children:[l&&(0,_t.jsx)(rt,{required:a,className:f,asteriskClassName:m,children:r}),(0,_t.jsxs)("div",{className:"flex items-center gap-4",children:[(0,_t.jsxs)("div",{className:`flex flex-[6] flex-col ${v}`,children:[(0,_t.jsx)("input",{ref:Ue,type:"range",min:n,max:s,step:i,value:tr,disabled:_,onChange:S=>{P(S.target.value),q()},onBlur:nt,className:`w-full ${v}`,style:{"--slider-fill":`${rr}%`}}),(0,_t.jsxs)("div",{className:"flex justify-between text-xs text-stone-400 mt-2 px-0.5",children:[(0,_t.jsx)("span",{children:n}),(0,_t.jsx)("span",{children:s})]})]}),(0,_t.jsx)("input",{type:"text",inputMode:"numeric",placeholder:o,value:x??"",disabled:_,onChange:S=>{P(S.target.value.replace(/[^0-9]/g,"").slice(0,5)),q()},onBlur:nt,"data-error":!!Z||void 0,className:`flex-1 text-center ${c}`})]}),u&&(0,_t.jsx)(_e,{name:e,className:h})]})}var My=Le(require("react"),1),ve=My.default.createContext({});var bn=Le(require("react"),1),$y=require("react");var sT=Object.defineProperty,Uy=Object.getOwnPropertySymbols,iT=Object.prototype.hasOwnProperty,aT=Object.prototype.propertyIsEnumerable,Fy=(t,e,r)=>e in t?sT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,hd=(t,e)=>{for(var r in e||(e={}))iT.call(e,r)&&Fy(t,r,e[r]);if(Uy)for(var r of Uy(e))aT.call(e,r)&&Fy(t,r,e[r]);return t},lT=(t,e)=>{let r=bn.useContext(ve),o=hd(hd({},r),t);return bn.createElement("svg",hd({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),bn.createElement("path",{d:"M10.5213 2.62368C11.3147 1.75255 12.6853 1.75255 13.4787 2.62368L14.4989 3.74391C14.8998 4.18418 15.4761 4.42288 16.071 4.39508L17.5845 4.32435C18.7614 4.26934 19.7307 5.23857 19.6757 6.41554L19.6049 7.92905C19.5771 8.52388 19.8158 9.10016 20.2561 9.50111L21.3763 10.5213C22.2475 11.3147 22.2475 12.6853 21.3763 13.4787L20.2561 14.4989C19.8158 14.8998 19.5771 15.4761 19.6049 16.071L19.6757 17.5845C19.7307 18.7614 18.7614 19.7307 17.5845 19.6757L16.071 19.6049C15.4761 19.5771 14.8998 19.8158 14.4989 20.2561L13.4787 21.3763C12.6853 22.2475 11.3147 22.2475 10.5213 21.3763L9.50111 20.2561C9.10016 19.8158 8.52388 19.5771 7.92905 19.6049L6.41553 19.6757C5.23857 19.7307 4.26934 18.7614 4.32435 17.5845L4.39508 16.071C4.42288 15.4761 4.18418 14.8998 3.74391 14.4989L2.62368 13.4787C1.75255 12.6853 1.75255 11.3147 2.62368 10.5213L3.74391 9.50111C4.18418 9.10016 4.42288 8.52388 4.39508 7.92905L4.32435 6.41553C4.26934 5.23857 5.23857 4.26934 6.41554 4.32435L7.92905 4.39508C8.52388 4.42288 9.10016 4.18418 9.50111 3.74391L10.5213 2.62368Z",stroke:"currentColor"}),bn.createElement("path",{d:"M9 12L11 14L15 10",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},uT=(0,$y.forwardRef)(lT),pd=uT;var _n=Le(require("react"),1),Vy=require("react");var cT=Object.defineProperty,By=Object.getOwnPropertySymbols,dT=Object.prototype.hasOwnProperty,fT=Object.prototype.propertyIsEnumerable,qy=(t,e,r)=>e in t?cT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,gd=(t,e)=>{for(var r in e||(e={}))dT.call(e,r)&&qy(t,r,e[r]);if(By)for(var r of By(e))fT.call(e,r)&&qy(t,r,e[r]);return t},mT=(t,e)=>{let r=_n.useContext(ve),o=gd(gd({},r),t);return _n.createElement("svg",gd({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),_n.createElement("path",{d:"M7 12.5L10 15.5L17 8.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),_n.createElement("path",{d:"M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},hT=(0,Vy.forwardRef)(mT),El=hT;var wn=Le(require("react"),1),zy=require("react");var pT=Object.defineProperty,Wy=Object.getOwnPropertySymbols,gT=Object.prototype.hasOwnProperty,yT=Object.prototype.propertyIsEnumerable,Hy=(t,e,r)=>e in t?pT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yd=(t,e)=>{for(var r in e||(e={}))gT.call(e,r)&&Hy(t,r,e[r]);if(Wy)for(var r of Wy(e))yT.call(e,r)&&Hy(t,r,e[r]);return t},bT=(t,e)=>{let r=wn.useContext(ve),o=yd(yd({},r),t);return wn.createElement("svg",yd({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),wn.createElement("path",{d:"M12 6L12 12L18 12",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),wn.createElement("path",{d:"M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},_T=(0,zy.forwardRef)(bT),Pl=_T;var zs=Le(require("react"),1),Jy=require("react");var wT=Object.defineProperty,Gy=Object.getOwnPropertySymbols,vT=Object.prototype.hasOwnProperty,ST=Object.prototype.propertyIsEnumerable,Ky=(t,e,r)=>e in t?wT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,bd=(t,e)=>{for(var r in e||(e={}))vT.call(e,r)&&Ky(t,r,e[r]);if(Gy)for(var r of Gy(e))ST.call(e,r)&&Ky(t,r,e[r]);return t},xT=(t,e)=>{let r=zs.useContext(ve),o=bd(bd({},r),t);return zs.createElement("svg",bd({width:"1.5em",height:"1.5em",viewBox:"0 0 24 24",strokeWidth:1.5,fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),zs.createElement("path",{d:"M22 9V17C22 18.1046 21.1046 19 20 19H4C2.89543 19 2 18.1046 2 17V7C2 5.89543 2.89543 5 4 5H20C21.1046 5 22 5.89543 22 7V9ZM22 9H6",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},kT=(0,Jy.forwardRef)(xT),_d=kT;var bo=Le(require("react"),1),Qy=require("react");var TT=Object.defineProperty,Yy=Object.getOwnPropertySymbols,CT=Object.prototype.hasOwnProperty,ET=Object.prototype.propertyIsEnumerable,Xy=(t,e,r)=>e in t?TT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wd=(t,e)=>{for(var r in e||(e={}))CT.call(e,r)&&Xy(t,r,e[r]);if(Yy)for(var r of Yy(e))ET.call(e,r)&&Xy(t,r,e[r]);return t},PT=(t,e)=>{let r=bo.useContext(ve),o=wd(wd({},r),t);return bo.createElement("svg",wd({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),bo.createElement("path",{d:"M1.5 12.5L5.57574 16.5757C5.81005 16.8101 6.18995 16.8101 6.42426 16.5757L9 14",stroke:"currentColor",strokeLinecap:"round"}),bo.createElement("path",{d:"M16 7L12 11",stroke:"currentColor",strokeLinecap:"round"}),bo.createElement("path",{d:"M7 12L11.5757 16.5757C11.8101 16.8101 12.1899 16.8101 12.4243 16.5757L22 7",stroke:"currentColor",strokeLinecap:"round"}))},OT=(0,Qy.forwardRef)(PT),vd=OT;var vn=Le(require("react"),1),tb=require("react");var AT=Object.defineProperty,Zy=Object.getOwnPropertySymbols,RT=Object.prototype.hasOwnProperty,IT=Object.prototype.propertyIsEnumerable,eb=(t,e,r)=>e in t?AT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Sd=(t,e)=>{for(var r in e||(e={}))RT.call(e,r)&&eb(t,r,e[r]);if(Zy)for(var r of Zy(e))IT.call(e,r)&&eb(t,r,e[r]);return t},DT=(t,e)=>{let r=vn.useContext(ve),o=Sd(Sd({},r),t);return vn.createElement("svg",Sd({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),vn.createElement("path",{d:"M7 9L12 12.5L17 9",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),vn.createElement("path",{d:"M2 17V7C2 5.89543 2.89543 5 4 5H20C21.1046 5 22 5.89543 22 7V17C22 18.1046 21.1046 19 20 19H4C2.89543 19 2 18.1046 2 17Z",stroke:"currentColor"}))},LT=(0,tb.forwardRef)(DT),xd=LT;var Sn=Le(require("react"),1),nb=require("react");var NT=Object.defineProperty,rb=Object.getOwnPropertySymbols,jT=Object.prototype.hasOwnProperty,MT=Object.prototype.propertyIsEnumerable,ob=(t,e,r)=>e in t?NT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,kd=(t,e)=>{for(var r in e||(e={}))jT.call(e,r)&&ob(t,r,e[r]);if(rb)for(var r of rb(e))MT.call(e,r)&&ob(t,r,e[r]);return t},UT=(t,e)=>{let r=Sn.useContext(ve),o=kd(kd({},r),t);return Sn.createElement("svg",kd({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),Sn.createElement("path",{d:"M20 5.99999L20 18C20 19.1046 19.1046 20 18 20H6C4.89543 20 4 19.1046 4 18V6C4 4.89543 4.89543 4 6 4H18C19.1045 4 19.9999 4.89543 20 5.99999Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),Sn.createElement("path",{d:"M12 9V4",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},FT=(0,nb.forwardRef)(UT),Td=FT;var xn=Le(require("react"),1),ab=require("react");var $T=Object.defineProperty,sb=Object.getOwnPropertySymbols,BT=Object.prototype.hasOwnProperty,qT=Object.prototype.propertyIsEnumerable,ib=(t,e,r)=>e in t?$T(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Cd=(t,e)=>{for(var r in e||(e={}))BT.call(e,r)&&ib(t,r,e[r]);if(sb)for(var r of sb(e))qT.call(e,r)&&ib(t,r,e[r]);return t},VT=(t,e)=>{let r=xn.useContext(ve),o=Cd(Cd({},r),t);return xn.createElement("svg",Cd({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),xn.createElement("path",{d:"M19.2609 9.69589L20.6455 18.6959C20.8319 19.9074 19.8945 21 18.6688 21H5.33122C4.10545 21 3.16809 19.9074 3.35448 18.6959L4.73909 9.69589C4.8892 8.72022 5.7287 8 6.71584 8H17.2842C18.2713 8 19.1108 8.72022 19.2609 9.69589Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),xn.createElement("path",{d:"M14 5C14 3.89543 13.1046 3 12 3C10.8954 3 10 3.89543 10 5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},WT=(0,ab.forwardRef)(VT),Ed=WT;var Gs=Le(require("react"),1),cb=require("react");var HT=Object.defineProperty,lb=Object.getOwnPropertySymbols,zT=Object.prototype.hasOwnProperty,GT=Object.prototype.propertyIsEnumerable,ub=(t,e,r)=>e in t?HT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Pd=(t,e)=>{for(var r in e||(e={}))zT.call(e,r)&&ub(t,r,e[r]);if(lb)for(var r of lb(e))GT.call(e,r)&&ub(t,r,e[r]);return t},KT=(t,e)=>{let r=Gs.useContext(ve),o=Pd(Pd({},r),t);return Gs.createElement("svg",Pd({width:"1.5em",height:"1.5em",viewBox:"0 0 24 24",strokeWidth:1.5,fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),Gs.createElement("path",{d:"M15 4L8 20",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},JT=(0,cb.forwardRef)(KT),Ol=JT;var kn=Le(require("react"),1),mb=require("react");var YT=Object.defineProperty,db=Object.getOwnPropertySymbols,XT=Object.prototype.hasOwnProperty,QT=Object.prototype.propertyIsEnumerable,fb=(t,e,r)=>e in t?YT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Od=(t,e)=>{for(var r in e||(e={}))XT.call(e,r)&&fb(t,r,e[r]);if(db)for(var r of db(e))QT.call(e,r)&&fb(t,r,e[r]);return t},ZT=(t,e)=>{let r=kn.useContext(ve),o=Od(Od({},r),t);return kn.createElement("svg",Od({width:"1.5em",height:"1.5em",strokeWidth:1.5,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"currentColor",ref:e},o),kn.createElement("path",{d:"M9.17218 14.8284L12.0006 12M14.829 9.17157L12.0006 12M12.0006 12L9.17218 9.17157M12.0006 12L14.829 14.8284",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}),kn.createElement("path",{d:"M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"}))},eC=(0,mb.forwardRef)(ZT),Al=eC;function hb(t){return{label:(t.split(".").at(-1)??t).replace(/_/g," "),color:"gray"}}var de=require("react/jsx-runtime"),tC={"order.placed":{label:"Order placed",color:"blue",icon:Ed},"device.order_received":{label:"Received",color:"blue",icon:Td},"order.requested":{label:"Requested",color:"blue",icon:Pl},"order.paid":{label:"Paid",color:"green",icon:_d},"device.order_acknowledged":{label:"Acknowledged",color:"blue",icon:vd},"order.confirmed":{label:"Confirmed",color:"green",icon:El},"order.confirmation_email_sent":{label:"Confirmation email sent",color:"green",icon:xd},"order.completed":{label:"Completed",color:"green",icon:pd},"order.failed":{label:"Failed",color:"red",icon:Al},"order.canceled":{label:"Cancelled",color:"red",icon:Ol},"order.cancelled":{label:"Cancelled",color:"red",icon:Ol},"order.catering.requested":{label:"Requested",color:"blue",icon:Pl},"order.catering.confirmed":{label:"Confirmed",color:"green",icon:El},"order.catering.charge_failed":{label:"Charge failed",color:"red",icon:Al}};function Ad(t){return tC[t]??hb(t)}var rC=new Set(["order.catering.requested","order.catering.confirmed","order.catering.charge_failed","order.canceled","order.cancelled"]);function Rd(t){let e=t.events.filter(i=>rC.has(i.event_name));if(!e.length)return null;let r=e[e.length-1],o=r.payload,n=r.event_name==="order.catering.confirmed"?"confirmed":r.event_name==="order.catering.requested"?"requested":"rejected",s=typeof o.userId=="string"?t.actorNames?.[o.userId]??o.userId:typeof o.deviceId=="number"?`Device #${o.deviceId}`:null;return{status:n,via:o.via??null,when:r.created_at,actorName:s}}function Id(t){let e=bs.ORDER_STATUS;switch(t.order_status){case e.REQUESTED:return{label:"Awaiting approval",color:"blue"};case e.CONFIRMED:return{label:"Confirmed",color:"green"};case e.CANCELLED:return t.is_catering?{label:"Rejected",color:"red"}:{label:"Cancelled",color:"red"};case e.PAID:case e.PARTIALLY_PAID:return{label:"Paid",color:"green"};case e.PREPARING:return{label:"Preparing",color:"blue"};case e.KITCHEN_DONE:case e.COMPLETED:return{label:"Completed",color:"green"};default:return{label:"Pending",color:"gray"}}}function Dd(t){let e=bs.ORDER_STATUS;return t.order_status===(t.is_catering?e.REQUESTED:e.STAGING)}function oC(t){return t<1e3?`${t}ms`:t<6e4?`${Math.round(t/1e3)}s`:t<36e5?`${Math.round(t/6e4)}m`:`${Math.round(t/36e5)}h`}var Ld={root:"flex flex-col gap-6 min-w-0 text-white",statusPill:"text-sm font-semibold px-3 py-1 rounded-full",approval:"text-white/60 text-sm",approvalEmpty:"text-white/40 text-sm",timeline:"flex items-start overflow-x-auto pb-2",eventIcon:"w-10 h-10 rounded-xl shrink-0 flex items-center justify-center",eventLabel:"text-xs font-medium text-center",eventTime:"text-white/30 text-xs text-center",connectorLine:"h-px w-8 bg-white/20",connectorDelta:"text-white/30 text-xs",confirmButton:"w-full py-4 rounded-lg text-base font-bold text-white bg-green-600 hover:bg-green-500 disabled:opacity-60 transition-colors",confirmError:"text-red-400 text-xs text-center",colors:{blue:{bg:"bg-blue-500/20",text:"text-blue-400",dot:"bg-blue-500/60"},green:{bg:"bg-green-500/20",text:"text-green-400",dot:"bg-green-500/60"},red:{bg:"bg-red-500/20",text:"text-red-400",dot:"bg-red-500/60"},gray:{bg:"bg-white/10",text:"text-white/50",dot:"bg-white/60"}}};function Nd(t){let e=Ld,{colors:r,...o}=t??{},n=Object.fromEntries(Object.keys(e.colors).map(i=>[i,{...e.colors[i],...r?.[i]}])),s=Object.fromEntries(Object.entries(o).filter(([,i])=>i!==void 0));return{...e,...s,colors:n}}var nC={pos:"at the POS",dashboard:"from the dashboard",email_link:"via an emailed link"};function pb({order:t,can:e,onConfirm:r,confirming:o,confirmError:n,itemClasses:s}){let i=Nd(s),a=Id(t),l=Rd(t),u=t.events,c=!!r&&e("catering.confirm")&&Dd(t);return(0,de.jsxs)("div",{className:i.root,children:[(0,de.jsx)("div",{className:"flex items-center gap-2",children:(0,de.jsx)("span",{className:`${i.statusPill} ${i.colors[a.color].bg} ${i.colors[a.color].text}`,children:a.label})}),(0,de.jsx)("div",{className:"flex flex-col gap-1",children:l===null?(0,de.jsx)("span",{className:i.approvalEmpty,children:"No approval recorded."}):l.status==="requested"?(0,de.jsx)("span",{className:i.approval,children:"Awaiting approval."}):(0,de.jsxs)("span",{className:i.approval,children:[l.status==="confirmed"?"Confirmed":"Rejected",l.actorName&&` by ${l.actorName}`,l.via&&` ${nC[l.via]}`," on ",Be(new Date(l.when),"MMM d, h:mm a")]})}),u.length>0&&(0,de.jsx)("div",{className:i.timeline,children:u.map((d,f)=>{let m=Ad(d.event_name),h=i.colors[m.color],g=f===u.length-1,y=m.icon;return(0,de.jsxs)("div",{className:"flex items-start shrink-0",children:[(0,de.jsxs)("div",{className:"flex flex-col items-center gap-2 min-w-20",children:[(0,de.jsx)("div",{className:`${i.eventIcon} ${h.bg}`,children:y?(0,de.jsx)(y,{width:18,height:18,className:h.text}):(0,de.jsx)("div",{className:`w-2 h-2 rounded-full ${h.dot}`})}),(0,de.jsx)("span",{className:`${i.eventLabel} ${h.text}`,children:m.label}),(0,de.jsx)("span",{className:i.eventTime,children:Be(new Date(d.created_at),"h:mm a")})]}),!g&&(0,de.jsxs)("div",{className:"flex flex-col items-center gap-1 mt-4 shrink-0",children:[(0,de.jsx)("div",{className:i.connectorLine}),(0,de.jsx)("span",{className:i.connectorDelta,children:oC(Ah(new Date(u[f+1].created_at),new Date(d.created_at)))})]})]},d.id)})}),c&&(0,de.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,de.jsx)("button",{onClick:r,disabled:o,className:i.confirmButton,children:o?"Confirming\u2026":"Confirm This Order"}),n&&(0,de.jsx)("span",{className:i.confirmError,children:n})]})]})}var K=require("react/jsx-runtime"),jd={root:"flex flex-col gap-1 min-w-0 text-white",line:"flex flex-col gap-1 py-2 border-b border-white/10 last:border-b-0",lineName:"text-sm font-semibold text-white",lineSublabel:"text-xs text-white/50",linePrice:"text-sm font-semibold text-white tabular-nums",addOn:"flex justify-between items-baseline gap-2 text-xs",addOnName:"text-white/60",addOnPrice:"text-white/40",totalsRow:"flex justify-between text-sm text-white/70",discountRow:"flex justify-between text-sm text-green-400",totalRow:"flex justify-between text-base font-bold text-white mt-2"};function Md(t){let e=Object.fromEntries(Object.entries(t??{}).filter(([,r])=>r!==void 0));return{...jd,...e}}function gb({order:t,promotion:e,tip:r=0,itemClasses:o}){let n=Md(o),s=sn(t,e,r);return(0,K.jsxs)("div",{className:n.root,children:[s.lines.map((i,a)=>(0,K.jsxs)("div",{className:n.line,children:[(0,K.jsxs)("div",{className:"flex justify-between items-start gap-2",children:[(0,K.jsxs)("div",{className:"min-w-0",children:[(0,K.jsx)("p",{className:n.lineName,children:i.name}),i.perPerson?(0,K.jsx)("p",{className:n.lineSublabel,children:As(i)}):i.quantity>1&&(0,K.jsxs)("p",{className:n.lineSublabel,children:["\xD7",i.quantity]})]}),(0,K.jsx)("span",{className:n.linePrice,children:Wt(i.lineTotal)})]}),(i.perPerson||i.addOns.length>0)&&(0,K.jsxs)("div",{className:"flex flex-col gap-0.5 mt-1",children:[i.perPerson&&(0,K.jsxs)("div",{className:n.addOn,children:[(0,K.jsx)("span",{className:n.addOnName,children:"Base Price"}),(0,K.jsx)("span",{className:n.addOnPrice,children:`${Wt(i.basePrice)}/person`})]}),i.addOns.map((l,u)=>(0,K.jsxs)("div",{className:n.addOn,children:[(0,K.jsx)("span",{className:n.addOnName,children:l.name}),(0,K.jsx)("span",{className:n.addOnPrice,children:Rs(l,i.perPerson)})]},u))]})]},a)),(0,K.jsxs)("div",{className:"flex flex-col gap-1 mt-2",children:[s.discount>0&&(0,K.jsxs)("div",{className:n.discountRow,children:[(0,K.jsx)("span",{children:"Discount"}),(0,K.jsx)("span",{children:`(${Wt(s.discount)})`})]}),(0,K.jsxs)("div",{className:n.totalsRow,children:[(0,K.jsx)("span",{children:"Tax"}),(0,K.jsx)("span",{children:Wt(s.tax)})]}),s.serviceFee>0&&(0,K.jsxs)("div",{className:n.totalsRow,children:[(0,K.jsx)("span",{children:"Service fee"}),(0,K.jsx)("span",{children:Wt(s.serviceFee)})]}),s.tip>0&&(0,K.jsxs)("div",{className:n.totalsRow,children:[(0,K.jsx)("span",{children:"Tip"}),(0,K.jsx)("span",{children:Wt(s.tip)})]}),(0,K.jsxs)("div",{className:n.totalRow,children:[(0,K.jsx)("span",{children:"Total"}),(0,K.jsx)("span",{children:Wt(s.total)})]})]})]})}Lc(yy);Nc(yb.usePathname);0&&(module.exports={CheckboxField,ClickableField,ConditionalRenderer,DateField,DateTime,DateTimeRange,DisclaimerText,DiscreteNumberField,DynamicFormShell,EmailField,FieldError,FieldLabel,GuestCountField,Header,IncrementField,LOCATION_ORDERING_TIMEZONE,LocationField,NameFields,ORDER_ITEMIZED_DEFAULT_ITEM_CLASSES,ORDER_STATUS_DEFAULT_ITEM_CLASSES,OrderItemized,OrderStatus,PhoneField,Platforms,PricePreview,SectionLabel,SliderField,SubmitButton,TextField,TimeField,deriveApproval,deriveOrderStatus,divisionsFor,formatAddOnPrice,formatCateringLineLabel,groupItemPortions,isConfirmable,isLocationClosedByWeeklySchedule,itemizeOrder,locationWindowOn,mergeOrderItemizedItemClasses,mergeOrderStatusItemClasses,parsePortion,parsePortionKey,portionGlyph,portionKey,portionLabel,portionRows,portionWeight,radialSectionPath,remapPortion,resolveEventDisplay,sectionLabel,selectionWeight,setZorgoBoot,setZorgoPathnameHook,splitUpcharge,useCart,useCateringConfig,useCustomer,useField,useFormStatus,useFormValidity,useFormValues,useHydrateMenu,useHydrateStore,useItemCustomization,useLocation,useMenu,useModal,usePayment,usePromotions,useRecommendations,useRegisterField,weightedUpcharges});
|
|
159
159
|
/*! Bundled license information:
|
|
160
160
|
|
|
161
161
|
cookie/index.js:
|