Loading The Simple Trade…
";function vD(e,t){var r=e.match(/[\s\S]*?<\/table>/gi);if(!r||r.length==0)throw new Error("Invalid HTML: could not find ");if(r.length==1)return vi(Iw(r[0],t),t);var a=Ym();return r.forEach(function(n,i){Qm(a,Iw(n,t),"Sheet"+(i+1))}),a}function yD(e,t,r){var a=[];return a.join("")+""}function Ek(e,t){var r=t||{},a=r.header!=null?r.header:gD,n=r.footer!=null?r.footer:xD,i=[a],s=Dr(e["!ref"]);r.dense=Array.isArray(e),i.push(yD(e,s,r));for(var o=s.s.r;o<=s.e.r;++o)i.push(mD(e,s,o,r));return i.push("
"+n),i.join("")}function Lk(e,t,r){var a=r||{};It!=null&&(a.dense=It);var n=0,i=0;if(a.origin!=null)if(typeof a.origin=="number")n=a.origin;else{var s=typeof a.origin=="string"?wt(a.origin):a.origin;n=s.r,i=s.c}var o=t.getElementsByTagName("tr"),l=Math.min(a.sheetRows||1e7,o.length),u={s:{r:0,c:0},e:{r:n,c:i}};if(e["!ref"]){var c=Dr(e["!ref"]);u.s.r=Math.min(u.s.r,c.s.r),u.s.c=Math.min(u.s.c,c.s.c),u.e.r=Math.max(u.e.r,c.e.r),u.e.c=Math.max(u.e.c,c.e.c),n==-1&&(u.e.r=n=c.e.r+1)}var f=[],h=0,m=e["!rows"]||(e["!rows"]=[]),g=0,p=0,y=0,w=0,v=0,x=0;for(e["!cols"]||(e["!cols"]=[]);g1||x>1)&&f.push({s:{r:p+n,c:w+i},e:{r:p+n+(v||1)-1,c:w+i+(x||1)-1}});var H={t:"s",v:k},U=E.getAttribute("data-t")||E.getAttribute("t")||"";k!=null&&(k.length==0?H.t=U||"z":a.raw||k.trim().length==0||U=="s"||(k==="TRUE"?H={t:"b",v:!0}:k==="FALSE"?H={t:"b",v:!1}:isNaN(Oa(k))?isNaN(yo(k).getDate())||(H={t:"d",v:ct(k)},a.cellDates||(H={t:"n",v:Vt(H.v)}),H.z=a.dateNF||Ae[14]):H={t:"n",v:Oa(k)})),H.z===void 0&&b!=null&&(H.z=b);var B="",te=E.getElementsByTagName("A");if(te&&te.length)for(var q=0;q=l&&(e["!fullref"]=Oe((u.e.r=o.length-g+p-1+n,u))),e}function Tk(e,t){var r=t||{},a=r.dense?[]:{};return Lk(a,e,t)}function wD(e,t){return vi(Tk(e,t),t)}function Ew(e){var t="",r=kD(e);return r&&(t=r(e).getPropertyValue("display")),t||(t=e.style&&e.style.display),t==="none"}function kD(e){return e.ownerDocument.defaultView&&typeof e.ownerDocument.defaultView.getComputedStyle=="function"?e.ownerDocument.defaultView.getComputedStyle:typeof getComputedStyle=="function"?getComputedStyle:null}function SD(e){var t=e.replace(/[\t\r\n]/g," ").trim().replace(/ +/g," ").replace(//g," ").replace(//g,function(a,n){return Array(parseInt(n,10)+1).join(" ")}).replace(/]*\/>/g," ").replace(//g,` `),r=$e(t.replace(/<[^>]*>/g,""));return[r]}var Lw={day:["d","dd"],month:["m","mm"],year:["y","yy"],hours:["h","hh"],minutes:["m","mm"],seconds:["s","ss"],"am-pm":["A/P","AM/PM"],"day-of-week":["ddd","dddd"],era:["e","ee"],quarter:["\\Qm",'m\\"th quarter"']};function Ak(e,t){var r=t||{};It!=null&&r.dense==null&&(r.dense=It);var a=vm(e),n=[],i,s,o={name:""},l="",u=0,c,f,h={},m=[],g=r.dense?[]:{},p,y,w={value:""},v="",x=0,_,T=[],E=-1,k=-1,b={s:{r:1e6,c:1e7},e:{r:0,c:0}},O=0,H={},U=[],B={},te=0,q=0,j=[],ie=1,K=1,de=[],se={Names:[]},ge={},ne=["",""],D=[],V={},N="",M=0,z=!1,W=!1,G=0;for(pu.lastIndex=0,a=a.replace(//mg,"").replace(//gm,"");p=pu.exec(a);)switch(p[3]=p[3].replace(/_.*$/,"")){case"table":case"\u5DE5\u4F5C\u8868":p[1]==="/"?(b.e.c>=b.s.c&&b.e.r>=b.s.r?g["!ref"]=Oe(b):g["!ref"]="A1:A1",r.sheetRows>0&&r.sheetRows<=b.e.r&&(g["!fullref"]=g["!ref"],b.e.r=r.sheetRows-1,g["!ref"]=Oe(b)),U.length&&(g["!merges"]=U),j.length&&(g["!rows"]=j),c.name=c.\u540D\u79F0||c.name,typeof JSON<"u"&&JSON.stringify(c),m.push(c.name),h[c.name]=g,W=!1):p[0].charAt(p[0].length-2)!=="/"&&(c=Re(p[0],!1),E=k=-1,b.s.r=b.s.c=1e7,b.e.r=b.e.c=0,g=r.dense?[]:{},U=[],j=[],W=!0);break;case"table-row-group":p[1]==="/"?--O:++O;break;case"table-row":case"\u884C":if(p[1]==="/"){E+=ie,ie=1;break}if(f=Re(p[0],!1),f.\u884C\u53F7?E=f.\u884C\u53F7-1:E==-1&&(E=0),ie=+f["number-rows-repeated"]||1,ie<10)for(G=0;G0&&(j[E+G]={level:O});k=-1;break;case"covered-table-cell":p[1]!=="/"&&++k,r.sheetStubs&&(r.dense?(g[E]||(g[E]=[]),g[E][k]={t:"z"}):g[Fe({r:E,c:k})]={t:"z"}),v="",T=[];break;case"table-cell":case"\u6570\u636E":if(p[0].charAt(p[0].length-2)==="/")++k,w=Re(p[0],!1),K=parseInt(w["number-columns-repeated"]||"1",10),y={t:"z",v:null},w.formula&&r.cellFormula!=!1&&(y.f=Sw($e(w.formula))),(w.\u6570\u636E\u7C7B\u578B||w["value-type"])=="string"&&(y.t="s",y.v=$e(w["string-value"]||""),r.dense?(g[E]||(g[E]=[]),g[E][k]=y):g[Fe({r:E,c:k})]=y),k+=K-1;else if(p[1]!=="/"){++k,v="",x=0,T=[],K=1;var ee=ie?E+ie-1:E;if(k>b.e.c&&(b.e.c=k),kb.e.r&&(b.e.r=ee),w=Re(p[0],!1),D=[],V={},y={t:w.\u6570\u636E\u7C7B\u578B||w["value-type"],v:null},r.cellFormula)if(w.formula&&(w.formula=$e(w.formula)),w["number-matrix-columns-spanned"]&&w["number-matrix-rows-spanned"]&&(te=parseInt(w["number-matrix-rows-spanned"],10)||0,q=parseInt(w["number-matrix-columns-spanned"],10)||0,B={s:{r:E,c:k},e:{r:E+te-1,c:k+q-1}},y.F=Oe(B),de.push([B,y.F])),w.formula)y.f=Sw(w.formula);else for(G=0;G=de[G][0].s.r&&E<=de[G][0].e.r&&k>=de[G][0].s.c&&k<=de[G][0].e.c&&(y.F=de[G][1]);switch((w["number-columns-spanned"]||w["number-rows-spanned"])&&(te=parseInt(w["number-rows-spanned"],10)||0,q=parseInt(w["number-columns-spanned"],10)||0,B={s:{r:E,c:k},e:{r:E+te-1,c:k+q-1}},U.push(B)),w["number-columns-repeated"]&&(K=parseInt(w["number-columns-repeated"],10)),y.t){case"boolean":y.t="b",y.v=ut(w["boolean-value"]);break;case"float":y.t="n",y.v=parseFloat(w.value);break;case"percentage":y.t="n",y.v=parseFloat(w.value);break;case"currency":y.t="n",y.v=parseFloat(w.value);break;case"date":y.t="d",y.v=ct(w["date-value"]),r.cellDates||(y.t="n",y.v=Vt(y.v)),y.z="m/d/yy";break;case"time":y.t="n",y.v=XE(w["time-value"])/86400,r.cellDates&&(y.t="d",y.v=kd(y.v)),y.z="HH:MM:SS";break;case"number":y.t="n",y.v=parseFloat(w.\u6570\u636E\u6570\u503C);break;default:if(y.t==="string"||y.t==="text"||!y.t)y.t="s",w["string-value"]!=null&&(v=$e(w["string-value"]),T=[]);else throw new Error("Unsupported value type "+y.t)}}else{if(z=!1,y.t==="s"&&(y.v=v||"",T.length&&(y.R=T),z=x==0),ge.Target&&(y.l=ge),D.length>0&&(y.c=D,D=[]),v&&r.cellText!==!1&&(y.w=v),z&&(y.t="z",delete y.v),(!z||r.sheetStubs)&&!(r.sheetRows&&r.sheetRows<=E))for(var Q=0;Q0;)g[E+Q][k+K]=ft(y);else for(g[Fe({r:E+Q,c:k})]=y;--K>0;)g[Fe({r:E+Q,c:k+K})]=ft(y);b.e.c<=k&&(b.e.c=k)}K=parseInt(w["number-columns-repeated"]||"1",10),k+=K-1,K=0,y={},v="",T=[]}ge={};break;case"document":case"document-content":case"\u7535\u5B50\u8868\u683C\u6587\u6863":case"spreadsheet":case"\u4E3B\u4F53":case"scripts":case"styles":case"font-face-decls":case"master-styles":if(p[1]==="/"){if((i=n.pop())[0]!==p[3])throw"Bad state: "+i}else p[0].charAt(p[0].length-2)!=="/"&&n.push([p[3],!0]);break;case"annotation":if(p[1]==="/"){if((i=n.pop())[0]!==p[3])throw"Bad state: "+i;V.t=v,T.length&&(V.R=T),V.a=N,D.push(V)}else p[0].charAt(p[0].length-2)!=="/"&&n.push([p[3],!1]);N="",M=0,v="",x=0,T=[];break;case"creator":p[1]==="/"?N=a.slice(M,p.index):M=p.index+p[0].length;break;case"meta":case"\u5143\u6570\u636E":case"settings":case"config-item-set":case"config-item-map-indexed":case"config-item-map-entry":case"config-item-map-named":case"shapes":case"frame":case"text-box":case"image":case"data-pilot-tables":case"list-style":case"form":case"dde-links":case"event-listeners":case"chart":if(p[1]==="/"){if((i=n.pop())[0]!==p[3])throw"Bad state: "+i}else p[0].charAt(p[0].length-2)!=="/"&&n.push([p[3],!1]);v="",x=0,T=[];break;case"scientific-number":break;case"currency-symbol":break;case"currency-style":break;case"number-style":case"percentage-style":case"date-style":case"time-style":if(p[1]==="/"){if(H[o.name]=l,(i=n.pop())[0]!==p[3])throw"Bad state: "+i}else p[0].charAt(p[0].length-2)!=="/"&&(l="",o=Re(p[0],!1),n.push([p[3],!0]));break;case"script":break;case"libraries":break;case"automatic-styles":break;case"default-style":case"page-layout":break;case"style":break;case"map":break;case"font-face":break;case"paragraph-properties":break;case"table-properties":break;case"table-column-properties":break;case"table-row-properties":break;case"table-cell-properties":break;case"number":switch(n[n.length-1][0]){case"time-style":case"date-style":s=Re(p[0],!1),l+=Lw[p[3]][s.style==="long"?1:0];break}break;case"fraction":break;case"day":case"month":case"year":case"era":case"day-of-week":case"week-of-year":case"quarter":case"hours":case"minutes":case"seconds":case"am-pm":switch(n[n.length-1][0]){case"time-style":case"date-style":s=Re(p[0],!1),l+=Lw[p[3]][s.style==="long"?1:0];break}break;case"boolean-style":break;case"boolean":break;case"text-style":break;case"text":if(p[0].slice(-2)==="/>")break;if(p[1]==="/")switch(n[n.length-1][0]){case"number-style":case"date-style":case"time-style":l+=a.slice(u,p.index);break}else u=p.index+p[0].length;break;case"named-range":s=Re(p[0],!1),ne=jp(s["cell-range-address"]);var Le={Name:s.name,Ref:ne[0]+"!"+ne[1]};W&&(Le.Sheet=m.length),se.Names.push(Le);break;case"text-content":break;case"text-properties":break;case"embedded-text":break;case"body":case"\u7535\u5B50\u8868\u683C":break;case"forms":break;case"table-column":break;case"table-header-rows":break;case"table-rows":break;case"table-column-group":break;case"table-header-columns":break;case"table-columns":break;case"null-date":break;case"graphic-properties":break;case"calculation-settings":break;case"named-expressions":break;case"label-range":break;case"label-ranges":break;case"named-expression":break;case"sort":break;case"sort-by":break;case"sort-groups":break;case"tab":break;case"line-break":break;case"span":break;case"p":case"\u6587\u672C\u4E32":if(["master-styles"].indexOf(n[n.length-1][0])>-1)break;if(p[1]==="/"&&(!w||!w["string-value"])){var P=SD(a.slice(x,p.index),_);v=(v.length>0?v+` `:"")+P[0]}else _=Re(p[0],!1),x=p.index+p[0].length;break;case"s":break;case"database-range":if(p[1]==="/")break;try{ne=jp(Re(p[0])["target-range-address"]),h[ne[0]]["!autofilter"]={ref:ne[1]}}catch{}break;case"date":break;case"object":break;case"title":case"\u6807\u9898":break;case"desc":break;case"binary-data":break;case"table-source":break;case"scenario":break;case"iteration":break;case"content-validations":break;case"content-validation":break;case"help-message":break;case"error-message":break;case"database-ranges":break;case"filter":break;case"filter-and":break;case"filter-or":break;case"filter-condition":break;case"list-level-style-bullet":break;case"list-level-style-number":break;case"list-level-properties":break;case"sender-firstname":case"sender-lastname":case"sender-initials":case"sender-title":case"sender-position":case"sender-email":case"sender-phone-private":case"sender-fax":case"sender-company":case"sender-phone-work":case"sender-street":case"sender-city":case"sender-postal-code":case"sender-country":case"sender-state-or-province":case"author-name":case"author-initials":case"chapter":case"file-name":case"template-name":case"sheet-name":break;case"event-listener":break;case"initial-creator":case"creation-date":case"print-date":case"generator":case"document-statistic":case"user-defined":case"editing-duration":case"editing-cycles":break;case"config-item":break;case"page-number":break;case"page-count":break;case"time":break;case"cell-range-source":break;case"detective":break;case"operation":break;case"highlighted-range":break;case"data-pilot-table":case"source-cell-range":case"source-service":case"data-pilot-field":case"data-pilot-level":case"data-pilot-subtotals":case"data-pilot-subtotal":case"data-pilot-members":case"data-pilot-member":case"data-pilot-display-info":case"data-pilot-sort-info":case"data-pilot-layout-info":case"data-pilot-field-reference":case"data-pilot-groups":case"data-pilot-group":case"data-pilot-group-member":break;case"rect":break;case"dde-connection-decls":case"dde-connection-decl":case"dde-link":case"dde-source":break;case"properties":break;case"property":break;case"a":if(p[1]!=="/"){if(ge=Re(p[0],!1),!ge.href)break;ge.Target=$e(ge.href),delete ge.href,ge.Target.charAt(0)=="#"&&ge.Target.indexOf(".")>-1?(ne=jp(ge.Target.slice(1)),ge.Target="#"+ne[0]+"!"+ne[1]):ge.Target.match(/^\.\.[\\\/]/)&&(ge.Target=ge.Target.slice(3))}break;case"table-protection":break;case"data-pilot-grand-total":break;case"office-document-common-attrs":break;default:switch(p[2]){case"dc:":case"calcext:":case"loext:":case"ooo:":case"chartooo:":case"draw:":case"style:":case"chart:":case"form:":case"uof:":case"\u8868:":case"\u5B57:":break;default:if(r.WTF)throw new Error(p)}}var Se={Sheets:h,SheetNames:m,Workbook:se};return r.bookSheets&&delete Se.Sheets,Se}function Tw(e,t){t=t||{},ma(e,"META-INF/manifest.xml")&&XL(Mt(e,"META-INF/manifest.xml"),t);var r=Xr(e,"content.xml");if(!r)throw new Error("Missing content.xml in ODS / UOF file");var a=Ak(tt(r),t);return ma(e,"meta.xml")&&(a.Props=y2(Mt(e,"meta.xml"))),a}function Aw(e,t){return Ak(e,t)}var _D=function(){var e=["",'',"",'',"",'',"",""].join(""),t=""+e+"";return function(){return Ot+t}}(),bw=function(){var e=function(i){return Ze(i).replace(/ +/g,function(s){return''}).replace(/\t/g,"").replace(/\n/g,"").replace(/^ /,"").replace(/ $/,"")},t=` `,r=` `,a=function(i,s,o){var l=[];l.push(' `);var u=0,c=0,f=Dr(i["!ref"]||"A1"),h=i["!merges"]||[],m=0,g=Array.isArray(i);if(i["!cols"])for(c=0;c<=f.e.c;++c)l.push(" `);var p="",y=i["!rows"]||[];for(u=0;u `);for(;u<=f.e.r;++u){for(p=y[u]?' table:style-name="ro'+y[u].ods+'"':"",l.push(" `),c=0;cc)&&!(h[m].s.r>u)&&!(h[m].e.c `)}return l.push(` `),l.join("")},n=function(i,s){i.push(` `),i.push(` `),i.push(` `),i.push(` / `),i.push(` `),i.push(` / `),i.push(` `),i.push(` `);var o=0;s.SheetNames.map(function(u){return s.Sheets[u]}).forEach(function(u){if(u&&u["!cols"]){for(var c=0;c `),i.push(' `),i.push(` `),++o}}});var l=0;s.SheetNames.map(function(u){return s.Sheets[u]}).forEach(function(u){if(u&&u["!rows"]){for(var c=0;c `),i.push(' `),i.push(` `),++l}}}),i.push(` `),i.push(` `),i.push(` `),i.push(` `),i.push(` `)};return function(s,o){var l=[Ot],u=hu({"xmlns:office":"urn:oasis:names:tc:opendocument:xmlns:office:1.0","xmlns:table":"urn:oasis:names:tc:opendocument:xmlns:table:1.0","xmlns:style":"urn:oasis:names:tc:opendocument:xmlns:style:1.0","xmlns:text":"urn:oasis:names:tc:opendocument:xmlns:text:1.0","xmlns:draw":"urn:oasis:names:tc:opendocument:xmlns:drawing:1.0","xmlns:fo":"urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0","xmlns:xlink":"http://www.w3.org/1999/xlink","xmlns:dc":"http://purl.org/dc/elements/1.1/","xmlns:meta":"urn:oasis:names:tc:opendocument:xmlns:meta:1.0","xmlns:number":"urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0","xmlns:presentation":"urn:oasis:names:tc:opendocument:xmlns:presentation:1.0","xmlns:svg":"urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0","xmlns:chart":"urn:oasis:names:tc:opendocument:xmlns:chart:1.0","xmlns:dr3d":"urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0","xmlns:math":"http://www.w3.org/1998/Math/MathML","xmlns:form":"urn:oasis:names:tc:opendocument:xmlns:form:1.0","xmlns:script":"urn:oasis:names:tc:opendocument:xmlns:script:1.0","xmlns:ooo":"http://openoffice.org/2004/office","xmlns:ooow":"http://openoffice.org/2004/writer","xmlns:oooc":"http://openoffice.org/2004/calc","xmlns:dom":"http://www.w3.org/2001/xml-events","xmlns:xforms":"http://www.w3.org/2002/xforms","xmlns:xsd":"http://www.w3.org/2001/XMLSchema","xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","xmlns:sheet":"urn:oasis:names:tc:opendocument:sh33tjs:1.0","xmlns:rpt":"http://openoffice.org/2005/report","xmlns:of":"urn:oasis:names:tc:opendocument:xmlns:of:1.2","xmlns:xhtml":"http://www.w3.org/1999/xhtml","xmlns:grddl":"http://www.w3.org/2003/g/data-view#","xmlns:tableooo":"http://openoffice.org/2009/table","xmlns:drawooo":"http://openoffice.org/2010/draw","xmlns:calcext":"urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0","xmlns:loext":"urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0","xmlns:field":"urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0","xmlns:formx":"urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0","xmlns:css3t":"http://www.w3.org/TR/css3-text/","office:version":"1.2"}),c=hu({"xmlns:config":"urn:oasis:names:tc:opendocument:xmlns:config:1.0","office:mimetype":"application/vnd.oasis.opendocument.spreadsheet"});o.bookType=="fods"?(l.push(" `),l.push(v2().replace(/office:document-meta/g,"office:meta"))):l.push(" `),n(l,s),l.push(` `),l.push(` `);for(var f=0;f!=s.SheetNames.length;++f)l.push(a(s.Sheets[s.SheetNames[f]],s,f,o));return l.push(` `),l.push(` `),o.bookType=="fods"?l.push(""):l.push(""),l.join("")}}();function bk(e,t){if(t.bookType=="fods")return bw(e,t);var r=pm(),a="",n=[],i=[];return a="mimetype",Ne(r,a,"application/vnd.oasis.opendocument.spreadsheet"),a="content.xml",Ne(r,a,bw(e,t)),n.push([a,"text/xml"]),i.push([a,"ContentFile"]),a="styles.xml",Ne(r,a,_D(e,t)),n.push([a,"text/xml"]),i.push([a,"StylesFile"]),a="meta.xml",Ne(r,a,Ot+v2()),n.push([a,"text/xml"]),i.push([a,"MetadataFile"]),a="manifest.rdf",Ne(r,a,QL(i)),n.push([a,"application/rdf+xml"]),a="META-INF/manifest.xml",Ne(r,a,JL(n)),r}function ns(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function sm(e){return typeof TextDecoder<"u"?new TextDecoder().decode(e):tt(xi(e))}function CD(e){return typeof TextEncoder<"u"?new TextEncoder().encode(e):Kr(Ja(e))}function ID(e,t){e:for(var r=0;r<=e.length-t.length;++r){for(var a=0;a>1&1431655765,e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>>24}function ED(e,t){for(var r=(e[t+15]&127)<<7|e[t+14]>>1,a=e[t+14]&1,n=t+13;n>=t;--n)a=a*256+e[n];return(e[t+15]&128?-a:a)*Math.pow(10,r-6176)}function LD(e,t,r){var a=Math.floor(r==0?0:Math.LOG10E*Math.log(Math.abs(r)))+6176-20,n=r/Math.pow(10,a-6176);e[t+15]|=a>>7,e[t+14]|=(a&127)<<1;for(var i=0;n>=1;++i,n/=256)e[t+i]=n&255;e[t+15]|=r>=0?0:128}function ku(e,t){var r=t?t[0]:0,a=e[r]&127;e:if(e[r++]>=128&&(a|=(e[r]&127)<<7,e[r++]<128||(a|=(e[r]&127)<<14,e[r++]<128)||(a|=(e[r]&127)<<21,e[r++]<128)||(a+=(e[r]&127)*Math.pow(2,28),++r,e[r++]<128)||(a+=(e[r]&127)*Math.pow(2,35),++r,e[r++]<128)||(a+=(e[r]&127)*Math.pow(2,42),++r,e[r++]<128)))break e;return t&&(t[0]=r),a}function Ye(e){var t=new Uint8Array(7);t[0]=e&127;var r=1;e:if(e>127){if(t[r-1]|=128,t[r]=e>>7&127,++r,e<=16383||(t[r-1]|=128,t[r]=e>>14&127,++r,e<=2097151)||(t[r-1]|=128,t[r]=e>>21&127,++r,e<=268435455)||(t[r-1]|=128,t[r]=e/256>>>21&127,++r,e<=34359738367)||(t[r-1]|=128,t[r]=e/65536>>>21&127,++r,e<=4398046511103))break e;t[r-1]|=128,t[r]=e/16777216>>>21&127,++r}return t.slice(0,r)}function Ct(e){var t=0,r=e[t]&127;e:if(e[t++]>=128){if(r|=(e[t]&127)<<7,e[t++]<128||(r|=(e[t]&127)<<14,e[t++]<128)||(r|=(e[t]&127)<<21,e[t++]<128))break e;r|=(e[t]&127)<<28}return r}function Ke(e){for(var t=[],r=[0];r[0]=128;);o=e.slice(l,r[0])}break;case 5:s=4,o=e.slice(r[0],r[0]+s),r[0]+=s;break;case 1:s=8,o=e.slice(r[0],r[0]+s),r[0]+=s;break;case 2:s=ku(e,r),o=e.slice(r[0],r[0]+s),r[0]+=s;break;case 3:case 4:default:throw new Error("PB Type ".concat(i," for Field ").concat(n," at offset ").concat(a))}var u={data:o,type:i};t[n]==null?t[n]=[u]:t[n].push(u)}return t}function tr(e){var t=[];return e.forEach(function(r,a){r.forEach(function(n){n.data&&(t.push(Ye(a*8+n.type)),n.type==2&&t.push(Ye(n.data.length)),t.push(n.data))})}),gi(t)}function qm(e,t){return e?.map(function(r){return t(r.data)})||[]}function ha(e){for(var t,r=[],a=[0];a[0]>>0>0),r.push(s)}return r}function lo(e){var t=[];return e.forEach(function(r){var a=[];a[1]=[{data:Ye(r.id),type:0}],a[2]=[],r.merge!=null&&(a[3]=[{data:Ye(+!!r.merge),type:0}]);var n=[];r.messages.forEach(function(s){n.push(s.data),s.meta[3]=[{type:0,data:Ye(s.data.length)}],a[2].push({data:tr(s.meta),type:2})});var i=tr(a);t.push(Ye(i.length)),t.push(i),n.forEach(function(s){return t.push(s)})}),gi(t)}function TD(e,t){if(e!=0)throw new Error("Unexpected Snappy chunk type ".concat(e));for(var r=[0],a=ku(t,r),n=[];r[0]>2;if(s<60)++s;else{var o=s-59;s=t[r[0]],o>1&&(s|=t[r[0]+1]<<8),o>2&&(s|=t[r[0]+2]<<16),o>3&&(s|=t[r[0]+3]<<24),s>>>=0,s++,r[0]+=o}n.push(t.slice(r[0],r[0]+s)),r[0]+=s;continue}else{var l=0,u=0;if(i==1?(u=(t[r[0]]>>2&7)+4,l=(t[r[0]++]&224)<<3,l|=t[r[0]++]):(u=(t[r[0]++]>>2)+1,i==2?(l=t[r[0]]|t[r[0]+1]<<8,r[0]+=2):(l=(t[r[0]]|t[r[0]+1]<<8|t[r[0]+2]<<16|t[r[0]+3]<<24)>>>0,r[0]+=4)),n=[gi(n)],l==0)throw new Error("Invalid offset 0");if(l>n[0].length)throw new Error("Invalid offset beyond length");if(u>=l)for(n.push(n[0].slice(-l)),u-=l;u>=n[n.length-1].length;)n.push(n[n.length-1]),u-=n[n.length-1].length;n.push(n[0].slice(-l,-l+u))}}var c=gi(n);if(c.length!=a)throw new Error("Unexpected length: ".concat(c.length," != ").concat(a));return c}function pa(e){for(var t=[],r=0;r>8&255]))):a<=16777216?(s+=4,t.push(new Uint8Array([248,a-1&255,a-1>>8&255,a-1>>16&255]))):a<=4294967296&&(s+=5,t.push(new Uint8Array([252,a-1&255,a-1>>8&255,a-1>>16&255,a-1>>>24&255]))),t.push(e.slice(r,r+a)),s+=a,n[0]=0,n[1]=s&255,n[2]=s>>8&255,n[3]=s>>16&255,r+=a}return gi(t)}function AD(e,t,r,a){var n=ns(e),i=n.getUint32(4,!0),s=(a>1?12:8)+Fw(i&(a>1?3470:398))*4,o=-1,l=-1,u=NaN,c=new Date(2001,0,1);i&512&&(o=n.getUint32(s,!0),s+=4),s+=Fw(i&(a>1?12288:4096))*4,i&16&&(l=n.getUint32(s,!0),s+=4),i&32&&(u=n.getFloat64(s,!0),s+=8),i&64&&(c.setTime(c.getTime()+n.getFloat64(s,!0)*1e3),s+=8);var f;switch(e[2]){case 0:break;case 2:f={t:"n",v:u};break;case 3:f={t:"s",v:t[l]};break;case 5:f={t:"d",v:c};break;case 6:f={t:"b",v:u>0};break;case 7:f={t:"n",v:u/86400};break;case 8:f={t:"e",v:0};break;case 9:if(o>-1)f={t:"s",v:r[o]};else if(l>-1)f={t:"s",v:t[l]};else if(!isNaN(u))f={t:"n",v:u};else throw new Error("Unsupported cell type ".concat(e.slice(0,4)));break;default:throw new Error("Unsupported cell type ".concat(e.slice(0,4)))}return f}function bD(e,t,r){var a=ns(e),n=a.getUint32(8,!0),i=12,s=-1,o=-1,l=NaN,u=NaN,c=new Date(2001,0,1);n&1&&(l=ED(e,i),i+=16),n&2&&(u=a.getFloat64(i,!0),i+=8),n&4&&(c.setTime(c.getTime()+a.getFloat64(i,!0)*1e3),i+=8),n&8&&(o=a.getUint32(i,!0),i+=4),n&16&&(s=a.getUint32(i,!0),i+=4);var f;switch(e[1]){case 0:break;case 2:f={t:"n",v:l};break;case 3:f={t:"s",v:t[o]};break;case 5:f={t:"d",v:c};break;case 6:f={t:"b",v:u>0};break;case 7:f={t:"n",v:u/86400};break;case 8:f={t:"e",v:0};break;case 9:if(s>-1)f={t:"s",v:r[s]};else throw new Error("Unsupported cell type ".concat(e[1]," : ").concat(n&31," : ").concat(e.slice(0,4)));break;case 10:f={t:"n",v:l};break;default:throw new Error("Unsupported cell type ".concat(e[1]," : ").concat(n&31," : ").concat(e.slice(0,4)))}return f}function qp(e,t){var r=new Uint8Array(32),a=ns(r),n=12,i=0;switch(r[0]=5,e.t){case"n":r[1]=2,LD(r,n,e.v),i|=1,n+=16;break;case"b":r[1]=6,a.setFloat64(n,e.v?1:0,!0),i|=2,n+=8;break;case"s":if(t.indexOf(e.v)==-1)throw new Error("Value ".concat(e.v," missing from SST!"));r[1]=3,a.setUint32(n,t.indexOf(e.v),!0),i|=8,n+=4;break;default:throw"unsupported cell type "+e.t}return a.setUint32(8,i,!0),r.slice(0,n)}function $p(e,t){var r=new Uint8Array(32),a=ns(r),n=12,i=0;switch(r[0]=3,e.t){case"n":r[2]=2,a.setFloat64(n,e.v,!0),i|=32,n+=8;break;case"b":r[2]=6,a.setFloat64(n,e.v?1:0,!0),i|=32,n+=8;break;case"s":if(t.indexOf(e.v)==-1)throw new Error("Value ".concat(e.v," missing from SST!"));r[2]=3,a.setUint32(n,t.indexOf(e.v),!0),i|=16,n+=4;break;default:throw"unsupported cell type "+e.t}return a.setUint32(4,i,!0),r.slice(0,n)}function FD(e,t,r){switch(e[0]){case 0:case 1:case 2:case 3:return AD(e,t,r,e[0]);case 5:return bD(e,t,r);default:throw new Error("Unsupported payload version ".concat(e[0]))}}function cr(e){var t=Ke(e);return ku(t[1][0].data)}function Rw(e,t){var r=Ke(t.data),a=Ct(r[1][0].data),n=r[3],i=[];return(n||[]).forEach(function(s){var o=Ke(s.data),l=Ct(o[1][0].data)>>>0;switch(a){case 1:i[l]=sm(o[3][0].data);break;case 8:{var u=e[cr(o[9][0].data)][0],c=Ke(u.data),f=e[cr(c[1][0].data)][0],h=Ct(f.meta[1][0].data);if(h!=2001)throw new Error("2000 unexpected reference to ".concat(h));var m=Ke(f.data);i[l]=m[3].map(function(g){return sm(g.data)}).join("")}break}}),i}function RD(e,t){var r,a,n,i,s,o,l,u,c,f,h,m,g,p,y=Ke(e),w=Ct(y[1][0].data)>>>0,v=Ct(y[2][0].data)>>>0,x=((a=(r=y[8])==null?void 0:r[0])==null?void 0:a.data)&&Ct(y[8][0].data)>0||!1,_,T;if((i=(n=y[7])==null?void 0:n[0])!=null&&i.data&&t!=0)_=(o=(s=y[7])==null?void 0:s[0])==null?void 0:o.data,T=(u=(l=y[6])==null?void 0:l[0])==null?void 0:u.data;else if((f=(c=y[4])==null?void 0:c[0])!=null&&f.data&&t!=1)_=(m=(h=y[4])==null?void 0:h[0])==null?void 0:m.data,T=(p=(g=y[3])==null?void 0:g[0])==null?void 0:p.data;else throw"NUMBERS Tile missing ".concat(t," cell storage");for(var E=x?4:1,k=ns(_),b=[],O=0;O<_.length/2;++O){var H=k.getUint16(O*2,!0);H<65535&&b.push([O,H])}if(b.length!=v)throw"Expected ".concat(v," cells, found ").concat(b.length);var U=[];for(O=0;O=1&&(U[b[b.length-1][0]]=T.subarray(b[b.length-1][1]*E)),{R:w,cells:U}}function PD(e,t){var r,a=Ke(t.data),n=(r=a?.[7])!=null&&r[0]?Ct(a[7][0].data)>>>0>0?1:0:-1,i=qm(a[5],function(s){return RD(s,n)});return{nrows:Ct(a[4][0].data)>>>0,data:i.reduce(function(s,o){return s[o.R]||(s[o.R]=[]),o.cells.forEach(function(l,u){if(s[o.R][u])throw new Error("Duplicate cell r=".concat(o.R," c=").concat(u));s[o.R][u]=l}),s},[])}}function OD(e,t,r){var a,n=Ke(t.data),i={s:{r:0,c:0},e:{r:0,c:0}};if(i.e.r=(Ct(n[6][0].data)>>>0)-1,i.e.r<0)throw new Error("Invalid row varint ".concat(n[6][0].data));if(i.e.c=(Ct(n[7][0].data)>>>0)-1,i.e.c<0)throw new Error("Invalid col varint ".concat(n[7][0].data));r["!ref"]=Oe(i);var s=Ke(n[4][0].data),o=Rw(e,e[cr(s[4][0].data)][0]),l=(a=s[17])!=null&&a[0]?Rw(e,e[cr(s[17][0].data)][0]):[],u=Ke(s[3][0].data),c=0;u[1].forEach(function(f){var h=Ke(f.data),m=e[cr(h[2][0].data)][0],g=Ct(m.meta[1][0].data);if(g!=6002)throw new Error("6001 unexpected reference to ".concat(g));var p=PD(e,m);p.data.forEach(function(y,w){y.forEach(function(v,x){var _=Fe({r:c+w,c:x}),T=FD(v,o,l);T&&(r[_]=T)})}),c+=p.nrows})}function DD(e,t){var r=Ke(t.data),a={"!ref":"A1"},n=e[cr(r[2][0].data)],i=Ct(n[0].meta[1][0].data);if(i!=6001)throw new Error("6000 unexpected reference to ".concat(i));return OD(e,n[0],a),a}function BD(e,t){var r,a=Ke(t.data),n={name:(r=a[1])!=null&&r[0]?sm(a[1][0].data):"",sheets:[]},i=qm(a[2],cr);return i.forEach(function(s){e[s].forEach(function(o){var l=Ct(o.meta[1][0].data);l==6e3&&n.sheets.push(DD(e,o))})}),n}function ND(e,t){var r=Ym(),a=Ke(t.data),n=qm(a[1],cr);if(n.forEach(function(i){e[i].forEach(function(s){var o=Ct(s.meta[1][0].data);if(o==2){var l=BD(e,s);l.sheets.forEach(function(u,c){Qm(r,u,c==0?l.name:l.name+"_"+c,!0)})}})}),r.SheetNames.length==0)throw new Error("Empty NUMBERS file");return r}function Gp(e){var t,r,a,n,i={},s=[];if(e.FullPaths.forEach(function(l){if(l.match(/\.iwpv2/))throw new Error("Unsupported password protection")}),e.FileIndex.forEach(function(l){if(l.name.match(/\.iwa$/)){var u;try{u=pa(l.content)}catch(f){return console.log("?? "+l.content.length+" "+(f.message||f))}var c;try{c=ha(u)}catch(f){return console.log("## "+(f.message||f))}c.forEach(function(f){i[f.id]=f.messages,s.push(f.id)})}}),!s.length)throw new Error("File has no messages");var o=((n=(a=(r=(t=i?.[1])==null?void 0:t[0])==null?void 0:r.meta)==null?void 0:a[1])==null?void 0:n[0].data)&&Ct(i[1][0].meta[1][0].data)==1&&i[1][0];if(o||s.forEach(function(l){i[l].forEach(function(u){var c=Ct(u.meta[1][0].data)>>>0;if(c==1)if(!o)o=u;else throw new Error("Document has multiple roots")})}),!o)throw new Error("Cannot find Document root");return ND(i,o)}function MD(e,t,r){var a,n,i,s;if(!((a=e[6])!=null&&a[0])||!((n=e[7])!=null&&n[0]))throw"Mutation only works on post-BNC storages!";var o=((s=(i=e[8])==null?void 0:i[0])==null?void 0:s.data)&&Ct(e[8][0].data)>0||!1;if(o)throw"Math only works with normal offsets";for(var l=0,u=ns(e[7][0].data),c=0,f=[],h=ns(e[4][0].data),m=0,g=[],p=0;p1&&console.error("The Numbers writer currently writes only the first table");var a=Dr(r["!ref"]);a.s.r=a.s.c=0;var n=!1;a.e.c>9&&(n=!0,a.e.c=9),a.e.r>49&&(n=!0,a.e.r=49),n&&console.error("The Numbers writer is currently limited to ".concat(Oe(a)));var i=gd(r,{range:a,header:1}),s=["~Sh33tJ5~"];i.forEach(function(N){return N.forEach(function(M){typeof M=="string"&&s.push(M)})});var o={},l=[],u=Ee.read(t.numbers,{type:"base64"});u.FileIndex.map(function(N,M){return[N,u.FullPaths[M]]}).forEach(function(N){var M=N[0],z=N[1];if(M.type==2&&M.name.match(/\.iwa/)){var W=M.content,G=pa(W),ee=ha(G);ee.forEach(function(Q){l.push(Q.id),o[Q.id]={deps:[],location:z,type:Ct(Q.messages[0].meta[1][0].data)}})}}),l.sort(function(N,M){return N-M});var c=l.filter(function(N){return N>1}).map(function(N){return[N,Ye(N)]});u.FileIndex.map(function(N,M){return[N,u.FullPaths[M]]}).forEach(function(N){var M=N[0],z=N[1];if(M.name.match(/\.iwa/)){var W=ha(pa(M.content));W.forEach(function(G){G.messages.forEach(function(ee){c.forEach(function(Q){G.messages.some(function(Le){return Ct(Le.meta[1][0].data)!=11006&&ID(Le.data,Q[1])})&&o[Q[0]].deps.push(G.id)})})})}});function f(){for(var N=927262;N<2e6;++N)if(!o[N])return N;throw new Error("Too many messages")}for(var h=Ee.find(u,o[1].location),m=ha(pa(h.content)),g,p=0;p-1?"sheet":Me.CS&&e==Me.CS?"chart":Me.DS&&e==Me.DS?"dialog":Me.MS&&e==Me.MS?"macro":e&&e.length?e:"sheet"}function WD(e,t){if(!e)return 0;try{e=t.map(function(a){return a.id||(a.id=a.strRelID),[a.name,e["!id"][a.id].Target,HD(e["!id"][a.id].Type)]})}catch{return null}return!e||e.length===0?null:e}function zD(e,t,r,a,n,i,s,o,l,u,c,f){try{i[a]=nu(Xr(e,r,!0),t);var h=Mt(e,t),m;switch(o){case"sheet":m=cO(h,t,n,l,i[a],u,c,f);break;case"chart":if(m=fO(h,t,n,l,i[a],u,c,f),!m||!m["!drawel"])break;var g=eu(m["!drawel"].Target,t),p=mu(g),y=Y4(Xr(e,g,!0),nu(Xr(e,p,!0),g)),w=eu(y,g),v=mu(w);m=MP(Xr(e,w,!0),w,l,nu(Xr(e,v,!0),w),u,m);break;case"macro":m=dO(h,t,n,l,i[a],u,c,f);break;case"dialog":m=hO(h,t,n,l,i[a],u,c,f);break;default:throw new Error("Unrecognized sheet type "+o)}s[a]=m;var x=[];i&&i[a]&&Et(i[a]).forEach(function(_){var T="";if(i[a][_].Type==Me.CMNT){T=eu(i[a][_].Target,t);var E=xO(Mt(e,T,!0),T,l);if(!E||!E.length)return;xw(m,E,!1)}i[a][_].Type==Me.TCMNT&&(T=eu(i[a][_].Target,t),x=x.concat(Z4(Mt(e,T,!0),l)))}),x&&x.length&&xw(m,x,!0,l.people||[])}catch(_){if(l.WTF)throw _}}function fa(e){return e.charAt(0)=="/"?e.slice(1):e}function jD(e,t){if(_o(),t=t||{},$m(t),ma(e,"META-INF/manifest.xml")||ma(e,"objectdata.xml"))return Tw(e,t);if(ma(e,"Index/Document.iwa")){if(typeof Uint8Array>"u")throw new Error("NUMBERS file parsing requires Uint8Array support");if(typeof Gp<"u"){if(e.FileIndex)return Gp(e);var r=Ee.utils.cfb_new();return My(e).forEach(function(q){Ne(r,q,Jw(e,q))}),Gp(r)}throw new Error("Unsupported NUMBERS file")}if(!ma(e,"[Content_Types].xml"))throw ma(e,"index.xml.gz")?new Error("Unsupported NUMBERS 08 file"):ma(e,"index.xml")?new Error("Unsupported NUMBERS 09 file"):new Error("Unsupported ZIP file");var a=My(e),n=GL(Xr(e,"[Content_Types].xml")),i=!1,s,o;if(n.workbooks.length===0&&(o="xl/workbook.xml",Mt(e,o,!0)&&n.workbooks.push(o)),n.workbooks.length===0){if(o="xl/workbook.bin",!Mt(e,o,!0))throw new Error("Could not find workbook");n.workbooks.push(o),i=!0}n.workbooks[0].slice(-3)=="bin"&&(i=!0);var l={},u={};if(!t.bookSheets&&!t.bookProps){if(iu=[],n.sst)try{iu=gO(Mt(e,fa(n.sst)),n.sst,t)}catch(q){if(t.WTF)throw q}t.cellStyles&&n.themes.length&&(l=mO(Xr(e,n.themes[0].replace(/^\//,""),!0)||"",n.themes[0],t)),n.style&&(u=pO(Mt(e,fa(n.style)),n.style,l,t))}n.links.map(function(q){try{var j=nu(Xr(e,mu(fa(q))),q);return yO(Mt(e,fa(q)),j,q,t)}catch{}});var c=uO(Mt(e,fa(n.workbooks[0])),n.workbooks[0],t),f={},h="";n.coreprops.length&&(h=Mt(e,fa(n.coreprops[0]),!0),h&&(f=y2(h)),n.extprops.length!==0&&(h=Mt(e,fa(n.extprops[0]),!0),h&&eT(h,f,t)));var m={};(!t.bookSheets||t.bookProps)&&n.custprops.length!==0&&(h=Xr(e,fa(n.custprops[0]),!0),h&&(m=rT(h,t)));var g={};if((t.bookSheets||t.bookProps)&&(c.Sheets?s=c.Sheets.map(function(j){return j.name}):f.Worksheets&&f.SheetNames.length>0&&(s=f.SheetNames),t.bookProps&&(g.Props=f,g.Custprops=m),t.bookSheets&&typeof s<"u"&&(g.SheetNames=s),t.bookSheets?g.SheetNames:t.bookProps))return g;s={};var p={};t.bookDeps&&n.calcchain&&(p=vO(Mt(e,fa(n.calcchain)),n.calcchain,t));var y=0,w={},v,x;{var _=c.Sheets;f.Worksheets=_.length,f.SheetNames=[];for(var T=0;T!=_.length;++T)f.SheetNames[T]=_[T].name}var E=i?"bin":"xml",k=n.workbooks[0].lastIndexOf("/"),b=(n.workbooks[0].slice(0,k+1)+"_rels/"+n.workbooks[0].slice(k+1)+".rels").replace(/^\//,"");ma(e,b)||(b="xl/_rels/workbook."+E+".rels");var O=nu(Xr(e,b,!0),b.replace(/_rels.*/,"s5s"));(n.metadata||[]).length>=1&&(t.xlmeta=wO(Mt(e,fa(n.metadata[0])),n.metadata[0],t)),(n.people||[]).length>=1&&(t.people=tF(Mt(e,fa(n.people[0])),t)),O&&(O=WD(O,c.Sheets));var H=Mt(e,"xl/worksheets/sheet.xml",!0)?1:0;e:for(y=0;y!=f.Worksheets;++y){var U="sheet";if(O&&O[y]?(v="xl/"+O[y][1].replace(/[\/]?xl\//,""),ma(e,v)||(v=O[y][1]),ma(e,v)||(v=b.replace(/_rels\/.*$/,"")+O[y][1]),U=O[y][2]):(v="xl/worksheets/sheet"+(y+1-H)+"."+E,v=v.replace(/sheet0\./,"sheet.")),x=v.replace(/^(.*)(\/)([^\/]*)$/,"$1/_rels/$3.rels"),t&&t.sheets!=null)switch(typeof t.sheets){case"number":if(y!=t.sheets)continue e;break;case"string":if(f.SheetNames[y].toLowerCase()!=t.sheets.toLowerCase())continue e;break;default:if(Array.isArray&&Array.isArray(t.sheets)){for(var B=!1,te=0;te!=t.sheets.length;++te)typeof t.sheets[te]=="number"&&t.sheets[te]==y&&(B=1),typeof t.sheets[te]=="string"&&t.sheets[te].toLowerCase()==f.SheetNames[y].toLowerCase()&&(B=1);if(!B)continue e}}zD(e,v,x,f.SheetNames[y],y,w,s,U,t,c,l,u)}return g={Directory:n,Workbook:c,Props:f,Custprops:m,Deps:p,Sheets:s,SheetNames:f.SheetNames,Strings:iu,Styles:u,Themes:l,SSF:ft(Ae)},t&&t.bookFiles&&(e.files?(g.keys=a,g.files=e.files):(g.keys=[],g.files={},e.FullPaths.forEach(function(q,j){q=q.replace(/^Root Entry[\/]/,""),g.keys.push(q),g.files[q]=e.FileIndex[j]}))),t&&t.bookVBA&&(n.vba.length>0?g.vbaraw=Mt(e,fa(n.vba[0]),!0):n.defaults&&n.defaults.bin===uF&&(g.vbaraw=Mt(e,"xl/vbaProject.bin",!0))),g}function VD(e,t){var r=t||{},a="Workbook",n=Ee.find(e,a);try{if(a="/!DataSpaces/Version",n=Ee.find(e,a),!n||!n.content)throw new Error("ECMA-376 Encrypted file missing "+a);if(wb(n.content),a="/!DataSpaces/DataSpaceMap",n=Ee.find(e,a),!n||!n.content)throw new Error("ECMA-376 Encrypted file missing "+a);var i=Sb(n.content);if(i.length!==1||i[0].comps.length!==1||i[0].comps[0].t!==0||i[0].name!=="StrongEncryptionDataSpace"||i[0].comps[0].v!=="EncryptedPackage")throw new Error("ECMA-376 Encrypted file bad "+a);if(a="/!DataSpaces/DataSpaceInfo/StrongEncryptionDataSpace",n=Ee.find(e,a),!n||!n.content)throw new Error("ECMA-376 Encrypted file missing "+a);var s=_b(n.content);if(s.length!=1||s[0]!="StrongEncryptionTransform")throw new Error("ECMA-376 Encrypted file bad "+a);if(a="/!DataSpaces/TransformInfo/StrongEncryptionTransform/!Primary",n=Ee.find(e,a),!n||!n.content)throw new Error("ECMA-376 Encrypted file missing "+a);Ib(n.content)}catch{}if(a="/EncryptionInfo",n=Ee.find(e,a),!n||!n.content)throw new Error("ECMA-376 Encrypted file missing "+a);var o=Eb(n.content);if(a="/EncryptedPackage",n=Ee.find(e,a),!n||!n.content)throw new Error("ECMA-376 Encrypted file missing "+a);if(o[0]==4&&typeof decrypt_agile<"u")return decrypt_agile(o[1],n.content,r.password||"",r);if(o[0]==2&&typeof decrypt_std76<"u")return decrypt_std76(o[1],n.content,r.password||"",r);throw new Error("File is password-protected")}function qD(e,t){return t.bookType=="ods"?bk(e,t):t.bookType=="numbers"?UD(e,t):t.bookType=="xlsb"?$D(e,t):GD(e,t)}function $D(e,t){ho=1024,e&&!e.SSF&&(e.SSF=ft(Ae)),e&&e.SSF&&(_o(),vd(e.SSF),t.revssf=wd(e.SSF),t.revssf[e.SSF[65535]]=0,t.ssf=e.SSF),t.rels={},t.wbrels={},t.Strings=[],t.Strings.Count=0,t.Strings.Unique=0,su?t.revStrings=new Map:(t.revStrings={},t.revStrings.foo=[],delete t.revStrings.foo);var r=t.bookType=="xlsb"?"bin":"xml",a=nk.indexOf(t.bookType)>-1,n=Rm();Gm(t=t||{});var i=pm(),s="",o=0;if(t.cellXfs=[],yi(t.cellXfs,{},{revssf:{General:0}}),e.Props||(e.Props={}),s="docProps/core.xml",Ne(i,s,w2(e.Props,t)),n.coreprops.push(s),Qe(t.rels,2,s,Me.CORE_PROPS),s="docProps/app.xml",!(e.Props&&e.Props.SheetNames))if(!e.Workbook||!e.Workbook.Sheets)e.Props.SheetNames=e.SheetNames;else{for(var l=[],u=0;u0&&(s="docProps/custom.xml",Ne(i,s,C2(e.Custprops,t)),n.custprops.push(s),Qe(t.rels,4,s,Me.CUST_PROPS)),o=1;o<=e.SheetNames.length;++o){var c={"!id":{}},f=e.Sheets[e.SheetNames[o-1]],h=(f||{})["!type"]||"sheet";switch(h){case"chart":default:s="xl/worksheets/sheet"+o+"."+r,Ne(i,s,SO(o-1,s,t,e,c)),n.sheets.push(s),Qe(t.wbrels,-1,"worksheets/sheet"+o+"."+r,Me.WS[0])}if(f){var m=f["!comments"],g=!1,p="";m&&m.length>0&&(p="xl/comments"+o+"."+r,Ne(i,p,IO(m,p,t)),n.comments.push(p),Qe(c,-1,"../comments"+o+"."+r,Me.CMNT),g=!0),f["!legacy"]&&g&&Ne(i,"xl/drawings/vmlDrawing"+o+".vml",rk(o,f["!comments"])),delete f["!comments"],delete f["!legacy"]}c["!id"].rId1&&Ne(i,mu(s),mo(c))}return t.Strings!=null&&t.Strings.length>0&&(s="xl/sharedStrings."+r,Ne(i,s,CO(t.Strings,s,t)),n.strs.push(s),Qe(t.wbrels,-1,"sharedStrings."+r,Me.SST)),s="xl/workbook."+r,Ne(i,s,kO(e,s,t)),n.workbooks.push(s),Qe(t.rels,1,s,Me.WB),s="xl/theme/theme1.xml",Ne(i,s,Mm(e.Themes,t)),n.themes.push(s),Qe(t.wbrels,-1,"theme/theme1.xml",Me.THEME),s="xl/styles."+r,Ne(i,s,_O(e,s,t)),n.styles.push(s),Qe(t.wbrels,-1,"styles."+r,Me.STY),e.vbaraw&&a&&(s="xl/vbaProject.bin",Ne(i,s,e.vbaraw),n.vba.push(s),Qe(t.wbrels,-1,"vbaProject.bin",Me.VBA)),s="xl/metadata."+r,Ne(i,s,EO(s)),n.metadata.push(s),Qe(t.wbrels,-1,"metadata."+r,Me.XLMETA),Ne(i,"[Content_Types].xml",x2(n,t)),Ne(i,"_rels/.rels",mo(t.rels)),Ne(i,"xl/_rels/workbook."+r+".rels",mo(t.wbrels)),delete t.revssf,delete t.ssf,i}function GD(e,t){ho=1024,e&&!e.SSF&&(e.SSF=ft(Ae)),e&&e.SSF&&(_o(),vd(e.SSF),t.revssf=wd(e.SSF),t.revssf[e.SSF[65535]]=0,t.ssf=e.SSF),t.rels={},t.wbrels={},t.Strings=[],t.Strings.Count=0,t.Strings.Unique=0,su?t.revStrings=new Map:(t.revStrings={},t.revStrings.foo=[],delete t.revStrings.foo);var r="xml",a=nk.indexOf(t.bookType)>-1,n=Rm();Gm(t=t||{});var i=pm(),s="",o=0;if(t.cellXfs=[],yi(t.cellXfs,{},{revssf:{General:0}}),e.Props||(e.Props={}),s="docProps/core.xml",Ne(i,s,w2(e.Props,t)),n.coreprops.push(s),Qe(t.rels,2,s,Me.CORE_PROPS),s="docProps/app.xml",!(e.Props&&e.Props.SheetNames))if(!e.Workbook||!e.Workbook.Sheets)e.Props.SheetNames=e.SheetNames;else{for(var l=[],u=0;u0&&(s="docProps/custom.xml",Ne(i,s,C2(e.Custprops,t)),n.custprops.push(s),Qe(t.rels,4,s,Me.CUST_PROPS));var c=["SheetJ5"];for(t.tcid=0,o=1;o<=e.SheetNames.length;++o){var f={"!id":{}},h=e.Sheets[e.SheetNames[o-1]],m=(h||{})["!type"]||"sheet";switch(m){case"chart":default:s="xl/worksheets/sheet"+o+"."+r,Ne(i,s,mk(o-1,t,e,f)),n.sheets.push(s),Qe(t.wbrels,-1,"worksheets/sheet"+o+"."+r,Me.WS[0])}if(h){var g=h["!comments"],p=!1,y="";if(g&&g.length>0){var w=!1;g.forEach(function(v){v[1].forEach(function(x){x.T==!0&&(w=!0)})}),w&&(y="xl/threadedComments/threadedComment"+o+"."+r,Ne(i,y,eF(g,c,t)),n.threadedcomments.push(y),Qe(f,-1,"../threadedComments/threadedComment"+o+"."+r,Me.TCMNT)),y="xl/comments"+o+"."+r,Ne(i,y,ak(g,t)),n.comments.push(y),Qe(f,-1,"../comments"+o+"."+r,Me.CMNT),p=!0}h["!legacy"]&&p&&Ne(i,"xl/drawings/vmlDrawing"+o+".vml",rk(o,h["!comments"])),delete h["!comments"],delete h["!legacy"]}f["!id"].rId1&&Ne(i,mu(s),mo(f))}return t.Strings!=null&&t.Strings.length>0&&(s="xl/sharedStrings."+r,Ne(i,s,V2(t.Strings,t)),n.strs.push(s),Qe(t.wbrels,-1,"sharedStrings."+r,Me.SST)),s="xl/workbook."+r,Ne(i,s,wk(e,t)),n.workbooks.push(s),Qe(t.rels,1,s,Me.WB),s="xl/theme/theme1.xml",Ne(i,s,Mm(e.Themes,t)),n.themes.push(s),Qe(t.wbrels,-1,"theme/theme1.xml",Me.THEME),s="xl/styles."+r,Ne(i,s,Q2(e,t)),n.styles.push(s),Qe(t.wbrels,-1,"styles."+r,Me.STY),e.vbaraw&&a&&(s="xl/vbaProject.bin",Ne(i,s,e.vbaraw),n.vba.push(s),Qe(t.wbrels,-1,"vbaProject.bin",Me.VBA)),s="xl/metadata."+r,Ne(i,s,tk()),n.metadata.push(s),Qe(t.wbrels,-1,"metadata."+r,Me.XLMETA),c.length>1&&(s="xl/persons/person.xml",Ne(i,s,rF(c,t)),n.people.push(s),Qe(t.wbrels,-1,"persons/person.xml",Me.PEOPLE)),Ne(i,"[Content_Types].xml",x2(n,t)),Ne(i,"_rels/.rels",mo(t.rels)),Ne(i,"xl/_rels/workbook."+r+".rels",mo(t.wbrels)),delete t.revssf,delete t.ssf,i}function Km(e,t){var r="";switch((t||{}).type||"base64"){case"buffer":return[e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7]];case"base64":r=Jr(e.slice(0,12));break;case"binary":r=e;break;case"array":return[e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7]];default:throw new Error("Unrecognized type "+(t&&t.type||"undefined"))}return[r.charCodeAt(0),r.charCodeAt(1),r.charCodeAt(2),r.charCodeAt(3),r.charCodeAt(4),r.charCodeAt(5),r.charCodeAt(6),r.charCodeAt(7)]}function KD(e,t){return Ee.find(e,"EncryptedPackage")?VD(e,t):Ck(e,t)}function XD(e,t){var r,a=e,n=t||{};return n.type||(n.type=Ue&&Buffer.isBuffer(e)?"buffer":"base64"),r=Yw(a,n),jD(r,n)}function Rk(e,t){var r=0;e:for(;r=2&&n[3]===0||n[2]===0&&(n[3]===8||n[3]===9)))return Yi.to_workbook(a,r);break;case 3:case 131:case 139:case 140:return am.to_workbook(a,r);case 123:if(n[1]===92&&n[2]===114&&n[3]===116)return X2.to_workbook(a,r);break;case 10:case 13:case 32:return JD(a,r);case 137:if(n[1]===80&&n[2]===78&&n[3]===71)throw new Error("PNG Image File is not a spreadsheet");break}return rb.indexOf(n[0])>-1&&n[2]<=12&&n[3]<=31?am.to_workbook(a,r):Kp(e,a,r,i)}function Pk(e,t){switch(t.type){case"base64":case"binary":break;case"buffer":case"array":t.type="";break;case"file":return _u(t.file,Ee.write(e,{type:Ue?"buffer":""}));case"string":throw new Error("'string' output type invalid for '"+t.bookType+"' files");default:throw new Error("Unrecognized type "+t.type)}return Ee.write(e,t)}function ZD(e,t){var r=ft(t||{}),a=qD(e,r);return e8(a,r)}function e8(e,t){var r={},a=Ue?"nodebuffer":typeof Uint8Array<"u"?"array":"string";if(t.compression&&(r.compression="DEFLATE"),t.password)r.type=a;else switch(t.type){case"base64":r.type="base64";break;case"binary":r.type="string";break;case"string":throw new Error("'string' output type invalid for '"+t.bookType+"' files");case"buffer":case"file":r.type=a;break;default:throw new Error("Unrecognized type "+t.type)}var n=e.FullPaths?Ee.write(e,{fileType:"zip",type:{nodebuffer:"buffer",string:"binary"}[r.type]||r.type,compression:!!t.compression}):e.generate(r);if(typeof Deno<"u"&&typeof n=="string"){if(t.type=="binary"||t.type=="base64")return n;n=new Uint8Array(xd(n))}return t.password&&typeof encrypt_agile<"u"?Pk(encrypt_agile(n,t.password),t):t.type==="file"?_u(t.file,n):t.type=="string"?tt(n):n}function t8(e,t){var r=t||{},a=QO(e,r);return Pk(a,r)}function Xa(e,t,r){r||(r="");var a=r+e;switch(t.type){case"base64":return cu(Ja(a));case"binary":return Ja(a);case"string":return e;case"file":return _u(t.file,a,"utf8");case"buffer":return Ue?Fn(a,"utf8"):typeof TextEncoder<"u"?new TextEncoder().encode(a):Xa(a,{type:"binary"}).split("").map(function(n){return n.charCodeAt(0)})}throw new Error("Unrecognized type "+t.type)}function r8(e,t){switch(t.type){case"base64":return cu(e);case"binary":return e;case"string":return e;case"file":return _u(t.file,e,"binary");case"buffer":return Ue?Fn(e,"binary"):e.split("").map(function(r){return r.charCodeAt(0)})}throw new Error("Unrecognized type "+t.type)}function ad(e,t){switch(t.type){case"string":case"base64":case"binary":for(var r="",a=0;a0&&(n=0);var f=Pt(l.s.r),h=[],m=[],g=0,p=0,y=Array.isArray(e),w=l.s.r,v=0,x={};y&&!e[w]&&(e[w]=[]);var _=u.skipHidden&&e["!cols"]||[],T=u.skipHidden&&e["!rows"]||[];for(v=l.s.c;v<=l.e.c;++v)if(!(_[v]||{}).hidden)switch(h[v]=yt(v),r=y?e[w][v]:e[h[v]+f],a){case 1:i[v]=v-l.s.c;break;case 2:i[v]=h[v];break;case 3:i[v]=u.header[v-l.s.c];break;default:if(r==null&&(r={w:"__EMPTY",t:"s"}),o=s=bn(r,null,u),p=x[s]||0,!p)x[s]=1;else{do o=s+"_"+p++;while(x[o]);x[s]=p,x[o]=1}i[v]=o}for(w=l.s.r+n;w<=l.e.r;++w)if(!(T[w]||{}).hidden){var E=n8(e,l,w,h,a,i,y,u);(E.isempty===!1||(a===1?u.blankrows!==!1:u.blankrows))&&(m[g++]=E.row)}return m.length=g,m}var Pw=/"/g;function i8(e,t,r,a,n,i,s,o){for(var l=!0,u=[],c="",f=Pt(r),h=t.s.c;h<=t.e.c;++h)if(a[h]){var m=o.dense?(e[r]||[])[h]:e[a[h]+f];if(m==null)c="";else if(m.v!=null){l=!1,c=""+(o.rawNumbers&&m.t=="n"?m.v:bn(m,null,o));for(var g=0,p=0;g!==c.length;++g)if((p=c.charCodeAt(g))===n||p===i||p===34||o.forceQuotes){c='"'+c.replace(Pw,'""')+'"';break}c=="ID"&&(c='"ID"')}else m.f!=null&&!m.F?(l=!1,c="="+m.f,c.indexOf(",")>=0&&(c='"'+c.replace(Pw,'""')+'"')):c="";u.push(c)}return o.blankrows===!1&&l?null:u.join(s)}function Jm(e,t){var r=[],a=t??{};if(e==null||e["!ref"]==null)return"";var n=Ge(e["!ref"]),i=a.FS!==void 0?a.FS:",",s=i.charCodeAt(0),o=a.RS!==void 0?a.RS:` `,l=o.charCodeAt(0),u=new RegExp((i=="|"?"\\|":i)+"+$"),c="",f=[];a.dense=Array.isArray(e);for(var h=a.skipHidden&&e["!cols"]||[],m=a.skipHidden&&e["!rows"]||[],g=n.s.c;g<=n.e.c;++g)(h[g]||{}).hidden||(f[g]=yt(g));for(var p=0,y=n.s.r;y<=n.e.r;++y)(m[y]||{}).hidden||(c=i8(e,n,y,f,s,l,i,a),c!=null&&(a.strip&&(c=c.replace(u,"")),(c||a.blankrows!==!1)&&r.push((p++?o:"")+c)));return delete a.dense,r.join("")}function Dk(e,t){t||(t={}),t.FS=" ",t.RS=` `;var r=Jm(e,t);if(typeof Xe>"u"||t.type=="string")return r;var a=Xe.utils.encode(1200,r,"str");return"\xFF\xFE"+a}function s8(e){var t="",r,a="";if(e==null||e["!ref"]==null)return[];var n=Ge(e["!ref"]),i="",s=[],o,l=[],u=Array.isArray(e);for(o=n.s.c;o<=n.e.c;++o)s[o]=yt(o);for(var c=n.s.r;c<=n.e.r;++c)for(i=Pt(c),o=n.s.c;o<=n.e.c;++o)if(t=s[o]+i,r=u?(e[c]||[])[o]:e[t],a="",r!==void 0){if(r.F!=null){if(t=r.F,!r.f)continue;a=r.f,t.indexOf(":")==-1&&(t=t+":"+t)}if(r.f!=null)a=r.f;else{if(r.t=="z")continue;if(r.t=="n"&&r.v!=null)a=""+r.v;else if(r.t=="b")a=r.v?"TRUE":"FALSE";else if(r.w!==void 0)a="'"+r.w;else{if(r.v===void 0)continue;r.t=="s"?a="'"+r.v:a=""+r.v}}l[l.length]=t+"="+a}return l}function Bk(e,t,r){var a=r||{},n=+!a.skipHeader,i=e||{},s=0,o=0;if(i&&a.origin!=null)if(typeof a.origin=="number")s=a.origin;else{var l=typeof a.origin=="string"?wt(a.origin):a.origin;s=l.r,o=l.c}var u,c={s:{c:0,r:0},e:{c:o,r:s+t.length-1+n}};if(i["!ref"]){var f=Ge(i["!ref"]);c.e.c=Math.max(c.e.c,f.e.c),c.e.r=Math.max(c.e.r,f.e.r),s==-1&&(s=f.e.r+1,c.e.r=s+t.length-1+n)}else s==-1&&(s=0,c.e.r=t.length-1+n);var h=a.header||[],m=0;t.forEach(function(p,y){Et(p).forEach(function(w){(m=h.indexOf(w))==-1&&(h[m=h.length]=w);var v=p[w],x="z",_="",T=Fe({c:o+m,r:s+y+n});u=Su(i,T),v&&typeof v=="object"&&!(v instanceof Date)?i[T]=v:(typeof v=="number"?x="n":typeof v=="boolean"?x="b":typeof v=="string"?x="s":v instanceof Date?(x="d",a.cellDates||(x="n",v=Vt(v)),_=a.dateNF||Ae[14]):v===null&&a.nullError&&(x="e",v=0),u?(u.t=x,u.v=v,delete u.w,delete u.R,_&&(u.z=_)):i[T]=u={t:x,v},_&&(u.z=_))})}),c.e.c=Math.max(c.e.c,o+h.length-1);var g=Pt(s);if(n)for(m=0;m=0&&e.SheetNames.length>t)return t;throw new Error("Cannot find sheet # "+t)}else if(typeof t=="string"){var r=e.SheetNames.indexOf(t);if(r>-1)return r;throw new Error("Cannot find sheet name |"+t+"|")}else throw new Error("Cannot find sheet |"+t+"|")}function Ym(){return{SheetNames:[],Sheets:{}}}function Qm(e,t,r,a){var n=1;if(!r)for(;n<=65535&&e.SheetNames.indexOf(r="Sheet"+n)!=-1;++n,r=void 0);if(!r||e.SheetNames.length>=65535)throw new Error("Too many worksheets");if(a&&e.SheetNames.indexOf(r)>=0){var i=r.match(/(^.*?)(\d+)$/);n=i&&+i[2]||0;var s=i&&i[1]||r;for(++n;n<=65535&&e.SheetNames.indexOf(r=s+n)!=-1;++n);}if(yk(r),e.SheetNames.indexOf(r)>=0)throw new Error("Worksheet with name |"+r+"| already exists!");return e.SheetNames.push(r),e.Sheets[r]=t,r}function u8(e,t,r){e.Workbook||(e.Workbook={}),e.Workbook.Sheets||(e.Workbook.Sheets=[]);var a=l8(e,t);switch(e.Workbook.Sheets[a]||(e.Workbook.Sheets[a]={}),r){case 0:case 1:case 2:break;default:throw new Error("Bad sheet visibility setting "+r)}e.Workbook.Sheets[a].Hidden=r}function c8(e,t){return e.z=t,e}function Nk(e,t,r){return t?(e.l={Target:t},r&&(e.l.Tooltip=r)):delete e.l,e}function f8(e,t,r){return Nk(e,"#"+t,r)}function d8(e,t,r){e.c||(e.c=[]),e.c.push({t,a:r||"SheetJS"})}function h8(e,t,r,a){for(var n=typeof t!="string"?t:Ge(t),i=typeof t=="string"?t:Oe(t),s=n.s.r;s<=n.e.r;++s)for(var o=n.s.c;o<=n.e.c;++o){var l=Su(e,s,o);l.t="n",l.F=i,delete l.v,s==n.s.r&&o==n.s.c&&(l.f=r,a&&(l.D=!0))}return e}var Ba={encode_col:yt,encode_row:Pt,encode_cell:Fe,encode_range:Oe,decode_col:Em,decode_row:Im,split_cell:CL,decode_cell:wt,decode_range:Dr,format_cell:bn,sheet_add_aoa:c2,sheet_add_json:Bk,sheet_add_dom:Lk,aoa_to_sheet:Io,json_to_sheet:o8,table_to_sheet:Tk,table_to_book:wD,sheet_to_csv:Jm,sheet_to_txt:Dk,sheet_to_json:gd,sheet_to_html:Ek,sheet_to_formulae:s8,sheet_to_row_object_array:gd,sheet_get_cell:Su,book_new:Ym,book_append_sheet:Qm,book_set_sheet_visibility:u8,cell_set_number_format:c8,cell_set_hyperlink:Nk,cell_set_internal_link:f8,cell_add_comment:d8,sheet_set_array_formula:h8,consts:{SHEET_VISIBLE:0,SHEET_HIDDEN:1,SHEET_VERY_HIDDEN:2}};var pN=uu.version;function fs(e,t){var r={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.indexOf(a)<0&&(r[a]=e[a]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,a=Object.getOwnPropertySymbols(e);ne?(...t)=>e(...t):(...t)=>fetch(...t);var Lo=class extends Error{constructor(t,r="FunctionsError",a){super(t),this.name=r,this.context=a}toJSON(){return{name:this.name,message:this.message,context:this.context}}},bu=class extends Lo{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}},To=class extends Lo{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}},Ao=class extends Lo{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}},Fu;(function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"})(Fu||(Fu={}));var Ru=class{constructor(t,{headers:r={},customFetch:a,region:n=Fu.Any}={}){this.url=t,this.headers=r,this.region=n,this.fetch=Uk(a)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t){return Mk(this,arguments,void 0,function*(r,a={}){var n;let i,s;try{let{headers:o,method:l,body:u,signal:c,timeout:f}=a,h={},{region:m}=a;m||(m=this.region);let g=new URL(`${this.url}/${r}`);m&&m!=="any"&&(h["x-region"]=m,g.searchParams.set("forceFunctionRegion",m));let p;u&&(o&&!Object.prototype.hasOwnProperty.call(o,"Content-Type")||!o)?typeof Blob<"u"&&u instanceof Blob||u instanceof ArrayBuffer?(h["Content-Type"]="application/octet-stream",p=u):typeof u=="string"?(h["Content-Type"]="text/plain",p=u):typeof FormData<"u"&&u instanceof FormData?p=u:(h["Content-Type"]="application/json",p=JSON.stringify(u)):u&&typeof u!="string"&&!(typeof Blob<"u"&&u instanceof Blob)&&!(u instanceof ArrayBuffer)&&!(typeof FormData<"u"&&u instanceof FormData)?p=JSON.stringify(u):p=u;let y=c;f&&(s=new AbortController,i=setTimeout(()=>s.abort(),f),c?(y=s.signal,c.addEventListener("abort",()=>s.abort())):y=s.signal);let w=yield this.fetch(g.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},h),this.headers),o),body:p,signal:y}).catch(T=>{throw new bu(T)}),v=w.headers.get("x-relay-error");if(v&&v==="true")throw new To(w);if(!w.ok)throw new Ao(w);let x=((n=w.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),_;return x==="application/json"?_=yield w.json():x==="application/octet-stream"||x==="application/pdf"?_=yield w.blob():x==="text/event-stream"?_=w:x==="multipart/form-data"?_=yield w.formData():_=yield w.text(),{data:_,error:null,response:w}}catch(o){return{data:null,error:o,response:o instanceof Ao||o instanceof To?o.context:void 0}}finally{i&&clearTimeout(i)}})}};var Hk=e=>Math.min(1e3*2**e,3e4),m8=[520,503],Vk=["GET","HEAD","OPTIONS"],Zm=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function Wk(e,t){return new Promise(r=>{if(t?.aborted){r();return}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);function n(){clearTimeout(a),r()}t?.addEventListener("abort",n)})}function g8(e,t,r,a){return!(!a||r>=3||!Vk.includes(e)||!m8.includes(t))}var x8=class{constructor(e){var t,r,a,n,i;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=(t=e.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=e.signal,this.isMaybeSingle=(r=e.isMaybeSingle)!==null&&r!==void 0?r:!1,this.shouldStripNulls=(a=e.shouldStripNulls)!==null&&a!==void 0?a:!1,this.urlLengthLimit=(n=e.urlLengthLimit)!==null&&n!==void 0?n:8e3,this.retryEnabled=(i=e.retry)!==null&&i!==void 0?i:!0,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}retry(e){return this.retryEnabled=e,this}then(e,t){var r=this;if(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"),this.shouldStripNulls){let s=this.headers.get("Accept");s==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!s||s==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}let a=this.fetch,i=(async()=>{let s=0;for(;;){let u={};r.headers.forEach((f,h)=>{u[h]=f}),s>0&&(u["X-Retry-Count"]=String(s));let c;try{c=await a(r.url.toString(),{method:r.method,headers:u,body:JSON.stringify(r.body,(f,h)=>typeof h=="bigint"?h.toString():h),signal:r.signal})}catch(f){if(f?.name==="AbortError"||f?.code==="ABORT_ERR"||!Vk.includes(r.method))throw f;if(r.retryEnabled&&s<3){let h=Hk(s);s++,await Wk(h,r.signal);continue}throw f}if(g8(r.method,c.status,s,r.retryEnabled)){var o,l;let f=(o=(l=c.headers)===null||l===void 0?void 0:l.get("Retry-After"))!==null&&o!==void 0?o:null,h=f!==null?Math.max(0,parseInt(f,10)||0)*1e3:Hk(s);await c.text(),s++,await Wk(h,r.signal);continue}return await r.processResponse(c)}})();return this.shouldThrowOnError||(i=i.catch(s=>{var o;let l="",u="",c="",f=s?.cause;if(f){var h,m,g,p;let v=(h=f?.message)!==null&&h!==void 0?h:"",x=(m=f?.code)!==null&&m!==void 0?m:"";l=`${(g=s?.name)!==null&&g!==void 0?g:"FetchError"}: ${s?.message}`,l+=` Caused by: ${(p=f?.name)!==null&&p!==void 0?p:"Error"}: ${v}`,x&&(l+=` (${x})`),f?.stack&&(l+=` ${f.stack}`)}else{var y;l=(y=s?.stack)!==null&&y!==void 0?y:""}let w=this.url.toString().length;return s?.name==="AbortError"||s?.code==="ABORT_ERR"?(c="",u="Request was aborted (timeout or manual cancellation)",w>this.urlLengthLimit&&(u+=`. Note: Your request URL is ${w} 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.`)):(f?.name==="HeadersOverflowError"||f?.code==="UND_ERR_HEADERS_OVERFLOW")&&(c="",u="HTTP headers exceeded server limits (typically 16KB)",w>this.urlLengthLimit&&(u+=`. Your request URL is ${w} 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.`)),{success:!1,error:{message:`${(o=s?.name)!==null&&o!==void 0?o:"FetchError"}: ${s?.message}`,details:l,hint:u,code:c},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}async processResponse(e){var t=this;let r=null,a=null,n=null,i=e.status,s=e.statusText;if(e.ok){var o,l;if(t.method!=="HEAD"){var u;let h=await e.text();if(h!=="")if(t.headers.get("Accept")==="text/csv")a=h;else if(t.headers.get("Accept")&&(!((u=t.headers.get("Accept"))===null||u===void 0)&&u.includes("application/vnd.pgrst.plan+text")))a=h;else try{a=JSON.parse(h)}catch{if(r={message:h},a=null,t.shouldThrowOnError)throw new Zm({message:h,details:"",hint:"",code:""})}}let c=(o=t.headers.get("Prefer"))===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),f=(l=e.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");c&&f&&f.length>1&&(n=parseInt(f[1])),t.isMaybeSingle&&Array.isArray(a)&&(a.length>1?(r={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,n=null,i=406,s="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{let c=await e.text();try{r=JSON.parse(c),Array.isArray(r)&&e.status===404&&(a=[],r=null,i=200,s="OK")}catch{e.status===404&&c===""?(i=204,s="No Content"):r={message:c}}if(r&&t.shouldThrowOnError)throw new Zm(r)}return{success:r===null,error:r,data:a,count:n,status:i,statusText:s}}returns(){return this}overrideTypes(){return this}},v8=class extends x8{throwOnError(){return super.throwOnError()}select(e){let t=!1,r=(e??"*").split("").map(a=>/\s/.test(a)&&!t?"":(a==='"'&&(t=!t),a)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:a,referencedTable:n=a}={}){let i=n?`${n}.order`:"order",s=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${s?`${s},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let a=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(a,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:a=r}={}){let n=typeof a>"u"?"offset":`${a}.offset`,i=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(i,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:a=!1,wal:n=!1,format:i="text"}={}){var s;let o=[e?"analyze":null,t?"verbose":null,r?"settings":null,a?"buffers":null,n?"wal":null].filter(Boolean).join("|"),l=(s=this.headers.get("Accept"))!==null&&s!==void 0?s:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${o};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}},zk=new RegExp("[,()]"),bo=class extends v8{throwOnError(){return super.throwOnError()}eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map(a=>typeof a=="string"&&zk.test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}notIn(e,t){let r=Array.from(new Set(t)).map(a=>typeof a=="string"&&zk.test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(e,`not.in.(${r})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:a}={}){let n="";a==="plain"?n="pl":a==="phrase"?n="ph":a==="websearch"&&(n="w");let i=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${i}.${t}`),this}match(e){return Object.entries(e).filter(([t,r])=>r!==void 0).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let a=r?`${r}.or`:"or";return this.url.searchParams.append(a,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}},y8=class{constructor(e,{headers:t={},schema:r,fetch:a,urlLengthLimit:n=8e3,retry:i}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=a,this.urlLengthLimit=n,this.retry=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){let{head:r=!1,count:a}=t??{},n=r?"HEAD":"GET",i=!1,s=(e??"*").split("").map(u=>/\s/.test(u)&&!i?"":(u==='"'&&(i=!i),u)).join(""),{url:o,headers:l}=this.cloneRequestState();return o.searchParams.set("select",s),a&&l.append("Prefer",`count=${a}`),new bo({method:n,url:o,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(e,{count:t,defaultToNull:r=!0}={}){var a;let n="POST",{url:i,headers:s}=this.cloneRequestState();if(t&&s.append("Prefer",`count=${t}`),r||s.append("Prefer","missing=default"),Array.isArray(e)){let o=e.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(o.length>0){let l=[...new Set(o)].map(u=>`"${u}"`);i.searchParams.set("columns",l.join(","))}}return new bo({method:n,url:i,headers:s,schema:this.schema,body:e,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:a,defaultToNull:n=!0}={}){var i;let s="POST",{url:o,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),t!==void 0&&o.searchParams.set("on_conflict",t),a&&l.append("Prefer",`count=${a}`),n||l.append("Prefer","missing=default"),Array.isArray(e)){let u=e.reduce((c,f)=>c.concat(Object.keys(f)),[]);if(u.length>0){let c=[...new Set(u)].map(f=>`"${f}"`);o.searchParams.set("columns",c.join(","))}}return new bo({method:s,url:o,headers:l,schema:this.schema,body:e,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(e,{count:t}={}){var r;let a="PATCH",{url:n,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new bo({method:a,url:n,headers:i,schema:this.schema,body:e,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:e}={}){var t;let r="DELETE",{url:a,headers:n}=this.cloneRequestState();return e&&n.append("Prefer",`count=${e}`),new bo({method:r,url:a,headers:n,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function Pu(e){"@babel/helpers - typeof";return Pu=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Pu(e)}function w8(e,t){if(Pu(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var a=r.call(e,t||"default");if(Pu(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function k8(e){var t=w8(e,"string");return Pu(t)=="symbol"?t:t+""}function S8(e,t,r){return(t=k8(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function jk(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter(function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable})),r.push.apply(r,a)}return r}function Ld(e){for(var t=1;t0?this.fetch=(u,c)=>{let f=new AbortController,h=setTimeout(()=>f.abort(),i),m=c?.signal;if(m){if(m.aborted)return clearTimeout(h),l(u,c);let g=()=>{clearTimeout(h),f.abort()};return m.addEventListener("abort",g,{once:!0}),l(u,Ld(Ld({},c),{},{signal:f.signal})).finally(()=>{clearTimeout(h),m.removeEventListener("abort",g)})}return l(u,Ld(Ld({},c),{},{signal:f.signal})).finally(()=>clearTimeout(h))}:this.fetch=l,this.retry=o}from(t){if(!t||typeof t!="string"||t.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new y8(new URL(`${this.url}/${t}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(t){return new $k(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(t,r={},{head:a=!1,get:n=!1,count:i}={}){var s;let o,l=new URL(`${this.url}/rpc/${t}`),u,c=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(c)),f=a&&Object.values(r).some(c);f?(o="POST",u=r):a||n?(o=a?"HEAD":"GET",Object.entries(r).filter(([m,g])=>g!==void 0).map(([m,g])=>[m,Array.isArray(g)?`{${g.join(",")}}`:`${g}`]).forEach(([m,g])=>{l.searchParams.append(m,g)})):(o="POST",u=r);let h=new Headers(this.headers);return f?h.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&h.set("Prefer",`count=${i}`),new bo({method:o,url:l,headers:h,schema:this.schemaName,body:u,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};var eg=class{constructor(){}static detectEnvironment(){var t;if(typeof WebSocket<"u")return{type:"native",wsConstructor:WebSocket};let r=globalThis;if(typeof globalThis<"u"&&typeof r.WebSocket<"u")return{type:"native",wsConstructor:r.WebSocket};let a=typeof global<"u"?global:void 0;if(a&&typeof a.WebSocket<"u")return{type:"native",wsConstructor:a.WebSocket};if(typeof globalThis<"u"&&typeof r.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"&&r.EdgeRuntime||typeof navigator<"u"&&(!((t=navigator.userAgent)===null||t===void 0)&&t.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let n=globalThis.process;if(n){let i=n.versions;if(i&&i.node){let s=i.node,o=parseInt(s.replace(/^v/,"").split(".")[0]);return o>=22?typeof globalThis.WebSocket<"u"?{type:"native",wsConstructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${o} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${o} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option: import ws from "ws" 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 t=this.detectEnvironment();if(t.wsConstructor)return t.wsConstructor;let r=t.error||"WebSocket not supported in this environment.";throw t.workaround&&(r+=` Suggested solution: ${t.workaround}`),new Error(r)}static isWebSocketSupported(){try{let t=this.detectEnvironment();return t.type==="native"||t.type==="ws"}catch{return!1}}},tg=eg;var Gk="2.108.2";var Kk=`realtime-js/${Gk}`,Xk="1.0.0",rg="2.0.0",Jk=rg;var Yk=1e4;var Qk=100;var en={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Td={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"};var Ou={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};var Du=class{constructor(t){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=t??[]}encode(t,r){if(t.event===this.BROADCAST_EVENT&&!(t.payload instanceof ArrayBuffer)&&typeof t.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(t));let a=[t.join_ref,t.ref,t.topic,t.event,t.payload];return r(JSON.stringify(a))}_binaryEncodeUserBroadcastPush(t){var r;return this._isArrayBuffer((r=t.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(t):this._encodeJsonUserBroadcastPush(t)}_encodeBinaryUserBroadcastPush(t){var r,a;let n=(a=(r=t.payload)===null||r===void 0?void 0:r.payload)!==null&&a!==void 0?a:new ArrayBuffer(0);return this._encodeUserBroadcastPush(t,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(t){var r,a;let n=(a=(r=t.payload)===null||r===void 0?void 0:r.payload)!==null&&a!==void 0?a:{},s=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(t,this.JSON_ENCODING,s)}_encodeUserBroadcastPush(t,r,a){var n,i;let s=t.topic,o=(n=t.ref)!==null&&n!==void 0?n:"",l=(i=t.join_ref)!==null&&i!==void 0?i:"",u=t.payload.event,c=this.allowedMetadataKeys?this._pick(t.payload,this.allowedMetadataKeys):{},f=Object.keys(c).length===0?"":JSON.stringify(c);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`ref length ${o.length} exceeds maximum of 255`);if(s.length>255)throw new Error(`topic length ${s.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`userEvent length ${u.length} exceeds maximum of 255`);if(f.length>255)throw new Error(`metadata length ${f.length} exceeds maximum of 255`);let h=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+o.length+s.length+u.length+f.length,m=new ArrayBuffer(this.HEADER_LENGTH+h),g=new DataView(m),p=0;g.setUint8(p++,this.KINDS.userBroadcastPush),g.setUint8(p++,l.length),g.setUint8(p++,o.length),g.setUint8(p++,s.length),g.setUint8(p++,u.length),g.setUint8(p++,f.length),g.setUint8(p++,r),Array.from(l,w=>g.setUint8(p++,w.charCodeAt(0))),Array.from(o,w=>g.setUint8(p++,w.charCodeAt(0))),Array.from(s,w=>g.setUint8(p++,w.charCodeAt(0))),Array.from(u,w=>g.setUint8(p++,w.charCodeAt(0))),Array.from(f,w=>g.setUint8(p++,w.charCodeAt(0)));var y=new Uint8Array(m.byteLength+a.byteLength);return y.set(new Uint8Array(m),0),y.set(new Uint8Array(a),m.byteLength),y.buffer}decode(t,r){if(this._isArrayBuffer(t)){let a=this._binaryDecode(t);return r(a)}if(typeof t=="string"){let a=JSON.parse(t),[n,i,s,o,l]=a;return r({join_ref:n,ref:i,topic:s,event:o,payload:l})}return r({})}_binaryDecode(t){let r=new DataView(t),a=r.getUint8(0),n=new TextDecoder;switch(a){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(t,r,n)}}_decodeUserBroadcast(t,r,a){let n=r.getUint8(1),i=r.getUint8(2),s=r.getUint8(3),o=r.getUint8(4),l=this.HEADER_LENGTH+4,u=a.decode(t.slice(l,l+n));l=l+n;let c=a.decode(t.slice(l,l+i));l=l+i;let f=a.decode(t.slice(l,l+s));l=l+s;let h=t.slice(l,t.byteLength),m=o===this.JSON_ENCODING?JSON.parse(a.decode(h)):h,g={type:this.BROADCAST_EVENT,event:c,payload:m};return s>0&&(g.meta=JSON.parse(f)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:g}}_isArrayBuffer(t){var r;return t instanceof ArrayBuffer||((r=t?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(t,r){return!t||typeof t!="object"?{}:Object.fromEntries(Object.entries(t).filter(([a])=>r.includes(a)))}};var it;(function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"})(it||(it={}));var ng=(e,t,r={})=>{var a;let n=(a=r.skipTypes)!==null&&a!==void 0?a:[];return t?Object.keys(t).reduce((i,s)=>(i[s]=_8(s,e,t,n),i),{}):{}},_8=(e,t,r,a)=>{let n=t.find(o=>o.name===e),i=n?.type,s=r[e];return i&&!a.includes(i)?Zk(i,s):ag(s)},Zk=(e,t)=>{if(e.charAt(0)==="_"){let r=e.slice(1,e.length);return L8(t,r)}switch(e){case it.bool:return C8(t);case it.float4:case it.float8:case it.int2:case it.int4:case it.int8:case it.numeric:case it.oid:return I8(t);case it.json:case it.jsonb:return E8(t);case it.timestamp:return T8(t);case it.abstime:case it.date:case it.daterange:case it.int4range:case it.int8range:case it.money:case it.reltime:case it.text:case it.time:case it.timestamptz:case it.timetz:case it.tsrange:case it.tstzrange:return ag(t);default:return ag(t)}},ag=e=>e,C8=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},I8=e=>{if(typeof e=="string"){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},E8=e=>{if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e},L8=(e,t)=>{if(typeof e!="string")return e;let r=e.length-1,a=e[r];if(e[0]==="{"&&a==="}"){let i,s=e.slice(1,r);try{i=JSON.parse("["+s+"]")}catch{i=s?s.split(","):[]}return i.map(o=>Zk(t,o))}return e},T8=e=>typeof e=="string"?e.replace(" ","T"):e,Ad=e=>{let t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),t.pathname===""||t.pathname==="/"?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};var Nu=e=>typeof e=="function"?e:function(){return e},b8=typeof self<"u"?self:null,Ro=typeof window<"u"?window:null,tn=b8||Ro||globalThis,F8="2.0.0",R8=1e4,P8=1e3,rn={connecting:0,open:1,closing:2,closed:3},Br={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},On={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},ig={longpoll:"longpoll",websocket:"websocket"},O8={complete:4},sg="base64url.bearer.phx.",bd=class{constructor(e,t,r,a){this.channel=e,this.event=t,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=a,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(e){this.timeout=e,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(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:e,response:t,_ref:r}){this.recHooks.filter(a=>a.status===e).forEach(a=>a.callback(t))}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,e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},eS=class{constructor(e,t){this.callback=e,this.timerCalc=t,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))}},D8=class{constructor(e,t,r){this.state=Br.closed,this.topic=e,this.params=Nu(t||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new bd(this,On.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new eS(()=>{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=Br.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(a=>a.send()),this.pushBuffer=[]}),this.joinPush.receive("error",a=>{this.state=Br.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,a),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=Br.closed,this.socket.remove(this)}),this.onError(a=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,a),this.isJoining()&&this.joinPush.reset(),this.state=Br.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 bd(this,On.leave,Nu({}),this.timeout).send(),this.state=Br.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(On.reply,(a,n)=>{this.trigger(this.replyEventName(n),a)})}join(e=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=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Br.closed,this.bindings=[]}onClose(e){this.on(On.close,e)}onError(e){return this.on(On.error,t=>e(t))}on(e,t){let r=this.bindingRef++;return this.bindings.push({event:e,ref:r,callback:t}),r}off(e,t){this.bindings=this.bindings.filter(r=>!(r.event===e&&(typeof t>"u"||t===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,r=this.timeout){if(t=t||{},!this.joinedOnce)throw new Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let a=new bd(this,e,function(){return t},r);return this.canPush()?a.send():(a.startTimeout(),this.pushBuffer.push(a)),a}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Br.leaving;let t=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(On.close,"leave")},r=new bd(this,On.leave,Nu({}),e);return r.receive("ok",()=>t()).receive("timeout",()=>t()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(e,t,r){return t}filterBindings(e,t,r){return!0}isMember(e,t,r,a){return this.topic!==e?!1:a&&a!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:e,event:t,payload:r,joinRef:a}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Br.joining,this.joinPush.resend(e))}trigger(e,t,r,a){let n=this.onMessage(e,t,r,a);if(t&&!n)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let i=this.bindings.filter(s=>s.event===e&&this.filterBindings(s,t,r));for(let s=0;sl.abort(),n);o.signal=l.signal}return tn.fetch(t,o).then(u=>u.text()).then(u=>this.parseJSON(u)).then(u=>s&&s(u)).catch(u=>{u.name==="AbortError"&&i?i():s&&s(null)}),l}static xdomainRequest(e,t,r,a,n,i,s){return e.timeout=n,e.open(t,r),e.onload=()=>{let o=this.parseJSON(e.responseText);s&&s(o)},i&&(e.ontimeout=i),e.onprogress=()=>{},e.send(a),e}static xhrRequest(e,t,r,a,n,i,s,o){e.open(t,r,!0),e.timeout=i;for(let[l,u]of Object.entries(a))e.setRequestHeader(l,u);return e.onerror=()=>o&&o(null),e.onreadystatechange=()=>{if(e.readyState===O8.complete&&o){let l=this.parseJSON(e.responseText);o(l)}},s&&(e.ontimeout=s),e.send(n),e}static parseJSON(e){if(!e||e==="")return null;try{return JSON.parse(e)}catch{return console&&console.log("failed to parse JSON response",e),null}}static serialize(e,t){let r=[];for(var a in e){if(!Object.prototype.hasOwnProperty.call(e,a))continue;let n=t?`${t}[${a}]`:a,i=e[a];typeof i=="object"?r.push(this.serialize(i,n)):r.push(encodeURIComponent(n)+"="+encodeURIComponent(i))}return r.join("&")}static appendParams(e,t){if(Object.keys(t).length===0)return e;let r=e.match(/\?/)?"&":"?";return`${e}${r}${this.serialize(t)}`}},B8=e=>{let t="",r=new Uint8Array(e),a=r.byteLength;for(let n=0;nthis.poll(),0)}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+ig.websocket),"$1/"+ig.longpoll)}endpointURL(){return Rd.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,r){this.close(e,t,r),this.readyState=rn.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===rn.open||this.readyState===rn.connecting}poll(){let e={Accept:"application/json"};this.authToken&&(e["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",e,null,()=>this.ontimeout(),t=>{if(t){var{status:r,token:a,messages:n}=t;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=a}else r=0;switch(r){case 200:n.forEach(i=>{setTimeout(()=>this.onmessage({data:i}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=rn.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(e){typeof e!="string"&&(e=B8(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(e){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},e.join(` `),()=>this.onerror("timeout"),t=>{this.awaitingBatchAck=!1,!t||t.status!==200?(this.onerror(t&&t.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(e,t,r){for(let n of this.reqs)n.abort();this.readyState=rn.closed;let a=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",a)):this.onclose(a)}ajax(e,t,r,a,n){let i,s=()=>{this.reqs.delete(i),a()};i=Rd.request(e,this.endpointURL(),t,r,this.timeout,s,o=>{this.reqs.delete(i),this.isActive()&&n(o)}),this.reqs.add(i)}},tS=class Bu{constructor(t,r={}){let a=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=t,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(a.state,n=>{let{onJoin:i,onLeave:s,onSync:o}=this.caller;this.joinRef=this.channel.joinRef(),this.state=Bu.syncState(this.state,n,i,s),this.pendingDiffs.forEach(l=>{this.state=Bu.syncDiff(this.state,l,i,s)}),this.pendingDiffs=[],o()}),this.channel.on(a.diff,n=>{let{onJoin:i,onLeave:s,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=Bu.syncDiff(this.state,n,i,s),o())})}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}list(t){return Bu.list(this.state,t)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(t,r,a,n){let i=this.clone(t),s={},o={};return this.map(i,(l,u)=>{r[l]||(o[l]=u)}),this.map(r,(l,u)=>{let c=i[l];if(c){let f=u.metas.map(p=>p.phx_ref),h=c.metas.map(p=>p.phx_ref),m=u.metas.filter(p=>h.indexOf(p.phx_ref)<0),g=c.metas.filter(p=>f.indexOf(p.phx_ref)<0);m.length>0&&(s[l]=u,s[l].metas=m),g.length>0&&(o[l]=this.clone(c),o[l].metas=g)}else s[l]=u}),this.syncDiff(i,{joins:s,leaves:o},a,n)}static syncDiff(t,r,a,n){let{joins:i,leaves:s}=this.clone(r);return a||(a=function(){}),n||(n=function(){}),this.map(i,(o,l)=>{let u=t[o];if(t[o]=this.clone(l),u){let c=t[o].metas.map(h=>h.phx_ref),f=u.metas.filter(h=>c.indexOf(h.phx_ref)<0);t[o].metas.unshift(...f)}a(o,u,l)}),this.map(s,(o,l)=>{let u=t[o];if(!u)return;let c=l.metas.map(f=>f.phx_ref);u.metas=u.metas.filter(f=>c.indexOf(f.phx_ref)<0),n(o,u,l),u.metas.length===0&&delete t[o]}),t}static list(t,r){return r||(r=function(a,n){return n}),this.map(t,(a,n)=>r(a,n))}static map(t,r){return Object.getOwnPropertyNames(t).map(a=>r(a,t[a]))}static clone(t){return JSON.parse(JSON.stringify(t))}},Fd={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){if(e.payload.constructor===ArrayBuffer)return t(this.binaryEncode(e));{let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(r))}},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));{let[r,a,n,i,s]=JSON.parse(e);return t({join_ref:r,ref:a,topic:n,event:i,payload:s})}},binaryEncode(e){let{join_ref:t,ref:r,event:a,topic:n,payload:i}=e,s=this.META_LENGTH+t.length+r.length+n.length+a.length,o=new ArrayBuffer(this.HEADER_LENGTH+s),l=new DataView(o),u=0;l.setUint8(u++,this.KINDS.push),l.setUint8(u++,t.length),l.setUint8(u++,r.length),l.setUint8(u++,n.length),l.setUint8(u++,a.length),Array.from(t,f=>l.setUint8(u++,f.charCodeAt(0))),Array.from(r,f=>l.setUint8(u++,f.charCodeAt(0))),Array.from(n,f=>l.setUint8(u++,f.charCodeAt(0))),Array.from(a,f=>l.setUint8(u++,f.charCodeAt(0)));var c=new Uint8Array(o.byteLength+i.byteLength);return c.set(new Uint8Array(o),0),c.set(new Uint8Array(i),o.byteLength),c.buffer},binaryDecode(e){let t=new DataView(e),r=t.getUint8(0),a=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(e,t,a);case this.KINDS.reply:return this.decodeReply(e,t,a);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,a)}},decodePush(e,t,r){let a=t.getUint8(1),n=t.getUint8(2),i=t.getUint8(3),s=this.HEADER_LENGTH+this.META_LENGTH-1,o=r.decode(e.slice(s,s+a));s=s+a;let l=r.decode(e.slice(s,s+n));s=s+n;let u=r.decode(e.slice(s,s+i));s=s+i;let c=e.slice(s,e.byteLength);return{join_ref:o,ref:null,topic:l,event:u,payload:c}},decodeReply(e,t,r){let a=t.getUint8(1),n=t.getUint8(2),i=t.getUint8(3),s=t.getUint8(4),o=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(e.slice(o,o+a));o=o+a;let u=r.decode(e.slice(o,o+n));o=o+n;let c=r.decode(e.slice(o,o+i));o=o+i;let f=r.decode(e.slice(o,o+s));o=o+s;let h=e.slice(o,e.byteLength),m={status:f,response:h};return{join_ref:l,ref:u,topic:c,event:On.reply,payload:m}},decodeBroadcast(e,t,r){let a=t.getUint8(1),n=t.getUint8(2),i=this.HEADER_LENGTH+2,s=r.decode(e.slice(i,i+a));i=i+a;let o=r.decode(e.slice(i,i+n));i=i+n;let l=e.slice(i,e.byteLength);return{join_ref:null,ref:null,topic:s,event:o,payload:l}}},rS=class{constructor(e,t={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=t.timeout||R8,this.transport=t.transport||tn.WebSocket||Fo,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null;let r=null;try{r=tn&&tn.sessionStorage}catch{}this.sessionStore=t.sessionStorage||r,this.establishedConnections=0,this.defaultEncoder=Fd.encode.bind(Fd),this.defaultDecoder=Fd.decode.bind(Fd),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=t.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==Fo?(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let a=null;Ro&&Ro.addEventListener&&(Ro.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),a=this.connectClock)}),Ro.addEventListener("pageshow",n=>{a===this.connectClock&&(a=null,this.connect())}),Ro.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=t.autoSendHeartbeat??!0,this.heartbeatCallback=t.heartbeatCallback??(()=>{}),this.rejoinAfterMs=n=>t.rejoinAfterMs?t.rejoinAfterMs(n):[1e3,2e3,5e3][n-1]||1e4,this.reconnectAfterMs=n=>t.reconnectAfterMs?t.reconnectAfterMs(n):[10,50,100,150,200,250,500,1e3,2e3][n-1]||5e3,this.logger=t.logger||null,!this.logger&&t.debug&&(this.logger=(n,i,s)=>{console.log(`${n}: ${i}`,s)}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=Nu(t.params||{}),this.endPoint=`${e}/${ig.websocket}`,this.vsn=t.vsn||F8,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new eS(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{t.beforeReconnect&&await t.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=t.authToken}getLongPollTransport(){return Fo}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=e}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let e=Rd.appendParams(Rd.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return e.charAt(0)!=="/"?e:e.charAt(1)==="/"?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`}disconnect(e,t,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,e&&e()},t,r)}connect(e){e&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Nu(e)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Fo?this.connectWithFallback(Fo,this.longPollFallbackMs):this.transportConnect())}log(e,t,r){this.logger&&this.logger(e,t,r)}hasLogger(){return this.logger!==null}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}onHeartbeat(e){this.heartbeatCallback=e}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:t});let a=this.onMessage(n=>{n.ref===t&&(this.off([a]),e(Date.now()-r))});return!0}transportName(e){switch(e){case Fo:return"LongPoll";default:return e.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let e;this.authToken&&(e=["phoenix",`${sg}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),e),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=t=>this.onConnError(t),this.conn.onmessage=t=>this.onConnMessage(t),this.conn.onclose=t=>this.onConnClose(t)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){clearTimeout(this.fallbackTimer);let r=!1,a=!0,n,i,s=this.transportName(e),o=l=>{this.log("transport",`falling back to ${s}...`,l),this.off([n,i]),a=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`phx:fallback:${s}`))return o("memorized");this.fallbackTimer=setTimeout(o,t),i=this.onError(l=>{this.log("transport","error",l),a&&!r&&(clearTimeout(this.fallbackTimer),o(l))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!a){let l=this.transportName(e);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(o,t),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(e){this.log("error","error in heartbeat callback",e)}this.triggerChanError(new Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),P8,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(e,t,r){if(!this.conn)return e&&e();let a=this.conn;this.waitForBufferDone(a,()=>{t?a.close(t,r||""):a.close(),this.waitForSocketClosed(a,()=>{this.conn===a&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e()})})}waitForBufferDone(e,t,r=1){if(r===5||!e.bufferedAmount){t();return}setTimeout(()=>{this.waitForBufferDone(e,t,r+1)},150*r)}waitForSocketClosed(e,t,r=1){if(r===5||e.readyState===rn.closed){t();return}setTimeout(()=>{this.waitForSocketClosed(e,t,r+1)},150*r)}onConnClose(e){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",e),this.triggerChanError(e),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",e)}onConnError(e){this.hasLogger()&&this.log("transport","error",e);let t=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",e,t,r),(t===this.transport||r>0)&&this.triggerChanError(e)}triggerChanError(e){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(On.error,e)})}connectionState(){switch(this.conn&&this.conn.readyState){case rn.connecting:return"connecting";case rn.open:return"open";case rn.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter(t=>t!==e)}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(([r])=>e.indexOf(r)===-1)}channel(e,t={}){let r=new D8(e,t,this);return this.channels.push(r),r}push(e){if(this.hasLogger()){let{topic:t,event:r,payload:a,ref:n,join_ref:i}=e;this.log("push",`${t} ${r} (${i}, ${n})`,a)}this.isConnected()?this.encode(e,t=>this.conn.send(t)):this.sendBuffer.push(()=>this.encode(e,t=>this.conn.send(t)))}makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}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(e){this.log("error","error in heartbeat callback",e)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,t=>{let{topic:r,event:a,payload:n,ref:i,join_ref:s}=t;if(i&&i===this.pendingHeartbeatRef){let o=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(n.status==="ok"?"ok":"error",o)}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} ${a} ${i&&"("+i+")"||""}`.trim(),n);for(let o=0;o{try{a(...t)}catch(n){this.log("error",`error in ${e} callback`,n)}})}catch(r){this.log("error",`error triggering ${e} callbacks`,r)}}leaveOpenTopic(e){let t=this.channels.find(r=>r.topic===e&&(r.isJoined()||r.isJoining()));t&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${e}"`),t.leave())}};var Mu=class e{constructor(t,r){let a=M8(r);this.presence=new tS(t.getChannel(),a),this.presence.onJoin((n,i,s)=>{let o=e.onJoinPayload(n,i,s);t.getChannel().trigger("presence",o)}),this.presence.onLeave((n,i,s)=>{let o=e.onLeavePayload(n,i,s);t.getChannel().trigger("presence",o)}),this.presence.onSync(()=>{t.getChannel().trigger("presence",{event:"sync"})})}get state(){return e.transformState(this.presence.state)}static transformState(t){return t=N8(t),Object.getOwnPropertyNames(t).reduce((r,a)=>{let n=t[a];return r[a]=Pd(n),r},{})}static onJoinPayload(t,r,a){let n=aS(r),i=Pd(a);return{event:"join",key:t,currentPresences:n,newPresences:i}}static onLeavePayload(t,r,a){let n=aS(r),i=Pd(a);return{event:"leave",key:t,currentPresences:n,leftPresences:i}}};function Pd(e){return e.metas.map(t=>(t.presence_ref=t.phx_ref,delete t.phx_ref,delete t.phx_ref_prev,t))}function N8(e){return JSON.parse(JSON.stringify(e))}function M8(e){return e?.events&&{events:e.events}}function aS(e){return e?.metas?Pd(e):[]}var og;(function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"})(og||(og={}));var Po=class{get state(){return this.presenceAdapter.state}constructor(t,r){this.channel=t,this.presenceAdapter=new Mu(this.channel.channelAdapter,r)}};function nS(e){if(e instanceof Error)return e;if(typeof e=="string")return new Error(e);if(e&&typeof e=="object"){let t=e;if(typeof t.code=="number"){let r=typeof t.reason=="string"&&t.reason?` (${t.reason})`:"";return new Error(`socket closed: ${t.code}${r}`,{cause:e})}return new Error("channel error: transport failure",{cause:e})}return new Error("channel error: connection lost")}var Uu=class{constructor(t,r,a){let n=U8(a);this.channel=t.getSocket().channel(r,n),this.socket=t}get state(){return this.channel.state}set state(t){this.channel.state=t}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(t,r){return this.channel.on(t,r)}off(t,r){this.channel.off(t,r)}subscribe(t){return this.channel.join(t)}unsubscribe(t){return this.channel.leave(t)}teardown(){this.channel.teardown()}onClose(t){this.channel.onClose(t)}onError(t){return this.channel.onError(t)}push(t,r,a){let n;try{n=this.channel.push(t,r,a)}catch{throw new Error(`tried to push '${t}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>Qk){let i=this.channel.pushBuffer.shift();i.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${i.event}`,i.payload())}return n}updateJoinPayload(t){let r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),t)}canPush(){return this.socket.isConnected()&&this.state===en.joined}isJoined(){return this.state===en.joined}isJoining(){return this.state===en.joining}isClosed(){return this.state===en.closed}isLeaving(){return this.state===en.leaving}updateFilterBindings(t){this.channel.filterBindings=t}updatePayloadTransform(t){this.channel.onMessage=t}getChannel(){return this.channel}};function U8(e){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},e.config)}}var lg;(function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"})(lg||(lg={}));var ds;(function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"})(ds||(ds={}));var an;(function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"})(an||(an={}));var Oo=class e{get state(){return this.channelAdapter.state}set state(t){this.channelAdapter.state=t}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(t,r={config:{}},a){var n,i;if(this.topic=t,this.params=r,this.socket=a,this.bindings={},this.subTopic=t.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new Uu(this.socket.socketAdapter,t,this.params),this.presence=new Po(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=Ad(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((i=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||i===void 0)&&i.replay))throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(t,r=this.timeout){var a,n,i;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:s,presence:o,private:l}}=this.params,u=(n=(a=this.bindings.postgres_changes)===null||a===void 0?void 0:a.map(m=>m.filter))!==null&&n!==void 0?n:[],c=!!this.bindings[ds.PRESENCE]&&this.bindings[ds.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,f={},h={broadcast:s,presence:Object.assign(Object.assign({},o),{enabled:c}),postgres_changes:u,private:l};this.socket.accessTokenValue&&(f.access_token=this.socket.accessTokenValue),this._onError(m=>{t?.(an.CHANNEL_ERROR,nS(m))}),this._onClose(()=>t?.(an.CLOSED)),this.updateJoinPayload(Object.assign({config:h},f)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:m})=>{if(this.socket._isManualToken()||this.socket.setAuth(),m===void 0){t?.(an.SUBSCRIBED);return}this._updatePostgresBindings(m,t)}).receive("error",m=>{this.state=en.errored;let g=Object.values(m).join(", ")||"error";t?.(an.CHANNEL_ERROR,new Error(g,{cause:m}))}).receive("timeout",()=>{t?.(an.TIMED_OUT)})}return this}_updatePostgresBindings(t,r){var a;let n=this.bindings.postgres_changes,i=(a=n?.length)!==null&&a!==void 0?a:0,s=[];for(let o=0;o{var s,o,l;let u=this.channelAdapter.push(t.type,t,r.timeout||this.timeout);t.type==="broadcast"&&!(!((l=(o=(s=this.params)===null||s===void 0?void 0:s.config)===null||o===void 0?void 0:o.broadcast)===null||l===void 0)&&l.ack)&&i("ok"),u.receive("ok",()=>i("ok")),u.receive("error",()=>i("error")),u.receive("timeout",()=>i("timed out"))})}updateJoinPayload(t){this.channelAdapter.updateJoinPayload(t)}async unsubscribe(t=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(t).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(t,r,a){let n=new AbortController,i=setTimeout(()=>n.abort(),a),s=await this.socket.fetch(t,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(i),s}_on(t,r,a){let n=t.toLocaleLowerCase(),i=this.channelAdapter.on(t,a),s={type:n,filter:r,callback:a,ref:i};return this.bindings[n]?this.bindings[n].push(s):this.bindings[n]=[s],this._updateFilterMessage(),this}_onClose(t){this.channelAdapter.onClose(t)}_onError(t){this.channelAdapter.onError(t)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((t,r,a)=>{var n,i,s,o,l,u,c;let f=t.event.toLocaleLowerCase();if(this._notThisChannelEvent(f,a))return!1;let h=(n=this.bindings[f])===null||n===void 0?void 0:n.find(m=>m.ref===t.ref);if(!h)return!0;if(["broadcast","presence","postgres_changes"].includes(f))if("id"in h){let m=h.id,g=(i=h.filter)===null||i===void 0?void 0:i.event;return m&&((s=r.ids)===null||s===void 0?void 0:s.includes(m))&&(g==="*"||g?.toLocaleLowerCase()===((o=r.data)===null||o===void 0?void 0:o.type.toLocaleLowerCase()))}else{let m=(u=(l=h?.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 h.type.toLocaleLowerCase()===f})}_notThisChannelEvent(t,r){let{close:a,error:n,leave:i,join:s}=Td;return r&&[a,n,i,s].includes(t)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((t,r,a)=>{if(typeof r=="object"&&"ids"in r){let n=r.data,{schema:i,table:s,commit_timestamp:o,type:l,errors:u}=n;return Object.assign(Object.assign({},{schema:i,table:s,commit_timestamp:o,eventType:l,new:{},old:{},errors:u}),this._getPayloadRecords(n))}return r})}copyBindings(t){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(let r in t.bindings)for(let a of t.bindings[r])this._on(a.type,a.filter,a.callback)}static isFilterValueEqual(t,r){return(t??void 0)===(r??void 0)}_getPayloadRecords(t){let r={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(r.new=ng(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(r.old=ng(t.columns,t.old_record)),r}};var Hu=class{constructor(t,r){this.socket=new rS(t,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(t){this.socket.heartbeatCallback=t}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(t,r,a,n=1e4){return new Promise(i=>{setTimeout(()=>i("timeout"),n),this.socket.disconnect(()=>{t(),i("ok")},r,a)})}push(t){this.socket.push(t)}log(t,r,a){this.socket.log(t,r,a)}makeRef(){return this.socket.makeRef()}onOpen(t){this.socket.onOpen(t)}onClose(t){this.socket.onClose(t)}onError(t){this.socket.onError(t)}onMessage(t){this.socket.onMessage(t)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==Ou.connecting}isDisconnecting(){return this.socket.connectionState()==Ou.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}};var iS={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},H8=[1e3,2e3,5e3,1e4],W8=1e4;function z8(){let e=new Map;return{get length(){return e.size},clear(){e.clear()},getItem(t){return e.has(t)?e.get(t):null},key(t){var r;return(r=Array.from(e.keys())[t])!==null&&r!==void 0?r:null},removeItem(t){e.delete(t)},setItem(t,r){e.set(t,String(r))}}}function j8(){try{if(typeof globalThis<"u"&&globalThis.sessionStorage)return globalThis.sessionStorage}catch{}return z8()}var V8=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`,Do=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(t,r){var a;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 Du,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=i=>i?(...s)=>i(...s):(...s)=>fetch(...s),!(!((a=r?.params)===null||a===void 0)&&a.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 Hu(t,n),this.httpEndpoint=Ad(t),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(t){let r=t.message;throw r.includes("Node.js")?new Error(`${r} To use Realtime in Node.js, you need to provide a WebSocket implementation: Option 1: Use Node.js 22+ which has native WebSocket support Option 2: Install and provide the "ws" package: npm install ws import ws from "ws" const client = new RealtimeClient(url, { ...options, transport: ws })`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(t,r){return this._cancelPendingDisconnect(),this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},t,r)}getChannels(){return this.channels}async removeChannel(t){let r=await t.unsubscribe();return r==="ok"&&t.teardown(),r}async removeAllChannels(){let t=this.channels.map(async a=>{let n=await a.unsubscribe();return a.teardown(),n}),r=await Promise.all(t);return await this.disconnect(),r}log(t,r,a){this.socketAdapter.log(t,r,a)}connectionState(){return this.socketAdapter.connectionState()||Ou.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(t,r={config:{}}){let a=`realtime:${t}`,n=this.getChannels().find(i=>i.topic===a);if(n)return n;{let i=new Oo(`realtime:${t}`,r,this);return this._cancelPendingDisconnect(),this.channels.push(i),i}}push(t){this.socketAdapter.push(t)}async setAuth(t=null){this._authPromise=this._performAuth(t);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(t){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(t)}_makeRef(){return this.socketAdapter.makeRef()}_remove(t){this.channels=this.channels.filter(r=>r.topic!==t.topic),this.channels.length===0&&(this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),this._disconnectOnEmptyChannelsAfterMs===0){this.log("transport","disconnecting immediately - no channels"),this.disconnect();return}this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,this.channels.length===0&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){this._pendingDisconnectTimer!==null&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(t=null){let r,a=!1;if(t)r=t,a=!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;a?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{let i={access_token:r,version:Kk};r&&n.updateJoinPayload(i),n.joinedOnce&&n.channelAdapter.isJoined()&&n.channelAdapter.push(Td.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(t="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${t}`,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(t=>{t.ref&&t.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(t){return(r,a)=>{r=="sent"&&this._setAuthSafely(),t&&t(r,a)}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let t=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(t),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(t){let r;if(t)r=t;else{let a=new Blob([V8],{type:"application/javascript"});r=URL.createObjectURL(a)}return r}_initializeOptions(t){var r,a,n,i,s,o,l,u,c,f,h,m;this.worker=(r=t?.worker)!==null&&r!==void 0?r:!1,this.accessToken=(a=t?.accessToken)!==null&&a!==void 0?a:null;let g={};g.timeout=(n=t?.timeout)!==null&&n!==void 0?n:Yk,g.heartbeatIntervalMs=(i=t?.heartbeatIntervalMs)!==null&&i!==void 0?i:iS.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=(s=t?.disconnectOnEmptyChannelsAfterMs)!==null&&s!==void 0?s:2*((o=t?.heartbeatIntervalMs)!==null&&o!==void 0?o:iS.HEARTBEAT_INTERVAL),g.transport=(l=t?.transport)!==null&&l!==void 0?l:tg.getWebSocketConstructor(),g.params=t?.params,g.logger=t?.logger,g.heartbeatCallback=this._wrapHeartbeatCallback(t?.heartbeatCallback),g.sessionStorage=(u=t?.sessionStorage)!==null&&u!==void 0?u:j8(),g.reconnectAfterMs=(c=t?.reconnectAfterMs)!==null&&c!==void 0?c:v=>H8[v-1]||W8;let p,y,w=(f=t?.vsn)!==null&&f!==void 0?f:Jk;switch(w){case Xk:p=(v,x)=>x(JSON.stringify(v)),y=(v,x)=>x(JSON.parse(v));break;case rg:p=this.serializer.encode.bind(this.serializer),y=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${g.vsn}`)}if(g.vsn=w,g.encode=(h=t?.encode)!==null&&h!==void 0?h:p,g.decode=(m=t?.decode)!==null&&m!==void 0?m:y,g.beforeReconnect=this._reconnectAuth.bind(this),(t?.logLevel||t?.log_level)&&(this.logLevel=t.logLevel||t.log_level,g.params=Object.assign(Object.assign({},g.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=t?.workerUrl,g.autoSendHeartbeat=!this.worker}return g}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}};var Wu=class extends Error{constructor(e,t){super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown=t.icebergType==="CommitStateUnknownException"||[500,502,504].includes(t.status)&&t.icebergType?.includes("CommitState")===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function q8(e,t,r){let a=new URL(t,e);if(r)for(let[n,i]of Object.entries(r))i!==void 0&&a.searchParams.set(n,i);return a.toString()}async function $8(e){return!e||e.type==="none"?{}:e.type==="bearer"?{Authorization:`Bearer ${e.token}`}:e.type==="header"?{[e.name]:e.value}:e.type==="custom"?await e.getHeaders():{}}function G8(e){let t=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:a,query:n,body:i,headers:s}){let o=q8(e.baseUrl,a,n),l=await $8(e.auth),u=await t(o,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...l,...s},body:i?JSON.stringify(i):void 0}),c=await u.text(),f=(u.headers.get("content-type")||"").includes("application/json"),h=f&&c?JSON.parse(c):c;if(!u.ok){let m=f?h:void 0,g=m?.error;throw new Wu(g?.message??`Request failed with status ${u.status}`,{status:u.status,icebergType:g?.type,icebergCode:g?.code,details:m})}return{status:u.status,headers:u.headers,data:h}}}}function Od(e){return e.join("")}var K8=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){let t=e?{parent:Od(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(a=>({namespace:a}))}async createNamespace(e,t){let r={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Od(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Od(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Od(e.namespace)}`}),!0}catch(t){if(t instanceof Wu&&t.status===404)return!1;throw t}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(r){if(r instanceof Wu&&r.status===409)return;throw r}}};function Bo(e){return e.join("")}var X8=class{constructor(e,t="",r){this.client=e,this.prefix=t,this.accessDelegation=r}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Bo(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Bo(e.namespace)}/tables`,body:t,headers:r})).data.metadata}async updateTable(e,t){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Bo(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Bo(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){let t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Bo(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){let t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Bo(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(r){if(r instanceof Wu&&r.status===404)return!1;throw r}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof Wu&&r.status===409)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}},sS=class{constructor(e){let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);let r=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=G8({baseUrl:r,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new K8(this.client,t),this.tableOps=new X8(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}};function ju(e){"@babel/helpers - typeof";return ju=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ju(e)}function J8(e,t){if(ju(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var a=r.call(e,t||"default");if(ju(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Y8(e){var t=J8(e,"string");return ju(t)=="symbol"?t:t+""}function Q8(e,t,r){return(t=Y8(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function oS(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter(function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable})),r.push.apply(r,a)}return r}function be(e){for(var t=1;te?(...t)=>e(...t):(...t)=>fetch(...t),t6=e=>{if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},ug=e=>{if(Array.isArray(e))return e.map(r=>ug(r));if(typeof e=="function"||e!==Object(e))return e;let t={};return Object.entries(e).forEach(([r,a])=>{let n=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));t[n]=ug(a)}),t},r6=e=>!e||typeof e!="string"||e.length===0||e.length>100||e.trim()!==e||e.includes("/")||e.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(e),lS=e=>{if(typeof e=="object"&&e!==null){let t=e;if(typeof t.msg=="string")return t.msg;if(typeof t.message=="string")return t.message;if(typeof t.error_description=="string")return t.error_description;if(typeof t.error=="string")return t.error;if(typeof t.error=="object"&&t.error!==null){let r=t.error;if(typeof r.message=="string")return r.message}}return JSON.stringify(e)},a6=async(e,t,r,a)=>{if(e!==null&&typeof e=="object"&&"json"in e&&typeof e.json=="function"){let n=e,i=parseInt(String(n.status),10);Number.isFinite(i)||(i=500),n.json().then(s=>{let o=s?.statusCode||s?.code||i+"";t(new Dd(lS(s),i,o,a))}).catch(()=>{let s=i+"";t(new Dd(n.statusText||`HTTP ${i} error`,i,s,a))})}else t(new cS(lS(e),e,a))},n6=(e,t,r,a)=>{let n={method:e,headers:t?.headers||{}};if(e==="GET"||e==="HEAD"||!a)return be(be({},n),r);if(t6(a)){var i;let s=t?.headers||{},o;for(let[l,u]of Object.entries(s))l.toLowerCase()==="content-type"&&(o=u);n.headers=Bd(s,"Content-Type",(i=o)!==null&&i!==void 0?i:"application/json"),n.body=JSON.stringify(a)}else n.body=a;return t?.duplex&&(n.duplex=t.duplex),be(be({},n),r)};async function zu(e,t,r,a,n,i,s){return new Promise((o,l)=>{e(r,n6(t,a,n,i)).then(u=>{if(!u.ok)throw u;if(a?.noResolveJson)return u;if(s==="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=>o(u)).catch(u=>a6(u,l,a,s))})}function fS(e="storage"){return{get:async(t,r,a,n)=>zu(t,"GET",r,a,n,void 0,e),post:async(t,r,a,n,i)=>zu(t,"POST",r,n,i,a,e),put:async(t,r,a,n,i)=>zu(t,"PUT",r,n,i,a,e),head:async(t,r,a,n)=>zu(t,"HEAD",r,be(be({},a),{},{noResolveJson:!0}),n,void 0,e),remove:async(t,r,a,n,i)=>zu(t,"DELETE",r,n,i,a,e)}}var i6=fS("storage"),{get:Vu,post:Na,put:cg,head:s6,remove:fg}=i6,Yr=fS("vectors"),No=class{constructor(e,t={},r,a="storage"){this.shouldThrowOnError=!1,this.url=e,this.headers=Z8(t),this.fetch=e6(r),this.namespace=a}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=Bd(this.headers,e,t),this}async handleOperation(e){var t=this;try{return{data:await e(),error:null}}catch(r){if(t.shouldThrowOnError)throw r;if(Md(r))return{data:null,error:r};throw r}}},dS;dS=Symbol.toStringTag;var o6=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[dS]="StreamDownloadBuilder",this.promise=null}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var e=this;try{return{data:(await e.downloadFn()).body,error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Md(t))return{data:null,error:t};throw t}}},hS;hS=Symbol.toStringTag;var l6=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[hS]="BlobDownloadBuilder",this.promise=null}asStream(){return new o6(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var e=this;try{return{data:await(await e.downloadFn()).blob(),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(Md(t))return{data:null,error:t};throw t}}},u6={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},uS={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},c6=class extends No{constructor(e,t={},r,a){super(e,t,a,"storage"),this.bucketId=r}async uploadOrUpdate(e,t,r,a){var n=this;return n.handleOperation(async()=>{let i,s=be(be({},uS),a),o=be(be({},n.headers),e==="POST"&&{"x-upsert":String(s.upsert)}),l=s.metadata;if(typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",s.cacheControl),l&&i.append("metadata",n.encodeMetadata(l)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",s.cacheControl),l&&!i.has("metadata")&&i.append("metadata",n.encodeMetadata(l))):(i=r,o["cache-control"]=`max-age=${s.cacheControl}`,o["content-type"]=s.contentType,l&&(o["x-metadata"]=n.toBase64(n.encodeMetadata(l))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!s.duplex&&(s.duplex="half")),a?.headers)for(let[h,m]of Object.entries(a.headers))o=Bd(o,h,m);let u=n._removeEmptyFolders(t),c=n._getFinalPath(u),f=await(e=="PUT"?cg:Na)(n.fetch,`${n.url}/object/${c}`,i,be({headers:o},s?.duplex?{duplex:s.duplex}:{}));return{path:u,id:f.Id,fullPath:f.Key}})}async upload(e,t,r){return this.uploadOrUpdate("POST",e,t,r)}async uploadToSignedUrl(e,t,r,a){var n=this;let i=n._removeEmptyFolders(e),s=n._getFinalPath(i),o=new URL(n.url+`/object/upload/sign/${s}`);return o.searchParams.set("token",t),n.handleOperation(async()=>{let l,u=be(be({},uS),a),c=be(be({},n.headers),{"x-upsert":String(u.upsert)}),f=u.metadata;if(typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",u.cacheControl),f&&l.append("metadata",n.encodeMetadata(f)),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.has("cacheControl")||l.append("cacheControl",u.cacheControl),f&&!l.has("metadata")&&l.append("metadata",n.encodeMetadata(f))):(l=r,c["cache-control"]=`max-age=${u.cacheControl}`,c["content-type"]=u.contentType,f&&(c["x-metadata"]=n.toBase64(n.encodeMetadata(f))),(typeof ReadableStream<"u"&&l instanceof ReadableStream||l&&typeof l=="object"&&"pipe"in l&&typeof l.pipe=="function")&&!u.duplex&&(u.duplex="half")),a?.headers)for(let[h,m]of Object.entries(a.headers))c=Bd(c,h,m);return{path:i,fullPath:(await cg(n.fetch,o.toString(),l,be({headers:c},u?.duplex?{duplex:u.duplex}:{}))).Key}})}async createSignedUploadUrl(e,t){var r=this;return r.handleOperation(async()=>{let a=r._getFinalPath(e),n=be({},r.headers);t?.upsert&&(n["x-upsert"]="true");let i=await Na(r.fetch,`${r.url}/object/upload/sign/${a}`,{},{headers:n}),s=new URL(r.url+i.url),o=s.searchParams.get("token");if(!o)throw new Nd("No token returned by API");return{signedUrl:s.toString(),path:e,token:o}})}async update(e,t,r){return this.uploadOrUpdate("PUT",e,t,r)}async move(e,t,r){var a=this;return a.handleOperation(async()=>await Na(a.fetch,`${a.url}/object/move`,{bucketId:a.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:a.headers}))}async copy(e,t,r){var a=this;return a.handleOperation(async()=>({path:(await Na(a.fetch,`${a.url}/object/copy`,{bucketId:a.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r?.destinationBucket},{headers:a.headers})).Key}))}async createSignedUrl(e,t,r){var a=this;return a.handleOperation(async()=>{let n=a._getFinalPath(e),i=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0,s=await Na(a.fetch,`${a.url}/object/sign/${n}`,be({expiresIn:t},i?{transform:r.transform}:{}),{headers:a.headers}),o=new URLSearchParams;r?.download&&o.set("download",r.download===!0?"":r.download),r?.cacheNonce!=null&&o.set("cacheNonce",String(r.cacheNonce));let l=o.toString();return{signedUrl:encodeURI(`${a.url}${s.signedURL}${l?`&${l}`:""}`)}})}async createSignedUrls(e,t,r){var a=this;return a.handleOperation(async()=>{let n=await Na(a.fetch,`${a.url}/object/sign/${a.bucketId}`,{expiresIn:t,paths:e},{headers:a.headers}),i=new URLSearchParams;r?.download&&i.set("download",r.download===!0?"":r.download),r?.cacheNonce!=null&&i.set("cacheNonce",String(r.cacheNonce));let s=i.toString();return n.map(o=>be(be({},o),{},{signedUrl:o.signedURL?encodeURI(`${a.url}${o.signedURL}${s?`&${s}`:""}`):null}))})}download(e,t,r){let a=typeof t?.transform=="object"&&t.transform!==null&&Object.keys(t.transform).length>0?"render/image/authenticated":"object",n=new URLSearchParams;t?.transform&&this.applyTransformOptsToQuery(n,t.transform),t?.cacheNonce!=null&&n.set("cacheNonce",String(t.cacheNonce));let i=n.toString(),s=this._getFinalPath(e),o=()=>Vu(this.fetch,`${this.url}/${a}/${s}${i?`?${i}`:""}`,{headers:this.headers,noResolveJson:!0},r);return new l6(o,this.shouldThrowOnError)}async info(e){var t=this;let r=t._getFinalPath(e);return t.handleOperation(async()=>ug(await Vu(t.fetch,`${t.url}/object/info/${r}`,{headers:t.headers})))}async exists(e){var t=this;let r=t._getFinalPath(e);try{return await s6(t.fetch,`${t.url}/object/${r}`,{headers:t.headers}),{data:!0,error:null}}catch(n){if(t.shouldThrowOnError)throw n;if(Md(n)){var a;let i=n instanceof Dd?n.status:n instanceof cS?(a=n.originalError)===null||a===void 0?void 0:a.status:void 0;if(i!==void 0&&[400,404].includes(i))return{data:!1,error:n}}throw n}}getPublicUrl(e,t){let r=this._getFinalPath(e),a=new URLSearchParams;t?.download&&a.set("download",t.download===!0?"":t.download),t?.transform&&this.applyTransformOptsToQuery(a,t.transform),t?.cacheNonce!=null&&a.set("cacheNonce",String(t.cacheNonce));let n=a.toString(),i=typeof t?.transform=="object"&&t.transform!==null&&Object.keys(t.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}`)+(n?`?${n}`:"")}}}async remove(e){var t=this;return t.handleOperation(async()=>await fg(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}))}async list(e,t,r){var a=this;return a.handleOperation(async()=>{let n=be(be(be({},u6),t),{},{prefix:e||""});return await Na(a.fetch,`${a.url}/object/list/${a.bucketId}`,n,{headers:a.headers},r)})}async listV2(e,t){var r=this;return r.handleOperation(async()=>{let a=be({},e);return await Na(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,a,{headers:r.headers},t)})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(e,t){return t.width&&e.set("width",t.width.toString()),t.height&&e.set("height",t.height.toString()),t.resize&&e.set("resize",t.resize),t.format&&e.set("format",t.format),t.quality&&e.set("quality",t.quality.toString()),e}},f6="2.108.2",qu={"X-Client-Info":`storage-js/${f6}`},d6=class extends No{constructor(e,t={},r,a){let n=new URL(e);a?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));let i=n.href.replace(/\/$/,""),s=be(be({},qu),t);super(i,s,r,"storage")}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let r=t.listBucketOptionsToQueryString(e);return await Vu(t.fetch,`${t.url}/bucket${r}`,{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await Vu(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}))}async createBucket(e,t={public:!1}){var r=this;return r.handleOperation(async()=>await Na(r.fetch,`${r.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}))}async updateBucket(e,t){var r=this;return r.handleOperation(async()=>await cg(r.fetch,`${r.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(e){var t=this;return t.handleOperation(async()=>await Na(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await fg(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}listBucketOptionsToQueryString(e){let t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},h6=class extends No{constructor(e,t={},r){let a=e.replace(/\/$/,""),n=be(be({},qu),t);super(a,n,r,"storage")}async createBucket(e){var t=this;return t.handleOperation(async()=>await Na(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}))}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let r=new URLSearchParams;e?.limit!==void 0&&r.set("limit",e.limit.toString()),e?.offset!==void 0&&r.set("offset",e.offset.toString()),e?.sortColumn&&r.set("sortColumn",e.sortColumn),e?.sortOrder&&r.set("sortOrder",e.sortOrder),e?.search&&r.set("search",e.search);let a=r.toString(),n=a?`${t.url}/bucket?${a}`:`${t.url}/bucket`;return await Vu(t.fetch,n,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await fg(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}from(e){var t=this;if(!r6(e))throw new Nd("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 sS({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),a=this.shouldThrowOnError;return new Proxy(r,{get(n,i){let s=n[i];return typeof s!="function"?s:async(...o)=>{try{return{data:await s.apply(n,o),error:null}}catch(l){if(a)throw l;return{data:null,error:l}}}}})}},p6=class extends No{constructor(e,t={},r){let a=e.replace(/\/$/,""),n=be(be({},qu),{},{"Content-Type":"application/json"},t);super(a,n,r,"vectors")}async createIndex(e){var t=this;return t.handleOperation(async()=>await Yr.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{})}async getIndex(e,t){var r=this;return r.handleOperation(async()=>await Yr.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await Yr.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}))}async deleteIndex(e,t){var r=this;return r.handleOperation(async()=>await Yr.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})||{})}},m6=class extends No{constructor(e,t={},r){let a=e.replace(/\/$/,""),n=be(be({},qu),{},{"Content-Type":"application/json"},t);super(a,n,r,"vectors")}async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return t.handleOperation(async()=>await Yr.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await Yr.post(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}))}async listVectors(e){var t=this;if(e.segmentCount!==void 0){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(e.segmentIndex!==void 0&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return t.handleOperation(async()=>await Yr.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await Yr.post(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return t.handleOperation(async()=>await Yr.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{})}},g6=class extends No{constructor(e,t={},r){let a=e.replace(/\/$/,""),n=be(be({},qu),{},{"Content-Type":"application/json"},t);super(a,n,r,"vectors")}async createBucket(e){var t=this;return t.handleOperation(async()=>await Yr.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await Yr.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}))}async listBuckets(e={}){var t=this;return t.handleOperation(async()=>await Yr.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await Yr.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}},x6=class extends g6{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new v6(this.url,this.headers,e,this.fetch)}async createBucket(e){var t=()=>super.createBucket,r=this;return t().call(r,e)}async getBucket(e){var t=()=>super.getBucket,r=this;return t().call(r,e)}async listBuckets(e={}){var t=()=>super.listBuckets,r=this;return t().call(r,e)}async deleteBucket(e){var t=()=>super.deleteBucket,r=this;return t().call(r,e)}},v6=class extends p6{constructor(e,t,r,a){super(e,t,a),this.vectorBucketName=r}async createIndex(e){var t=()=>super.createIndex,r=this;return t().call(r,be(be({},e),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(e={}){var t=()=>super.listIndexes,r=this;return t().call(r,be(be({},e),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(e){var t=()=>super.getIndex,r=this;return t().call(r,r.vectorBucketName,e)}async deleteIndex(e){var t=()=>super.deleteIndex,r=this;return t().call(r,r.vectorBucketName,e)}index(e){return new y6(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},y6=class extends m6{constructor(e,t,r,a,n){super(e,t,n),this.vectorBucketName=r,this.indexName=a}async putVectors(e){var t=()=>super.putVectors,r=this;return t().call(r,be(be({},e),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(e){var t=()=>super.getVectors,r=this;return t().call(r,be(be({},e),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(e={}){var t=()=>super.listVectors,r=this;return t().call(r,be(be({},e),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(e){var t=()=>super.queryVectors,r=this;return t().call(r,be(be({},e),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(e){var t=()=>super.deleteVectors,r=this;return t().call(r,be(be({},e),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},pS=class extends d6{constructor(e,t={},r,a){super(e,t,r,a)}from(e){return new c6(this.url,this.headers,e,this.fetch)}get vectors(){return new x6(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new h6(this.url+"/iceberg",this.headers,this.fetch)}};var Ud="2.108.2";var nn=30*1e3,Mo=3,Hd=Mo*nn,mS=2*nn,gS="http://localhost:9999",xS="supabase.auth.token";var vS={"X-Client-Info":`gotrue-js/${Ud}`};var $u="X-Supabase-Api-Version",dg={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},yS=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,wS=10*60*1e3;var wi=class extends Error{constructor(t,r,a){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=a}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}};function ve(e){return typeof e=="object"&&e!==null&&"__isAuthError"in e}var Wd=class extends wi{constructor(t,r,a){super(t,r,a),this.name="AuthApiError",this.status=r,this.code=a}};function kS(e){return ve(e)&&e.name==="AuthApiError"}var vr=class extends wi{constructor(t,r){super(t),this.name="AuthUnknownError",this.originalError=r}},wa=class extends wi{constructor(t,r,a,n){super(t,a,n),this.name=r,this.status=a}},Lt=class extends wa{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function Ju(e){return ve(e)&&e.name==="AuthSessionMissingError"}var Dn=class extends wa{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},hs=class extends wa{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}},ps=class extends wa{constructor(t,r=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}};function SS(e){return ve(e)&&e.name==="AuthImplicitGrantRedirectError"}var Gu=class extends wa{constructor(t,r=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}},zd=class extends wa{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 Uo=class extends wa{constructor(t,r){super(t,"AuthRetryableFetchError",r,void 0)}};function hg(e){return ve(e)&&e.name==="AuthRetryableFetchError"}var Ku=class extends wa{constructor(t="Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)"){super(t,"AuthRefreshDiscardedError",409,void 0)}};function _S(e){return ve(e)&&e.name==="AuthRefreshDiscardedError"}var Xu=class extends wa{constructor(t,r,a){super(t,"AuthWeakPasswordError",r,"weak_password"),this.reasons=a}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}};var ki=class extends wa{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}};var jd="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),CS=` \r=`.split(""),w6=(()=>{let e=new Array(128);for(let t=0;t=6;){let a=t.queue>>t.queuedBits-6&63;r(jd[a]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){let a=t.queue>>t.queuedBits-6&63;r(jd[a]),t.queuedBits-=6}}function ES(e,t,r){let a=w6[e];if(a>-1)for(t.queue=t.queue<<6|a,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else{if(a===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}}function pg(e){let t=[],r=s=>{t.push(String.fromCodePoint(s))},a={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=s=>{_6(s,a,r)};for(let s=0;s>6),t(128|e&63);return}else if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|e&63);return}else if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|e&63);return}throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}function S6(e,t){for(let r=0;r55295&&a<=56319){let n=(a-55296)*1024&65535;a=(e.charCodeAt(r+1)-56320&65535|n)+65536,r+=1}k6(a,t)}}function _6(e,t,r){if(t.utf8seq===0){if(e<=127){r(e);return}for(let a=1;a<6;a+=1)if(!(e>>7-a&1)){t.utf8seq=a;break}if(t.utf8seq===2)t.codepoint=e&31;else if(t.utf8seq===3)t.codepoint=e&15;else if(t.utf8seq===4)t.codepoint=e&7;else throw new Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|e&63,t.utf8seq-=1,t.utf8seq===0&&r(t.codepoint)}}function Si(e){let t=[],r={queue:0,queuedBits:0},a=n=>{t.push(n)};for(let n=0;nt.push(r)),new Uint8Array(t)}function Bn(e){let t=[],r={queue:0,queuedBits:0},a=n=>{t.push(n)};return e.forEach(n=>IS(n,r,a)),IS(null,r,a),t.join("")}function TS(e){return Math.round(Date.now()/1e3)+e}function AS(){return Symbol("auth-callback")}var Yt=()=>typeof window<"u"&&typeof document<"u",ms={tested:!1,writable:!1},Vd=()=>{if(!Yt())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(ms.tested)return ms.writable;let e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),ms.tested=!0,ms.writable=!0}catch{ms.tested=!0,ms.writable=!1}return ms.writable};function bS(e){let t={},r=new URL(e);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((n,i)=>{t[i]=n})}catch{}return r.searchParams.forEach((a,n)=>{t[n]=a}),t}var qd=e=>e?(...t)=>e(...t):(...t)=>fetch(...t),FS=e=>typeof e=="object"&&e!==null&&"status"in e&&"ok"in e&&"json"in e&&typeof e.json=="function",gs=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},ka=async(e,t)=>{let r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch{return null}},Tt=async(e,t)=>{await e.removeItem(t)},Yu=class e{constructor(){this.promise=new e.promiseConstructor((t,r)=>{this.resolve=t,this.reject=r})}};Yu.promiseConstructor=Promise;function Qu(e){let t=e.split(".");if(t.length!==3)throw new ki("Invalid JWT structure");for(let a=0;a{setTimeout(()=>t(null),e)})}function PS(e,t){return new Promise((a,n)=>{(async()=>{for(let i=0;i<1/0;i++)try{let s=await e(i);if(!t(i,null,s)){a(s);return}}catch(s){if(!t(i,s)){n(s);return}}})()})}function C6(e){return("0"+e.toString(16)).substr(-2)}function I6(){let t=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",a=r.length,n="";for(let i=0;i<56;i++)n+=r.charAt(Math.floor(Math.random()*a));return n}return crypto.getRandomValues(t),Array.from(t,C6).join("")}async function E6(e){let r=new TextEncoder().encode(e),a=await crypto.subtle.digest("SHA-256",r),n=new Uint8Array(a);return Array.from(n).map(i=>String.fromCharCode(i)).join("")}async function L6(e){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."),e;let r=await E6(e);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function _i(e,t,r=!1){let a=I6(),n=a;r&&(n+="/recovery"),await gs(e,`${t}-code-verifier`,n);let i=await L6(a);return[i,a===i?"plain":"s256"]}var T6=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function OS(e){let t=e.headers.get($u);if(!t||!t.match(T6))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function DS(e){if(!e)throw new Error("Missing exp claim");let t=Math.floor(Date.now()/1e3);if(e<=t)throw new Error("JWT has expired")}function BS(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var A6=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function sn(e){if(!A6.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Qr(e){if(!e.passkey)throw new Error("@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).")}function $d(){let e={};return new Proxy(e,{get:(t,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){let a=r.toString();if(a==="Symbol(Symbol.toPrimitive)"||a==="Symbol(Symbol.toStringTag)"||a==="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:(t,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:(t,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 NS(e,t){return new Proxy(e,{get:(r,a,n)=>{if(a==="__isInsecureUserWarningProxy")return!0;if(typeof a=="symbol"){let i=a.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,a,n)}return!t.value&&typeof a=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),t.value=!0),Reflect.get(r,a,n)}})}function mg(e){return JSON.parse(JSON.stringify(e))}var xs=e=>{if(typeof e=="object"&&e!==null){let t=e;if(typeof t.msg=="string")return t.msg;if(typeof t.message=="string")return t.message;if(typeof t.error_description=="string")return t.error_description;if(typeof t.error=="string")return t.error}return JSON.stringify(e)},b6=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function MS(e){var t;if(!FS(e))throw new Uo(xs(e),0);if(b6.includes(e.status))throw new Uo(xs(e),e.status);let r;try{r=await e.json()}catch(i){throw new vr(xs(i),i)}let a,n=OS(e);if(n&&n.getTime()>=dg["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?a=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(a=r.error_code),a){if(a==="weak_password")throw new Xu(xs(r),e.status,((t=r.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(a==="session_not_found")throw new Lt}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((i,s)=>i&&typeof s=="string",!0))throw new Xu(xs(r),e.status,r.weak_password.reasons);throw new Wd(xs(r),e.status||500,a)}var F6=(e,t,r,a)=>{let n={method:e,headers:t?.headers||{}};return e==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t?.headers),n.body=JSON.stringify(a),Object.assign(Object.assign({},n),r))};async function Ce(e,t,r,a){var n;let i=Object.assign({},a?.headers);i[$u]||(i[$u]=dg["2024-01-01"].name),a?.jwt&&(i.Authorization=`Bearer ${a.jwt}`);let s=(n=a?.query)!==null&&n!==void 0?n:{};a?.redirectTo&&(s.redirect_to=a.redirectTo);let o=Object.keys(s).length?"?"+new URLSearchParams(s).toString():"",l=await R6(e,t,r+o,{headers:i,noResolveJson:a?.noResolveJson},{},a?.body);return a?.xform?a?.xform(l):{data:Object.assign({},l),error:null}}async function R6(e,t,r,a,n,i){let s=F6(t,a,n,i),o;try{o=await e(r,Object.assign({},s))}catch(l){throw console.error(l),new Uo(xs(l),0)}if(o.ok||await MS(o),a?.noResolveJson)return o;try{return await o.json()}catch(l){await MS(l)}}function Zr(e){var t;let r=null;P6(e)&&(r=Object.assign({},e),e.expires_at||(r.expires_at=TS(e.expires_in)));let a=(t=e.user)!==null&&t!==void 0?t:typeof e?.id=="string"?e:null;return{data:{session:r,user:a},error:null}}function gg(e){let t=Zr(e);return!t.error&&e.weak_password&&typeof e.weak_password=="object"&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message=="string"&&e.weak_password.reasons.reduce((r,a)=>r&&typeof a=="string",!0)&&(t.data.weak_password=e.weak_password),t}function on(e){var t;return{data:{user:(t=e.user)!==null&&t!==void 0?t:e},error:null}}function US(e){return{data:e,error:null}}function HS(e){let{action_link:t,email_otp:r,hashed_token:a,redirect_to:n,verification_type:i}=e,s=fs(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:t,email_otp:r,hashed_token:a,redirect_to:n,verification_type:i},l=Object.assign({},s);return{data:{properties:o,user:l},error:null}}function xg(e){return e}function P6(e){return!!e.access_token&&!!e.refresh_token&&!!e.expires_in}var Gd=["global","local","others"];var vs=class{constructor({url:t="",headers:r={},fetch:a,experimental:n}){this.url=t,this.headers=r,this.fetch=qd(a),this.experimental=n??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(t,r=Gd[0]){if(Gd.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Gd.join(", ")}`);try{return await Ce(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:t,noResolveJson:!0}),{data:null,error:null}}catch(a){if(ve(a))return{data:null,error:a};throw a}}async inviteUserByEmail(t,r={}){try{return await Ce(this.fetch,"POST",`${this.url}/invite`,{body:{email:t,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:on})}catch(a){if(ve(a))return{data:{user:null},error:a};throw a}}async generateLink(t){try{let{options:r}=t,a=fs(t,["options"]),n=Object.assign(Object.assign({},a),r);return"newEmail"in a&&(n.new_email=a?.newEmail,delete n.newEmail),await Ce(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:HS,redirectTo:r?.redirectTo})}catch(r){if(ve(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(t){try{return await Ce(this.fetch,"POST",`${this.url}/admin/users`,{body:t,headers:this.headers,xform:on})}catch(r){if(ve(r))return{data:{user:null},error:r};throw r}}async listUsers(t){var r,a,n,i,s,o,l;try{let u={nextPage:null,lastPage:0,total:0},c=await Ce(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(a=(r=t?.page)===null||r===void 0?void 0:r.toString())!==null&&a!==void 0?a:"",per_page:(i=(n=t?.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:xg});if(c.error)throw c.error;let f=await c.json(),h=(s=c.headers.get("x-total-count"))!==null&&s!==void 0?s:0,m=(l=(o=c.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(g=>{let p=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(g.split(";")[1].split("=")[1]);u[`${y}Page`]=p}),u.total=parseInt(h)),{data:Object.assign(Object.assign({},f),u),error:null}}catch(u){if(ve(u))return{data:{users:[]},error:u};throw u}}async getUserById(t){sn(t);try{return await Ce(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:on})}catch(r){if(ve(r))return{data:{user:null},error:r};throw r}}async updateUserById(t,r){sn(t);try{return await Ce(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:r,headers:this.headers,xform:on})}catch(a){if(ve(a))return{data:{user:null},error:a};throw a}}async deleteUser(t,r=!1){sn(t);try{return await Ce(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:r},xform:on})}catch(a){if(ve(a))return{data:{user:null},error:a};throw a}}async _listFactors(t){sn(t.userId);try{let{data:r,error:a}=await Ce(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:r,error:a}}catch(r){if(ve(r))return{data:null,error:r};throw r}}async _deleteFactor(t){sn(t.userId),sn(t.id);try{return{data:await Ce(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(r){if(ve(r))return{data:null,error:r};throw r}}async _listOAuthClients(t){var r,a,n,i,s,o,l;try{let u={nextPage:null,lastPage:0,total:0},c=await Ce(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(a=(r=t?.page)===null||r===void 0?void 0:r.toString())!==null&&a!==void 0?a:"",per_page:(i=(n=t?.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:xg});if(c.error)throw c.error;let f=await c.json(),h=(s=c.headers.get("x-total-count"))!==null&&s!==void 0?s:0,m=(l=(o=c.headers.get("link"))===null||o===void 0?void 0:o.split(","))!==null&&l!==void 0?l:[];return m.length>0&&(m.forEach(g=>{let p=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(g.split(";")[1].split("=")[1]);u[`${y}Page`]=p}),u.total=parseInt(h)),{data:Object.assign(Object.assign({},f),u),error:null}}catch(u){if(ve(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(t){try{return await Ce(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:t,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(ve(r))return{data:null,error:r};throw r}}async _getOAuthClient(t){try{return await Ce(this.fetch,"GET",`${this.url}/admin/oauth/clients/${t}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(ve(r))return{data:null,error:r};throw r}}async _updateOAuthClient(t,r){try{return await Ce(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${t}`,{body:r,headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(ve(a))return{data:null,error:a};throw a}}async _deleteOAuthClient(t){try{return await Ce(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${t}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(ve(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(t){try{return await Ce(this.fetch,"POST",`${this.url}/admin/oauth/clients/${t}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(ve(r))return{data:null,error:r};throw r}}async _listCustomProviders(t){try{let r={};return t?.type&&(r.type=t.type),await Ce(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:a=>{var n;return{data:{providers:(n=a?.providers)!==null&&n!==void 0?n:[]},error:null}}})}catch(r){if(ve(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(t){try{return await Ce(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:t,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(ve(r))return{data:null,error:r};throw r}}async _getCustomProvider(t){try{return await Ce(this.fetch,"GET",`${this.url}/admin/custom-providers/${t}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(ve(r))return{data:null,error:r};throw r}}async _updateCustomProvider(t,r){try{return await Ce(this.fetch,"PUT",`${this.url}/admin/custom-providers/${t}`,{body:r,headers:this.headers,xform:a=>({data:a,error:null})})}catch(a){if(ve(a))return{data:null,error:a};throw a}}async _deleteCustomProvider(t){try{return await Ce(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${t}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(ve(r))return{data:null,error:r};throw r}}async _adminListPasskeys(t){Qr(this.experimental),sn(t.userId);try{return await Ce(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/passkeys`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(ve(r))return{data:null,error:r};throw r}}async _adminDeletePasskey(t){Qr(this.experimental),sn(t.userId),sn(t.passkeyId);try{return await Ce(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/passkeys/${t.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(ve(r))return{data:null,error:r};throw r}}};function vg(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}var O6={debug:!!(globalThis&&Vd()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Kd=class extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}};function WS(){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 yg(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function zS(e){return parseInt(e,16)}function jS(e){let t=new TextEncoder().encode(e);return"0x"+Array.from(t,a=>a.toString(16).padStart(2,"0")).join("")}function VS(e){var t;let{chainId:r,domain:a,expirationTime:n,issuedAt:i=new Date,nonce:s,notBefore:o,requestId:l,resources:u,scheme:c,uri:f,version:h}=e;{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(!a)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(s&&s.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${s}`);if(!f)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(h!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${h}`);if(!((t=e.statement)===null||t===void 0)&&t.includes(` `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`)}let m=yg(e.address),g=c?`${c}://${a}`:a,p=e.statement?`${e.statement} `:"",y=`${g} wants you to sign in with your Ethereum account: ${m} ${p}`,w=`URI: ${f} Version: ${h} Chain ID: ${r}${s?` Nonce: ${s}`:""} Issued At: ${i.toISOString()}`;if(n&&(w+=` Expiration Time: ${n.toISOString()}`),o&&(w+=` Not Before: ${o.toISOString()}`),l&&(w+=` Request ID: ${l}`),u){let v=` Resources:`;for(let x of u){if(!x||typeof x!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${x}`);v+=` - ${x}`}w+=v}return`${y} ${w}`}var kt=class extends Error{constructor({message:t,code:r,cause:a,name:n}){var i;super(t,{cause:a}),this.__isWebAuthnError=!0,this.name=(i=n??(a instanceof Error?a.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=r}toJSON(){return{name:this.name,message:this.message,code:this.code}}},ys=class extends kt{constructor(t,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:t}),this.name="WebAuthnUnknownError",this.originalError=r}};function qS({error:e,options:t}){var r,a,n;let{publicKey:i}=t;if(!i)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new kt({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new kt({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if(t.mediation==="conditional"&&((a=i.authenticatorSelection)===null||a===void 0?void 0:a.userVerification)==="required")return new kt({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new kt({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if(e.name==="InvalidStateError")return new kt({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if(e.name==="NotAllowedError")return new kt({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="NotSupportedError")return i.pubKeyCredParams.filter(o=>o.type==="public-key").length===0?new kt({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new kt({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if(e.name==="SecurityError"){let s=window.location.hostname;if(wg(s)){if(i.rp.id!==s)return new kt({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new kt({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new kt({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if(e.name==="UnknownError")return new kt({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new kt({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function $S({error:e,options:t}){let{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new kt({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if(e.name==="NotAllowedError")return new kt({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="SecurityError"){let a=window.location.hostname;if(wg(a)){if(r.rpId!==a)return new kt({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new kt({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="UnknownError")return new kt({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new kt({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}var kg=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 t=new AbortController;return this.controller=t,t.signal}cancelCeremony(){if(this.controller){let t=new Error("Manually cancelling existing WebAuthn API call");t.name="AbortError",this.controller.abort(t),this.controller=void 0}}},Yd=new kg;function Sg(e){if(!e)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(e);let{challenge:t,user:r,excludeCredentials:a}=e,n=fs(e,["challenge","user","excludeCredentials"]),i=Si(t).buffer,s=Object.assign(Object.assign({},r),{id:Si(r.id).buffer}),o=Object.assign(Object.assign({},n),{challenge:i,user:s});if(a&&a.length>0){o.excludeCredentials=new Array(a.length);for(let l=0;l0){i.allowCredentials=new Array(r.length);for(let s=0;sn!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),a={};for(let n of e)if(n)for(let i in n){let s=n[i];if(s!==void 0)if(Array.isArray(s))a[i]=s;else if(r(s))a[i]=s;else if(t(s)){let o=a[i];t(o)?a[i]=Xd(o,s):a[i]=Xd(s)}else a[i]=s}return a}function N6(e,t){return Xd(D6,e,t||{})}function M6(e,t){return Xd(B6,e,t||{})}var Jd=class{constructor(t){this.client=t,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(t){return this.client.mfa.enroll(Object.assign(Object.assign({},t),{factorType:"webauthn"}))}async _challenge({factorId:t,webauthn:r,friendlyName:a,signal:n},i){var s;try{let{data:o,error:l}=await this.client.mfa.challenge({factorId:t,webauthn:r});if(!o)return{data:null,error:l};let u=n??Yd.createNewAbortSignal();if(o.webauthn.type==="create"){let{user:c}=o.webauthn.credential_options.publicKey;if(!c.name){let f=a;if(f)c.name=`${c.id}:${f}`;else{let m=(await this.client.getUser()).data.user,g=((s=m?.user_metadata)===null||s===void 0?void 0:s.name)||m?.email||m?.id||"User";c.name=`${c.id}:${g}`}}c.displayName||(c.displayName=c.name)}switch(o.webauthn.type){case"create":{let c=N6(o.webauthn.credential_options.publicKey,i?.create),{data:f,error:h}=await Eg({publicKey:c,signal:u});return f?{data:{factorId:t,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:f}},error:null}:{data:null,error:h}}case"request":{let c=M6(o.webauthn.credential_options.publicKey,i?.request),{data:f,error:h}=await Lg(Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:c,signal:u}));return f?{data:{factorId:t,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:f}},error:null}:{data:null,error:h}}}}catch(o){return ve(o)?{data:null,error:o}:{data:null,error:new vr("Unexpected error in challenge",o)}}}async _verify({challengeId:t,factorId:r,webauthn:a}){return this.client.mfa.verify({factorId:r,challengeId:t,webauthn:a})}async _authenticate({factorId:t,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:a=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new wi("rpId is required for WebAuthn authentication")};try{if(!Zu())return{data:null,error:new vr("Browser does not support WebAuthn",null)};let{data:s,error:o}=await this.challenge({factorId:t,webauthn:{rpId:r,rpOrigins:a},signal:n},{request:i});if(!s)return{data:null,error:o};let{webauthn:l}=s;return this._verify({factorId:t,challengeId:s.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:a,credential_response:l.credential_response}})}catch(s){return ve(s)?{data:null,error:s}:{data:null,error:new vr("Unexpected error in authenticate",s)}}}async _register({friendlyName:t,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:a=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new wi("rpId is required for WebAuthn registration")};try{if(!Zu())return{data:null,error:new vr("Browser does not support WebAuthn",null)};let{data:s,error:o}=await this._enroll({friendlyName:t});if(!s)return await this.client.mfa.listFactors().then(c=>{var f;return(f=c.data)===null||f===void 0?void 0:f.all.find(h=>h.factor_type==="webauthn"&&h.friendly_name===t&&h.status!=="unverified")}).then(c=>c?this.client.mfa.unenroll({factorId:c?.id}):void 0),{data:null,error:o};let{data:l,error:u}=await this._challenge({factorId:s.id,friendlyName:s.friendly_name,webauthn:{rpId:r,rpOrigins:a},signal:n},{create:i});return l?this._verify({factorId:s.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:a,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:u}}catch(s){return ve(s)?{data:null,error:s}:{data:null,error:new vr("Unexpected error in register",s)}}}};WS();var U6={url:gS,storageKey:xS,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:vS,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};var Ho={},Qd=class e{get jwks(){var t,r;return(r=(t=Ho[this.storageKey])===null||t===void 0?void 0:t.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(t){Ho[this.storageKey]=Object.assign(Object.assign({},Ho[this.storageKey]),{jwks:t})}get jwks_cached_at(){var t,r;return(r=(t=Ho[this.storageKey])===null||t===void 0?void 0:t.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(t){Ho[this.storageKey]=Object.assign(Object.assign({},Ho[this.storageKey]),{cachedAt:t})}constructor(t){var r,a,n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},U6),t);if(this.storageKey=i.storageKey,this.instanceID=(r=e.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,e.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&Yt()){let s=`${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(s),this.logDebugMessages&&console.trace(s)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(a=i.experimental)!==null&&a!==void 0?a:{},this.admin=new vs({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=qd(i.fetch),this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock!=null&&(this.lock=i.lock),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 Jd(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.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:Vd()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=vg(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=vg(this.memoryStorage)),Yt()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(s){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",s)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async s=>{this._debug("received broadcast notification from other tab or client",s),(s.data.event==="TOKEN_REFRESHED"||s.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(s.data.event,s.data.session,!1)}catch(o){this._debug("#broadcastChannel","error",o)}})}i.skipAutoInitialize||this.initialize().catch(s=>{this._debug("#initialize()","error",s)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(t){if(this.throwOnError&&t&&t.error)throw t.error;return t}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Ud}) ${new Date().toISOString()}`}_debug(...t){return this.logDebugMessages&&this.logger(this._logPrefix(),...t),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())(),await this.initializePromise)}async _initialize(){var t;try{let r={},a="none";if(Yt()&&(r=bS(window.location.href),this._isImplicitGrantCallback(r)?a="implicit":await this._isPKCECallback(r)&&(a="pkce")),Yt()&&this.detectSessionInUrl&&a!=="none"){let{data:n,error:i}=await this._getSessionFromURL(r,a);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),SS(i)){let l=(t=i.details)===null||t===void 0?void 0:t.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:i}}return{error:i}}let{session:s,redirectType:o}=n;return this._debug("#_initialize()","detected session in URL",s,"redirect type",o),await this._saveSession(s),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",s):await this._notifyAllSubscribers("SIGNED_IN",s)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return ve(r)?this._returnResult({error:r}):this._returnResult({error:new vr("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var r,a,n;try{let i=await Ce(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(a=(r=t?.options)===null||r===void 0?void 0:r.data)!==null&&a!==void 0?a:{},gotrue_meta_security:{captcha_token:(n=t?.options)===null||n===void 0?void 0:n.captchaToken}},xform:Zr}),{data:s,error:o}=i;if(o||!s)return this._returnResult({data:{user:null,session:null},error:o});let l=s.session,u=s.user;return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(i){if(ve(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(t){var r,a,n;try{let i;if("email"in t){let{email:c,password:f,options:h}=t,m=null,g=null;this.flowType==="pkce"&&([m,g]=await _i(this.storage,this.storageKey)),i=await Ce(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:h?.emailRedirectTo,body:{email:c,password:f,data:(r=h?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:h?.captchaToken},code_challenge:m,code_challenge_method:g},xform:Zr})}else if("phone"in t){let{phone:c,password:f,options:h}=t;i=await Ce(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:c,password:f,data:(a=h?.data)!==null&&a!==void 0?a:{},channel:(n=h?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:h?.captchaToken}},xform:Zr})}else throw new hs("You must provide either an email or phone number and a password");let{data:s,error:o}=i;if(o||!s)return await Tt(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:o});let l=s.session,u=s.user;return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(i){if(await Tt(this.storage,`${this.storageKey}-code-verifier`),ve(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(t){try{let r;if("email"in t){let{email:i,password:s,options:o}=t;r=await Ce(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:s,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:gg})}else if("phone"in t){let{phone:i,password:s,options:o}=t;r=await Ce(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:s,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:gg})}else throw new hs("You must provide either an email or phone number and a password");let{data:a,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!a||!a.session||!a.user){let i=new Dn;return this._returnResult({data:{user:null,session:null},error:i})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),this._returnResult({data:Object.assign({user:a.user,session:a.session},a.weak_password?{weakPassword:a.weak_password}:null),error:n})}catch(r){if(ve(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(t){var r,a,n,i;return await this._handleProviderSignIn(t.provider,{redirectTo:(r=t.options)===null||r===void 0?void 0:r.redirectTo,scopes:(a=t.options)===null||a===void 0?void 0:a.scopes,queryParams:(n=t.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=t.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(t){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(t)):this._exchangeCodeForSession(t)}async signInWithWeb3(t){let{chain:r}=t;switch(r){case"ethereum":return await this.signInWithEthereum(t);case"solana":return await this.signInWithSolana(t);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(t){var r,a,n,i,s,o,l,u,c,f,h;let m,g;if("message"in t)m=t.message,g=t.signature;else{let{chain:p,wallet:y,statement:w,options:v}=t,x;if(Yt())if(typeof y=="object")x=y;else{let O=window;if("ethereum"in O&&typeof O.ethereum=="object"&&"request"in O.ethereum&&typeof O.ethereum.request=="function")x=O.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"||!v?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");x=y}let _=new URL((r=v?.url)!==null&&r!==void 0?r:window.location.href),T=await x.request({method:"eth_requestAccounts"}).then(O=>O).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!T||T.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let E=yg(T[0]),k=(a=v?.signInWithEthereum)===null||a===void 0?void 0:a.chainId;if(!k){let O=await x.request({method:"eth_chainId"});k=zS(O)}let b={domain:_.host,address:E,statement:w,uri:_.href,version:"1",chainId:k,nonce:(n=v?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(s=(i=v?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&s!==void 0?s:new Date,expirationTime:(o=v?.signInWithEthereum)===null||o===void 0?void 0:o.expirationTime,notBefore:(l=v?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(u=v?.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(c=v?.signInWithEthereum)===null||c===void 0?void 0:c.resources};m=VS(b),g=await x.request({method:"personal_sign",params:[jS(m),E]})}try{let{data:p,error:y}=await Ce(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:m,signature:g},!((f=t.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(h=t.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:Zr});if(y)throw y;if(!p||!p.session||!p.user){let w=new Dn;return this._returnResult({data:{user:null,session:null},error:w})}return p.session&&(await this._saveSession(p.session),await this._notifyAllSubscribers("SIGNED_IN",p.session)),this._returnResult({data:Object.assign({},p),error:y})}catch(p){if(ve(p))return this._returnResult({data:{user:null,session:null},error:p});throw p}}async signInWithSolana(t){var r,a,n,i,s,o,l,u,c,f,h,m;let g,p;if("message"in t)g=t.message,p=t.signature;else{let{chain:y,wallet:w,statement:v,options:x}=t,_;if(Yt())if(typeof w=="object")_=w;else{let E=window;if("solana"in E&&typeof E.solana=="object"&&("signIn"in E.solana&&typeof E.solana.signIn=="function"||"signMessage"in E.solana&&typeof E.solana.signMessage=="function"))_=E.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 w!="object"||!x?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=w}let T=new URL((r=x?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in _&&_.signIn){let E=await _.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},x?.signInWithSolana),{version:"1",domain:T.host,uri:T.href}),v?{statement:v}:null)),k;if(Array.isArray(E)&&E[0]&&typeof E[0]=="object")k=E[0];else if(E&&typeof E=="object"&&"signedMessage"in E&&"signature"in E)k=E;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in k&&"signature"in k&&(typeof k.signedMessage=="string"||k.signedMessage instanceof Uint8Array)&&k.signature instanceof Uint8Array)g=typeof k.signedMessage=="string"?k.signedMessage:new TextDecoder().decode(k.signedMessage),p=k.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in _)||typeof _.signMessage!="function"||!("publicKey"in _)||typeof _!="object"||!_.publicKey||!("toBase58"in _.publicKey)||typeof _.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");g=[`${T.host} wants you to sign in with your Solana account:`,_.publicKey.toBase58(),...v?["",v,""]:[""],"Version: 1",`URI: ${T.href}`,`Issued At: ${(n=(a=x?.signInWithSolana)===null||a===void 0?void 0:a.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=x?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${x.signInWithSolana.notBefore}`]:[],...!((s=x?.signInWithSolana)===null||s===void 0)&&s.expirationTime?[`Expiration Time: ${x.signInWithSolana.expirationTime}`]:[],...!((o=x?.signInWithSolana)===null||o===void 0)&&o.chainId?[`Chain ID: ${x.signInWithSolana.chainId}`]:[],...!((l=x?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${x.signInWithSolana.nonce}`]:[],...!((u=x?.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${x.signInWithSolana.requestId}`]:[],...!((f=(c=x?.signInWithSolana)===null||c===void 0?void 0:c.resources)===null||f===void 0)&&f.length?["Resources",...x.signInWithSolana.resources.map(k=>`- ${k}`)]:[]].join(` `);let E=await _.signMessage(new TextEncoder().encode(g),"utf8");if(!E||!(E instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");p=E}}try{let{data:y,error:w}=await Ce(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:g,signature:Bn(p)},!((h=t.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(m=t.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:Zr});if(w)throw w;if(!y||!y.session||!y.user){let v=new Dn;return this._returnResult({data:{user:null,session:null},error:v})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:w})}catch(y){if(ve(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async _exchangeCodeForSession(t){let r=await ka(this.storage,`${this.storageKey}-code-verifier`),[a,n]=(r??"").split("/");try{if(!a&&this.flowType==="pkce")throw new zd;let{data:i,error:s}=await Ce(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:a},xform:Zr});if(await Tt(this.storage,`${this.storageKey}-code-verifier`),s)throw s;if(!i||!i.session||!i.user){let o=new Dn;return this._returnResult({data:{user:null,session:null,redirectType:null},error:o})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers(n==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:n??null}),error:s})}catch(i){if(await Tt(this.storage,`${this.storageKey}-code-verifier`),ve(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(t){try{let{options:r,provider:a,token:n,access_token:i,nonce:s}=t,o=await Ce(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:a,id_token:n,access_token:i,nonce:s,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:Zr}),{data:l,error:u}=o;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!l||!l.session||!l.user){let c=new Dn;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(ve(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(t){var r,a,n,i,s;try{if("email"in t){let{email:o,options:l}=t,u=null,c=null;this.flowType==="pkce"&&([u,c]=await _i(this.storage,this.storageKey));let{error:f}=await Ce(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(a=l?.shouldCreateUser)!==null&&a!==void 0?a:!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:f})}if("phone"in t){let{phone:o,options:l}=t,{data:u,error:c}=await Ce(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(n=l?.data)!==null&&n!==void 0?n:{},create_user:(i=l?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(s=l?.channel)!==null&&s!==void 0?s:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:u?.message_id},error:c})}throw new hs("You must provide either an email or phone number.")}catch(o){if(await Tt(this.storage,`${this.storageKey}-code-verifier`),ve(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async verifyOtp(t){var r,a;try{let n,i;"options"in t&&(n=(r=t.options)===null||r===void 0?void 0:r.redirectTo,i=(a=t.options)===null||a===void 0?void 0:a.captchaToken);let{data:s,error:o}=await Ce(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:Zr});if(o)throw o;if(!s)throw new Error("An error occurred on token verification.");let l=s.session,u=s.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(t.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:u,session:l},error:null})}catch(n){if(ve(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(t){var r,a,n,i,s;try{let o=null,l=null;this.flowType==="pkce"&&([o,l]=await _i(this.storage,this.storageKey));let u=await Ce(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in t?{provider_id:t.providerId}:null),"domain"in t?{domain:t.domain}:null),{redirect_to:(a=(r=t.options)===null||r===void 0?void 0:r.redirectTo)!==null&&a!==void 0?a:void 0}),!((n=t?.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:t.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:l}),headers:this.headers,xform:US});return!((i=u.data)===null||i===void 0)&&i.url&&Yt()&&!(!((s=t.options)===null||s===void 0)&&s.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(o){if(await Tt(this.storage,`${this.storageKey}-code-verifier`),ve(o))return this._returnResult({data:null,error:o});throw o}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async t=>{let{data:{session:r},error:a}=t;if(a)throw a;if(!r)throw new Lt;let{error:n}=await Ce(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(t){if(ve(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async resend(t){try{let r=`${this.url}/resend`;if("email"in t){let{email:a,type:n,options:i}=t,s=null,o=null;this.flowType==="pkce"&&([s,o]=await _i(this.storage,this.storageKey));let{error:l}=await Ce(this.fetch,"POST",r,{headers:this.headers,body:{email:a,type:n,gotrue_meta_security:{captcha_token:i?.captchaToken},code_challenge:s,code_challenge_method:o},redirectTo:i?.emailRedirectTo});return l&&await Tt(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:l})}else if("phone"in t){let{phone:a,type:n,options:i}=t,{data:s,error:o}=await Ce(this.fetch,"POST",r,{headers:this.headers,body:{phone:a,type:n,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:s?.message_id},error:o})}throw new hs("You must provide either an email or phone number and a type")}catch(r){if(await Tt(this.storage,`${this.storageKey}-code-verifier`),ve(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async t=>t)):await this._useSession(async t=>t)}async _acquireLock(t,r){this._debug("#_acquireLock","begin",t);try{if(this.lockAcquired){let a=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await a,await r()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,t,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let a=r();for(this.pendingInLock.push((async()=>{try{await a}catch{}})()),await a;this.pendingInLock.length;){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await a}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(t){this._debug("#_useSession","begin");try{let r=await this.__loadSession();return await t(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let t=null,r=await ka(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?t=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};let a=t.expires_at?t.expires_at*1e3-Date.now()Date.now())){let o=await ka(this.storage,this.storageKey);if(o&&o.refresh_token===t.refresh_token)return this._returnResult({data:{session:t},error:null})}return this._returnResult({data:{session:null},error:i})}return this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(t){if(t)return await this._getUser(t);await this.initializePromise;let r;return this.lock!=null?r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):r=await this._getUser(),r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(t){try{return t?await Ce(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:on}):await this._useSession(async r=>{var a,n,i;let{data:s,error:o}=r;if(o)throw o;return!(!((a=s.session)===null||a===void 0)&&a.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Lt}:await Ce(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=s.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:on})})}catch(r){if(ve(r))return Ju(r)&&(await this._removeSession(),await Tt(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(t,r={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(t,r)):await this._updateUser(t,r)}async _updateUser(t,r={}){try{return await this._useSession(async a=>{let{data:n,error:i}=a;if(i)throw i;if(!n.session)throw new Lt;let s=n.session,o=null,l=null;this.flowType==="pkce"&&t.email!=null&&([o,l]=await _i(this.storage,this.storageKey));let{data:u,error:c}=await Ce(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r?.emailRedirectTo,body:Object.assign(Object.assign({},t),{code_challenge:o,code_challenge_method:l}),jwt:s.access_token,xform:on});if(c)throw c;return s.user=u.user,await this._saveSession(s),await this._notifyAllSubscribers("USER_UPDATED",s),this._returnResult({data:{user:s.user},error:null})})}catch(a){if(await Tt(this.storage,`${this.storageKey}-code-verifier`),ve(a))return this._returnResult({data:{user:null},error:a});throw a}}async setSession(t){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(t)):await this._setSession(t)}async _setSession(t){try{if(!t.access_token||!t.refresh_token)throw new Lt;let r=Date.now()/1e3,a=r,n=!0,i=null,{payload:s}=Qu(t.access_token);if(s.exp&&(a=s.exp,n=a<=r),n){let{data:o,error:l}=await this._callRefreshToken(t.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!o)return{data:{user:null,session:null},error:null};i=o}else{let{data:o,error:l}=await this._getUser(t.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});i={access_token:t.access_token,refresh_token:t.refresh_token,user:o.user,token_type:"bearer",expires_in:a-r,expires_at:a},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(r){if(ve(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(t){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(t)):await this._refreshSession(t)}async _refreshSession(t){try{return await this._useSession(async r=>{var a;if(!t){let{data:s,error:o}=r;if(o)throw o;t=(a=s.session)!==null&&a!==void 0?a:void 0}if(!t?.refresh_token)throw new Lt;let{data:n,error:i}=await this._callRefreshToken(t.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(ve(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(t,r){var a;try{if(!Yt())throw new ps("No browser detected.");if(t.error||t.error_description||t.error_code)throw new ps(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new Gu("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new ps("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!t.code)throw new Gu("No code detected.");let{data:x,error:_}=await this._exchangeCodeForSession(t.code);if(_)throw _;let T=new URL(window.location.href);return T.searchParams.delete("code"),window.history.replaceState(window.history.state,"",T.toString()),{data:{session:x.session,redirectType:(a=x.redirectType)!==null&&a!==void 0?a:null},error:null}}let{provider_token:n,provider_refresh_token:i,access_token:s,refresh_token:o,expires_in:l,expires_at:u,token_type:c}=t;if(!s||!l||!o||!c)throw new ps("No session defined in URL");let f=Math.round(Date.now()/1e3),h=parseInt(l),m=f+h;u&&(m=parseInt(u));let g=m-f;g*1e3<=nn&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${g}s, should have been closer to ${h}s`);let p=m-h;f-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,m,f):f-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",p,m,f);let{data:y,error:w}=await this._getUser(s);if(w)throw w;let v={provider_token:n,provider_refresh_token:i,access_token:s,expires_in:h,expires_at:m,refresh_token:o,token_type:c,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:v,redirectType:t.type},error:null})}catch(n){if(ve(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(t){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),t):!!(t.access_token||t.error||t.error_description||t.error_code)}async _isPKCECallback(t){let r=await ka(this.storage,`${this.storageKey}-code-verifier`);return!!(t.code&&r)}async signOut(t={scope:"global"}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(t)):await this._signOut(t)}async _signOut({scope:t}={scope:"global"}){return await this._useSession(async r=>{var a;let{data:n,error:i}=r;if(i&&!Ju(i))return this._returnResult({error:i});let s=(a=n.session)===null||a===void 0?void 0:a.access_token;if(s){let{error:o}=await this.admin.signOut(s,t);if(o&&!(kS(o)&&(o.status===404||o.status===401||o.status===403)||Ju(o)))return this._returnResult({error:o})}return t!=="others"&&(await this._removeSession(),await Tt(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(t){let r=AS(),a={id:r,callback:t,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,a),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)}):await this._emitInitialSession(r)))(),{data:{subscription:a}}}async _emitInitialSession(t){return await this._useSession(async r=>{var a,n;try{let{data:{session:i},error:s}=r;if(s)throw s;await((a=this.stateChangeEmitters.get(t))===null||a===void 0?void 0:a.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",t,"session",i)}catch(i){await((n=this.stateChangeEmitters.get(t))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",t,"error",i),Ju(i)?console.warn(i):console.error(i)}})}async resetPasswordForEmail(t,r={}){let a=null,n=null;this.flowType==="pkce"&&([a,n]=await _i(this.storage,this.storageKey,!0));try{return await Ce(this.fetch,"POST",`${this.url}/recover`,{body:{email:t,code_challenge:a,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(await Tt(this.storage,`${this.storageKey}-code-verifier`),ve(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var t;try{let{data:r,error:a}=await this.getUser();if(a)throw a;return this._returnResult({data:{identities:(t=r.user.identities)!==null&&t!==void 0?t:[]},error:null})}catch(r){if(ve(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(t){return"token"in t?this.linkIdentityIdToken(t):this.linkIdentityOAuth(t)}async linkIdentityOAuth(t){var r;try{let{data:a,error:n}=await this._useSession(async i=>{var s,o,l,u,c;let{data:f,error:h}=i;if(h)throw h;let m=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,t.provider,{redirectTo:(s=t.options)===null||s===void 0?void 0:s.redirectTo,scopes:(o=t.options)===null||o===void 0?void 0:o.scopes,queryParams:(l=t.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await Ce(this.fetch,"GET",m,{headers:this.headers,jwt:(c=(u=f.session)===null||u===void 0?void 0:u.access_token)!==null&&c!==void 0?c:void 0})});if(n)throw n;return Yt()&&!(!((r=t.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(a?.url),this._returnResult({data:{provider:t.provider,url:a?.url},error:null})}catch(a){if(ve(a))return this._returnResult({data:{provider:t.provider,url:null},error:a});throw a}}async linkIdentityIdToken(t){return await this._useSession(async r=>{var a;try{let{error:n,data:{session:i}}=r;if(n)throw n;let{options:s,provider:o,token:l,access_token:u,nonce:c}=t,f=await Ce(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(a=i?.access_token)!==null&&a!==void 0?a:void 0,body:{provider:o,id_token:l,access_token:u,nonce:c,link_identity:!0,gotrue_meta_security:{captcha_token:s?.captchaToken}},xform:Zr}),{data:h,error:m}=f;return m?this._returnResult({data:{user:null,session:null},error:m}):!h||!h.session||!h.user?this._returnResult({data:{user:null,session:null},error:new Dn}):(h.session&&(await this._saveSession(h.session),await this._notifyAllSubscribers("USER_UPDATED",h.session)),this._returnResult({data:h,error:m}))}catch(n){if(await Tt(this.storage,`${this.storageKey}-code-verifier`),ve(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(t){try{return await this._useSession(async r=>{var a,n;let{data:i,error:s}=r;if(s)throw s;return await Ce(this.fetch,"DELETE",`${this.url}/user/identities/${t.identity_id}`,{headers:this.headers,jwt:(n=(a=i.session)===null||a===void 0?void 0:a.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(ve(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(t){let r="#_refreshAccessToken()";this._debug(r,"begin");try{let a=Date.now();return await PS(async n=>(n>0&&await RS(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await Ce(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:Zr})),(n,i)=>{let s=200*Math.pow(2,n);return i&&hg(i)&&Date.now()+s-aDate.now())?this._debug(n,"proactive refresh failed, access token still valid \u2014 preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:t,result:s,expiresAt:Date.now()+mS},(r=this.refreshingDeferred)===null||r===void 0||r.resolve(s),s}throw(a=this.refreshingDeferred)===null||a===void 0||a.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(t,r,a=!0){let n=`#_notifyAllSubscribers(${t})`;this._debug(n,"begin",r,`broadcast = ${a}`);try{this.broadcastChannel&&a&&this.broadcastChannel.postMessage({event:t,session:r});let i=[],s=Array.from(this.stateChangeEmitters.values()).map(async o=>{try{await o.callback(t,r)}catch(l){i.push(l)}});if(await Promise.all(s),i.length>0){for(let o=0;othis._autoRefreshTokenTick(),nn);this.autoRefreshTicker=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t);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 t=this.autoRefreshTicker;this.autoRefreshTicker=null,t&&clearInterval(t);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 dispose(){var t;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(t=this.broadcastChannel)===null||t===void 0||t.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{let t=Date.now();try{return await this._useSession(async r=>{let{data:{session:a}}=r;if(!a||!a.refresh_token||!a.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((a.expires_at*1e3-t)/nn);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${nn}ms, refresh threshold is ${Mo} ticks`),n<=Mo&&await this._callRefreshToken(a.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(t){if(t instanceof Kd)this._debug("auto refresh token tick lock not available");else throw t}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{let t=Date.now();try{await this._useSession(async r=>{let{data:{session:a}}=r;if(!a||!a.refresh_token||!a.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((a.expires_at*1e3-t)/nn);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${nn}ms, refresh threshold is ${Mo} ticks`),n<=Mo&&await this._callRefreshToken(a.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Yt()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(t){this._debug("#visibilityChangedCallback","error",t)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(t){console.error("_handleVisibilityChange",t)}}async _onVisibilityChanged(t){let r=`#_onVisibilityChanged(${t})`;if(this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken&&this._startAutoRefresh(),!t)if(await this.initializePromise,this.lock!=null)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()});else{if(document.visibilityState!=="visible"){this._debug(r,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(t,r,a){let n=[`provider=${encodeURIComponent(r)}`];if(a?.redirectTo&&n.push(`redirect_to=${encodeURIComponent(a.redirectTo)}`),a?.scopes&&n.push(`scopes=${encodeURIComponent(a.scopes)}`),this.flowType==="pkce"){let[i,s]=await _i(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(s)}`});n.push(o.toString())}if(a?.queryParams){let i=new URLSearchParams(a.queryParams);n.push(i.toString())}return a?.skipBrowserRedirect&&n.push(`skip_http_redirect=${a.skipBrowserRedirect}`),`${t}?${n.join("&")}`}async _unenroll(t){try{return await this._useSession(async r=>{var a;let{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await Ce(this.fetch,"DELETE",`${this.url}/factors/${t.factorId}`,{headers:this.headers,jwt:(a=n?.session)===null||a===void 0?void 0:a.access_token})})}catch(r){if(ve(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(t){try{return await this._useSession(async r=>{var a,n;let{data:i,error:s}=r;if(s)return this._returnResult({data:null,error:s});let o=Object.assign({friendly_name:t.friendlyName,factor_type:t.factorType},t.factorType==="phone"?{phone:t.phone}:t.factorType==="totp"?{issuer:t.issuer}:{}),{data:l,error:u}=await Ce(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(a=i?.session)===null||a===void 0?void 0:a.access_token});return u?this._returnResult({data:null,error:u}):(t.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(ve(r))return this._returnResult({data:null,error:r});throw r}}async _verify(t){let r=async()=>{try{return await this._useSession(async a=>{var n;let{data:i,error:s}=a;if(s)return this._returnResult({data:null,error:s});let o=Object.assign({challenge_id:t.challengeId},"webauthn"in t?{webauthn:Object.assign(Object.assign({},t.webauthn),{credential_response:t.webauthn.type==="create"?Cg(t.webauthn.credential_response):Ig(t.webauthn.credential_response)})}:{code:t.code}),{data:l,error:u}=await Ce(this.fetch,"POST",`${this.url}/factors/${t.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});return u?this._returnResult({data:null,error:u}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),this._returnResult({data:l,error:u}))})}catch(a){if(ve(a))return this._returnResult({data:null,error:a});throw a}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challenge(t){let r=async()=>{try{return await this._useSession(async a=>{var n;let{data:i,error:s}=a;if(s)return this._returnResult({data:null,error:s});let o=await Ce(this.fetch,"POST",`${this.url}/factors/${t.factorId}/challenge`,{body:t,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;let{data:l}=o;if(l.type!=="webauthn")return{data:l,error:null};switch(l.webauthn.type){case"create":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:Sg(l.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},l),{webauthn:Object.assign(Object.assign({},l.webauthn),{credential_options:Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:_g(l.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(a){if(ve(a))return this._returnResult({data:null,error:a});throw a}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,r):r()}async _challengeAndVerify(t){let{data:r,error:a}=await this._challenge({factorId:t.factorId});return a?this._returnResult({data:null,error:a}):await this._verify({factorId:t.factorId,challengeId:r.id,code:t.code})}async _listFactors(){var t;let{data:{user:r},error:a}=await this.getUser();if(a)return{data:null,error:a};let n={all:[],phone:[],totp:[],webauthn:[]};for(let i of(t=r?.factors)!==null&&t!==void 0?t:[])n.all.push(i),i.status==="verified"&&n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(t){var r,a,n,i;if(t)try{let{payload:m}=Qu(t),g=null;m.aal&&(g=m.aal);let p=g,{data:{user:y},error:w}=await this.getUser(t);if(w)return this._returnResult({data:null,error:w});((a=(r=y?.factors)===null||r===void 0?void 0:r.filter(_=>_.status==="verified"))!==null&&a!==void 0?a:[]).length>0&&(p="aal2");let x=m.amr||[];return{data:{currentLevel:g,nextLevel:p,currentAuthenticationMethods:x},error:null}}catch(m){if(ve(m))return this._returnResult({data:null,error:m});throw m}let{data:{session:s},error:o}=await this.getSession();if(o)return this._returnResult({data:null,error:o});if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:l}=Qu(s.access_token),u=null;l.aal&&(u=l.aal);let c=u;((i=(n=s.user.factors)===null||n===void 0?void 0:n.filter(m=>m.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(c="aal2");let h=l.amr||[];return{data:{currentLevel:u,nextLevel:c,currentAuthenticationMethods:h},error:null}}async _getAuthorizationDetails(t){try{return await this._useSession(async r=>{let{data:{session:a},error:n}=r;return n?this._returnResult({data:null,error:n}):a?await Ce(this.fetch,"GET",`${this.url}/oauth/authorizations/${t}`,{headers:this.headers,jwt:a.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new Lt})})}catch(r){if(ve(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(t,r){try{return await this._useSession(async a=>{let{data:{session:n},error:i}=a;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new Lt});let s=await Ce(this.fetch,"POST",`${this.url}/oauth/authorizations/${t}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:o=>({data:o,error:null})});return s.data&&s.data.redirect_url&&Yt()&&!r?.skipBrowserRedirect&&window.location.assign(s.data.redirect_url),s})}catch(a){if(ve(a))return this._returnResult({data:null,error:a});throw a}}async _denyAuthorization(t,r){try{return await this._useSession(async a=>{let{data:{session:n},error:i}=a;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new Lt});let s=await Ce(this.fetch,"POST",`${this.url}/oauth/authorizations/${t}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:o=>({data:o,error:null})});return s.data&&s.data.redirect_url&&Yt()&&!r?.skipBrowserRedirect&&window.location.assign(s.data.redirect_url),s})}catch(a){if(ve(a))return this._returnResult({data:null,error:a});throw a}}async _listOAuthGrants(){try{return await this._useSession(async t=>{let{data:{session:r},error:a}=t;return a?this._returnResult({data:null,error:a}):r?await Ce(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 Lt})})}catch(t){if(ve(t))return this._returnResult({data:null,error:t});throw t}}async _revokeOAuthGrant(t){try{return await this._useSession(async r=>{let{data:{session:a},error:n}=r;return n?this._returnResult({data:null,error:n}):a?(await Ce(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:a.access_token,query:{client_id:t.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Lt})})}catch(r){if(ve(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(t,r={keys:[]}){let a=r.keys.find(o=>o.kid===t);if(a)return a;let n=Date.now();if(a=this.jwks.keys.find(o=>o.kid===t),a&&this.jwks_cached_at+wS>n)return a;let{data:i,error:s}=await Ce(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(s)throw s;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=n,a=i.keys.find(o=>o.kid===t),!a)?null:a}async getClaims(t,r={}){try{let a=t;if(!a){let{data:m,error:g}=await this.getSession();if(g||!m.session)return this._returnResult({data:null,error:g});a=m.session.access_token}let{header:n,payload:i,signature:s,raw:{header:o,payload:l}}=Qu(a);if(!r?.allowExpired)try{DS(i.exp)}catch(m){throw new ki(m instanceof Error?m.message:"JWT validation failed")}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(a);if(m)throw m;return{data:{claims:i,header:n,signature:s},error:null}}let c=BS(n.alg),f=await crypto.subtle.importKey("jwk",u,c,!0,["verify"]);if(!await crypto.subtle.verify(c,f,s,LS(`${o}.${l}`)))throw new ki("Invalid JWT signature");return{data:{claims:i,header:n,signature:s},error:null}}catch(a){if(ve(a))return this._returnResult({data:null,error:a});throw a}}async signInWithPasskey(t){var r,a,n;Qr(this.experimental);try{if(!Zu())return this._returnResult({data:null,error:new vr("Browser does not support WebAuthn",null)});let{data:i,error:s}=await this._startPasskeyAuthentication({options:{captchaToken:(r=t?.options)===null||r===void 0?void 0:r.captchaToken}});if(s||!i)return this._returnResult({data:null,error:s});let o=_g(i.options),l=(n=(a=t?.options)===null||a===void 0?void 0:a.signal)!==null&&n!==void 0?n:Yd.createNewAbortSignal(),{data:u,error:c}=await Lg({publicKey:o,signal:l});if(c||!u)return this._returnResult({data:null,error:c??new vr("WebAuthn ceremony failed",null)});let f=Ig(u);return this._verifyPasskeyAuthentication({challengeId:i.challenge_id,credential:f})}catch(i){if(ve(i))return this._returnResult({data:null,error:i});throw i}}async registerPasskey(t){var r,a;Qr(this.experimental);try{if(!Zu())return this._returnResult({data:null,error:new vr("Browser does not support WebAuthn",null)});let{data:n,error:i}=await this._startPasskeyRegistration();if(i||!n)return this._returnResult({data:null,error:i});let s=Sg(n.options),o=(a=(r=t?.options)===null||r===void 0?void 0:r.signal)!==null&&a!==void 0?a:Yd.createNewAbortSignal(),{data:l,error:u}=await Eg({publicKey:s,signal:o});if(u||!l)return this._returnResult({data:null,error:u??new vr("WebAuthn ceremony failed",null)});let c=Cg(l);return this._verifyPasskeyRegistration({challengeId:n.challenge_id,credential:c})}catch(n){if(ve(n))return this._returnResult({data:null,error:n});throw n}}async _startPasskeyRegistration(){Qr(this.experimental);try{return await this._useSession(async t=>{let{data:{session:r},error:a}=t;if(a)return this._returnResult({data:null,error:a});if(!r)return this._returnResult({data:null,error:new Lt});let{data:n,error:i}=await Ce(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:r.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(t){if(ve(t))return this._returnResult({data:null,error:t});throw t}}async _verifyPasskeyRegistration(t){Qr(this.experimental);try{return await this._useSession(async r=>{let{data:{session:a},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!a)return this._returnResult({data:null,error:new Lt});let{data:i,error:s}=await Ce(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:a.access_token,body:{challenge_id:t.challengeId,credential:t.credential}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:i,error:null})})}catch(r){if(ve(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(t){var r;Qr(this.experimental);try{let{data:a,error:n}=await Ce(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(r=t?.options)===null||r===void 0?void 0:r.captchaToken}}});return n?this._returnResult({data:null,error:n}):this._returnResult({data:a,error:null})}catch(a){if(ve(a))return this._returnResult({data:null,error:a});throw a}}async _verifyPasskeyAuthentication(t){Qr(this.experimental);try{let{data:r,error:a}=await Ce(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:t.challengeId,credential:t.credential},xform:Zr});return a?this._returnResult({data:null,error:a}):(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:r,error:null}))}catch(r){if(ve(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){Qr(this.experimental);try{return await this._useSession(async t=>{let{data:{session:r},error:a}=t;if(a)return this._returnResult({data:null,error:a});if(!r)return this._returnResult({data:null,error:new Lt});let{data:n,error:i}=await Ce(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:s=>({data:s,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(t){if(ve(t))return this._returnResult({data:null,error:t});throw t}}async _updatePasskey(t){Qr(this.experimental);try{return await this._useSession(async r=>{let{data:{session:a},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!a)return this._returnResult({data:null,error:new Lt});let{data:i,error:s}=await Ce(this.fetch,"PATCH",`${this.url}/passkeys/${t.passkeyId}`,{headers:this.headers,jwt:a.access_token,body:{friendly_name:t.friendlyName}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:i,error:null})})}catch(r){if(ve(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(t){Qr(this.experimental);try{return await this._useSession(async r=>{let{data:{session:a},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!a)return this._returnResult({data:null,error:new Lt});let{error:i}=await Ce(this.fetch,"DELETE",`${this.url}/passkeys/${t.passkeyId}`,{headers:this.headers,jwt:a.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(r){if(ve(r))return this._returnResult({data:null,error:r});throw r}}};Qd.nextInstanceID={};var Tg=Qd;var H6=Tg,Ag=H6;var W6="2.108.2",ec="",t0;typeof Deno<"u"?(ec="deno",t0=(Zd=Deno.version)===null||Zd===void 0?void 0:Zd.deno):typeof document<"u"?ec="web":typeof navigator<"u"&&navigator.product==="ReactNative"?ec="react-native":(ec="node",t0=typeof process<"u"?(e0=process.version)===null||e0===void 0?void 0:e0.replace(/^v/,""):void 0);var Zd,e0,XS=[`runtime=${ec}`];t0&&XS.push(`runtime-version=${t0}`);var z6={"X-Client-Info":`supabase-js/${W6}; ${XS.join("; ")}`},j6={headers:z6},V6={schema:"public"},q6={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},$6={},G6={enabled:!1,respectSamplingDecision:!0};function K6(e,t,r,a){function n(i){return i instanceof r?i:new r(function(s){s(i)})}return new(r||(r=Promise))(function(i,s){function o(c){try{u(a.next(c))}catch(f){s(f)}}function l(c){try{u(a.throw(c))}catch(f){s(f)}}function u(c){c.done?i(c.value):n(c.value).then(o,l)}u((a=a.apply(e,t||[])).next())})}var bg=null,X6="@opentelemetry/api";function J6(){return bg===null&&(bg=import(X6).catch(()=>null)),bg}function Y6(){return K6(this,void 0,void 0,function*(){try{let e=yield J6();if(!e||!e.propagation||!e.context)return null;let t={};e.propagation.inject(e.context.active(),t);let r=t.traceparent;return r?{traceparent:r,tracestate:t.tracestate,baggage:t.baggage}:null}catch{return null}})}function Q6(e){if(!e||typeof e!="string")return null;let t=e.split("-");if(t.length!==4)return null;let[r,a,n,i]=t;if(r.length!==2||a.length!==32||n.length!==16||i.length!==2)return null;let s=/^[0-9a-f]+$/i;return!s.test(r)||!s.test(a)||!s.test(n)||!s.test(i)||a==="00000000000000000000000000000000"||n==="0000000000000000"?null:{version:r,traceId:a,parentId:n,traceFlags:i,isSampled:(parseInt(i,16)&1)===1}}function Z6(e,t){if(!e||!t||t.length===0)return!1;let r;if(e instanceof URL)r=e;else try{r=new URL(e)}catch{return!1}for(let a of t)try{if(typeof a=="string"){if(eB(r.hostname,a))return!0}else if(a instanceof RegExp){if(a.test(r.hostname))return!0}else if(typeof a=="function"&&a(r))return!0}catch{continue}return!1}function eB(e,t){if(t===e)return!0;if(t.startsWith("*.")){let r=t.slice(2);if(e.endsWith(r)&&(e===r||e.endsWith("."+r)))return!0}return!1}function tB(e){let t=[];try{let r=new URL(e);t.push(r.hostname)}catch{}return t.push("*.supabase.co","*.supabase.in"),t.push("localhost","127.0.0.1","[::1]"),t}function tc(e){"@babel/helpers - typeof";return tc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},tc(e)}function rB(e,t){if(tc(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var a=r.call(e,t||"default");if(tc(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function aB(e){var t=rB(e,"string");return tc(t)=="symbol"?t:t+""}function nB(e,t,r){return(t=aB(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function GS(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter(function(n){return Object.getOwnPropertyDescriptor(e,n).enumerable})),r.push.apply(r,a)}return r}function At(e){for(var t=1;te?(...t)=>e(...t):(...t)=>fetch(...t),sB=()=>Headers,oB=(e,t,r,a,n)=>{let i=iB(a),s=sB(),o=n?.enabled===!0,l=n?.respectSamplingDecision!==!1,u=o?tB(t):null;return async(c,f)=>{var h;let m=(h=await r())!==null&&h!==void 0?h:e,g=new s(f?.headers);if(g.has("apikey")||g.set("apikey",e),g.has("Authorization")||g.set("Authorization",`Bearer ${m}`),u){let p=await lB(c,u,l);p&&(p.traceparent&&!g.has("traceparent")&&g.set("traceparent",p.traceparent),p.tracestate&&!g.has("tracestate")&&g.set("tracestate",p.tracestate),p.baggage&&!g.has("baggage")&&g.set("baggage",p.baggage))}return i(c,At(At({},f),{},{headers:g}))}};async function lB(e,t,r){if(!Z6(typeof e=="string"||e instanceof URL?e:e.url,t))return null;let a=await Y6();if(!a||!a.traceparent)return null;if(r){let n=Q6(a.traceparent);if(n&&!n.isSampled)return null}return a}function KS(e){return typeof e=="boolean"?{enabled:e}:e}function uB(e){return e.endsWith("/")?e:e+"/"}function cB(e,t){var r,a,n,i,s,o;let{db:l,auth:u,realtime:c,global:f}=e,{db:h,auth:m,realtime:g,global:p}=t,y=KS(e.tracePropagation),w=KS(t.tracePropagation),v={db:At(At({},h),l),auth:At(At({},m),u),realtime:At(At({},g),c),storage:{},global:At(At(At({},p),f),{},{headers:At(At({},(r=p?.headers)!==null&&r!==void 0?r:{}),(a=f?.headers)!==null&&a!==void 0?a:{})}),tracePropagation:{enabled:(n=(i=y?.enabled)!==null&&i!==void 0?i:w?.enabled)!==null&&n!==void 0?n:!1,respectSamplingDecision:(s=(o=y?.respectSamplingDecision)!==null&&o!==void 0?o:w?.respectSamplingDecision)!==null&&s!==void 0?s:!0},accessToken:async()=>""};return e.accessToken?v.accessToken=e.accessToken:delete v.accessToken,v}function fB(e){let t=e?.trim();if(!t)throw new Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(uB(t))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var dB=class extends Ag{constructor(e){super(e)}},hB=class{constructor(e,t,r){var a,n;this.supabaseUrl=e,this.supabaseKey=t;let i=fB(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);let s=`sb-${i.hostname.split(".")[0]}-auth-token`,o={db:V6,realtime:$6,auth:At(At({},q6),{},{storageKey:s}),global:j6,tracePropagation:G6},l=cB(r??{},o);if(this.settings=l,this.storageKey=(a=l.auth.storageKey)!==null&&a!==void 0?a:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(c,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} 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=oB(t,e,this._getAccessToken.bind(this),l.global.fetch,l.tracePropagation),this.realtime=this._initRealtimeClient(At({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},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 qk(new URL("rest/v1",i).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new pS(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new Ru(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e=this,t,r;if(e.accessToken)return await e.accessToken();let{data:a}=await e.auth.getSession();return(t=(r=a.session)===null||r===void 0?void 0:r.access_token)!==null&&t!==void 0?t:e.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:a,userStorage:n,storageKey:i,flowType:s,lock:o,debug:l,throwOnError:u,experimental:c,lockAcquireTimeout:f,skipAutoInitialize:h},m,g){let p={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new dB({url:this.authUrl.href,headers:At(At({},p),m),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:a,userStorage:n,flowType:s,lock:o,debug:l,throwOnError:u,experimental:c,fetch:g,lockAcquireTimeout:f,skipAutoInitialize:h,hasCustomAuthorizationHeader:Object.keys(this.headers).some(y=>y.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new Do(this.realtimeUrl.href,At(At({},e),{},{params:At(At({},{apikey:this.supabaseKey}),e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",t?.access_token)})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},Fg=(e,t,r)=>new hB(e,t,r);function pB(){if(typeof window<"u")return!1;let e=globalThis.process;if(!e)return!1;let t=e.version;if(t==null)return!1;let r=t.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}pB()&&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 a0=zn(Fs());var JS=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),r0=(...e)=>e.filter((t,r,a)=>!!t&&a.indexOf(t)===r).join(" ");var rc=zn(Fs());var YS={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};var QS=(0,rc.forwardRef)(({color:e="currentColor",size:t=24,strokeWidth:r=2,absoluteStrokeWidth:a,className:n="",children:i,iconNode:s,...o},l)=>(0,rc.createElement)("svg",{ref:l,...YS,width:t,height:t,stroke:e,strokeWidth:a?Number(r)*24/Number(t):r,className:r0("lucide",n),...o},[...s.map(([u,c])=>(0,rc.createElement)(u,c)),...Array.isArray(i)?i:[i]]));var ce=(e,t)=>{let r=(0,a0.forwardRef)(({className:a,...n},i)=>(0,a0.createElement)(QS,{ref:i,iconNode:t,className:r0(`lucide-${JS(e)}`,a),...n}));return r.displayName=`${e}`,r};var ac=ce("AlarmClock",[["circle",{cx:"12",cy:"13",r:"8",key:"3y4lt7"}],["path",{d:"M12 9v4l2 2",key:"1c63tq"}],["path",{d:"M5 3 2 6",key:"18tl5t"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.38 18.7 4 21",key:"17xu3x"}],["path",{d:"M17.64 18.67 20 21",key:"kv2oe2"}]]);var ws=ce("Briefcase",[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]]);var ln=ce("Building2",[["path",{d:"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z",key:"1b4qmf"}],["path",{d:"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"i71pzd"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2",key:"10jefs"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"M10 10h4",key:"tcdvrf"}],["path",{d:"M10 14h4",key:"kelpxr"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);var nc=ce("Cake",[["path",{d:"M20 21v-8a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8",key:"1w3rig"}],["path",{d:"M4 16s.5-1 2-1 2.5 2 4 2 2.5-2 4-2 2.5 2 4 2 2-1 2-1",key:"n2jgmb"}],["path",{d:"M2 21h20",key:"1nyx9w"}],["path",{d:"M7 8v3",key:"1qtyvj"}],["path",{d:"M12 8v3",key:"hwp4zt"}],["path",{d:"M17 8v3",key:"1i6e5u"}],["path",{d:"M7 4h0.01",key:"hsw7lv"}],["path",{d:"M12 4h0.01",key:"1e3d8f"}],["path",{d:"M17 4h0.01",key:"p7cxgy"}]]);var Ci=ce("CalendarDays",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 18h.01",key:"lrp35t"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M16 18h.01",key:"kzsmim"}]]);var Ii=ce("CalendarPlus",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 13V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h8",key:"3spt84"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M16 19h6",key:"xwg31i"}],["path",{d:"M19 16v6",key:"tddt3s"}]]);var ic=ce("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);var Wo=ce("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);var Er=ce("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);var sc=ce("CircleDot",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]);var Ma=ce("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);var zo=ce("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);var jo=ce("Contact",[["path",{d:"M17 18a2 2 0 0 0-2-2H9a2 2 0 0 0-2 2",key:"1mghuy"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["circle",{cx:"12",cy:"10",r:"2",key:"1yojzk"}],["line",{x1:"8",x2:"8",y1:"2",y2:"4",key:"1ff9gb"}],["line",{x1:"16",x2:"16",y1:"2",y2:"4",key:"1ufoma"}]]);var Nn=ce("CreditCard",[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]]);var ks=ce("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);var oc=ce("Droplet",[["path",{d:"M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-.5 2.5-2 4.9-4 6.5C6 11.1 5 13 5 15a7 7 0 0 0 7 7z",key:"c7niix"}]]);var Vo=ce("EyeOff",[["path",{d:"M9.88 9.88a3 3 0 1 0 4.24 4.24",key:"1jxqfv"}],["path",{d:"M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68",key:"9wicm4"}],["path",{d:"M6.61 6.61A13.526 13.526 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 5.39-1.61",key:"1jreej"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);var qo=ce("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);var lc=ce("FileSpreadsheet",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]]);var Ss=ce("FileText",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);var $o=ce("Inbox",[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]]);var _s=ce("KeyRound",[["path",{d:"M2 18v3c0 .6.4 1 1 1h4v-3h3v-3h2l1.4-1.4a6.5 6.5 0 1 0-4-4Z",key:"167ctg"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]]);var Go=ce("Landmark",[["line",{x1:"3",x2:"21",y1:"22",y2:"22",key:"j8o0r"}],["line",{x1:"6",x2:"6",y1:"18",y2:"11",key:"10tf0k"}],["line",{x1:"10",x2:"10",y1:"18",y2:"11",key:"54lgf6"}],["line",{x1:"14",x2:"14",y1:"18",y2:"11",key:"380y"}],["line",{x1:"18",x2:"18",y1:"18",y2:"11",key:"1kevvc"}],["polygon",{points:"12 2 20 7 4 7",key:"jkujk7"}]]);var Ko=ce("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);var Cs=ce("LifeBuoy",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.93 4.93 4.24 4.24",key:"1ymg45"}],["path",{d:"m14.83 9.17 4.24-4.24",key:"1cb5xl"}],["path",{d:"m14.83 14.83 4.24 4.24",key:"q42g0n"}],["path",{d:"m9.17 14.83-4.24 4.24",key:"bqpfvv"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}]]);var Xo=ce("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);var uc=ce("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);var cc=ce("LogIn",[["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}],["polyline",{points:"10 17 15 12 10 7",key:"1ail0h"}],["line",{x1:"15",x2:"3",y1:"12",y2:"12",key:"v6grx8"}]]);var Jo=ce("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);var Is=ce("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);var Ei=ce("MapPin",[["path",{d:"M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z",key:"2oe9fu"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);var fc=ce("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);var dc=ce("Navigation",[["polygon",{points:"3 11 22 2 13 21 11 13 3 11",key:"1ltx0t"}]]);var hc=ce("Pencil",[["path",{d:"M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z",key:"5qss01"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);var Es=ce("Phone",[["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);var Ls=ce("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);var pc=ce("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);var Li=ce("ShieldCheck",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);var Nr=ce("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);var Mn=ce("TrendingUp",[["polyline",{points:"22 7 13.5 15.5 8.5 10.5 2 17",key:"126l90"}],["polyline",{points:"16 7 22 7 22 13",key:"kwv8wd"}]]);var mc=ce("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);var un=ce("UserCheck",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["polyline",{points:"16 11 18 13 22 9",key:"1pwet4"}]]);var gc=ce("UserPlus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);var Ti=ce("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);var ea=ce("Video",[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]]);var Ai=ce("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);var d=zn(xc()),I={bg:"#F4F5F8",surface:"#FFFFFF",ink:"#101828",sub:"#5A6678",faint:"#98A2B3",border:"#E6E8EE",line:"#EFF1F5",brand:"#4338CA",brandSoft:"#EEF0FF",brandInk:"#312E81",green:"#12B76A",greenSoft:"#E7F8F0",red:"#F04438",redSoft:"#FEECEB",amber:"#F79009",amberSoft:"#FEF3E2",sky:"#0BA5EC",skySoft:"#E8F6FE"},cn='ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Inter, sans-serif',Be='ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',Og="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAAB/lBMVEWaoqjf4ugNEyUDDiMQFB9cXV2ztLje3+KnyswDCyJNV2aZnqWWl5nc4OgbHWIAAP8/TmV/Pz9aWlqCgn+hodC3vsm8v8L/AADAv8bX2uIfMEh/f59rdYJ/hY1///+ZZmaJdYmAf4a5vcT/AP8AAAADFS37/PwBChrGy9OkqrXQ09mRmqazusMBDSGrsrybo67m6OspM0W8wsvY2+IaJDAwMjQlKjH+/v5lanEKExxQWGaEipSNk5vd4eVxeYVFSlNuc3pRVVm+vr46RFQkLkF8g5BbY3CqqavGy9F/f3/FydDN0dbFys/Fys/Jyc3FydDIytDQ09e8xMvQ1tchIh2w///P0df6+/rO0teqqv/P0tj4+fnO09f5+vm1vMW7w8yZmJm/v/+7w8z2+PkdK0Gxu8y7xMzj5+y8w8vl5+v19vkAAD9/f//m5ugAAFUIFioA//9HTGC5urq6wsrS5OTi5+z4+fkHFCoDEy03Oz5CQj9jboDQ0OXn6+/p7O8AAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzwH9GAAAAgHRSTlMSoBea5Phf+AthWJbwaxgB/wQF/wVHlQH/Lf8Ix4ICBQ3/ygEA/v7+/v/+/v7+/v/+/v7+/v7/Av7///7//v/+/v8E///+/wfQAnLSUZINsDAvTxL/A5HSsANwkFG2Lm8KBI1U/xTJsbJOLAQCDgMTAf8xNBEpdC1WC///DWzJQ0Owkr0AAClXSURBVHjazZ2Hn9tIdqA5yZttn8OdfTkQrEIhB6IRCJBsNtlqxdHkWU3Ou7c5e3e9/tf9XiUUQABkS1rv4Ce12C02gQ8vV3iYzZ/zcYHH0Q86Pzp6y/M4Zs/zw270BV788Ief/ubJk/fff/9tecDLJ09+8+mnP7xoab6WIOrCLn746ZP3315MHG+//0ThXD4/mOcDcnF5jf/8+AdP3l+cebwNNPxX37z4uoBcXOKlXPzghT+Fi1sd4Z+efMp/9eOLvzyIUKhf/+uXCBHicTYGf2v45b/+Wn/MXw7k5hK+/Op7SBGqQ10otQOf8ldOeWj4pQduaHLIt4d/kix/MZDrCzSLF8LOIS+ziSyPeFaGKBtCMvyhS0jUk4n8nfDL7/0RUN79i4CgkT7+3jfCsE6SpEfCMuJ5BP8iSONZHGDlWcTWFG6tUeo6DJMX/vmZxPK0IG/C38fvsLBmCT9a5cKrjDzLivImj7gkFEhOLG+tQBqSHjQIvxXJC+8hyt/8R4Kgs73/ThIyxiRG6NsLpScL17O8Pb9cZoLsAM8TZrNYEYvsFtJIxL2Au3LvPlzPu/9hICj/+/fgzHjA+cMwbiIv1Qq/sOEq49YWNoSDhKllWYSbPaJaXsNBKh++4P2AD6vrex/+N3Gf/vwgF6BV/3iHqaNehHZpEa7+CsQnlpU2gcs6IBR+anlc2ZiFTCv4BXy5DpIFoIj7ktx5Dc7xoz8/CEjjg68oo1Ry0H3kgVFbuyoxbASuGX5qZTlrQUBOn6Xc3EO0IctzEaQCNSTZnoWJvDOA8o+QvPzszwsCWvX5J4ghQcK9hUqS5hAh2sCwYBF4LLxWYrkaZE+8soG/i0WJ/2dZDH8lwrfBJ1SaBGTz1Qe31q/bgUD8+1BgaBC495GTGGFBqJNfHXYZXmGkQUrP2yRw2WEF3+fwP/hmMHqvRC9ASgUCn53QT2bz2yVhs9tp1S+/kBjA4cKZE5rChYAMQtqsWS9BCWkJthIuNsJrRWgVIIwdXDXdePhrIVeyJPQBheShBoGP/+K12wlldhtxXH9CaRyLE7m7Ky6SEkQSh0EJarRf9FMtx0MQ4X7Bqj1/4aNWkWqx404L3QLB+1Cv4edxzfVK3in6ySVqwHMHAev45R0WxwKEBeg+4RaGAcY+sHcw7lyDsKixQQVXIK6diiPoyhjKJSU5umLPAQC8DS5YRwiAZAWfl7iJRIkZ+K//cvG8Qd5F66CxBnExKPhwCxNUDuCImrg1EZAEt3UuBAnSECvjkRCjO+NOi7vhNIaIGNoAUoEPtq0SLESQgFA+Olsos3PV6vNHzHVjTZLs4cw7sJKwwaBR2txbKZIcnBY6ZZL5GNkti5s8TxnDcldr8aCrsKyDm8TgvDwbJAK5ZqbcSQxC+eW5JLMz1eo1Sl0Bwm8VyAQk4YEyhK6F+sMjYbCmCyESO19H0S4P+HchRGzUN9/XxgMEEfxCxIUJAoN7YUUJ3pXUO0iJAIhL6f35xc3zAoEPuktjwUFpXjFlJVYKtlmj84SEhEFk5PZ+TlV1IJBpLdC+8h3heuhZfli7+JmtQIAkZg/O815ngFzPP3oAaiVAgohkVFuJtwGRQFggjV/i1ZD1mSCJv4EEZce9s12ivUU+fNQaosqqpi0I3L7k0Vnea3aOedwRHEBCD3CqPIEosufBGW4jo3gd3G1dNfQWte6CgsvOeQzybZ8BB/qIXdKRCBzs3gfzj58d5B/mHygO/sl41U7t85QcrQMUu/RSsGvrYIeLxbkg3C3Q3HJVQgBpG/sM70xCuxxAwl6bP3xWkG/OX2PU9zlH4FCX7THtwAyLpM4O6466DkAcu4qZdbiM7H6w2m9yODbN3rFjFvYHH5gurMD/HeBDG6VY6FMUCQWSy2cDuUR3JTnsNAXdopGQBSkpD4YQ1tk6j8MORUiDpsSqvXNAmI8Oez8xCva2RmQYStBzqcgeg/fwKQfxKbt7imR2jjx8wQGiANcecNtIKwjAdQnecl1jnVrrJD50q3WKSbxIcbsHFvIQO+3aHHvAI6kxshIMJYojgJzYViTJKZJJkIeSw4dPstFJNXCCBNIK7yoGDsiMrojVJEktRx/g4vw84/d+6vCIl5YOM1ngPjTo/EKVNMbMtogm8U+TzKb1SnD4fhxwDoaBxEXNsjlH6KxjrLhrHAgBWeSpdwJCw3i8MFQoSUgx528SrVpuCgKCNwbUR5CTJLOprB05bM7h4MkrnvrGDAIHeitZz/Hhh2+A26ki6zwIzZJuqESp62SFDmTnhlIimDjsuIsEEl+SPHwakIfz+4y6isPjHykzxjVmJ3Vb0CXhIj5Y5FYY/IB60ecoqJzuDm6QVdUoE4YOMUK7hNOi7/JtlyYfTpDMxuVxH2on29bygJMEIs2ivsgk9PhDCBi3p1AorhgPAslWeJYSAiLDYthzKBUkFJXLhnhyf1y7ZqN5yasUOQDERY4UbSR1BUnSYPWgStMQ4tpTYoj7U9JFzQdRQsoFQZMD/zywdEnCdcvmkfHidiA/mj+8x6iNIK6PnxWg1/UiV6W+VqUwWMON8tgChAcW6bx4RUZ8spUzUebWdYP1Gq8MUg99VmxHIDNu7jZEVPbqWAY5DHJx/fmdhHMgyR71NF7hKXey0A3sRI4++NGQbXQDITEj4xALuXJCKRRnl6y4XqHbSsEs7UMsQICEsjsPf3ZzC5DL+aMEHJYA8eNmRSGScA1eq6EH/rdmB28EwyKF5PH4gDZ/XRDONBRaSikUljg4KLaH82MO4bgiT+EcNriuOx8PD3QPgnw8v5swN1Ag6Mgx49lzW9SDA5TVdjSkVfLGE65UwENwfMviABgrxYujX8psToLDGh5m2JBq7QhZy3RLgATguh7wAfSzQN5FhxVLDk7ii9ytQZlv5HgNZWDzXk/ZLaI5uHFY/KIxtEkOvNuWJOn9stfUNSdhJQZ5IKG7nawfpGrZQTyWds2GCtvX4eNsDuJLicgs9A94eluQJHRN+nkUVx6uRp40bYLiEAKRHBYXVCEMpvsBO8pJKMOq58CT37gHAo5s2OBnQ3ObYCCuKRBZjgAJnGEv9Kp2M3KEQaQN8H88oUeoV8QquGTEOCqAFJ6nMmJTvVJbZPEJkpRU5/E8jggSyITv/GrATGYDhn43oXEQSApDIlhBl40ofGqnoxmtU1K3HgGEIOBqC0uJSeSMxKD2OupViVGtJId7UJocUiSgXAzM5PI0CERCrliBto8WBA5p6sl+yNtKW5b3XmmUMHgiUxhPyq6wlJZ1BEtyQcJy+IUNdTsktlSu5P6xwfdBLt798T1ITQLlskwbUWNa4jR9EG3anIN/1SAWOmM+WiKvvCj0b3q9jypl/nsgkRsfcaDnAjt6eHNzAuRy/gB0JxgEcRUIupUeB/qoQoIUHMTjoU/ZuBAKD+9S9YpWkH0Scbcaf0AgAAKeK3l0lKrMjhULEhxHkwyBdDk8abSevFZBReS9Rn3CF/w/hUD4uzSGNCjzAwVJbNq6a4II5bqeAvnZ9Zt3QLGcFsP2j0B68lBWa/hYCaKlwb0tBwHcVF62EoaQZodkLUYeNIffBUHlog97nmvWy93vCsVqQY5sBF3jkVpxFAWiQqGII4rGEqqmg7rCED/2+jLpkPRAAooBfgLkRxgKuUAGJcKH/lhDjs3cjHiCQ/xLLKKEo9SstRiipXLsuw6Ma1YrEl8YrABxfHYUFmfd3OQROL8AQSSK27MRl+2P5EFIF0REdatjKcIFtyBCEtphH9k8aVhsgACHYJESCSCPufP/RkGu54+B1BccSOLvS6yXtXxjlzpD8UOC8NChVM0i2gkT4RA80uZibeTxdDzpalfFOqrluofG1RwoErD3i1EQsHTqtCD2kiwr2yCBItc7UqzW+YhI6Bk2IjWszUekAJTLSjvxtHPYzARx1iQNfA3ioEg+v7kYBIEqPekIxMXoatmuoVpRj8MTUdtrb7QGsbTtCC1SohJE6rqJqaQdkUSxmWpBYke2rgIRIrk7HwG5lgKRKL6Twh07GLpFy6E8UYZn+VLWuMLa8eeFzum1exOZpWcUjUS6vY7rakGgtoNLKVa+BkGRdFzwzIjpQiBKIoFfFmm6NIydVgOJicg42sBG1KxbIcr1opWSVjstImKZJXCvZiYNNZxvVKTFWoNwkdRmZdKC3FzfMy0ksFdWmqWNq0liP/UGQYhlRjhiXK2ybo9PnxAtF0+5Kkvm+4UQcK9qDKh2Wm6F9lT50kaESNjrrUhmrUDeA4G4Bsi6yNK1GGnkJHQ3UEhZrZ0ambmnSnMtM0/VVIJJk0gXJ+9Er5CPaFvoulucZlQgjrKSyyOQm/mdhDF4iySxqwIEUrkahDb97E6qdW/uwNNXjv/ulCVEOqfyiFnBcCxZKPfHY1rlwtG1NE2Lva/us4OxhH1Ti2SmXdZ7CQb1FmQNFrJ2bQUS+/1ROKlXRVdGWJ9HAiLKHTdxS3hjWtoJXR2WSp/ajLlz7ccDS7YhktLKrMjWII4LIvm+FslMx5B3pEBkXAedTFEgEsSPS3I0WCI1pOiViZZjb/IGTpQkCYU/EIjFWDfzq7wsnUYrodcpRo6nI8Bz6STeXaFIGl+DBBC9713/qAtyAUGdsdjRIOCysnTn+6pIjJ2hOZvOwBvmtUIMLKnrWlZ68IcvyhAVrDjcqsy4uknDVyOTxyNe3ipuSbZWVkTa/zoOlKvsPVUrzpSpvyV8r9IsHkMaaeoIEnkDIOrMBVeYresIMbQriNRyn3bZD+VkCfWDyi9JGwe9geDOB2n1sJaPIrGqlgTN/ZFKHWdSIH/EMwVaIv7BytII8k2JEu+9gXE4ruGFyskJTsIlBsDxQVsyXNK5bocqiKjlj4cgm1gXiO46zYqtrwQiPfD8xgARvldoloMeIcjAZW3QQqSNXHkD44kqYEgTxhlZdv5Bw8YM50dDKuJIfV2OuBjes8BWHGjutTJ3JRE0dVsJxLEbEMiyHUiJmyGBqMpD0bjJJEf/P2niem1AHxjmUiLRBWKwBHPf+BrEhk+5J3cIzEQMwYKKOlqz7DWA5H5bWX02DCLHEESaW7YcfESVaTsxDYYZr5KfY3noEXOs+1gkbX2ICl/sbK1aXLdkgTUTmvX9GoLISoOAWWUppmi+mOpphofcOzViShNzKZ8Y5VZL5cPEMHlDJKqeHM62tJWoQhfNPa20bq2geE/eEro1E5p1DzVLgTh2DkFk57c1e+RZIySeKrotOzE9E7ja/lqOUM7Yak2D99gyR1ZL6Yemga6kRPB6IhDJQevWis8t/4pn8zMdRKRmIQq8P7U2rirb3WpwZo2Y9VLqJnLaZARDwtSGF0YS1yKm3xicm9vHXCD4J4fovmytHXSLJiKUzPiC/e/X4LNWGgQlmDl6/AEnLMZApETIOqHmMbmyJkwMGkhneBjyPEJGQHauArGdjIcSfc9Bt2qhWzPts3wNYudFZq1bDmd4PtbI2nHIlrYXR89cHoTHQRWWY6olJ0PFGIoPXsjKNciK+62HUrVu5g/baMg1i7/b1yAHbwyk0Ll7ZUqkvsVGq4p4RhEzeCavjNWglt9g5hi0VsCU35qJaNgxkVXGfYOYVYC/6ahE1HAQIUFyrmL1Dld9jpj2HTxVaru2RHH4tbUkYGkQE9+UIG+h8620Zm0giOz0IPaIqasRNpFzWbEJcqutb2pUldeQI1Pxe14W8Stag5EYuoUO+B10WzOcaoMaVzlfBMFoeNBTb25JxkAKPSh3ZXCwW0lkkelRSG9sWREpXcUBfisF++0YCeRbFwAinC8LFEgAiUCW7pVEfP/KmzJ2PntA8tr0WcltQLZE11Qj/hdXO+mhX6zdl63/dZgcqkOQ9+quiYAWLoM2iIytIpFVOR8Jcrve9zYgNmcQIBO6pUDsJTrgrpFg6T6TJmJEEUwYDedbetaUjXDH2RjOF3XrViIp5UjeFAj6LTkZugaR5EHHSLAomcn8pI0iAdaGB18PxkejIHxIGmv0Rkc4Jv/eykpynWV5I+eCNEVKJHC5kWiQysek5OH8YnbBM98kaEEgn0n3GsQZXaCkR6T1QsQ2wb0dyUquHvC80VVGjkyYAnvfMZKVjCQIwm3d0baOnrrNT9yGjH22mIUqSB5SWc4+tcHLUnF8HaHX6MyPR5KVBnFQDPfnlwCCKTxrbR2HT6LW1ksyusQSA0hBLMrrEC4RvjyR3d5ObOl4R2+aV+rpEZ7R7pUDXq3g5MmD+cPZw/lbqBkrIxym1tYOTpmIHusFzyv1KWyTQl5Z3SIqpkQtZhkBifTMm11aadGGxIqKkDi7nr/TcVr4PuugQZyJVXyivPNV/t5LcG9lJzmZNhHTSCCVL8oWBKfd792A17rhTksnKAFmjI0CcffjN0mEkbUcq+JLXxcLxsJvqPR2PPHFPSUshC96vT8h0yDaSIS17+yu25oByDVqhl0ZTosPHkmQ3JtYV4lfNlTOWvvUBycOOmuv7Mr3w8WAasGZfHtTbTa2/92qquDdq+/aq+rvq01WEG9CtSzvoEF4wNY2XfEk5RcA8gueoFSm00odDVJOgKBE0uVyuV5vt/l2u16v4ZssWuKRLdfZNm+PLT/4f+CXNzI4xBc4iuKN5YnVtt5agwTcrTqm/03+CkDuJx3vW6XotNT8tBudAIHr+v16+8qmQhJ+jVkm/xk6lqOHdUIikfK/4LbMJIX73xpB7tYdkH2KObxyv+7VxGcLEBTHZmVvpEyiKFo+zSFAxi0ytbXbWqdgxS0IZlv/WYLQlQaBYgTS5EBl8ZOLjxFku0YO8Lbc0YNfD8o0EjI5vlr8UbS8uoqiK/hyJRWNH4UxoD14BArELzvZFgd5ACAPwg4IjlOUermWcwokqn7/ymaFm2DYP8GZ0PqiLMLjSsvmZXW5kXFc6Rf8fzdiGnXibI4GOVid2orysezZ/FHYyX1LWVUJiVTTS6zTdGtvQR5y/w4KxDmk7UVGGd70VZVxLzByXCGInZ3yv3sjkKRW2aaNMYDcQZBOnYsggCutfXCI0eDIskP8yt8LkOSfkKOqDAwB4i8WVXEKhEZkel26EUhQ+w0QF5IIBLnTBdmCRDa2XPkwDSI2KIGN+Nj0gQIHxIa8c8HZMstRWiCXURCugGKKYcIFe3/QIE03kecgfzfjc6DuUWAPpkaChDiiFDMtBiC2S6lrO1W1b5qOQBCENxDJ3+haSEci8Kb1gq+yyNJzIuL+GIR+NHuxB7IDxd9r1RqPh9HfliXOuyYQDqsA/RViNOVV915nGQ/wfjYOgu/a4viWFUWffTaR/yoQLNsjs7QCkOvZv9zpplq7VICcCOxRnu/+NiKkCrfLdQ4qVTUNbtSLro4ukXsCkM0EyBs5doQAj9zsxyJwFyQ1QOwREEsM3J8AqcIFLXcWCcI8W243G6Q4lOU669/rSmRZ/2dCJNmyqBYuAWUF6bknJIITzhCz+yCXs//FQfYdiVTK/Y6BiIYzrEwtt24guJfy+HmU9TjWrkxv16MkGA3tBSPpjomxiFMgq9QcNuVZI0jkpgcik1/ptUZAyEoMd2YZTTBIrNc/h/Rkt4uyvu91qKxPVvDd1RgIuOgws3y1Q/yURHjV3let/9RVLSeH27sKThg7gXNiBbiOWOLgrQYG7oCuet6olPVWSFEk2dXVoGYtl9hDAftCOFD2eidAAudQrkunL5E+CBIEp0CwzcEBSqlNmVA/M+34yuQA36tAYhRJlo04LdTUQ44+wefdeCaqdnlpwRHIvKta7dqHSWOPF3aJTRCahMY7qf292w0gb+QsViBCJCMgGDQr7Cr088OCnjL2oJ1ob0vE635ANFbVTAVECsLAZjpOQtmWZ1JXVz0QzLJ8GmvVYna2HLJ3+Okb6NrsDVp6VDNvMiD2OSAg4vDgRydA/jDyqTQsD4tFvI0TmjSZLKSu+ia8xx2YCoQmOb7xylTDK1mF+bwFCXw9RC4dMfZ8TCIc5H/3k0bHXGRq+yO5FrHprlk4UZlA5um3lQeq19WVLAWzEteJtiBcuXgJIuqRrK1S+DjFOq0WeRTY5ETSeAQCpS4mjV/haNCIRMbSeFL5uz2NOAhNVsuhKjZbh12QOKTL43dB0Z4JZ77epXFz5Yy5370hEeNiV5DGC5BuYdUVyVhh5ZX+buVEEW49pixxV5t8vczeKN6QpfkbRZHlEPtx6bY2dpos6DYripdVAY9vh/xmJYdbol1kN58FY/7FGbaRFR+he6RAnNWgatnBWOob7FbBf40iOT7KR7Wov6ryV/hoSV75qC1MgyzUHCm1+TDF+ve8QraNQbww3V3ZTbZKvclS90giK7NmZ2MgY9NVXl5WLNrppjJDUzshSwAkUSB4t2y1kGBg9C5Mo13Y7EasUg8+6FWmncGH7+Bw0BTI2HCQd1XuwdhT1eeHDUyjB4Efg2GooTla7fdNBUbDhocgmRXZi0M5dsLItPUOiBrX+kVnBlGHw1Pp767COXI1mdu/NnRmDgg0ViAJc/ZIwqexBwfqKcFPHDsfDtD5gyB6gO4aX9jVQFyfrnUhLWKFOwyCo/HAgUvG5P/UQbPnRzhG4hf4Zaxw9w5y0UAfRAyZ4tjvDbYIOAokp6ZCsfPaYpHZyZCJAEdNcduGqxFD33YaYGko/u/Q2gh7Ce/KRmd69vGwRGSGMp9dzO91phW6KH4wWkUTIFk6yYCJ4M/APdluzxrqqqkAZDHsHKo15IxkYlqhlYjjdOMhn1boT/TgWhTbbkUSTYxiuutmAARjBsQQNzx2AFXDG2pCBnasXPnaTsfPddXuseKX5xjjc3xaFyRyN+y4rcCp8jI4ZxxFLAo6mjAU34f+wm8qQ4VYCXV+E6o4PzhLbU1Nval53fKwd9rJ0JUYMX04u+DD8Z1ZXUJIW7VPjjXiOsb+fGEoBRSGeZQuKzuU3X936dU6bt9zJK8dmR6eUyBOQcjS6U6G3uWToZfcbbVzb9siLTZ69DeYHP3N+NrRDoiehHPEAv+XbcAQq+WzVdsfiR0trpkcaHQUiN/A5UXmYhSK8zwXuF4L597cViIbKy229hlGgoO1wv+yjkD4P1WmN4KvaKFWQ8n8EN92FEamBJLpDe24Pcc6tCB8VGuGIJc8kW+tHad6cN3g9LIzJZJ9H0Qsn7MzOSnIt+sWRGyDwddL2YiuH99XkyB6CQeuz0zTfXcJx535DV+LcrezqMbBZcKpc2IhoAKRaxkNELzdW7lTxJMLC+RmaY9/U8p0q2/rU+ep9IpZiAdp5vRnRy75WpRXu0kKru0icl4Xf31Kt4gl0kZ9VfjCTtXi006DrXYlvz20/mxK8ClupxRrmHGf164de8AEpRbLnObc2ntrM6NKgYBukakOU2IxY2ioVi43LOFVp+vtGr7JynKdqqWk8H3us6O1D5POMVatEuwqSknpd0yEPRQgF70lA0GVO7YdnKlbUS+QLNsdV9ZGqBwT/0tz/kOxeWZ5vBpl4natYrXMFJdj5+1yrRXO8tyTSwEvZUlihPa21rXH1mHrqV2epTBjMUZR8M3qGWaVK4iBDnWrcltWLtz3SO+jDHs+i0z6rHb3tBh3c8wVzLwFBF8u+2pnuazcUamaV5yY7SERM61drbVc2ot6tcal7LijxuIvooot4rVYr5aGA+sBx0Dy2DdAzGwrwFL7vlwuO7+46Sw9C4zt02IFdDopEm4lobnWEjFwhDvtjnQB0NoObb5lLOsLZOpmBW4PxFiJTfmyM7USm+eNThdEtxOx43IShPfs1LrFE5zQL7P0qj8WDN+AXPJwZfVa+qNhnTD1nkQCQ7PeMRf5J4YDNkvdtsHWxGInnnC1je1xVH1jcYyMD0CKl1d8AC+FehYKMtl1Xa/GnjQR5wjE1Kz6Pb02fo7NtFjir44lIvfB7CZFQlZJ67coWeIAgwuXfHykO5FtZYR2FYtMLt7w/WEbEc73dS0RudCUOkMgfP/IVAqMy50w45IZe0gybjD1JrU+6wxqp1a0D5UhGbYeZpMW4lUx3whp9nxQEom5Zl0bG2EeG37rGOSUByYZH4Tgzb3DwpKWTxs0iZQrF/qs3Na5b0GMgBgRb0qxotjsuNMFoW2jAblZ7OKe2uCqQOx2KfZJkXgkE1lwHDOXWLG+YL/ZRlmaRVG5NwtGALGNUDgtkL3aLGaCCBSe+b5ugrzJV2jSQYmIbeAnrISktmjsF0e4LLszTEePRrLAKDI1Ark8wRHFR51qtExQs97qbN+TW0jsERDsuWBNWgn6Lsd37QapsD+dvPQDn9rhI72ludUClKkCTaQbQiY9FrqsLohh6wHeo8dya+hMPU7kHa1bXe8rG6PQctredQcEyAubhLeCQZhNm/xuOsvhvbYvyqRAjF3HR0OmYhHKTW/T8X1t7kdxhItkeuWWTNpFx40ti9WOGKrbapnmvSGyQd3IvtbjfeCDAZGaW/PVNvAfQZpCzf3sfRA6nXER1TkAL0x2c8SsOCKitxNZd7aMeKTdgDj1sQ1zR0FEBq925s90pwRt7sMg7nTxTtpGIh5Zt7v4HKVZtLPIt1tvjVs6jd0hW9e+962jjfnzi0tl7gMgvHPxZF3SkuDF5bqxdYJXDfXtqpOQmN3bJi2duu6w0wocu43qveYVKJJ4HOSEcnX6ypGSKRTI0DGN7CZWbTvNSX3N2VELula1Yr4m/t2j5hW8qaH0wMMgbrw7SaJlEvkJNxQIjlWRteEvfIWYDUEnPzBSPXf8ARA+CP94oJ2IIZKuA277UsW+daZ2YWOXTcxRWGfkx846gpteMenSARAV2XsCMUBEn8nWSo4l4tKVd4LE81qxZI2LHQeMWUJe6ZJWJNOfhv2c3DEb4RbyeLDlDhcJba1kAMTtdwMc3AlntEBbV77K72Xbb2JwTH/UwejmdJzGx6zX9MxsgnTz43tcJMGRaumeZ3RNTqmXp7s2iW3E0aZaVdulZTZ1Oq1WZMfa3m1HNiJdlvkcjNm835eKjgYS3rstmiZRliIbmnndJkeGnU9/ConMHnTHIEcC6bZuu+bZvO+MgQAJdbMTbaNNELPtiWHiJzm81GUGiVFW2aZAxkHEDv1gAiSmvnWaRG/ZV32dOj73NIflM/MxEbrBgO4KyPfjX061N+T7j50J1cIW+2eQEN0p1yN9itMcdhL3QUyRiLT33ak+jTfogrudM3utM88hMRq1tb3BzvS6vK17oh7c4R5JJOCdM/nWw6kWoMLe40mQc0g8sRvEa0HaVuXWaXnoB8IcS0Ra+t1+M9Oj7rLY1hvt3Wid6XZbTvLH2pxqFE9IL2icqVa46CShAyC2Fgmm73devz4FcvGYK9eosYt2ppM5Pd73yKkicnREK7s8sSkhU4spuiD6tqJitQXuRONi0VMvnmgCKjZ+TkRGz9tBlljnVqcbGhZeJS4XKMc3gGL8YN1nDR1FdpcOPvhioCe2UK5pEMqSsblFz8IHP+BkiMJqZQA1F/wfy8dQdNfiLojJ4cO5h3rHzwaehC08VzAJwrtJD7TcItYB7rq/JsOHJ+aoWZMOmAs2XG+b3cTDkZ3yNuXnNPcWXbGH+sZ3QWht9w3lsMlxrUnow794bOBo5LFR3+Q5jv8mK/imu86FpHbIJiTCQdDVDD7zYjb4QIK7OBARDCSNBgijNS27MeE2/VDUU2sNtaKh2RhtEMSldLBH+egjCcBMqB8MxxGjL1vodLSdhZsDf9gT/yOPTb7ZdL5V3zAThFirsGanQLiBXA4+unI2/LCLP0JCT33db31QtcSzR0pjKQwLLXL+QVsQj5RxyDocgyBUzU+d/dgO3jyetoPYYyCsDp02sWdhVlii9W2K26UKK8PXGd86labixzijmIll6QqEZE5YM8amJSIMZOwBJLOxB9v8Ej4wnlIt1eEhTPYqzicAUqzDPUlJHm7haxWui7TwwyVSxoVVRKEDP9iGOUk1CEkbfGZycgJEcIw+Ymw2+uin+wy3sk14Lf2woZBthKnUcMXFdrEChA2uySCrBS41oguUwIIhyMImALLYAIiwEWKBsYRJMsjRAQFDZ3dHH183G3+IFTYsd4/7lB+DsHBB+UOTFEiBjwUtAccECVmRWhyEaBAMOwySgDppSSg9emqd5nhw+4cN4eOfHnCSUferQfDZTQvaZOB+FUhxBJL2QVIAsSDsqMfWsb6xd9N4l8bJo/nlxVM8kOty/oApkgkQvJl1UoeLOghDE6QYBAkESJEBiK0fLTYAQjupFnCwR/9wffFUTxa74DLx7fE4okCwdynv5HAsESstYgliGSBcIhpjSLXMJuW47pY9+mjq4bRTz3q7uO6TDJoIB5EPBTRAwGsVRyDLjmrpR9bVyYBqmRJBjsvJp6BOPn1Pkri9CrEDknRAMgWCXusYpFh2vJbx8L1kwvvieBrIY/pprtPPQ0QSRmP3lETqWl5R1lEtCYI2kiqJgGoV5bkgsTotcMxvnuUJlRfvzu8aJKPGrkEKLZGtthHD2IVEzgExRAIcn8wvLp7tmaEXH8/vUtVjeySOdEAIgmQmiNWCoGoVfZB6HESNCn54kuOsx9G+pklOgwjV6oMsp0CErYdj7hfO9+H83b95Dg8IvsQH0sYjIAk+o60F4V7LUcYu4ogAsSZAAKOmyYhqUfra83lAMH8w+yNBcgRSO6UbhsprcZB1WMHFi6RxH2KjNZ+hakHSmELSuOJJ46YwVCsJQ39XhoNeK6ZffH7Wc7TPeoj2NT7TPB40dsjh8UngoQZJ5ZHxRYCp1XvNX2JLhDaOLEJ7DUWNe1xXIccns+Fnuz3dY83xceAx7fpfHBBPbN50bYsoXCgZKfh6ZXmIxsbqJTF+CpmwAIEKf82bgK7CLgjeORq/Np//z+f6oPnL+edfwUf3VUuM+nhetBJp0yYfOvRPcQBCv0oWXBo7vn42co5sBDi++GAiTXw6EBz7/jCmbt/YQ7qPRHW0oYvwVi30FuEiqSL+mK6dU/e9Ft60Tz469zHztwCZ31zMP/iCcnfYcb8LXw3M5cbzsc9qkYvLhOA3Sz8MWdI1diGO+cX8+YOgeoFQYrcX2mtcch5l+Li8hb9ubHauWJBkDWq15/YVb+JEg3BxzM4Xxy1B0OY/+ApQOoGEP57dr6sdCRYNjvBGB2eyjx5zNuU2d2rULQefNYyiOYCvrhUInOGrD+Zjjzl9DiBcKK990TWSFV4LPrDZZ3iDxWrNwwgKC/JIPbJkj0LJwERsfCIG7g7SEnE/hFP9bP5nBEFL+eiuXGgiQLDpz0rExCRVndC8dmuFvT1s1ZKaraU7m+PeExAFf/Is70IUrVQTdvbg+nRu9awgXODffIslaoTOFQNaCQZoH3dw0tUhRU/EzH6+YbsnAXSv3OQ4GEYOC9nhgYDfSmo5lPHW4/mtrONpQfhZXn1LjkOFDU57hPg88GRREdExJSxxZ5+xMUStctqDGuZMLhISzTz4EsMt+i1WM79m77w6Pzt2PCvI/AJQHr/F8BYmGEXsEB8HXuNFER+jCcPuQsbGEC/TVHptIzg7hPU93GMKqhkmdhS98CrOyD7NNT0VCDeV+cPv30tCdDuReK55GOKAG+PxOlUgFH60wyYRcqu3JZf3h6hUXoS/hOuA4DYEO/LSi7ho4emu6ClBAAWk8vp7L/BAgOEMYgG11NJFuM2ivRDe9xSkppY0YoM2tTUfzCStubmTHEL8y996cX57G392EKFg89++BBcKIGDsUI6DBzpULrUzHuekCHJ+rVQpmifbWfCtoCzk3iJNX/o3QPj/T38xzwKC9w/O/tNvf8m74yZQLcktezx/SuQmDKirUFSl2pRBHCURD8pG0MPSe+l3+GnPgvGMIHD8NZ7+Vz/4EtOrHWcQI+yFLXZcYeIiNhkyae1e3toIKFz45V/Nn8cxe/aP+DtMJX78gxfuoYXb1RpBWh/rBQlLHFC1RqqaNJ4QH5X93Sc/4Ebxk68FiFSx+fzFb7303+Xtr9WWI7khEv+GctqQv/Cjl1/63W/x1968+bpIxGSZP3z8m++8LG8/D4bt4xF5UDyAHJz/+51v/1v3174+IPz4ibTXn7747U9/8+T9t1/BBJ93RMowaLz99vtP/se3fvfb3ru/hiDiFhuq8uJP/+Wff/348auvvvrX85+2CRS85yfP+bzzfwdsxdORP4ohrgAAAABJRU5ErkJggg==",Zo=[{key:"new",label:"New",color:"#0BA5EC",tone:"sky"},{key:"assigned",label:"Assigned",color:"#6938EF",tone:"violet"},{key:"qualifying",label:"Qualifying",color:"#EAAA08",tone:"amber"},{key:"followup",label:"Follow-up",color:"#F79009",tone:"amber"},{key:"kyc",label:"KYC",color:"#DD2590",tone:"pink"},{key:"account",label:"Account Setup",color:"#4338CA",tone:"brand"},{key:"traded",label:"Traded \u2713",color:"#12B76A",tone:"green"}],s0={key:"dead",label:"Dead",color:"#98A2B3",tone:"gray"},o0=[{key:"request",label:"New Request",color:"#0BA5EC",tone:"sky"},{key:"progress",label:"In Progress",color:"#F79009",tone:"amber"},{key:"awaiting",label:"Awaiting Client",color:"#EAAA08",tone:"amber"},{key:"resolved",label:"Resolved",color:"#12B76A",tone:"green"},{key:"closed",label:"Closed \u2713",color:"#6938EF",tone:"violet"}],l_={key:"svc_dead",label:"Cancelled",color:"#98A2B3",tone:"gray"};var kB=[...Zo,s0,...o0,l_],SB=["Acquisition","Service"];var _B=e=>e==="Service"?o0:Zo,CB=e=>e==="Service"?"svc_dead":"dead",IB=e=>e==="Service"?"request":"assigned",u_=e=>o0.some(t=>t.key===e)||e==="svc_dead"?o0:Zo,Rg=["DD Class","Walk-in","DD WhatsApp","Call Lead","Influencer","Campaign (AD)","DD Nifty (old)","Website","Referral","Event","Telegram"],wc=["Our Client","Dhan Client","New Lead"],Dg=e=>({"Our Client":{tone:"green",color:"#12B76A"},"Dhan Client":{tone:"brand",color:"#4338CA"},"New Lead":{tone:"sky",color:"#0BA5EC"}})[e]||{tone:"gray",color:"#98A2B3"},EB=e=>{let t=u_(e),r=t.findIndex(a=>a.key===e);return r>=0&&rkB.find(t=>t.key===e)||Zo[0],u0=e=>{let r=u_(e).findIndex(a=>a.key===e);return r<0?99:r},Ts=e=>String(e).padStart(2,"0"),Yo=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)}),Qo=e=>`${e.getFullYear()}-${Ts(e.getMonth()+1)}-${Ts(e.getDate())}`,c_=e=>{let t=new Date;return t.setDate(t.getDate()+e),t},ra=e=>Qo(c_(e)),LB=e=>`${Ts(e.getHours())}:${Ts(e.getMinutes())}:${Ts(e.getSeconds())}`,Un=e=>{let t=e.getHours(),r=Ts(e.getMinutes()),a=t<12?"AM":"PM";return t=t%12||12,`${t}:${r} ${a}`},fn=e=>{let[t,r]=e.split(":").map(Number),a=t,n=a<12?"AM":"PM";return a=a%12||12,`${a}:${Ts(r)} ${n}`},f_=e=>e.toLocaleDateString("en-IN",{weekday:"short",day:"numeric",month:"short"}),ta=e=>{let[t,r,a]=e.split("-").map(Number);return new Date(t,r-1,a).toLocaleDateString("en-IN",{day:"numeric",month:"short",year:"numeric"})};var TB=e=>{if(!e)return"";let t=new Date(e);return isNaN(t)?e:t.toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"numeric"})},r_=e=>{if(!e)return null;let t=new Date(e);if(isNaN(t))return null;let r=new Date,a=r.getFullYear()-t.getFullYear(),n=r.getMonth()-t.getMonth();return(n<0||n===0&&r.getDate()=0&&a<120?a:null},i0=(e,t)=>(new Date(t)-new Date(e))/36e5;function AB(){return new Promise(e=>{if(typeof navigator>"u"||!navigator.geolocation)return e(null);navigator.geolocation.getCurrentPosition(t=>e({lat:+t.coords.latitude.toFixed(5),lng:+t.coords.longitude.toFixed(5),acc:Math.round(t.coords.accuracy)}),()=>e(null),{enableHighAccuracy:!0,timeout:8e3,maximumAge:6e4})})}function kc(e,t){let r=new Date(`${e.date}T${e.start}:00`),a=new Date(`${e.date}T${e.end}:00`);return t>=r&&t<=a?"live":tString(e||"").trim().toLowerCase().replace(/[^a-z0-9._-]/g,"")+"@"+bB,Ng=e=>({id:e.id,loginId:e.login_id,name:e.name,role:e.role,empId:e.emp_id,title:e.title,dept:e.dept,color:e.color,dob:e.dob,phone:e.phone,email:e.email,address:e.address,bloodGroup:e.blood_group,bankName:e.bank_name,bankAccount:e.bank_account,ifsc:e.ifsc,emergencyName:e.emergency_name,emergencyPhone:e.emergency_phone,emergencyRelation:e.emergency_relation,password:""}),p_=e=>({login_id:(e.loginId||"").trim().toLowerCase(),name:e.name,role:e.role,emp_id:e.empId,title:e.title,dept:e.dept,color:e.color,dob:e.dob||null,phone:e.phone||null,email:e.email||null,address:e.address||null,blood_group:e.bloodGroup||null,bank_name:e.bankName||null,bank_account:e.bankAccount||null,ifsc:e.ifsc||null,emergency_name:e.emergencyName||null,emergency_phone:e.emergencyPhone||null,emergency_relation:e.emergencyRelation||null}),FB=e=>({id:e.id,employeeId:e.employee_id,date:e.date,checkIn:e.check_in,checkOut:e.check_out,loc:e.loc}),RB=e=>({id:e.id,employeeId:e.employee_id,type:e.type,from:e.from_date,to:e.to_date,reason:e.reason,status:e.status,createdAt:e.created_at}),PB=e=>({id:e.id,name:e.name,phone:e.phone,email:e.email,source:e.source,stage:e.stage,category:e.category,subCategory:e.sub_category,ownerId:e.owner_id,notes:e.notes,updatedAt:e.updated_at}),a_=e=>({id:e.id,name:e.name,phone:e.phone||null,email:e.email||null,source:e.source||null,stage:e.stage,category:e.category||null,sub_category:e.subCategory||null,owner_id:e.ownerId||null,notes:e.notes||null,updated_at:e.updatedAt||new Date().toISOString()}),OB=e=>({id:e.id,title:e.title,location:e.location,link:e.link,online:e.online,organizer:e.organizer,attendees:e.attendees||[],date:e.date,start:e.start_time,end:e.end_time}),DB=e=>({id:e.id,title:e.title,location:e.location||null,link:e.link||null,online:!!e.online,organizer:e.organizer||null,attendees:e.attendees||[],date:e.date,start_time:e.start,end_time:e.end}),BB=e=>({id:e.id,title:e.title,date:e.date,type:e.type});async function n_(){let e=["employees","attendance","leaves","leads","meetings","events"],t=await Promise.all(e.map(u=>dt.from(u).select("*"))),r=t.find(u=>u.error);if(r)throw r.error;let[a,n,i,s,o,l]=t.map(u=>u.data||[]);return{employees:a.map(Ng),attendance:n.map(FB),leaves:i.map(RB),leads:s.map(PB),meetings:o.map(OB),events:l.map(BB)}}async function NB(e){let t=Bg(e.loginId),r=Fg(d_,h_,{auth:{storageKey:"stp_tmp_signup",persistSession:!1,autoRefreshToken:!1}}),{data:a,error:n}=await r.auth.signUp({email:t,password:e.password});if(n)throw new Error(n.message);let i=a&&a.user&&a.user.id;if(!i)throw new Error("Login not created. Check that signups are enabled in Supabase \u2192 Authentication.");if(!a.session){try{await r.auth.signOut()}catch{}throw new Error("Email confirmation is ON \u2014 this employee couldn't sign in. In Supabase \u2192 Authentication \u2192 Email, turn OFF 'Confirm email', then add them again.")}try{await r.auth.signOut()}catch{}let s={id:i,...p_(e)},{error:o}=await dt.from("employees").insert(s);if(o)throw new Error(o.message+" (a login may have been created \u2014 if it persists, delete the user in Supabase \u2192 Authentication \u2192 Users)");return Ng(s)}var MB=["A+","A-","B+","B-","O+","O-","AB+","AB-"],UB=["Creative","Brokerage","Social","Operations","Management"],yc={Casual:15,Emergency:10},m_=e=>{let t=new Date((e.from||e.to)+"T00:00:00"),r=new Date((e.to||e.from)+"T00:00:00");return Math.max(1,Math.round((r-t)/864e5)+1)},Mg=()=>String(new Date().getFullYear()),g_=(e,t,r,a=Mg())=>e.filter(n=>n.employeeId===t&&n.type===r&&n.status==="approved"&&String(n.from||"").slice(0,4)===a).reduce((n,i)=>n+m_(i),0),HB=(e,t,r,a=Mg())=>e.filter(n=>n.employeeId===t&&n.type===r&&n.status==="pending"&&String(n.from||"").slice(0,4)===a).reduce((n,i)=>n+m_(i),0);var WB=e=>{let t=0;return e.forEach(r=>{let a=/(\d+)\s*$/.exec(r.empId||"");a&&(t=Math.max(t,parseInt(a[1],10)))}),"DP-"+String(t+1).padStart(3,"0")};var x_={green:{bg:I.greenSoft,fg:"#067647"},red:{bg:I.redSoft,fg:"#B42318"},amber:{bg:I.amberSoft,fg:"#B54708"},sky:{bg:I.skySoft,fg:"#026AA2"},brand:{bg:I.brandSoft,fg:I.brandInk},gray:{bg:"#F2F4F7",fg:"#475467"},violet:{bg:"#F4F0FF",fg:"#5925DC"},pink:{bg:"#FCE7F6",fg:"#C11574"}};function et({tone:e="gray",children:t,dot:r}){let a=x_[e];return(0,d.jsxs)("span",{style:{background:a.bg,color:a.fg,fontSize:11.5,fontWeight:600,padding:"3px 9px",borderRadius:999,display:"inline-flex",alignItems:"center",gap:5,whiteSpace:"nowrap"},children:[r&&(0,d.jsx)("span",{style:{width:6,height:6,borderRadius:999,background:a.fg}}),t]})}function je({children:e,onClick:t,variant:r="primary",size:a="md",icon:n,disabled:i,full:s,type:o,style:l}){let u={sm:{padding:"6px 10px",fontSize:12},md:{padding:"9px 14px",fontSize:13.5},lg:{padding:"12px 18px",fontSize:15}},c={primary:{background:I.brand,color:"#fff"},soft:{background:I.brandSoft,color:I.brandInk},ghost:{background:"#fff",color:I.sub,border:`1px solid ${I.border}`},success:{background:I.green,color:"#fff"},danger:{background:"#fff",color:"#B42318",border:`1px solid ${I.redSoft}`},dark:{background:I.ink,color:"#fff"}};return(0,d.jsxs)("button",{type:o||"button",onClick:t,disabled:i,style:{borderRadius:10,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:7,cursor:i?"not-allowed":"pointer",border:"1px solid transparent",opacity:i?.55:1,width:s?"100%":void 0,...u[a],...c[r],...l},children:[n&&(0,d.jsx)(n,{size:a==="sm"?14:16}),e]})}function rt({title:e,sub:t,action:r,children:a,pad:n=!0}){return(0,d.jsxs)("section",{style:{background:I.surface,border:`1px solid ${I.border}`,borderRadius:14,boxShadow:"0 1px 2px rgba(16,24,40,.04)"},children:[(e||r)&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 16px",borderBottom:`1px solid ${I.line}`},children:[(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{style:{fontWeight:700,fontSize:14.5,color:I.ink},children:e}),t&&(0,d.jsx)("div",{style:{fontSize:12,color:I.faint,marginTop:2},children:t})]}),r]}),(0,d.jsx)("div",{style:{padding:n?16:0},children:a})]})}function Mr({label:e,value:t,sub:r,icon:a,tone:n="brand"}){let i=x_[n];return(0,d.jsxs)("div",{style:{background:I.surface,border:`1px solid ${I.border}`,borderRadius:14,padding:16,boxShadow:"0 1px 2px rgba(16,24,40,.04)"},children:[(0,d.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[(0,d.jsx)("div",{style:{fontSize:12.5,color:I.sub,fontWeight:600},children:e}),(0,d.jsx)("div",{style:{width:32,height:32,borderRadius:9,background:i.bg,color:i.fg,display:"grid",placeItems:"center"},children:(0,d.jsx)(a,{size:17})})]}),(0,d.jsx)("div",{style:{fontSize:26,fontWeight:800,color:I.ink,marginTop:8,letterSpacing:-.5},children:t}),r&&(0,d.jsx)("div",{style:{fontSize:12,color:I.faint,marginTop:2},children:r})]})}function Sa({emp:e,size:t=34}){let r=e.name.split(" ").map(a=>a[0]).slice(0,2).join("");return(0,d.jsx)("div",{style:{width:t,height:t,borderRadius:9,background:e.color,color:"#fff",display:"grid",placeItems:"center",fontWeight:700,fontSize:t*.36,flexShrink:0},children:r})}function We({label:e,children:t,hint:r}){return(0,d.jsxs)("label",{style:{display:"block"},children:[(0,d.jsx)("div",{style:{fontSize:12,fontWeight:600,color:I.sub,marginBottom:6},children:e}),t,r&&(0,d.jsx)("div",{style:{fontSize:11,color:I.faint,marginTop:4},children:r})]})}var De={width:"100%",padding:"9px 11px",borderRadius:9,border:`1px solid ${I.border}`,fontSize:13.5,color:I.ink,background:"#fff",outline:"none",boxSizing:"border-box",fontFamily:cn};function c0({loc:e}){return e?(0,d.jsxs)("a",{href:`https://www.google.com/maps?q=${e.lat},${e.lng}`,target:"_blank",rel:"noreferrer",style:{fontSize:11.5,fontFamily:Be,color:I.brandInk,background:I.brandSoft,padding:"2px 7px",borderRadius:7,display:"inline-flex",alignItems:"center",gap:4,textDecoration:"none"},children:[(0,d.jsx)(Ei,{size:11}),e.lat,", ",e.lng]}):(0,d.jsxs)("span",{style:{fontSize:11.5,color:I.faint,display:"inline-flex",alignItems:"center",gap:4},children:[(0,d.jsx)(Ei,{size:12})," No location"]})}function zB(){let[e,t]=(0,ke.useState)(new Date);return(0,ke.useEffect)(()=>{let r=setInterval(()=>t(new Date),1e3);return()=>clearInterval(r)},[]),(0,d.jsxs)("div",{style:{textAlign:"right"},children:[(0,d.jsx)("div",{style:{fontSize:12,color:I.sub,fontWeight:600},children:f_(e)}),(0,d.jsx)("div",{style:{fontFamily:Be,fontSize:15,fontWeight:700,color:I.ink,letterSpacing:.5},children:LB(e)})]})}function jB({leaves:e,empId:t}){let r=Mg();return(0,d.jsx)(rt,{title:"Leave balance",sub:`Company policy \u2014 ${yc.Casual} Casual + ${yc.Emergency} Emergency per year (${r})`,children:(0,d.jsx)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},className:"att-grid",children:Object.entries(yc).map(([a,n])=>{let i=g_(e,t,a,r),s=HB(e,t,a,r),o=Math.max(0,n-i),l=i>n,u=Math.min(100,Math.round(i/n*100)),c=l?I.red:a==="Casual"?I.brand:I.amber;return(0,d.jsxs)("div",{style:{border:`1px solid ${I.border}`,borderRadius:12,padding:14},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"baseline",justifyContent:"space-between",marginBottom:8},children:[(0,d.jsxs)("span",{style:{fontSize:13,fontWeight:700,color:I.ink},children:[a," Leave"]}),(0,d.jsxs)("span",{style:{fontSize:12,color:I.faint},children:[(0,d.jsx)("strong",{style:{color:l?I.red:I.ink,fontSize:16},children:o})," / ",n," left"]})]}),(0,d.jsx)("div",{style:{height:8,background:"#EEF0F4",borderRadius:999,overflow:"hidden"},children:(0,d.jsx)("div",{style:{width:`${u}%`,height:"100%",background:c,borderRadius:999,transition:"width .3s"}})}),(0,d.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",marginTop:7,fontSize:11.5,color:I.faint},children:[(0,d.jsxs)("span",{children:[i," taken",l?" \xB7 over limit":""]}),s>0&&(0,d.jsxs)("span",{style:{color:"#B54708",fontWeight:600},children:[s," pending"]})]})]},a)})})})}function VB({onSubmit:e}){let[t,r]=(0,ke.useState)("Casual"),[a,n]=(0,ke.useState)(ra(1)),[i,s]=(0,ke.useState)(ra(1)),[o,l]=(0,ke.useState)("");return(0,d.jsxs)("div",{style:{display:"grid",gap:12},children:[(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[(0,d.jsx)(We,{label:"Leave type",children:(0,d.jsxs)("select",{style:De,value:t,onChange:c=>r(c.target.value),children:[(0,d.jsx)("option",{children:"Casual"}),(0,d.jsx)("option",{children:"Emergency"})]})}),(0,d.jsx)(We,{label:"Reason (short)",children:(0,d.jsx)("input",{style:De,value:o,onChange:c=>l(c.target.value),placeholder:"e.g. Family function"})})]}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[(0,d.jsx)(We,{label:"From",children:(0,d.jsx)("input",{type:"date",style:De,value:a,onChange:c=>n(c.target.value)})}),(0,d.jsx)(We,{label:"To",children:(0,d.jsx)("input",{type:"date",style:De,value:i,onChange:c=>s(c.target.value)})})]}),(0,d.jsx)(je,{onClick:()=>{o.trim()&&(e({type:t,from:a,to:i,reason:o.trim()}),l(""),r("Casual"))},icon:Ls,disabled:!o.trim(),children:"Submit request"})]})}function v_({employees:e,organizerId:t,defaultDate:r,onSubmit:a}){let[n,i]=(0,ke.useState)(""),[s,o]=(0,ke.useState)(r||ra(0)),[l,u]=(0,ke.useState)("11:00"),[c,f]=(0,ke.useState)("11:30"),[h,m]=(0,ke.useState)(!0),[g,p]=(0,ke.useState)("Google Meet"),[y,w]=(0,ke.useState)(""),[v,x]=(0,ke.useState)([t]),_=k=>x(b=>b.includes(k)?b.filter(O=>O!==k):[...b,k]),T=y.trim()&&!Sc(y),E=()=>{n.trim()&&(a({title:n.trim(),date:s,start:l,end:c,online:h,location:g.trim()||(h?"Online":"Office"),link:y.trim(),organizer:t,attendees:v}),i(""),w(""))};return(0,d.jsxs)("div",{style:{display:"grid",gap:12},children:[(0,d.jsx)(We,{label:"Meeting title",children:(0,d.jsx)("input",{style:De,value:n,onChange:k=>i(k.target.value),placeholder:"e.g. Quantman demo walkthrough"})}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:12},children:[(0,d.jsx)(We,{label:"Date",children:(0,d.jsx)("input",{type:"date",style:De,value:s,onChange:k=>o(k.target.value)})}),(0,d.jsx)(We,{label:"Start",children:(0,d.jsx)("input",{type:"time",style:De,value:l,onChange:k=>u(k.target.value)})}),(0,d.jsx)(We,{label:"End",children:(0,d.jsx)("input",{type:"time",style:De,value:c,onChange:k=>f(k.target.value)})})]}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"auto 1fr",gap:12,alignItems:"end"},children:[(0,d.jsx)(We,{label:"Mode",children:(0,d.jsxs)("select",{style:De,value:h?"online":"office",onChange:k=>m(k.target.value==="online"),children:[(0,d.jsx)("option",{value:"online",children:"Online"}),(0,d.jsx)("option",{value:"office",children:"In-office"})]})}),(0,d.jsx)(We,{label:h?"Platform":"Location",children:(0,d.jsx)("input",{style:De,value:g,onChange:k=>p(k.target.value),placeholder:h?"e.g. Google Meet / Zoom / Teams":"e.g. Office \u2014 conference room"})})]}),(0,d.jsx)(We,{label:"Meeting link",hint:T?"\u26A0 Doesn't look like a valid URL":"Optional \u2014 paste the Google Meet / Zoom / Teams URL",children:(0,d.jsxs)("div",{style:{position:"relative"},children:[(0,d.jsx)(Xo,{size:15,style:{position:"absolute",left:11,top:"50%",transform:"translateY(-50%)",color:I.faint}}),(0,d.jsx)("input",{style:{...De,paddingLeft:34,borderColor:T?I.red:I.border},value:y,onChange:k=>w(k.target.value),placeholder:"https://meet.google.com/abc-defg-hij"})]})}),(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{style:{fontSize:12,fontWeight:600,color:I.sub,marginBottom:7},children:"Attendees"}),(0,d.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:7},children:e.map(k=>{let b=v.includes(k.id);return(0,d.jsxs)("button",{onClick:()=>_(k.id),style:{border:`1px solid ${b?I.brand:I.border}`,background:b?I.brandSoft:"#fff",color:b?I.brandInk:I.sub,padding:"5px 10px",borderRadius:999,fontSize:12,fontWeight:600,cursor:"pointer",display:"inline-flex",alignItems:"center",gap:5},children:[b&&(0,d.jsx)(Er,{size:13}),k.name]},k.id)})})]}),(0,d.jsx)(je,{onClick:E,icon:Ls,disabled:!n.trim(),children:"Schedule meeting"})]})}var Sc=e=>(e=String(e||"").trim(),/^https?:\/\//i.test(e)||/^(www\.)?[a-z0-9-]+(\.[a-z0-9-]+)+(\/\S*)?$/i.test(e)),Pg=e=>(e=String(e||"").trim(),/^https?:\/\//i.test(e)?e:"https://"+e.replace(/^\/+/,""));function f0({loc:e,stop:t,style:r}){return Sc(e)?(0,d.jsx)("a",{href:Pg(e),target:"_blank",rel:"noopener noreferrer",onClick:t?a=>a.stopPropagation():void 0,style:{color:I.brand,fontWeight:600,textDecoration:"none",wordBreak:"break-all",...r},children:e}):(0,d.jsx)("span",{style:r,children:e||"\u2014"})}var As=e=>{let t=String(e&&e.link||"").trim();return Sc(t)?Pg(t):Sc(e&&e.location)?Pg(e.location):""};function y_({m:e,stop:t,compact:r}){let a=As(e);return a?(0,d.jsxs)("a",{href:a,target:"_blank",rel:"noopener noreferrer",onClick:t?n=>n.stopPropagation():void 0,style:{display:"inline-flex",alignItems:"center",gap:4,color:I.brand,fontWeight:700,fontSize:r?11.5:12.5,textDecoration:"none",whiteSpace:"nowrap"},children:[(0,d.jsx)(ea,{size:r?12:13})," Join"]}):null}var w_=e=>{let t=r=>String(r).padStart(2,"0");return`${e.getUTCFullYear()}${t(e.getUTCMonth()+1)}${t(e.getUTCDate())}T${t(e.getUTCHours())}${t(e.getUTCMinutes())}${t(e.getUTCSeconds())}Z`},d0=(e,t)=>{let r=new Date(`${e}T${t||"00:00"}:00`);return isNaN(r)?"":w_(r)},k_=e=>{let t=`${e.online?"Online meeting":"In-office meeting"}${e.location?" \u2014 "+e.location:""}`,r=As(e);return r?`${t} Join: ${r}`:t};function qB(e){return`https://calendar.google.com/calendar/render?${new URLSearchParams({action:"TEMPLATE",text:e.title||"Meeting",dates:`${d0(e.date,e.start)}/${d0(e.date,e.end)}`,details:k_(e),location:As(e)||e.location||""}).toString()}`}function $B(e){let t=a=>String(a||"").replace(/\\/g,"\\\\").replace(/;/g,"\\;").replace(/,/g,"\\,").replace(/\r?\n/g,"\\n"),r=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//The Simple Trade//Team Console//EN","CALSCALE:GREGORIAN","METHOD:PUBLISH","BEGIN:VEVENT",`UID:${e.id||Yo()}@thesimpletrade`,`DTSTAMP:${w_(new Date)}`,`DTSTART:${d0(e.date,e.start)}`,`DTEND:${d0(e.date,e.end)}`,`SUMMARY:${t(e.title)}`,`LOCATION:${t(As(e)||e.location)}`,`DESCRIPTION:${t(k_(e))}`,"END:VEVENT","END:VCALENDAR"].join(`\r `);try{let a=new Blob([r],{type:"text/calendar;charset=utf-8"}),n=URL.createObjectURL(a),i=document.createElement("a");i.href=n,i.download=`${(e.title||"meeting").replace(/[^\w]+/g,"-").toLowerCase()}.ics`,document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(()=>URL.revokeObjectURL(n),1500)}catch{}}function h0({meeting:e,compact:t}){let[r,a]=(0,ke.useState)(!1),n={display:"flex",alignItems:"center",gap:8,width:"100%",textAlign:"left",border:"none",background:"transparent",padding:"8px 10px",borderRadius:8,fontSize:12.5,color:I.ink,cursor:"pointer",fontWeight:600};return(0,d.jsxs)("div",{style:{position:"relative",flexShrink:0},children:[(0,d.jsxs)("button",{onClick:i=>{i.stopPropagation(),a(s=>!s)},title:"Add to calendar",style:{border:`1px solid ${I.border}`,background:"#fff",borderRadius:8,padding:t?"5px 8px":"6px 10px",fontSize:12,fontWeight:600,color:I.brand,cursor:"pointer",display:"inline-flex",alignItems:"center",gap:5,whiteSpace:"nowrap"},children:[(0,d.jsx)(Ii,{size:13}),t?"Add":"Add to Calendar"]}),r&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("div",{onClick:i=>{i.stopPropagation(),a(!1)},style:{position:"fixed",inset:0,zIndex:50}}),(0,d.jsxs)("div",{onClick:i=>i.stopPropagation(),style:{position:"absolute",right:0,top:"calc(100% + 6px)",zIndex:51,background:"#fff",border:`1px solid ${I.border}`,borderRadius:11,boxShadow:"0 12px 32px rgba(16,24,40,.2)",padding:5,minWidth:210},children:[(0,d.jsxs)("button",{style:n,className:"row-hover",onClick:()=>{window.open(qB(e),"_blank","noopener"),a(!1)},children:[(0,d.jsx)(Ci,{size:15,style:{color:I.brand}})," Google Calendar"]}),(0,d.jsxs)("button",{style:n,className:"row-hover",onClick:()=>{$B(e),a(!1)},children:[(0,d.jsx)(ks,{size:15,style:{color:I.sub}})," Download .ics ",(0,d.jsx)("span",{style:{fontSize:10.5,color:I.faint,fontWeight:500},children:"(Apple / Outlook)"})]})]})]})]})}function GB({employees:e,organizerId:t,defaultDate:r,onSubmit:a,onClose:n}){return(0,d.jsx)("div",{onClick:n,style:{position:"fixed",inset:0,background:"rgba(15,23,42,.45)",zIndex:70,display:"grid",placeItems:"center",padding:16},children:(0,d.jsxs)("div",{onClick:i=>i.stopPropagation(),style:{background:"#fff",borderRadius:16,width:"100%",maxWidth:560,maxHeight:"88vh",overflowY:"auto",boxShadow:"0 24px 70px rgba(16,24,40,.35)"},children:[(0,d.jsxs)("div",{style:{position:"sticky",top:0,background:"#fff",padding:"16px 20px 13px",borderBottom:`1px solid ${I.line}`,display:"flex",alignItems:"center",gap:10,zIndex:1},children:[(0,d.jsx)("div",{style:{width:36,height:36,borderRadius:10,background:I.brandSoft,color:I.brand,display:"grid",placeItems:"center"},children:(0,d.jsx)(Ii,{size:18})}),(0,d.jsx)("div",{style:{flex:1,fontSize:15.5,fontWeight:800,color:I.ink},children:"New meeting"}),(0,d.jsx)("button",{onClick:n,style:{border:"none",background:"transparent",cursor:"pointer",color:I.faint,display:"grid",placeItems:"center",padding:4},children:(0,d.jsx)(Ai,{size:20})})]}),(0,d.jsx)("div",{style:{padding:"16px 20px 20px"},children:(0,d.jsx)(v_,{employees:e,organizerId:t,defaultDate:r,onSubmit:a})})]})})}function S_({meeting:e,empById:t,now:r,canDelete:a,onDelete:n,onClose:i}){if(!e)return null;let s=e,o=kc(s,r),l=As(s),u=Sc(s.link),c=t(s.organizer),f=({icon:h,label:m,children:g})=>(0,d.jsxs)("div",{style:{display:"flex",gap:12,padding:"9px 0",borderBottom:`1px solid ${I.line}`,alignItems:"flex-start"},children:[(0,d.jsx)("div",{style:{width:26,color:I.faint,display:"grid",placeItems:"center",flexShrink:0,marginTop:1},children:h&&(0,d.jsx)(h,{size:15})}),(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:11,color:I.faint,fontWeight:600,textTransform:"uppercase",letterSpacing:.4,marginBottom:2},children:m}),(0,d.jsx)("div",{style:{fontSize:13.5,color:I.ink},children:g})]})]});return(0,d.jsx)("div",{onClick:i,style:{position:"fixed",inset:0,background:"rgba(15,23,42,.45)",zIndex:75,display:"grid",placeItems:"center",padding:16},children:(0,d.jsxs)("div",{onClick:h=>h.stopPropagation(),style:{background:"#fff",borderRadius:16,width:"100%",maxWidth:480,maxHeight:"88vh",overflowY:"auto",boxShadow:"0 24px 70px rgba(16,24,40,.35)"},children:[(0,d.jsxs)("div",{style:{padding:"18px 20px 14px",borderBottom:`1px solid ${I.line}`,display:"flex",alignItems:"flex-start",gap:12},children:[(0,d.jsx)("div",{style:{width:42,height:42,borderRadius:11,background:s.online?I.skySoft:"#F2F4F7",color:s.online?"#026AA2":I.sub,display:"grid",placeItems:"center",flexShrink:0},children:s.online?(0,d.jsx)(ea,{size:20}):(0,d.jsx)(ln,{size:20})}),(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:16.5,fontWeight:800,color:I.ink,lineHeight:1.25},children:s.title}),(0,d.jsx)("div",{style:{marginTop:5},children:o==="live"?(0,d.jsx)(et,{tone:"green",dot:!0,children:"Live now"}):o==="soon"?(0,d.jsx)(et,{tone:"amber",dot:!0,children:"Starting soon"}):o==="past"?(0,d.jsx)(et,{tone:"gray",children:"Ended"}):(0,d.jsx)(et,{tone:"sky",dot:!0,children:"Upcoming"})})]}),(0,d.jsx)("button",{onClick:i,style:{border:"none",background:"transparent",cursor:"pointer",color:I.faint,display:"grid",placeItems:"center",padding:4},children:(0,d.jsx)(Ai,{size:20})})]}),(0,d.jsxs)("div",{style:{padding:"8px 20px 4px"},children:[(0,d.jsx)(f,{icon:Ci,label:"Date",children:ta(s.date)}),(0,d.jsx)(f,{icon:zo,label:"Time",children:(0,d.jsxs)("span",{style:{fontFamily:Be},children:[fn(s.start)," \u2013 ",fn(s.end)]})}),(0,d.jsx)(f,{icon:s.online?ea:ln,label:s.online?"Platform":"Location",children:(0,d.jsx)(f0,{loc:s.location})}),u&&(0,d.jsx)(f,{icon:Xo,label:"Meeting link",children:(0,d.jsx)(f0,{loc:s.link})}),(0,d.jsx)(f,{icon:Li,label:"Organised by",children:(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,d.jsx)(Sa,{emp:c,size:24})," ",c.name]})}),(0,d.jsx)(f,{icon:Ti,label:`Attendees (${s.attendees.length})`,children:(0,d.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:8,marginTop:2},children:s.attendees.map(h=>{let m=t(h);return(0,d.jsxs)("div",{style:{display:"inline-flex",alignItems:"center",gap:6,background:"#F7F8FA",border:`1px solid ${I.line}`,borderRadius:999,padding:"3px 10px 3px 3px"},children:[(0,d.jsx)(Sa,{emp:m,size:22}),(0,d.jsx)("span",{style:{fontSize:12.5,color:I.ink},children:m.name})]},h)})})})]}),(0,d.jsxs)("div",{style:{padding:"12px 20px 18px",display:"flex",gap:9,flexWrap:"wrap",alignItems:"center"},children:[l&&(0,d.jsx)(je,{icon:ea,onClick:()=>window.open(l,"_blank","noopener"),children:"Join meeting"}),(0,d.jsx)(h0,{meeting:s}),a&&(0,d.jsx)(je,{variant:"danger",icon:Nr,onClick:()=>n(s),style:{marginLeft:"auto"},children:"Delete"})]})]})})}function KB({employees:e,subCategory:t="Acquisition",onSubmit:r}){let[a,n]=(0,ke.useState)(""),[i,s]=(0,ke.useState)(""),[o,l]=(0,ke.useState)(""),[u,c]=(0,ke.useState)(Rg[0]),[f,h]=(0,ke.useState)(t==="Service"?"Dhan Client":"New Lead"),[m,g]=(0,ke.useState)(""),p=()=>{a.trim()&&(r({name:a.trim(),phone:i.trim()||"\u2014",email:o.trim(),source:u,category:f,subCategory:t,ownerId:m||null}),n(""),s(""),l(""),g(""))};return(0,d.jsxs)("div",{style:{display:"grid",gap:12},children:[(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:12},children:[(0,d.jsx)(We,{label:"Name",children:(0,d.jsx)("input",{style:De,value:a,onChange:y=>n(y.target.value),placeholder:"Full name"})}),(0,d.jsx)(We,{label:"Phone",children:(0,d.jsx)("input",{style:De,value:i,onChange:y=>s(y.target.value),placeholder:"+91 ..."})}),(0,d.jsx)(We,{label:"Email",children:(0,d.jsx)("input",{type:"email",style:De,value:o,onChange:y=>l(y.target.value),placeholder:"name@email.com"})})]}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:12},children:[(0,d.jsx)(We,{label:"Source",children:(0,d.jsx)("select",{style:De,value:u,onChange:y=>c(y.target.value),children:Rg.map(y=>(0,d.jsx)("option",{children:y},y))})}),(0,d.jsx)(We,{label:"Category",children:(0,d.jsx)("select",{style:De,value:f,onChange:y=>h(y.target.value),children:wc.map(y=>(0,d.jsx)("option",{children:y},y))})}),(0,d.jsx)(We,{label:"Assign to",hint:"Optional",children:(0,d.jsxs)("select",{style:De,value:m,onChange:y=>g(y.target.value),children:[(0,d.jsx)("option",{value:"",children:"Unassigned"}),e.map(y=>(0,d.jsx)("option",{value:y.id,children:y.name},y.id))]})})]}),(0,d.jsx)(je,{onClick:p,icon:Ls,disabled:!a.trim(),children:t==="Service"?"Add service record":"Add lead"})]})}function XB(e,t,r="lead"){let a=l=>{let u=t.find(c=>c.id===l);return u?u.name:""},n=e.map(l=>({Name:l.name||"",Phone:l.phone||"",Email:l.email||"",Source:l.source||"",Category:l.category||"",Module:l.subCategory||"Acquisition",Stage:(l0(l.stage)||{}).label||l.stage||"","Assigned To":a(l.ownerId),Notes:l.notes||"","Last Updated":l.updatedAt?new Date(l.updatedAt).toLocaleString():""})),i=["Name","Phone","Email","Source","Category","Module","Stage","Assigned To","Notes","Last Updated"],s=n.length?Ba.json_to_sheet(n,{header:i}):Ba.aoa_to_sheet([i]);s["!cols"]=[20,16,24,16,14,12,14,16,30,20].map(l=>({wch:l}));let o=Ba.book_new();Ba.book_append_sheet(o,s,r==="record"?"Service Records":"Leads"),Xm(o,`the-simple-trade-${r==="record"?"service-records":"leads"}-${new Date().toISOString().slice(0,10)}.xlsx`)}function JB({employees:e,subCategory:t="Acquisition",onImport:r}){let a=(0,ke.useRef)(null),[n,i]=(0,ke.useState)(null),[s,o]=(0,ke.useState)(!1),l=f=>String(f??"").trim().toLowerCase(),u=f=>{let h=f.target.files&&f.target.files[0];if(!h)return;o(!0),i(null);let m=new FileReader;m.onload=g=>{try{let p=md(g.target.result,{type:"array"}),y=p.Sheets[p.SheetNames[0]],w=Ba.sheet_to_json(y,{defval:""}),v=[],x=0,_=0;w.forEach(O=>{let H=V=>{for(let N of Object.keys(O))if(V.includes(l(N)))return O[N];return""},U=String(H(["name","lead name","lead","full name"])).trim();if(!U){x++;return}let B=String(H(["phone","mobile","contact","phone number"])).trim()||"\u2014",te=String(H(["email","e-mail","mail","email id","email address"])).trim(),q=String(H(["source"])).trim()||"Walk-in",j=String(H(["category","client type"])).trim();j=wc.find(V=>l(V)===l(j))||(t==="Service"?"Dhan Client":"New Lead");let K=String(H(["sub category","subcategory","sub-category","module"])).trim(),se=SB.find(V=>l(V)===l(K))||t,ge=String(H(["assign to","assigned to","assignee","owner"])).trim(),ne=null;if(ge){let V=e.find(N=>l(N.name)===l(ge)||l(N.loginId)===l(ge));V?ne=V.id:_++}let D=String(H(["notes","note","remark","remarks"])).trim();v.push({name:U,phone:B,email:te,source:q,category:j,subCategory:se,ownerId:ne,notes:D})}),v.length&&r(v);let T=v.filter(O=>O.ownerId).length,E=t==="Service"?"record":"lead",k=[`Imported ${v.length} ${E}${v.length!==1?"s":""}`,`${T} assigned`],b="";x&&(b+=` Skipped ${x} row${x!==1?"s":""} with no name.`),_&&(b+=` ${_} "Assign To" name${_!==1?"s":""} didn't match an employee.`),i({ok:v.length>0,text:v.length?`${k[0]} (${k[1]}).${b}`:`No valid rows found.${b}`})}catch{i({ok:!1,text:"Couldn't read that file. Use the template (.xlsx) \u2014 it must have a Name column."})}o(!1)},m.onerror=()=>{i({ok:!1,text:"Failed to read the file."}),o(!1)},m.readAsArrayBuffer(h),f.target.value=""},c=()=>{let f=["Name","Phone","Email","Sub Category","Source","Category","Assign To","Notes"],h=[["Suresh Kumar","+91 9876543210","suresh.kumar@gmail.com","Acquisition","DD Class","New Lead","Vignesh M","Met at Saturday class, wants options training"],["Lakshmi Priya","+91 9123456780","lakshmi.priya@gmail.com","Acquisition","Referral","Our Client","","Wants a second account"],["Ramesh Iyer","+91 9001122334","ramesh.iyer@gmail.com","Service","Call Lead","Dhan Client","Karthik R","Needs help with fund withdrawal"]],m=Ba.aoa_to_sheet([f,...h]);m["!cols"]=[{wch:20},{wch:16},{wch:26},{wch:14},{wch:16},{wch:14},{wch:16},{wch:36}];let g=[["The Simple Trade \u2014 Lead Upload Template"],[],["Column","Required","Notes"],["Name","Yes","Full name of the lead / client"],["Phone","No","Mobile number (any format)"],["Email","No","Email address"],["Sub Category","No","Acquisition or Service. Picks the CRM module. Defaults to the module you upload from."],["Source","No","Where it came from. Suggested: "+Rg.join(", ")],["Category","No","One of: "+wc.join(", ")+". Defaults to 'New Lead'."],["Assign To","No","Employee name or login ID. Blank = unassigned."],["Notes","No","Any remark"],[],["Acquisition flow","","New \u2192 Assigned \u2192 Qualifying \u2192 Follow-up \u2192 KYC \u2192 Account Setup \u2192 Traded"],["Service flow","","New Request \u2192 In Progress \u2192 Awaiting Client \u2192 Resolved \u2192 Closed"],["Tip","","Delete the 3 sample rows in the 'Leads' sheet before you upload."]],p=Ba.aoa_to_sheet(g);p["!cols"]=[{wch:16},{wch:10},{wch:76}];let y=Ba.book_new();Ba.book_append_sheet(y,m,"Leads"),Ba.book_append_sheet(y,p,"Instructions"),Xm(y,"dhan-partner-leads-template.xlsx")};return(0,d.jsxs)(rt,{title:`Bulk upload (Excel) \u2014 ${t}`,sub:"Import many records at once. Sub Category column can route rows to either module.",children:[(0,d.jsxs)("div",{style:{display:"flex",gap:10,flexWrap:"wrap",alignItems:"center"},children:[(0,d.jsx)("input",{ref:a,type:"file",accept:".xlsx,.xls",onChange:u,style:{display:"none"}}),(0,d.jsx)(je,{icon:mc,onClick:()=>a.current&&a.current.click(),disabled:s,children:s?"Reading\u2026":"Upload Excel"}),(0,d.jsx)(je,{variant:"ghost",icon:ks,onClick:c,children:"Download template"}),(0,d.jsxs)("div",{style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:11.5,color:I.faint},children:[(0,d.jsx)(lc,{size:13})," Name \xB7 Phone \xB7 Email \xB7 Sub Category \xB7 Source \xB7 Category \xB7 Assign To \xB7 Notes"]})]}),n&&(0,d.jsx)("div",{style:{marginTop:12,fontSize:12.5,fontWeight:600,color:n.ok?"#067647":"#B42318",background:n.ok?I.greenSoft:I.redSoft,padding:"9px 12px",borderRadius:10},children:n.text})]})}var i_=["#4338CA","#0BA5EC","#F79009","#12B76A","#EC4899","#7C3AED","#F04438","#0E9384","#DD2590","#6938EF"];function vc({icon:e,title:t}){return(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,margin:"8px 0 -2px",fontSize:11,fontWeight:800,color:I.faint,textTransform:"uppercase",letterSpacing:.6},children:[e&&(0,d.jsx)(e,{size:12}),t]})}function __({data:e,set:t,existing:r,selfId:a,mode:n,idPlaceholder:i}){let[s,o]=(0,ke.useState)(!1),l=(e.loginId||"").trim().toLowerCase(),u=!!l&&r.some(c=>c.id!==a&&(c.loginId||"").toLowerCase()===l);return(0,d.jsxs)("div",{style:{display:"grid",gap:11},children:[(0,d.jsx)(vc,{icon:Nn,title:"Basic"}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:11},children:[(0,d.jsx)(We,{label:"Employee ID",children:(0,d.jsx)("input",{style:{...De,fontFamily:Be},value:e.empId,onChange:c=>t("empId",c.target.value),placeholder:i||"DP-007"})}),(0,d.jsx)(We,{label:"Full name",children:(0,d.jsx)("input",{style:De,value:e.name,onChange:c=>t("name",c.target.value),placeholder:"e.g. Ramesh K"})})]}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:11},children:[(0,d.jsx)(We,{label:"Designation",children:(0,d.jsx)("input",{style:De,value:e.title,onChange:c=>t("title",c.target.value),placeholder:"e.g. Video Editor"})}),(0,d.jsx)(We,{label:"Department",children:(0,d.jsx)("select",{style:De,value:e.dept,onChange:c=>t("dept",c.target.value),children:UB.map(c=>(0,d.jsx)("option",{children:c},c))})}),(0,d.jsx)(We,{label:"Role",children:(0,d.jsxs)("select",{style:De,value:e.role,onChange:c=>t("role",c.target.value),children:[(0,d.jsx)("option",{value:"employee",children:"Employee"}),(0,d.jsx)("option",{value:"manager",children:"Management"})]})})]}),(0,d.jsx)(vc,{icon:_s,title:"Login"}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:11},children:[(0,d.jsx)(We,{label:"Login ID",hint:n==="edit"?"Can't be changed":u?"\u26A0 Already in use":"Used to sign in",children:(0,d.jsx)("input",{style:{...De,fontFamily:Be,borderColor:u?I.red:I.border,...n==="edit"?{background:I.line,color:I.faint,cursor:"not-allowed"}:null},value:e.loginId,onChange:c=>t("loginId",c.target.value.replace(/\s/g,"")),placeholder:"e.g. ramesh",disabled:n==="edit"})}),n==="add"&&(0,d.jsx)(We,{label:"Password",hint:"Min 4 characters",children:(0,d.jsxs)("div",{style:{position:"relative"},children:[(0,d.jsx)("input",{style:{...De,fontFamily:Be,paddingRight:38},type:s?"text":"password",value:e.password,onChange:c=>t("password",c.target.value),placeholder:"Set a password"}),(0,d.jsx)("button",{onClick:()=>o(c=>!c),type:"button",style:{position:"absolute",right:6,top:"50%",transform:"translateY(-50%)",border:"none",background:"transparent",cursor:"pointer",color:I.faint,display:"grid",placeItems:"center",padding:4},children:s?(0,d.jsx)(Vo,{size:16}):(0,d.jsx)(qo,{size:16})})]})})]}),n==="edit"&&(0,d.jsx)("div",{style:{fontSize:11.5,color:I.faint,marginTop:-3},children:"To change this person's password, use the Supabase dashboard \u2192 Authentication \u2192 Users."}),(0,d.jsx)(vc,{icon:jo,title:"Personal"}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:11},children:[(0,d.jsx)(We,{label:"Date of birth",children:(0,d.jsx)("input",{type:"date",style:De,value:e.dob,onChange:c=>t("dob",c.target.value)})}),(0,d.jsx)(We,{label:"Phone",children:(0,d.jsx)("input",{style:De,value:e.phone,onChange:c=>t("phone",c.target.value),placeholder:"+91 ..."})}),(0,d.jsx)(We,{label:"Blood group",children:(0,d.jsxs)("select",{style:De,value:e.bloodGroup,onChange:c=>t("bloodGroup",c.target.value),children:[(0,d.jsx)("option",{value:"",children:"\u2014"}),MB.map(c=>(0,d.jsx)("option",{children:c},c))]})})]}),(0,d.jsx)(We,{label:"Email",children:(0,d.jsx)("input",{type:"email",style:De,value:e.email,onChange:c=>t("email",c.target.value),placeholder:"name@email.com"})}),(0,d.jsx)(We,{label:"Address",children:(0,d.jsx)("textarea",{style:{...De,minHeight:54,resize:"vertical",fontFamily:cn},value:e.address,onChange:c=>t("address",c.target.value),placeholder:"Street, area, city, PIN"})}),(0,d.jsx)(vc,{icon:Go,title:"Bank account"}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:11},children:[(0,d.jsx)(We,{label:"Bank name",children:(0,d.jsx)("input",{style:De,value:e.bankName,onChange:c=>t("bankName",c.target.value),placeholder:"e.g. HDFC Bank"})}),(0,d.jsx)(We,{label:"Account number",children:(0,d.jsx)("input",{style:{...De,fontFamily:Be},value:e.bankAccount,onChange:c=>t("bankAccount",c.target.value),placeholder:"Account no."})}),(0,d.jsx)(We,{label:"IFSC code",children:(0,d.jsx)("input",{style:{...De,fontFamily:Be},value:e.ifsc,onChange:c=>t("ifsc",c.target.value.toUpperCase()),placeholder:"HDFC0001234"})})]}),(0,d.jsx)(vc,{icon:Es,title:"Emergency contact"}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:11},children:[(0,d.jsx)(We,{label:"Contact name",children:(0,d.jsx)("input",{style:De,value:e.emergencyName,onChange:c=>t("emergencyName",c.target.value),placeholder:"Full name"})}),(0,d.jsx)(We,{label:"Contact phone",children:(0,d.jsx)("input",{style:De,value:e.emergencyPhone,onChange:c=>t("emergencyPhone",c.target.value),placeholder:"+91 ..."})}),(0,d.jsx)(We,{label:"Relationship",children:(0,d.jsx)("input",{style:De,value:e.emergencyRelation,onChange:c=>t("emergencyRelation",c.target.value),placeholder:"e.g. Spouse"})})]})]})}var s_={empId:"",name:"",title:"",dept:"Creative",role:"employee",loginId:"",password:"",dob:"",phone:"",email:"",address:"",bloodGroup:"",bankName:"",bankAccount:"",ifsc:"",emergencyName:"",emergencyPhone:"",emergencyRelation:""};function YB({existing:e,onSubmit:t}){let[r,a]=(0,ke.useState)(s_),[n,i]=(0,ke.useState)(""),[s,o]=(0,ke.useState)(!1),l=(g,p)=>{a(y=>({...y,[g]:p})),i("")},u=WB(e),c=(r.loginId||"").trim().toLowerCase(),f=!!c&&e.some(g=>(g.loginId||"").toLowerCase()===c),h=r.name.trim()&&r.loginId.trim()&&r.password.length>=4&&!f&&!s,m=async()=>{if(!r.name.trim())return i("Name is required.");if(!r.loginId.trim())return i("Login ID is required.");if(f)return i("That login ID is already taken.");if(r.password.length<4)return i("Password must be at least 4 characters.");let g=i_[e.length%i_.length],p={...r,name:r.name.trim(),title:r.title.trim()||"Team Member",loginId:r.loginId.trim().toLowerCase(),empId:(r.empId||"").trim()||u,color:g};o(!0),i("");try{await t(p),a(s_)}catch(y){i(y?.message||"Could not create employee.")}finally{o(!1)}};return(0,d.jsxs)("div",{style:{display:"grid",gap:11},children:[(0,d.jsx)(__,{data:r,set:l,existing:e,selfId:null,mode:"add",idPlaceholder:u}),n&&(0,d.jsx)("div",{style:{fontSize:12,color:I.red,fontWeight:600},children:n}),(0,d.jsx)(je,{onClick:m,icon:gc,disabled:!h,children:s?"Creating account\u2026":"Add employee"})]})}function C_({emp:e,showLogin:t}){let r=({icon:a,label:n,value:i,mono:s})=>(0,d.jsxs)("div",{style:{display:"flex",gap:12,padding:"8px 0",borderBottom:`1px solid ${I.line}`},children:[(0,d.jsxs)("div",{style:{width:130,color:I.faint,fontSize:12,display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[a&&(0,d.jsx)(a,{size:13}),n]}),(0,d.jsx)("div",{style:{fontSize:13,color:i?I.ink:I.faint,fontFamily:s&&i?Be:cn,wordBreak:"break-word"},children:i||"\u2014"})]});return(0,d.jsxs)("div",{children:[(0,d.jsx)(r,{icon:Nn,label:"Employee ID",value:e.empId,mono:!0}),(0,d.jsx)(r,{icon:ws,label:"Designation",value:e.title}),(0,d.jsx)(r,{icon:ln,label:"Department",value:e.dept}),(0,d.jsx)(r,{icon:Li,label:"Role",value:e.role==="manager"?"Management":"Employee"}),(0,d.jsx)(r,{icon:nc,label:"Date of birth",value:e.dob?`${TB(e.dob)}${r_(e.dob)!=null?` \xB7 ${r_(e.dob)} yrs`:""}`:""}),(0,d.jsx)(r,{icon:Es,label:"Phone",value:e.phone,mono:!0}),(0,d.jsx)(r,{icon:Is,label:"Email",value:e.email}),(0,d.jsx)(r,{icon:Ei,label:"Address",value:e.address}),(0,d.jsx)(r,{icon:oc,label:"Blood group",value:e.bloodGroup}),(0,d.jsx)(r,{icon:Go,label:"Bank",value:e.bankName}),(0,d.jsx)(r,{label:"Account no.",value:e.bankAccount,mono:!0}),(0,d.jsx)(r,{label:"IFSC code",value:e.ifsc,mono:!0}),(0,d.jsx)(r,{icon:jo,label:"Emergency",value:e.emergencyName?`${e.emergencyName}${e.emergencyRelation?` (${e.emergencyRelation})`:""}`:""}),(0,d.jsx)(r,{label:"Emergency phone",value:e.emergencyPhone,mono:!0}),t&&(0,d.jsx)(r,{icon:_s,label:"Login ID",value:e.loginId,mono:!0})]})}function QB({emp:e,employees:t,canEdit:r,onSave:a,onClose:n}){let[i,s]=(0,ke.useState)(!1),[o,l]=(0,ke.useState)(()=>({...e,password:""})),u=(g,p)=>l(y=>({...y,[g]:p})),c=(o.loginId||"").trim().toLowerCase(),f=!!c&&t.some(g=>g.id!==e.id&&(g.loginId||"").toLowerCase()===c),h=o.name.trim()&&o.loginId.trim()&&!f,m=()=>{if(!h)return;let g={...o,name:o.name.trim(),title:o.title.trim()||"Team Member",empId:(o.empId||"").trim()};g.password||delete g.password,a(e.id,g),s(!1)};return(0,d.jsx)("div",{onClick:n,style:{position:"fixed",inset:0,background:"rgba(15,23,42,.45)",zIndex:70,display:"grid",placeItems:"center",padding:16},children:(0,d.jsxs)("div",{onClick:g=>g.stopPropagation(),style:{background:"#fff",borderRadius:16,width:"100%",maxWidth:560,maxHeight:"88vh",overflowY:"auto",boxShadow:"0 24px 70px rgba(16,24,40,.35)"},children:[(0,d.jsxs)("div",{style:{position:"sticky",top:0,background:"#fff",padding:"18px 20px 14px",borderBottom:`1px solid ${I.line}`,display:"flex",alignItems:"center",gap:12,zIndex:1},children:[(0,d.jsx)(Sa,{emp:e,size:44}),(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsxs)("div",{style:{fontSize:16,fontWeight:800,color:I.ink,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[e.name," ",e.role==="manager"&&(0,d.jsx)(et,{tone:"brand",dot:!0,children:"Management"})]}),(0,d.jsxs)("div",{style:{fontSize:12,color:I.faint,fontFamily:Be},children:[e.empId," \xB7 ",e.title]})]}),r&&!i&&(0,d.jsx)(je,{size:"sm",variant:"soft",icon:hc,onClick:()=>s(!0),children:"Edit"}),(0,d.jsx)("button",{onClick:n,style:{border:"none",background:"transparent",cursor:"pointer",color:I.faint,display:"grid",placeItems:"center",padding:4},children:(0,d.jsx)(Ai,{size:20})})]}),(0,d.jsx)("div",{style:{padding:"14px 20px 20px"},children:i?(0,d.jsx)(__,{data:o,set:u,existing:t,selfId:e.id,mode:"edit"}):(0,d.jsx)(C_,{emp:e,showLogin:r})}),i&&(0,d.jsxs)("div",{style:{position:"sticky",bottom:0,background:"#fff",borderTop:`1px solid ${I.line}`,padding:"12px 20px",display:"flex",gap:9},children:[(0,d.jsx)(je,{full:!0,variant:"ghost",onClick:()=>{l({...e,password:""}),s(!1)},children:"Cancel"}),(0,d.jsx)(je,{full:!0,icon:Er,onClick:m,disabled:!h,children:"Save changes"})]})]})})}function I_({getDayItems:e,onCreate:t,onOpenMeeting:r}){let[a,n]=(0,ke.useState)(()=>{let g=new Date;return{y:g.getFullYear(),m:g.getMonth()}}),[i,s]=(0,ke.useState)(Qo(new Date)),o=new Date(a.y,a.m,1),l=o.getDay(),u=new Date(a.y,a.m+1,0).getDate(),c=Qo(new Date),f=[];for(let g=0;gn(g=>({...g.m===0?{y:g.y-1,m:11}:{y:g.y,m:g.m-1}})),icon:ic,children:""}),(0,d.jsx)(je,{size:"sm",variant:"ghost",onClick:()=>{let g=new Date;n({y:g.getFullYear(),m:g.getMonth()}),s(Qo(g))},children:"Today"}),(0,d.jsx)(je,{size:"sm",variant:"ghost",onClick:()=>n(g=>({...g.m===11?{y:g.y+1,m:0}:{y:g.y,m:g.m+1}})),icon:Wo,children:""})]})]}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(7,1fr)",padding:"0 10px 10px"},children:[["S","M","T","W","T","F","S"].map((g,p)=>(0,d.jsx)("div",{style:{textAlign:"center",fontSize:11,fontWeight:700,color:I.faint,padding:"4px 0 8px"},children:g},p)),f.map((g,p)=>{if(g===null)return(0,d.jsx)("div",{},p);let y=Qo(new Date(a.y,a.m,g)),w=e(y),v=y===c,x=y===i;return(0,d.jsxs)("button",{onClick:()=>s(y),style:{aspectRatio:"1",margin:2,borderRadius:9,border:`1px solid ${x?I.brand:"transparent"}`,background:x?I.brandSoft:v?"#F8FAFC":"transparent",cursor:"pointer",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"flex-start",padding:"5px 0",position:"relative"},children:[(0,d.jsx)("span",{style:{fontSize:12.5,fontWeight:v?800:600,color:v?I.brand:I.ink},children:g}),(0,d.jsx)("div",{style:{display:"flex",gap:2,marginTop:3,flexWrap:"wrap",justifyContent:"center"},children:w.slice(0,3).map((_,T)=>(0,d.jsx)("span",{style:{width:5,height:5,borderRadius:999,background:_.color}},T))})]},p)})]})]}),(0,d.jsx)(rt,{title:ta(i),sub:m.length?`${m.length} item${m.length>1?"s":""}`:"Nothing scheduled",action:t?(0,d.jsx)(je,{size:"sm",icon:Ii,onClick:()=>t(i),children:"New meeting"}):null,children:m.length===0?(0,d.jsxs)("div",{style:{color:I.faint,fontSize:13,padding:"12px 0"},children:["No meetings, leaves or events on this day.",t&&" Use \u201CNew meeting\u201D to schedule one."]}):(0,d.jsx)("div",{style:{display:"grid",gap:9},children:m.map((g,p)=>{let y=g.meeting&&r;return(0,d.jsxs)("div",{onClick:y?()=>r(g.meeting):void 0,className:y?"row-hover":void 0,style:{display:"flex",gap:10,alignItems:"center",padding:10,border:`1px solid ${I.line}`,borderRadius:10,cursor:y?"pointer":"default"},children:[(0,d.jsx)("span",{style:{width:8,height:8,borderRadius:999,background:g.color,flexShrink:0}}),(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsxs)("div",{style:{fontSize:13.5,fontWeight:600,color:I.ink,display:"flex",alignItems:"center",gap:6},children:[g.label,y&&(0,d.jsx)(Wo,{size:14,style:{color:I.faint}})]}),g.meta&&(0,d.jsx)("div",{style:{fontSize:12,color:I.faint,marginTop:1,fontFamily:g.mono?Be:cn},children:g.meta})]}),g.meeting&&(0,d.jsx)(h0,{meeting:g.meeting,compact:!0})]},p)})})})]})}function o_({leads:e,stages:t=Zo,deadStage:r=s0}){let a=t.map(s=>e.filter(o=>o.stage===s.key).length),n=e.filter(s=>s.stage===r.key).length,i=Math.max(...a,1);return(0,d.jsxs)("div",{style:{display:"grid",gap:10},children:[t.map((s,o)=>{let l=Math.max(a[o]/i*100,a[o]?14:6),u=o>0&&a[o-1]?Math.round(a[o]/a[o-1]*100):null;return(0,d.jsxs)("div",{children:[(0,d.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:5},children:[(0,d.jsxs)("div",{style:{fontSize:13,fontWeight:600,color:I.ink,display:"flex",alignItems:"center",gap:7},children:[(0,d.jsx)("span",{style:{width:9,height:9,borderRadius:3,background:s.color}}),s.label,u!==null&&(0,d.jsxs)("span",{style:{fontSize:11,color:I.faint,fontFamily:Be},children:["\u2193 ",u,"%"]})]}),(0,d.jsxs)("div",{style:{fontSize:12,color:I.sub,fontFamily:Be},children:[a[o]," record",a[o]!==1?"s":""]})]}),(0,d.jsx)("div",{style:{height:30,background:"#F4F5F8",borderRadius:8,overflow:"hidden"},children:(0,d.jsx)("div",{style:{width:`${l}%`,height:"100%",background:s.color,borderRadius:8,display:"flex",alignItems:"center",paddingLeft:10,minWidth:28},children:(0,d.jsx)("span",{style:{color:"#fff",fontWeight:800,fontSize:13,fontFamily:Be},children:a[o]})})})]},s.key)}),n>0&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,fontSize:12,color:I.faint,marginTop:2},children:[(0,d.jsx)("span",{style:{width:9,height:9,borderRadius:3,background:r.color}})," ",r.label,": ",(0,d.jsx)("strong",{style:{color:I.sub,fontFamily:Be},children:n})]})]})}function ZB({leads:e}){return(0,d.jsx)("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:wc.map(t=>{let r=e.filter(n=>n.category===t).length,a=Dg(t);return(0,d.jsxs)("div",{style:{display:"inline-flex",alignItems:"center",gap:7,background:"#fff",border:`1px solid ${I.line}`,borderRadius:10,padding:"7px 12px"},children:[(0,d.jsx)("span",{style:{width:9,height:9,borderRadius:3,background:a.color}}),(0,d.jsx)("span",{style:{fontSize:12.5,color:I.sub,fontWeight:600},children:t}),(0,d.jsx)("span",{style:{fontFamily:Be,fontSize:13,fontWeight:800,color:I.ink},children:r})]},t)})})}function eN({attendance:e,total:t}){let r=[];for(let n=6;n>=0;n--){let i=c_(-n),s=Qo(i),o=new Set(e.filter(l=>l.date===s).map(l=>l.employeeId)).size;r.push({key:s,label:i.toLocaleDateString("en-IN",{weekday:"short"})[0],n:o,today:n===0})}let a=Math.max(t,1);return(0,d.jsx)("div",{style:{display:"flex",alignItems:"flex-end",gap:10,height:132,padding:"4px 2px"},children:r.map((n,i)=>(0,d.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",gap:6,height:"100%",justifyContent:"flex-end"},children:[(0,d.jsx)("div",{style:{fontSize:11,fontWeight:700,color:I.sub,fontFamily:Be},children:n.n}),(0,d.jsx)("div",{style:{width:"100%",height:`${n.n/a*100}%`,minHeight:4,background:n.today?I.brand:I.brandSoft,borderRadius:6}}),(0,d.jsx)("div",{style:{fontSize:11,color:I.faint,fontWeight:600},children:n.label})]},i))})}function E_({meetings:e,now:t,scopeIds:r}){let a=e.filter(l=>!r||l.attendees.includes(r)||l.organizer===r),n=a.find(l=>kc(l,t)==="live"),i=a.find(l=>kc(l,t)==="soon"),s=n||i;if(!s)return null;let o=!!n;return(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"12px 16px",borderRadius:12,marginBottom:18,background:o?"#0F172A":I.amberSoft,color:o?"#fff":"#7A4A06",border:o?"none":`1px solid ${I.amber}33`},children:[(0,d.jsx)("div",{style:{width:36,height:36,borderRadius:9,display:"grid",placeItems:"center",background:o?I.green:I.amber,color:"#fff",flexShrink:0},children:o?(0,d.jsx)(sc,{size:18}):(0,d.jsx)(ac,{size:18})}),(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:11,fontWeight:700,textTransform:"uppercase",letterSpacing:.6,opacity:.85},children:o?"\u25CF Meeting in progress":"Starting soon"}),(0,d.jsx)("div",{style:{fontWeight:700,fontSize:14.5,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s.title})]}),(0,d.jsxs)("div",{style:{textAlign:"right",flexShrink:0},children:[(0,d.jsxs)("div",{style:{fontFamily:Be,fontSize:13,fontWeight:700},children:[fn(s.start)," \u2013 ",fn(s.end)]}),(0,d.jsxs)("div",{style:{fontSize:11.5,opacity:.8,display:"flex",alignItems:"center",gap:4,justifyContent:"flex-end"},children:[s.online?(0,d.jsx)(ea,{size:12}):(0,d.jsx)(ln,{size:12}),s.location]})]})]})}function L_({user:e,nav:t,active:r,setActive:a,onLogout:n,children:i}){let[s,o]=(0,ke.useState)(!1),l=f=>(0,d.jsx)("div",{style:{display:"grid",gap:3},children:t.map(h=>{let m=r===h.id,g=h.icon;return(0,d.jsxs)("button",{onClick:()=>{a(h.id),f&&f()},style:{display:"flex",alignItems:"center",gap:11,padding:"9px 12px",borderRadius:10,border:"none",cursor:"pointer",background:m?I.brandSoft:"transparent",color:m?I.brandInk:I.sub,fontWeight:m?700:600,fontSize:13.5,textAlign:"left",width:"100%"},children:[(0,d.jsx)(g,{size:18}),h.label,h.badge?(0,d.jsx)("span",{style:{marginLeft:"auto",background:I.red,color:"#fff",fontSize:10.5,fontWeight:800,borderRadius:999,minWidth:18,height:18,display:"grid",placeItems:"center",padding:"0 5px"},children:h.badge}):null]},h.id)})}),u=(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"4px 6px 16px"},children:[(0,d.jsx)("img",{src:Og,alt:"The Simple Trade",width:38,height:38,style:{display:"block",borderRadius:"50%"}}),(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{style:{fontWeight:800,fontSize:17,color:I.ink,letterSpacing:-.3},children:"The Simple Trade"}),(0,d.jsx)("div",{style:{fontSize:10.5,color:I.faint,fontWeight:600,letterSpacing:.3},children:"TEAM CONSOLE"})]})]}),c=(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:10,border:`1px solid ${I.line}`,borderRadius:11,marginTop:"auto"},children:[(0,d.jsx)(Sa,{emp:e,size:36}),(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:13,fontWeight:700,color:I.ink,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,d.jsx)("div",{style:{fontSize:11,color:I.faint},children:e.title})]}),(0,d.jsx)("button",{onClick:n,title:"Sign out",style:{border:`1px solid ${I.border}`,background:"#fff",borderRadius:9,padding:7,cursor:"pointer",color:I.sub,display:"grid",placeItems:"center"},children:(0,d.jsx)(Jo,{size:15})})]});return(0,d.jsxs)("div",{style:{minHeight:"100vh",background:I.bg,color:I.ink,fontFamily:cn,display:"flex"},children:[(0,d.jsxs)("aside",{className:"dsk-side",style:{width:250,borderRight:`1px solid ${I.border}`,background:"#fff",padding:16,display:"flex",flexDirection:"column",position:"sticky",top:0,height:"100vh"},children:[u,(0,d.jsx)("div",{style:{flex:1,overflowY:"auto"},children:l()}),c]}),s&&(0,d.jsx)("div",{onClick:()=>o(!1),style:{position:"fixed",inset:0,background:"rgba(15,23,42,.4)",zIndex:40}}),(0,d.jsxs)("aside",{style:{position:"fixed",top:0,left:s?0:-290,width:270,height:"100vh",background:"#fff",borderRight:`1px solid ${I.border}`,padding:16,display:"flex",flexDirection:"column",zIndex:50,transition:"left .22s ease",boxShadow:s?"8px 0 30px rgba(16,24,40,.12)":"none"},className:"mob-side",children:[(0,d.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[u,(0,d.jsx)("button",{onClick:()=>o(!1),style:{border:"none",background:"transparent",cursor:"pointer",color:I.sub,marginBottom:16},children:(0,d.jsx)(Ai,{size:20})})]}),(0,d.jsx)("div",{style:{flex:1,overflowY:"auto"},children:l(()=>o(!1))}),c]}),(0,d.jsxs)("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column"},children:[(0,d.jsxs)("header",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:`1px solid ${I.border}`,background:"rgba(255,255,255,.85)",backdropFilter:"blur(8px)",position:"sticky",top:0,zIndex:30},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12},children:[(0,d.jsx)("button",{className:"mob-menu",onClick:()=>o(!0),style:{border:`1px solid ${I.border}`,background:"#fff",borderRadius:9,padding:8,cursor:"pointer",color:I.ink,display:"none"},children:(0,d.jsx)(fc,{size:18})}),(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{style:{fontSize:17,fontWeight:800,color:I.ink,letterSpacing:-.3},children:t.find(f=>f.id===r)?.label}),(0,d.jsxs)("div",{style:{fontSize:12,color:I.faint},children:[e.role==="manager"?"Management workspace":"Employee workspace"," \xB7 Puducherry"]})]})]}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14},children:[(0,d.jsx)(et,{tone:e.role==="manager"?"brand":"sky",dot:!0,children:e.role==="manager"?"Management":"Employee"}),(0,d.jsx)("div",{className:"dsk-clock",children:(0,d.jsx)(zB,{})})]})]}),(0,d.jsx)("main",{style:{padding:18,flex:1},className:"main-pad",children:i})]}),(0,d.jsx)("style",{children:` *{ -webkit-font-smoothing:antialiased; box-sizing:border-box; } input:focus,textarea:focus,select:focus{ border-color:${I.brand}!important; box-shadow:0 0 0 3px ${I.brandSoft}; } button{ transition:filter .15s, background .15s, transform .05s, border-color .15s; } button:active{ transform:translateY(1px); } a{ transition:opacity .15s; } a:hover{ opacity:.82; } ::-webkit-scrollbar{ width:10px; height:10px; } ::-webkit-scrollbar-thumb{ background:#D7DCE3; border-radius:8px; border:2px solid ${I.bg}; } .row-hover:hover{ background:#FBFCFE; } @media (max-width:860px){ .dsk-side{ display:none!important; } .mob-menu{ display:grid!important; } .dsk-clock{ display:none; } .cal-grid{ grid-template-columns:1fr!important; } .main-pad{ padding:14px!important; } } @media (min-width:861px){ .mob-side{ display:none!important; } } `})]})}function tN({user:e,db:t,actions:r,now:a,onLogout:n}){let[i,s]=(0,ke.useState)("today"),[o,l]=(0,ke.useState)("Acquisition"),[u,c]=(0,ke.useState)(null),[f,h]=(0,ke.useState)(!1),m=U=>t.employees.find(B=>B.id===U)||{name:"\u2014",color:"#999"},g=t.attendance.find(U=>U.employeeId===e.id&&U.date===ra(0)),p=t.attendance.filter(U=>U.employeeId===e.id).sort((U,B)=>B.date.localeCompare(U.date)).slice(0,6),y=t.leaves.filter(U=>U.employeeId===e.id),w=t.leads.filter(U=>U.ownerId===e.id),v=t.meetings.filter(U=>U.attendees.includes(e.id)||U.organizer===e.id),x=async()=>{h(!0),await r.checkIn(e.id),h(!1)},_=U=>{let B=[];return t.meetings.filter(te=>te.date===U&&(te.attendees.includes(e.id)||te.organizer===e.id)).forEach(te=>B.push({color:I.brand,label:te.title,meta:`${fn(te.start)} \u2013 ${fn(te.end)} \xB7 ${te.location}`,meeting:te})),t.leaves.filter(te=>te.employeeId===e.id&&te.status!=="rejected"&&U>=te.from&&U<=te.to).forEach(te=>B.push({color:I.amber,label:`${te.type} leave (${te.status})`,meta:te.reason})),t.events.filter(te=>te.date===U).forEach(te=>B.push({color:te.type==="holiday"?I.red:I.sky,label:te.title})),B},T=[{id:"today",label:"Today",icon:Ko},{id:"leave",label:"Leave",icon:Ss,badge:y.filter(U=>U.status==="pending").length||0},{id:"calendar",label:"Calendar",icon:Ci},{id:"meetings",label:"Meetings",icon:ea},{id:"leads",label:"My Leads",icon:Mn},{id:"profile",label:"My Profile",icon:Nn}].map(U=>({...U,badge:U.badge||null})),E=()=>{let U=t.leaves.some(B=>B.employeeId===e.id&&B.status==="approved"&&ra(0)>=B.from&&ra(0)<=B.to)?"leave":g?g.checkOut?"done":"in":"out";return(0,d.jsxs)("div",{style:{display:"grid",gap:16},children:[(0,d.jsx)(rt,{title:"Attendance",sub:f_(a),children:(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr auto",gap:16,alignItems:"center"},className:"att-grid",children:[(0,d.jsxs)("div",{children:[U==="leave"&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,d.jsx)("div",{style:{width:46,height:46,borderRadius:12,background:I.amberSoft,color:"#B54708",display:"grid",placeItems:"center"},children:(0,d.jsx)(ws,{size:22})}),(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{style:{fontWeight:700,fontSize:15},children:"On approved leave today"}),(0,d.jsx)("div",{style:{fontSize:12.5,color:I.faint},children:"Enjoy your day off."})]})]}),U==="out"&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,d.jsx)("div",{style:{width:46,height:46,borderRadius:12,background:"#F2F4F7",color:I.sub,display:"grid",placeItems:"center"},children:(0,d.jsx)(zo,{size:22})}),(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{style:{fontWeight:700,fontSize:15},children:"Not checked in yet"}),(0,d.jsx)("div",{style:{fontSize:12.5,color:I.faint},children:"Capture your location to mark attendance."})]})]}),(U==="in"||U==="done")&&(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,d.jsx)("div",{style:{width:46,height:46,borderRadius:12,background:I.greenSoft,color:"#067647",display:"grid",placeItems:"center"},children:(0,d.jsx)(Er,{size:22})}),(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{style:{fontWeight:700,fontSize:15},children:U==="done"?"Day completed":"Checked in"}),(0,d.jsxs)("div",{style:{fontSize:12.5,color:I.faint,fontFamily:Be},children:["In ",Un(new Date(g.checkIn)),g.checkOut?` \xB7 Out ${Un(new Date(g.checkOut))}`:"",g.checkOut?` \xB7 ${i0(g.checkIn,g.checkOut).toFixed(1)} hrs`:""]})]})]}),g&&(0,d.jsx)("div",{style:{marginTop:12},children:(0,d.jsx)(c0,{loc:g.loc})})]}),(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,minWidth:170},children:[U==="out"&&(0,d.jsx)(je,{size:"lg",full:!0,icon:f?dc:Ei,onClick:x,disabled:f,children:f?"Capturing location\u2026":"Check in"}),U==="in"&&(0,d.jsx)(je,{size:"lg",full:!0,variant:"dark",icon:Jo,onClick:()=>r.checkOut(g.id),children:"Check out"}),U==="done"&&(0,d.jsx)(je,{size:"lg",full:!0,variant:"ghost",disabled:!0,icon:Er,children:"Completed"}),U==="leave"&&(0,d.jsx)(je,{size:"lg",full:!0,variant:"ghost",disabled:!0,children:"On leave"})]})]})}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:14},className:"stat-grid",children:[(0,d.jsx)(Mr,{label:"This week present",value:`${p.length}/6`,sub:"days",icon:un,tone:"green"}),(0,d.jsx)(Mr,{label:"Pending leaves",value:y.filter(B=>B.status==="pending").length,sub:"awaiting approval",icon:Ss,tone:"amber"}),(0,d.jsx)(Mr,{label:"Active leads",value:w.filter(B=>B.stage!=="traded"&&B.stage!=="dead").length,sub:"in your funnel",icon:Mn,tone:"brand"})]}),(0,d.jsx)(rt,{title:"Recent attendance",sub:"Your last check-ins",children:p.length===0?(0,d.jsx)("div",{style:{color:I.faint,fontSize:13},children:"No records yet."}):(0,d.jsx)("div",{style:{display:"grid",gap:8},children:p.map(B=>(0,d.jsxs)("div",{className:"row-hover",style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"9px 4px",borderBottom:`1px solid ${I.line}`},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,d.jsx)("div",{style:{width:8,height:8,borderRadius:999,background:B.date===ra(0)?I.green:I.faint}}),(0,d.jsx)("span",{style:{fontSize:13,fontWeight:600},children:ta(B.date)})]}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12},children:[(0,d.jsxs)("span",{style:{fontFamily:Be,fontSize:12.5,color:I.sub},children:[Un(new Date(B.checkIn)),B.checkOut?` \u2192 ${Un(new Date(B.checkOut))}`:" \u2192 \u2014"]}),(0,d.jsx)(c0,{loc:B.loc})]})]},B.id))})})]})},k=()=>(0,d.jsxs)("div",{style:{display:"grid",gap:16},children:[(0,d.jsx)(jB,{leaves:t.leaves,empId:e.id}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0,1fr) minmax(0,1.2fr)",gap:16},className:"cal-grid",children:[(0,d.jsx)(rt,{title:"Request leave",sub:"Submit for management approval",children:(0,d.jsx)(VB,{onSubmit:U=>r.addLeave({...U,employeeId:e.id})})}),(0,d.jsx)(rt,{title:"My requests",sub:`${y.length} total`,children:y.length===0?(0,d.jsx)("div",{style:{color:I.faint,fontSize:13},children:"No requests yet."}):(0,d.jsx)("div",{style:{display:"grid",gap:9},children:y.map(U=>(0,d.jsxs)("div",{style:{border:`1px solid ${I.line}`,borderRadius:11,padding:12},children:[(0,d.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:5},children:[(0,d.jsxs)("span",{style:{fontWeight:700,fontSize:13.5},children:[U.type," leave"]}),(0,d.jsx)(et,{tone:U.status==="approved"?"green":U.status==="rejected"?"red":"amber",dot:!0,children:U.status})]}),(0,d.jsxs)("div",{style:{fontSize:12.5,color:I.sub,fontFamily:Be},children:[ta(U.from),U.from!==U.to?` \u2192 ${ta(U.to)}`:""]}),(0,d.jsx)("div",{style:{fontSize:12.5,color:I.faint,marginTop:3},children:U.reason})]},U.id))})})]})]}),b=()=>(0,d.jsx)(I_,{getDayItems:_,onOpenMeeting:U=>c(U)}),O=()=>{let U=[...v].sort((B,te)=>(B.date+B.start).localeCompare(te.date+te.start));return(0,d.jsx)(rt,{title:"My meetings",sub:`${U.length} scheduled \xB7 add any to your calendar`,children:U.length===0?(0,d.jsx)("div",{style:{color:I.faint,fontSize:13},children:"No meetings scheduled for you yet."}):(0,d.jsx)("div",{style:{display:"grid",gap:12},children:U.map(B=>{let te=kc(B,a);return(0,d.jsxs)("div",{onClick:()=>c(B),className:"row-hover",style:{background:"#fff",border:`1px solid ${te==="live"?I.green:I.border}`,borderRadius:13,padding:14,display:"flex",gap:13,alignItems:"center",flexWrap:"wrap",boxShadow:"0 1px 2px rgba(16,24,40,.04)",cursor:"pointer"},children:[(0,d.jsx)("div",{style:{width:44,height:44,borderRadius:11,background:B.online?I.skySoft:"#F2F4F7",color:B.online?"#026AA2":I.sub,display:"grid",placeItems:"center",flexShrink:0},children:B.online?(0,d.jsx)(ea,{size:20}):(0,d.jsx)(ln,{size:20})}),(0,d.jsxs)("div",{style:{flex:1,minWidth:130},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,d.jsx)("span",{style:{fontWeight:700,fontSize:14},children:B.title}),te==="live"&&(0,d.jsx)(et,{tone:"green",dot:!0,children:"Live now"}),te==="soon"&&(0,d.jsx)(et,{tone:"amber",dot:!0,children:"Soon"}),te==="past"&&(0,d.jsx)(et,{tone:"gray",children:"Ended"})]}),(0,d.jsxs)("div",{style:{fontSize:12.5,color:I.faint,marginTop:2},children:[(0,d.jsx)(f0,{loc:B.location,stop:!0})," \xB7 with ",B.attendees.slice(0,3).map(q=>m(q).name.split(" ")[0]).join(", "),B.attendees.length>3?` +${B.attendees.length-3}`:"",As(B)&&(0,d.jsxs)(d.Fragment,{children:[" \xB7 ",(0,d.jsx)(y_,{m:B,stop:!0,compact:!0})]})]})]}),(0,d.jsxs)("div",{style:{textAlign:"right",flexShrink:0},children:[(0,d.jsx)("div",{style:{fontFamily:Be,fontSize:13,fontWeight:700},children:fn(B.start)}),(0,d.jsx)("div",{style:{fontSize:11.5,color:I.faint},children:ta(B.date)})]}),(0,d.jsx)(h0,{meeting:B})]},B.id)})})})},H=()=>{let U=o==="Service",B=w.filter(K=>(K.subCategory||"Acquisition")===o),te=w.filter(K=>(K.subCategory||"Acquisition")==="Acquisition").length,q=w.filter(K=>K.subCategory==="Service").length,j=CB(o),ie=(K,de,se)=>{let ge=o===K;return(0,d.jsxs)("button",{onClick:()=>l(K),style:{border:`1.5px solid ${ge?I.brand:I.border}`,background:ge?I.brandSoft:"#fff",color:ge?I.brandInk:I.sub,borderRadius:9,padding:"7px 13px",fontSize:12.5,fontWeight:700,cursor:"pointer",display:"inline-flex",alignItems:"center",gap:6},children:[de," ",(0,d.jsx)("span",{style:{fontFamily:Be,fontSize:11,opacity:.8},children:se})]})};return(0,d.jsx)(rt,{title:"My leads",sub:"Move your assigned records down the pipeline",action:(0,d.jsxs)("div",{style:{display:"flex",gap:7},children:[ie("Acquisition","Acquisition",te),ie("Service","Service",q)]}),children:B.length===0?(0,d.jsxs)("div",{style:{color:I.faint,fontSize:13},children:["No ",U?"service records":"leads"," assigned to you yet. Your manager assigns them to you."]}):(0,d.jsx)("div",{style:{display:"grid",gap:8},children:[...B].sort((K,de)=>u0(K.stage)-u0(de.stage)).map(K=>{let de=EB(K.stage),se=l0(K.stage),ge=K.stage===j;return(0,d.jsxs)("div",{className:"row-hover",style:{display:"flex",alignItems:"center",gap:10,padding:"10px 4px",borderBottom:`1px solid ${I.line}`,flexWrap:"wrap",opacity:ge?.6:1},children:[(0,d.jsxs)("div",{style:{flex:1,minWidth:150},children:[(0,d.jsx)("div",{style:{fontSize:13.5,fontWeight:600},children:K.name}),(0,d.jsxs)("div",{style:{fontSize:11.5,color:I.faint,display:"flex",gap:8,alignItems:"center",flexWrap:"wrap"},children:[(0,d.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:3},children:[(0,d.jsx)(Es,{size:11}),K.phone]}),K.email&&(0,d.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:3},children:[(0,d.jsx)(Is,{size:11}),K.email]}),(0,d.jsxs)("span",{children:["\xB7 ",K.source]})]})]}),(0,d.jsx)(et,{tone:Dg(K.category).tone,children:K.category||"New Lead"}),(0,d.jsx)(et,{tone:se.tone,dot:!0,children:se.label}),ge?(0,d.jsx)(je,{size:"sm",variant:"ghost",onClick:()=>r.moveLead(K.id,IB(o)),children:"Reopen"}):(0,d.jsxs)(d.Fragment,{children:[de?(0,d.jsxs)(je,{size:"sm",variant:"soft",onClick:()=>r.moveLead(K.id,de),children:["\u2192 ",l0(de).label]}):(0,d.jsx)(et,{tone:"green",children:U?"Closed \u2713":"Traded \u2713"}),(0,d.jsx)("button",{onClick:()=>r.moveLead(K.id,j),title:U?"Cancel request":"Mark as dead/lost",style:{border:`1px solid ${I.border}`,background:"#fff",borderRadius:8,padding:"5px 8px",fontSize:11.5,color:I.faint,cursor:"pointer"},children:U?"Cancel":"Dead"})]})]},K.id)})})})};return(0,d.jsxs)(L_,{user:e,nav:T,active:i,setActive:s,onLogout:n,children:[(0,d.jsx)(E_,{meetings:t.meetings,now:a,scopeIds:e.id}),i==="today"&&E(),i==="leave"&&k(),i==="calendar"&&b(),i==="meetings"&&O(),i==="leads"&&H(),i==="profile"&&(0,d.jsxs)(rt,{title:"My profile",sub:"Your details on file \u2014 ask your manager to update anything",children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:14,paddingBottom:14,borderBottom:`1px solid ${I.line}`},children:[(0,d.jsx)(Sa,{emp:e,size:48}),(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{style:{fontSize:16,fontWeight:800,color:I.ink},children:e.name}),(0,d.jsxs)("div",{style:{fontSize:12,color:I.faint,fontFamily:Be},children:[e.empId," \xB7 ",e.title]})]})]}),(0,d.jsx)(C_,{emp:e,showLogin:!0})]}),u&&(0,d.jsx)(S_,{meeting:u,empById:m,now:a,onClose:()=>c(null)}),(0,d.jsx)("style",{children:"@media (max-width:760px){ .att-grid{ grid-template-columns:1fr!important; } .stat-grid{ grid-template-columns:1fr!important; } }"})]})}function rN({user:e,db:t,actions:r,now:a,onLogout:n}){let[i,s]=(0,ke.useState)("overview"),[o,l]=(0,ke.useState)(ra(0)),[u,c]=(0,ke.useState)("date"),[f,h]=(0,ke.useState)(null),[m,g]=(0,ke.useState)(null),[p,y]=(0,ke.useState)(null),[w,v]=(0,ke.useState)(null),[x,_]=(0,ke.useState)(null),[T,E]=(0,ke.useState)(null),[k,b]=(0,ke.useState)(null),O=t.employees,H=z=>O.find(W=>W.id===z)||{name:"\u2014",color:"#999",title:""},U=O.length,B=(z,W=ra(0))=>t.leaves.some(G=>G.employeeId===z&&G.status==="approved"&&W>=G.from&&W<=G.to),te=new Set(t.attendance.filter(z=>z.date===ra(0)).map(z=>z.employeeId)),q=O.filter(z=>B(z.id)).length,j=t.leaves.filter(z=>z.status==="pending"),ie=z=>{let W=[];return t.meetings.filter(G=>G.date===z).forEach(G=>W.push({color:I.brand,label:G.title,meta:`${fn(G.start)} \u2013 ${fn(G.end)} \xB7 ${G.location}`,meeting:G})),t.leaves.filter(G=>G.status==="approved"&&z>=G.from&&z<=G.to).forEach(G=>W.push({color:I.amber,label:`${H(G.employeeId).name} \u2014 ${G.type} leave`,meta:G.reason})),t.events.filter(G=>G.date===z).forEach(G=>W.push({color:G.type==="holiday"?I.red:I.sky,label:G.title})),W},K=[{id:"overview",label:"Overview",icon:Ko},{id:"team",label:"Employees",icon:Ti},{id:"attendance",label:"Attendance",icon:un},{id:"approvals",label:"Leave Approvals",icon:Ss,badge:j.length||null},{id:"calendar",label:"Calendar",icon:Ci},{id:"meetings",label:"Meetings",icon:ea},{id:"acq",label:"Acquisition",icon:Mn},{id:"svc",label:"Service",icon:Cs}],de=z=>{h(z),c("employee"),s("attendance")},se=O.map(z=>{let W=t.attendance.find(ee=>ee.employeeId===z.id&&ee.date===o),G=B(z.id,o);return{e:z,rec:W,leave:G}}),ge=()=>{let z=t.leads.filter(ee=>(ee.subCategory||"Acquisition")==="Acquisition"),W=t.leads.filter(ee=>ee.subCategory==="Service"),G=z.filter(ee=>ee.stage==="traded");return(0,d.jsxs)("div",{style:{display:"grid",gap:16},children:[(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:14},className:"kpi-grid",children:[(0,d.jsx)(Mr,{label:"Present today",value:te.size,sub:`of ${U} team`,icon:un,tone:"green"}),(0,d.jsx)(Mr,{label:"On leave",value:q,sub:"approved today",icon:ws,tone:"amber"}),(0,d.jsx)(Mr,{label:"Acquisition",value:z.length,sub:`${G.length} traded`,icon:Mn,tone:"brand"}),(0,d.jsx)(Mr,{label:"Service",value:W.length,sub:"open + closed",icon:Cs,tone:"amber"})]}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0,1.3fr) minmax(0,1fr)",gap:16},className:"cal-grid",children:[(0,d.jsx)(rt,{title:"Attendance \u2014 last 7 days",sub:"Daily team check-ins",children:(0,d.jsx)(eN,{attendance:t.attendance,total:U})}),(0,d.jsx)(rt,{title:"Who's in today",sub:`${te.size} checked in`,children:(0,d.jsx)("div",{style:{display:"grid",gap:8,maxHeight:230,overflowY:"auto"},children:O.map(ee=>{let Q=t.attendance.find(P=>P.employeeId===ee.id&&P.date===ra(0)),Le=B(ee.id);return(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,d.jsx)(Sa,{emp:ee,size:32}),(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsx)("div",{style:{fontSize:13,fontWeight:600},children:ee.name}),(0,d.jsx)("div",{style:{fontSize:11,color:I.faint},children:Q?`In ${Un(new Date(Q.checkIn))}`:Le?"On leave":"Not in"})]}),Q?(0,d.jsx)(et,{tone:"green",dot:!0,children:Q.checkOut?"Out":"Present"}):Le?(0,d.jsx)(et,{tone:"amber",dot:!0,children:"Leave"}):(0,d.jsx)(et,{tone:"gray",children:"Absent"})]},ee.id)})})})]}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0,1fr) minmax(0,1fr)",gap:16},className:"cal-grid",children:[(0,d.jsx)(rt,{title:"Acquisition funnel",sub:`${G.length} traded \xB7 ${z.length} leads`,action:(0,d.jsx)(je,{size:"sm",variant:"soft",onClick:()=>s("acq"),children:"Open"}),children:(0,d.jsx)(o_,{leads:z,stages:Zo,deadStage:s0})}),(0,d.jsx)(rt,{title:"Pending leave requests",action:j.length?(0,d.jsx)(je,{size:"sm",variant:"soft",onClick:()=>s("approvals"),children:"Review"}):null,children:j.length===0?(0,d.jsx)("div",{style:{color:I.faint,fontSize:13},children:"All caught up \u2014 nothing pending."}):(0,d.jsx)("div",{style:{display:"grid",gap:9},children:j.map(ee=>(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:10,border:`1px solid ${I.line}`,borderRadius:11},children:[(0,d.jsx)(Sa,{emp:H(ee.employeeId),size:32}),(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsxs)("div",{style:{fontSize:13,fontWeight:600},children:[H(ee.employeeId).name," \xB7 ",ee.type]}),(0,d.jsxs)("div",{style:{fontSize:11.5,color:I.faint,fontFamily:Be},children:[ta(ee.from),ee.from!==ee.to?` \u2192 ${ta(ee.to)}`:""]})]}),(0,d.jsx)(je,{size:"sm",variant:"success",icon:Er,onClick:()=>r.decideLeave(ee.id,"approved"),children:""}),(0,d.jsx)(je,{size:"sm",variant:"danger",icon:Ma,onClick:()=>r.decideLeave(ee.id,"rejected"),children:""})]},ee.id))})})]})]})},ne=()=>{let z=(G,ee)=>{let Q=u===G;return(0,d.jsx)("button",{onClick:()=>c(G),style:{border:`1.5px solid ${Q?I.brand:I.border}`,background:Q?I.brandSoft:"#fff",color:Q?I.brandInk:I.sub,borderRadius:9,padding:"7px 13px",fontSize:12.5,fontWeight:700,cursor:"pointer"},children:ee})},W=(0,d.jsxs)("div",{style:{display:"flex",gap:7},children:[z("date","By date"),z("employee","By employee")]});if(u==="employee"){let G=O.find(Se=>Se.id===f)||O[0],ee=t.attendance.filter(Se=>Se.employeeId===G?.id).sort((Se,Te)=>Te.date.localeCompare(Se.date)),Q=ee.filter(Se=>Se.checkOut),Le=Q.length?Q.reduce((Se,Te)=>Se+i0(Te.checkIn,Te.checkOut),0)/Q.length:0,P=t.leaves.filter(Se=>Se.employeeId===G?.id&&Se.status==="approved");return(0,d.jsx)("div",{style:{display:"grid",gap:16},children:(0,d.jsxs)(rt,{title:"Attendance \u2014 by employee",sub:"Full check-in history with captured location",action:W,children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap",marginBottom:16},children:[(0,d.jsx)(Sa,{emp:G,size:44}),(0,d.jsx)("div",{style:{flex:1,minWidth:180},children:(0,d.jsx)("select",{style:{...De,fontWeight:700,maxWidth:280},value:G?.id,onChange:Se=>h(Se.target.value),children:O.map(Se=>(0,d.jsxs)("option",{value:Se.id,children:[Se.name," \u2014 ",Se.title]},Se.id))})}),(0,d.jsxs)("div",{style:{display:"flex",gap:10},children:[(0,d.jsxs)("div",{style:{textAlign:"center",padding:"6px 14px",background:I.greenSoft,borderRadius:10},children:[(0,d.jsx)("div",{style:{fontSize:18,fontWeight:800,color:"#087443",fontFamily:Be},children:ee.length}),(0,d.jsx)("div",{style:{fontSize:10.5,color:"#087443",fontWeight:600},children:"Days present"})]}),(0,d.jsxs)("div",{style:{textAlign:"center",padding:"6px 14px",background:I.brandSoft,borderRadius:10},children:[(0,d.jsx)("div",{style:{fontSize:18,fontWeight:800,color:I.brandInk,fontFamily:Be},children:Le.toFixed(1)}),(0,d.jsx)("div",{style:{fontSize:10.5,color:I.brandInk,fontWeight:600},children:"Avg hours"})]}),(0,d.jsxs)("div",{style:{textAlign:"center",padding:"6px 14px",background:I.amberSoft,borderRadius:10},children:[(0,d.jsx)("div",{style:{fontSize:18,fontWeight:800,color:"#B54708",fontFamily:Be},children:P.length}),(0,d.jsx)("div",{style:{fontSize:10.5,color:"#B54708",fontWeight:600},children:"Leaves taken"})]})]})]}),(0,d.jsx)("div",{style:{overflowX:"auto"},children:(0,d.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse",minWidth:620},children:[(0,d.jsx)("thead",{children:(0,d.jsx)("tr",{style:{textAlign:"left",color:I.faint,fontSize:11.5,textTransform:"uppercase",letterSpacing:.4},children:["Date","Status","In","Out","Hours","Location"].map((Se,Te)=>(0,d.jsx)("th",{style:{padding:"8px 10px",fontWeight:700},children:Se},Te))})}),(0,d.jsx)("tbody",{children:ee.length===0?(0,d.jsx)("tr",{children:(0,d.jsxs)("td",{colSpan:6,style:{padding:22,textAlign:"center",color:I.faint,fontSize:13},children:["No attendance records yet for ",G?.name,"."]})}):ee.map(Se=>(0,d.jsxs)("tr",{className:"row-hover",style:{borderTop:`1px solid ${I.line}`},children:[(0,d.jsx)("td",{style:{padding:"10px",fontSize:12.5,fontWeight:600},children:ta(Se.date)}),(0,d.jsx)("td",{style:{padding:"10px"},children:Se.checkOut?(0,d.jsx)(et,{tone:"green",dot:!0,children:"Completed"}):(0,d.jsx)(et,{tone:"sky",dot:!0,children:"Open"})}),(0,d.jsx)("td",{style:{padding:"10px",fontFamily:Be,fontSize:12.5,color:I.sub},children:Un(new Date(Se.checkIn))}),(0,d.jsx)("td",{style:{padding:"10px",fontFamily:Be,fontSize:12.5,color:I.sub},children:Se.checkOut?Un(new Date(Se.checkOut)):"\u2014"}),(0,d.jsx)("td",{style:{padding:"10px",fontFamily:Be,fontSize:12.5,color:I.ink,fontWeight:600},children:Se.checkOut?i0(Se.checkIn,Se.checkOut).toFixed(1):"\u2022"}),(0,d.jsx)("td",{style:{padding:"10px"},children:(0,d.jsx)(c0,{loc:Se.loc})})]},Se.id))})]})})]})})}return(0,d.jsx)(rt,{title:"Team attendance",sub:"Everyone's check-in for the selected day",action:(0,d.jsxs)("div",{style:{display:"flex",gap:10,alignItems:"center",flexWrap:"wrap"},children:[W,(0,d.jsx)("input",{type:"date",style:{...De,width:"auto"},value:o,onChange:G=>l(G.target.value)})]}),children:(0,d.jsx)("div",{style:{overflowX:"auto"},children:(0,d.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse",minWidth:680},children:[(0,d.jsx)("thead",{children:(0,d.jsxs)("tr",{style:{textAlign:"left",color:I.faint,fontSize:11.5,textTransform:"uppercase",letterSpacing:.4},children:[(0,d.jsx)("th",{style:{padding:"8px 10px",fontWeight:700},children:"Employee"}),(0,d.jsx)("th",{style:{padding:"8px 10px",fontWeight:700},children:"Status"}),(0,d.jsx)("th",{style:{padding:"8px 10px",fontWeight:700},children:"In"}),(0,d.jsx)("th",{style:{padding:"8px 10px",fontWeight:700},children:"Out"}),(0,d.jsx)("th",{style:{padding:"8px 10px",fontWeight:700},children:"Hours"}),(0,d.jsx)("th",{style:{padding:"8px 10px",fontWeight:700},children:"Location"}),(0,d.jsx)("th",{style:{padding:"8px 10px",fontWeight:700}})]})}),(0,d.jsx)("tbody",{children:se.map(({e:G,rec:ee,leave:Q})=>(0,d.jsxs)("tr",{className:"row-hover",style:{borderTop:`1px solid ${I.line}`},children:[(0,d.jsx)("td",{style:{padding:"10px"},children:(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,d.jsx)(Sa,{emp:G,size:32}),(0,d.jsxs)("div",{children:[(0,d.jsx)("div",{style:{fontSize:13,fontWeight:600},children:G.name}),(0,d.jsx)("div",{style:{fontSize:11,color:I.faint},children:G.title})]})]})}),(0,d.jsx)("td",{style:{padding:"10px"},children:ee?(0,d.jsx)(et,{tone:"green",dot:!0,children:ee.checkOut?"Completed":"Present"}):Q?(0,d.jsx)(et,{tone:"amber",dot:!0,children:"On leave"}):(0,d.jsx)(et,{tone:"gray",children:"Absent"})}),(0,d.jsx)("td",{style:{padding:"10px",fontFamily:Be,fontSize:12.5,color:I.sub},children:ee?Un(new Date(ee.checkIn)):"\u2014"}),(0,d.jsx)("td",{style:{padding:"10px",fontFamily:Be,fontSize:12.5,color:I.sub},children:ee?.checkOut?Un(new Date(ee.checkOut)):"\u2014"}),(0,d.jsx)("td",{style:{padding:"10px",fontFamily:Be,fontSize:12.5,color:I.ink,fontWeight:600},children:ee?.checkOut?i0(ee.checkIn,ee.checkOut).toFixed(1):ee?"\u2022":"\u2014"}),(0,d.jsx)("td",{style:{padding:"10px"},children:ee?(0,d.jsx)(c0,{loc:ee.loc}):(0,d.jsx)("span",{style:{color:I.faint,fontSize:12},children:"\u2014"})}),(0,d.jsx)("td",{style:{padding:"10px"},children:(0,d.jsxs)("button",{onClick:()=>de(G.id),title:"View full history",style:{border:`1px solid ${I.border}`,background:"#fff",borderRadius:8,padding:"5px 9px",fontSize:11.5,fontWeight:600,color:I.brand,cursor:"pointer",display:"inline-flex",alignItems:"center",gap:5},children:[(0,d.jsx)(pc,{size:13})," History"]})})]},G.id))})]})})})},D=()=>{let z=t.leaves.filter(W=>W.status!=="pending");return(0,d.jsxs)("div",{style:{display:"grid",gap:16},children:[(0,d.jsx)(rt,{title:"Pending requests",sub:`${j.length} awaiting your decision`,children:j.length===0?(0,d.jsx)("div",{style:{color:I.faint,fontSize:13},children:"Nothing pending right now."}):(0,d.jsx)("div",{style:{display:"grid",gap:10},children:j.map(W=>(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:12,padding:12,border:`1px solid ${I.line}`,borderRadius:12},children:[(0,d.jsx)(Sa,{emp:H(W.employeeId),size:38}),(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsxs)("div",{style:{fontSize:13.5,fontWeight:700},children:[H(W.employeeId).name," ",(0,d.jsxs)("span",{style:{color:I.faint,fontWeight:600},children:["\xB7 ",W.type]})]}),(0,d.jsxs)("div",{style:{fontSize:12,color:I.sub,fontFamily:Be},children:[ta(W.from),W.from!==W.to?` \u2192 ${ta(W.to)}`:""]}),(0,d.jsx)("div",{style:{fontSize:12,color:I.faint,marginTop:2},children:W.reason}),yc[W.type]!=null&&(0,d.jsxs)("div",{style:{fontSize:11,color:I.faint,marginTop:4},children:[W.type," used this year: ",(0,d.jsx)("strong",{style:{color:I.ink},children:g_(t.leaves,W.employeeId,W.type)})," / ",yc[W.type]]})]}),(0,d.jsx)(je,{size:"sm",variant:"success",icon:Er,onClick:()=>r.decideLeave(W.id,"approved"),children:"Approve"}),(0,d.jsx)(je,{size:"sm",variant:"danger",icon:Ma,onClick:()=>r.decideLeave(W.id,"rejected"),children:"Reject"})]},W.id))})}),(0,d.jsx)(rt,{title:"Decision history",children:z.length===0?(0,d.jsx)("div",{style:{color:I.faint,fontSize:13},children:"No history yet."}):(0,d.jsx)("div",{style:{display:"grid",gap:8},children:z.map(W=>(0,d.jsxs)("div",{className:"row-hover",style:{display:"flex",alignItems:"center",gap:10,padding:"9px 4px",borderBottom:`1px solid ${I.line}`},children:[(0,d.jsx)(Sa,{emp:H(W.employeeId),size:30}),(0,d.jsxs)("div",{style:{flex:1},children:[(0,d.jsx)("span",{style:{fontSize:13,fontWeight:600},children:H(W.employeeId).name})," ",(0,d.jsxs)("span",{style:{fontSize:12,color:I.faint},children:["\xB7 ",W.type," \xB7 ",ta(W.from)]})]}),(0,d.jsx)(et,{tone:W.status==="approved"?"green":"red",dot:!0,children:W.status})]},W.id))})})]})},V=()=>{let z=[...t.meetings].sort((W,G)=>(W.date+W.start).localeCompare(G.date+G.start));return(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0,1fr) minmax(0,1.2fr)",gap:16},className:"cal-grid",children:[(0,d.jsx)(rt,{title:"Schedule a meeting",sub:"Notifies attendees on their dashboard",children:(0,d.jsx)(v_,{employees:O,organizerId:e.id,onSubmit:r.addMeeting})}),(0,d.jsx)(rt,{title:"All meetings",sub:`${t.meetings.length} scheduled`,action:(0,d.jsx)(je,{size:"sm",icon:Ii,onClick:()=>v(ra(0)),children:"New meeting"}),children:(0,d.jsx)("div",{style:{display:"grid",gap:9},children:z.map(W=>{let G=kc(W,a);return(0,d.jsxs)("div",{onClick:()=>_(W),className:"row-hover",style:{border:`1px solid ${G==="live"?I.green:I.line}`,borderRadius:11,padding:11,display:"flex",gap:11,alignItems:"center",flexWrap:"wrap",cursor:"pointer"},children:[(0,d.jsx)("div",{style:{width:38,height:38,borderRadius:10,background:W.online?I.skySoft:"#F2F4F7",color:W.online?"#026AA2":I.sub,display:"grid",placeItems:"center",flexShrink:0},children:W.online?(0,d.jsx)(ea,{size:17}):(0,d.jsx)(ln,{size:17})}),(0,d.jsxs)("div",{style:{flex:1,minWidth:120},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[(0,d.jsx)("span",{style:{fontWeight:700,fontSize:13.5},children:W.title}),G==="live"&&(0,d.jsx)(et,{tone:"green",dot:!0,children:"Live"}),G==="soon"&&(0,d.jsx)(et,{tone:"amber",dot:!0,children:"Soon"}),G==="past"&&(0,d.jsx)(et,{tone:"gray",children:"Ended"})]}),(0,d.jsxs)("div",{style:{fontSize:11.5,color:I.faint},children:[W.attendees.length," attendees \xB7 ",(0,d.jsx)(f0,{loc:W.location,stop:!0,style:{fontSize:11.5}}),As(W)&&(0,d.jsxs)(d.Fragment,{children:[" \xB7 ",(0,d.jsx)(y_,{m:W,stop:!0,compact:!0})]})]})]}),(0,d.jsxs)("div",{style:{textAlign:"right",flexShrink:0},children:[(0,d.jsx)("div",{style:{fontFamily:Be,fontSize:12.5,fontWeight:700},children:fn(W.start)}),(0,d.jsx)("div",{style:{fontSize:11,color:I.faint},children:ta(W.date)})]}),(0,d.jsx)(h0,{meeting:W}),(0,d.jsx)("button",{onClick:ee=>{ee.stopPropagation(),E(W)},title:"Delete meeting",style:{border:`1px solid ${I.redSoft}`,background:I.redSoft,borderRadius:8,padding:"6px 8px",color:I.red,cursor:"pointer",display:"inline-flex",alignItems:"center",flexShrink:0},children:(0,d.jsx)(Nr,{size:14})})]},W.id)})})})]})},N=z=>{let W=z==="Service",G=_B(z),ee=W?l_:s0,Q=t.leads.filter(we=>(we.subCategory||"Acquisition")===z),Le=[...Q].sort((we,xe)=>u0(we.stage)-u0(xe.stage)),P=W?"record":"lead",Se=W?{label:"New requests",value:Q.filter(we=>we.stage==="request").length,sub:"to action",icon:$o,tone:"sky"}:{label:"Unassigned",value:Q.filter(we=>we.stage==="new").length,sub:"new \u2014 assign these",icon:$o,tone:"sky"},Te=W?{label:"In progress",value:Q.filter(we=>["progress","awaiting"].includes(we.stage)).length,sub:"being worked",icon:Cs,tone:"amber"}:{label:"In progress",value:Q.filter(we=>!["new","traded","dead"].includes(we.stage)).length,sub:"being worked",icon:Mn,tone:"violet"},Ve=W?{label:"Resolved",value:Q.filter(we=>["resolved","closed"].includes(we.stage)).length,sub:"done",icon:Er,tone:"green"}:{label:"Traded",value:Q.filter(we=>we.stage==="traded").length,sub:"converted",icon:Er,tone:"green"};return(0,d.jsxs)("div",{style:{display:"grid",gap:16},children:[(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:14},className:"kpi-grid",children:[(0,d.jsx)(Mr,{label:Se.label,value:Se.value,sub:Se.sub,icon:Se.icon,tone:Se.tone}),(0,d.jsx)(Mr,{label:Te.label,value:Te.value,sub:Te.sub,icon:Te.icon,tone:Te.tone}),(0,d.jsx)(Mr,{label:Ve.label,value:Ve.value,sub:Ve.sub,icon:Ve.icon,tone:Ve.tone}),(0,d.jsx)(Mr,{label:`Total ${P}s`,value:Q.length,sub:W?"in service":"in pipeline",icon:Ti,tone:"brand"})]}),(0,d.jsx)(rt,{title:"By category",sub:"Our Client \xB7 Dhan Client \xB7 New Lead",children:(0,d.jsx)(ZB,{leads:Q})}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0,1fr) minmax(0,1fr)",gap:16},className:"cal-grid",children:[(0,d.jsx)(rt,{title:W?"Service pipeline":"Conversion funnel",sub:W?"New Request \u2192 Closed":"New \u2192 Traded account",children:(0,d.jsx)(o_,{leads:Q,stages:G,deadStage:ee})}),(0,d.jsx)(rt,{title:W?"Add a service record":"Add a lead",sub:"You add & assign \u2014 employees move the stages",children:(0,d.jsx)(KB,{employees:O,subCategory:z,onSubmit:r.addLead})})]}),(0,d.jsx)(JB,{employees:O,subCategory:z,onImport:r.addLeads}),(0,d.jsx)(rt,{title:W?"All service records":"All leads",sub:`${Q.length} ${P}${Q.length!==1?"s":""} \xB7 set category, assign or remove`,action:Q.length>0?(0,d.jsx)(je,{size:"sm",variant:"soft",icon:ks,onClick:()=>XB(Q,O,P),children:"Export Excel"}):null,children:(0,d.jsx)("div",{style:{overflowX:"auto"},children:(0,d.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse",minWidth:800},children:[(0,d.jsx)("thead",{children:(0,d.jsx)("tr",{style:{textAlign:"left",color:I.faint,fontSize:11.5,textTransform:"uppercase",letterSpacing:.4},children:[W?"Client":"Lead","Source",W?"Status":"Stage","Category","Assigned to",""].map((we,xe)=>(0,d.jsx)("th",{style:{padding:"8px 10px",fontWeight:700},children:we},xe))})}),(0,d.jsx)("tbody",{children:Le.length===0?(0,d.jsx)("tr",{children:(0,d.jsxs)("td",{colSpan:6,style:{padding:22,textAlign:"center",color:I.faint,fontSize:13},children:["No ",P,"s yet. Add one above or bulk-upload via Excel."]})}):Le.map(we=>{let xe=l0(we.stage),ht=Dg(we.category);return(0,d.jsxs)("tr",{className:"row-hover",style:{borderTop:`1px solid ${I.line}`,opacity:we.stage==="dead"||we.stage==="svc_dead"?.6:1},children:[(0,d.jsxs)("td",{style:{padding:"9px 10px"},children:[(0,d.jsx)("div",{style:{fontSize:13,fontWeight:600},children:we.name}),(0,d.jsx)("div",{style:{fontSize:11,color:I.faint,fontFamily:Be},children:we.phone}),we.email&&(0,d.jsxs)("div",{style:{fontSize:11,color:I.faint,fontFamily:Be,display:"flex",alignItems:"center",gap:4},children:[(0,d.jsx)(Is,{size:10}),we.email]})]}),(0,d.jsx)("td",{style:{padding:"9px 10px",fontSize:12.5,color:I.sub},children:we.source}),(0,d.jsx)("td",{style:{padding:"9px 10px"},children:(0,d.jsx)(et,{tone:xe.tone,dot:!0,children:xe.label})}),(0,d.jsx)("td",{style:{padding:"9px 10px"},children:(0,d.jsx)("select",{value:we.category||"New Lead",onChange:pt=>r.setLeadCategory(we.id,pt.target.value),style:{...De,padding:"5px 8px",fontSize:12,width:"auto",minWidth:120,color:ht.color==="#98A2B3"?I.sub:ht.color,fontWeight:600},children:wc.map(pt=>(0,d.jsx)("option",{value:pt,style:{color:I.ink},children:pt},pt))})}),(0,d.jsx)("td",{style:{padding:"9px 10px"},children:(0,d.jsxs)("select",{value:we.ownerId||"",onChange:pt=>r.assignLead(we.id,pt.target.value),style:{...De,padding:"5px 8px",fontSize:12,width:"auto",minWidth:138},children:[(0,d.jsx)("option",{value:"",children:"Unassigned"}),O.map(pt=>(0,d.jsx)("option",{value:pt.id,children:pt.name},pt.id))]})}),(0,d.jsx)("td",{style:{padding:"9px 10px"},children:(0,d.jsx)("button",{onClick:()=>b(we),title:`Delete ${P}`,style:{border:`1px solid ${I.redSoft}`,background:I.redSoft,borderRadius:8,padding:"6px 8px",color:I.red,cursor:"pointer",display:"inline-flex",alignItems:"center"},children:(0,d.jsx)(Nr,{size:14})})})]},we.id)})})]})})}),k&&(0,d.jsx)("div",{onClick:()=>b(null),style:{position:"fixed",inset:0,background:"rgba(15,23,42,.45)",zIndex:60,display:"grid",placeItems:"center",padding:20},children:(0,d.jsxs)("div",{onClick:we=>we.stopPropagation(),style:{background:"#fff",borderRadius:16,padding:22,width:"100%",maxWidth:360,boxShadow:"0 20px 60px rgba(16,24,40,.3)"},children:[(0,d.jsx)("div",{style:{width:44,height:44,borderRadius:12,background:I.redSoft,color:I.red,display:"grid",placeItems:"center",marginBottom:13},children:(0,d.jsx)(Nr,{size:22})}),(0,d.jsxs)("div",{style:{fontSize:16,fontWeight:800,color:I.ink},children:['Delete "',k.name,'"?']}),(0,d.jsx)("div",{style:{fontSize:13,color:I.sub,marginTop:6,lineHeight:1.5},children:"This removes the record. This can't be undone."}),(0,d.jsxs)("div",{style:{display:"flex",gap:9,marginTop:18},children:[(0,d.jsx)(je,{full:!0,variant:"ghost",onClick:()=>b(null),children:"Cancel"}),(0,d.jsx)(je,{full:!0,variant:"danger",icon:Nr,onClick:()=>{r.deleteLead(k.id),b(null)},children:"Delete"})]})]})})]})},M=()=>{let z=O.filter(W=>W.role==="manager");return(0,d.jsxs)("div",{style:{display:"grid",gap:16},children:[(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:14},className:"kpi-grid",children:[(0,d.jsx)(Mr,{label:"Total team",value:O.length,sub:"active members",icon:Ti,tone:"brand"}),(0,d.jsx)(Mr,{label:"Management",value:z.length,sub:"admin access",icon:Li,tone:"sky"}),(0,d.jsx)(Mr,{label:"Employees",value:O.length-z.length,sub:"standard access",icon:un,tone:"green"})]}),(0,d.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0,1fr) minmax(0,1.25fr)",gap:16},className:"cal-grid",children:[(0,d.jsx)(rt,{title:"Add an employee",sub:"Create a login so they can sign in & check in",children:(0,d.jsx)(YB,{existing:O,onSubmit:W=>{r.addEmployee(W)}})}),(0,d.jsx)(rt,{title:"Team members",sub:`${O.length} people \xB7 Profile for full details, History for attendance`,children:(0,d.jsx)("div",{style:{display:"grid",gap:9},children:O.map(W=>{let G=W.id===e.id,ee=W.role==="manager"&&z.length===1,Q=G||ee,Le=te.has(W.id);return(0,d.jsxs)("div",{style:{border:`1px solid ${I.line}`,borderRadius:12,padding:12},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:11},children:[(0,d.jsx)(Sa,{emp:W,size:40}),(0,d.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,flexWrap:"wrap"},children:[(0,d.jsx)("span",{style:{fontSize:13.5,fontWeight:700,color:I.ink},children:W.name}),W.role==="manager"?(0,d.jsx)(et,{tone:"brand",dot:!0,children:"Management"}):(0,d.jsx)(et,{tone:"gray",children:"Employee"}),Le&&(0,d.jsx)(et,{tone:"green",dot:!0,children:"In today"})]}),(0,d.jsxs)("div",{style:{fontSize:11.5,color:I.faint,marginTop:1},children:[W.title," \xB7 ",W.dept]})]})]}),(0,d.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:10,flexWrap:"wrap"},children:[(0,d.jsxs)("div",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11.5,fontFamily:Be,color:I.sub,background:"#F7F8FA",padding:"4px 9px",borderRadius:7},children:[(0,d.jsx)(Nn,{size:12})," ",W.empId||"\u2014"]}),(0,d.jsxs)("div",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:11.5,fontFamily:Be,color:I.sub,background:"#F7F8FA",padding:"4px 9px",borderRadius:7},children:[(0,d.jsx)(_s,{size:12})," ",W.loginId]}),(0,d.jsxs)("div",{style:{marginLeft:"auto",display:"flex",gap:8,flexWrap:"wrap"},children:[(0,d.jsxs)("button",{onClick:()=>y(W),style:{border:`1px solid ${I.border}`,background:"#fff",borderRadius:8,padding:"6px 11px",fontSize:12,fontWeight:600,color:I.brand,cursor:"pointer",display:"inline-flex",alignItems:"center",gap:5},children:[(0,d.jsx)(Nn,{size:13})," Profile"]}),(0,d.jsxs)("button",{onClick:()=>de(W.id),style:{border:`1px solid ${I.border}`,background:"#fff",borderRadius:8,padding:"6px 11px",fontSize:12,fontWeight:600,color:I.sub,cursor:"pointer",display:"inline-flex",alignItems:"center",gap:5},children:[(0,d.jsx)(un,{size:13})," History"]}),(0,d.jsxs)("button",{onClick:()=>!Q&&g(W),disabled:Q,title:G?"You can't remove yourself":ee?"Can't remove the only manager":"Remove employee",style:{border:`1px solid ${Q?I.border:I.redSoft}`,background:Q?"#F7F8FA":I.redSoft,borderRadius:8,padding:"6px 11px",fontSize:12,fontWeight:600,color:Q?I.faint:I.red,cursor:Q?"not-allowed":"pointer",display:"inline-flex",alignItems:"center",gap:5},children:[(0,d.jsx)(Nr,{size:13})," Remove"]})]})]})]},W.id)})})})]}),m&&(0,d.jsx)("div",{onClick:()=>g(null),style:{position:"fixed",inset:0,background:"rgba(15,23,42,.45)",zIndex:60,display:"grid",placeItems:"center",padding:20},children:(0,d.jsxs)("div",{onClick:W=>W.stopPropagation(),style:{background:"#fff",borderRadius:16,padding:22,width:"100%",maxWidth:380,boxShadow:"0 20px 60px rgba(16,24,40,.3)"},children:[(0,d.jsx)("div",{style:{width:44,height:44,borderRadius:12,background:I.redSoft,color:I.red,display:"grid",placeItems:"center",marginBottom:13},children:(0,d.jsx)(Nr,{size:22})}),(0,d.jsxs)("div",{style:{fontSize:16,fontWeight:800,color:I.ink},children:["Remove ",m.name,"?"]}),(0,d.jsx)("div",{style:{fontSize:13,color:I.sub,marginTop:6,lineHeight:1.5},children:"This deletes their login, attendance history, and leave records. This can't be undone."}),(0,d.jsxs)("div",{style:{display:"flex",gap:9,marginTop:18},children:[(0,d.jsx)(je,{full:!0,variant:"ghost",onClick:()=>g(null),children:"Cancel"}),(0,d.jsx)(je,{full:!0,variant:"danger",icon:Nr,onClick:()=>{r.deleteEmployee(m.id),f===m.id&&h(null),g(null)},children:"Remove"})]})]})}),p&&(0,d.jsx)(QB,{emp:O.find(W=>W.id===p.id)||p,employees:O,canEdit:!0,onSave:(W,G)=>{r.updateEmployee(W,G),y(ee=>({...ee,...G}))},onClose:()=>y(null)})]})};return(0,d.jsxs)(L_,{user:e,nav:K,active:i,setActive:s,onLogout:n,children:[(0,d.jsx)(E_,{meetings:t.meetings,now:a,scopeIds:null}),i==="overview"&&ge(),i==="team"&&M(),i==="attendance"&&ne(),i==="approvals"&&D(),i==="calendar"&&(0,d.jsx)(I_,{getDayItems:ie,onCreate:z=>v(z),onOpenMeeting:z=>_(z)}),i==="meetings"&&V(),i==="acq"&&N("Acquisition"),i==="svc"&&N("Service"),w!==null&&(0,d.jsx)(GB,{employees:O,organizerId:e.id,defaultDate:w,onSubmit:z=>{r.addMeeting(z),v(null),s("meetings")},onClose:()=>v(null)}),x&&(0,d.jsx)(S_,{meeting:x,empById:H,now:a,canDelete:!0,onDelete:z=>{_(null),E(z)},onClose:()=>_(null)}),T&&(0,d.jsx)("div",{onClick:()=>E(null),style:{position:"fixed",inset:0,background:"rgba(15,23,42,.45)",zIndex:80,display:"grid",placeItems:"center",padding:20},children:(0,d.jsxs)("div",{onClick:z=>z.stopPropagation(),style:{background:"#fff",borderRadius:16,padding:22,width:"100%",maxWidth:380,boxShadow:"0 20px 60px rgba(16,24,40,.3)"},children:[(0,d.jsx)("div",{style:{width:44,height:44,borderRadius:12,background:I.redSoft,color:I.red,display:"grid",placeItems:"center",marginBottom:13},children:(0,d.jsx)(Nr,{size:22})}),(0,d.jsxs)("div",{style:{fontSize:16,fontWeight:800,color:I.ink},children:['Delete "',T.title,'"?']}),(0,d.jsx)("div",{style:{fontSize:13,color:I.sub,marginTop:6,lineHeight:1.5},children:"This removes the meeting for everyone and takes it off the calendar. This can't be undone."}),(0,d.jsxs)("div",{style:{display:"flex",gap:9,marginTop:18},children:[(0,d.jsx)(je,{full:!0,variant:"ghost",onClick:()=>E(null),children:"Cancel"}),(0,d.jsx)(je,{full:!0,variant:"danger",icon:Nr,onClick:()=>{r.deleteMeeting(T.id),E(null)},children:"Delete"})]})]})}),(0,d.jsx)("style",{children:"@media (max-width:760px){ .kpi-grid{ grid-template-columns:1fr 1fr!important; } }"})]})}function aN({onBootstrap:e,initialError:t}){let[r,a]=(0,ke.useState)("signin"),[n,i]=(0,ke.useState)(""),[s,o]=(0,ke.useState)(""),[l,u]=(0,ke.useState)(""),[c,f]=(0,ke.useState)(!1),[h,m]=(0,ke.useState)(!1),[g,p]=(0,ke.useState)(t||""),y=n.trim()&&s&&(r==="signin"||l.trim())&&!h,w=async()=>{m(!0),p("");let{error:T}=await dt.auth.signInWithPassword({email:Bg(n),password:s});if(T){let E=/invalid login credentials/i.test(T.message)?"Invalid login ID or password.":T.message;p(E),m(!1)}},v=async()=>{m(!0),p("");try{await e(n,s,l)}catch(T){p(T?.message||"Setup failed."),m(!1)}},x=()=>{y&&(r==="setup"?v():w())},_=T=>{T.key==="Enter"&&x()};return(0,d.jsx)("div",{style:{minHeight:"100vh",background:I.bg,fontFamily:cn,display:"grid",placeItems:"center",padding:20},children:(0,d.jsxs)("div",{style:{width:"100%",maxWidth:420},children:[(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",marginBottom:22},children:[(0,d.jsx)("img",{src:Og,alt:"The Simple Trade",width:92,height:92,style:{display:"block",borderRadius:"50%",filter:"drop-shadow(0 8px 20px rgba(16,24,40,.18))"}}),(0,d.jsx)("div",{style:{fontSize:26,fontWeight:800,color:I.ink,marginTop:14,letterSpacing:-.6},children:"The Simple Trade"}),(0,d.jsx)("div",{style:{fontSize:13,color:I.faint,marginTop:3},children:"Management / Employee Login"})]}),(0,d.jsxs)("div",{style:{background:"#fff",border:`1px solid ${I.border}`,borderRadius:16,padding:22,boxShadow:"0 2px 8px rgba(16,24,40,.05)"},children:[(0,d.jsx)("div",{style:{fontSize:15,fontWeight:800,color:I.ink,marginBottom:3},children:r==="setup"?"First-time setup":"Sign in"}),(0,d.jsx)("div",{style:{fontSize:12.5,color:I.faint,marginBottom:18},children:r==="setup"?"Create the founder (admin) account \u2014 do this once.":"Enter your login ID and password"}),r==="setup"&&(0,d.jsx)("div",{style:{marginBottom:13},children:(0,d.jsx)(We,{label:"Your name",children:(0,d.jsx)("input",{style:De,value:l,onChange:T=>{u(T.target.value),p("")},onKeyDown:_,placeholder:"e.g. Dharanidharan",autoFocus:!0})})}),(0,d.jsx)("div",{style:{marginBottom:13},children:(0,d.jsx)(We,{label:"Login ID",children:(0,d.jsxs)("div",{style:{position:"relative"},children:[(0,d.jsx)("span",{style:{position:"absolute",left:11,top:"50%",transform:"translateY(-50%)",color:I.faint,display:"grid",placeItems:"center"},children:(0,d.jsx)(un,{size:16})}),(0,d.jsx)("input",{style:{...De,paddingLeft:36,fontFamily:Be},value:n,onChange:T=>{i(T.target.value.replace(/\s/g,"")),p("")},onKeyDown:_,placeholder:"e.g. admin",autoFocus:r==="signin"})]})})}),(0,d.jsx)("div",{style:{marginBottom:16},children:(0,d.jsx)(We,{label:"Password",children:(0,d.jsxs)("div",{style:{position:"relative"},children:[(0,d.jsx)("span",{style:{position:"absolute",left:11,top:"50%",transform:"translateY(-50%)",color:I.faint,display:"grid",placeItems:"center"},children:(0,d.jsx)(uc,{size:15})}),(0,d.jsx)("input",{style:{...De,paddingLeft:36,paddingRight:38,fontFamily:Be},type:c?"text":"password",value:s,onChange:T=>{o(T.target.value),p("")},onKeyDown:_,placeholder:r==="setup"?"Set a strong password":"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"}),(0,d.jsx)("button",{onClick:()=>f(T=>!T),type:"button",style:{position:"absolute",right:6,top:"50%",transform:"translateY(-50%)",border:"none",background:"transparent",cursor:"pointer",color:I.faint,display:"grid",placeItems:"center",padding:4},children:c?(0,d.jsx)(Vo,{size:16}):(0,d.jsx)(qo,{size:16})})]})})}),g&&(0,d.jsxs)("div",{style:{fontSize:12.5,color:I.red,fontWeight:600,marginBottom:13,display:"flex",alignItems:"flex-start",gap:6},children:[(0,d.jsx)(Ma,{size:14,style:{flexShrink:0,marginTop:1}})," ",(0,d.jsx)("span",{children:g})]}),(0,d.jsx)(je,{full:!0,size:"lg",icon:r==="setup"?Li:cc,onClick:x,disabled:!y,children:h?r==="setup"?"Creating\u2026":"Signing in\u2026":r==="setup"?"Create admin & sign in":"Sign in"}),(0,d.jsx)("div",{style:{textAlign:"center",marginTop:16},children:r==="signin"?(0,d.jsx)("button",{type:"button",onClick:()=>{a("setup"),p(""),n||i("admin")},style:{border:"none",background:"transparent",color:I.brand,fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:cn},children:"First time here? Set up the founder account \u2192"}):(0,d.jsx)("button",{type:"button",onClick:()=>{a("signin"),p("")},style:{border:"none",background:"transparent",color:I.faint,fontSize:12,fontWeight:600,cursor:"pointer",fontFamily:cn},children:"\u2190 Back to sign in"})}),(0,d.jsx)("div",{style:{fontSize:11.5,color:I.faint,textAlign:"center",marginTop:14,lineHeight:1.5},children:"Check-in captures your device location once. Your data is stored securely in the cloud and shared across your team."})]})]})})}function nN({msg:e,onClose:t}){return(0,d.jsxs)("div",{style:{position:"fixed",top:0,left:0,right:0,zIndex:300,background:"#FEF2F2",borderBottom:"1px solid #FECACA",color:"#991B1B",fontSize:12.5,fontWeight:600,padding:"8px 14px",display:"flex",alignItems:"center",gap:10,justifyContent:"center",fontFamily:cn},children:[(0,d.jsx)(Ma,{size:14,style:{flexShrink:0}}),(0,d.jsxs)("span",{style:{wordBreak:"break-word"},children:["Sync issue: ",e]}),(0,d.jsx)("button",{onClick:t,style:{marginLeft:4,border:"none",background:"transparent",color:"#991B1B",cursor:"pointer",textDecoration:"underline",fontWeight:700,flexShrink:0},children:"dismiss"})]})}function Ug(){let[e,t]=(0,ke.useState)("loading"),[r,a]=(0,ke.useState)(null),[n,i]=(0,ke.useState)(new Date),[s,o]=(0,ke.useState)([]),[l,u]=(0,ke.useState)([]),[c,f]=(0,ke.useState)([]),[h,m]=(0,ke.useState)([]),[g,p]=(0,ke.useState)([]),[y,w]=(0,ke.useState)([]),[v,x]=(0,ke.useState)(""),_=(0,ke.useRef)(null),T=(0,ke.useRef)(!1),E=q=>{o(q.employees),u(q.attendance),f(q.leaves),m(q.meetings),p(q.leads),w(q.events)},k=async()=>{try{let q=await n_();E(q),x("")}catch(q){x(q&&q.message||"Sync failed")}},b=q=>{console.error("[supabase]",q),x(q&&q.message||"Action failed \u2014 refreshing."),k()},O=async q=>{try{let{data:j,error:ie}=await dt.from("employees").select("*").eq("id",q).maybeSingle();if(ie)throw ie;if(!j){await dt.auth.signOut(),a(null),x("This login has no employee profile yet. Ask an admin to add you."),t("login");return}let K=await n_();E(K),a(Ng(j)),_.current=q,x(""),t("app")}catch(j){x(j&&j.message||"Could not load your data."),t("login")}},H=async(q,j,ie)=>{T.current=!0;try{let{data:K,error:de}=await dt.auth.signUp({email:Bg(q),password:j});if(de)throw new Error(/already registered|already been registered/i.test(de.message)?"That login already exists \u2014 switch to Sign in.":de.message);let se=K&&K.user&&K.user.id;if(!se)throw new Error("Sign-up didn't return a user. Check that signups are enabled in Supabase \u2192 Authentication.");if(!K.session){try{await dt.auth.signOut()}catch{}throw new Error("Email confirmation is ON. In Supabase \u2192 Authentication \u2192 Sign In / Providers \u2192 Email, turn OFF 'Confirm email', then try setup again.")}let ge={id:se,login_id:(q||"").trim().toLowerCase(),name:(ie||"").trim()||"Founder",role:"manager",emp_id:"DP-001",title:"Founder",dept:"Management",color:"#4338CA"},{error:ne}=await dt.from("employees").insert(ge);if(ne)throw await dt.auth.signOut(),new Error("Couldn't create the founder profile \u2014 an admin may already exist. Try Sign in instead. ("+ne.message+")");T.current=!1,await O(se)}catch(K){throw T.current=!1,t("login"),K}};(0,ke.useEffect)(()=>{let{data:{subscription:q}}=dt.auth.onAuthStateChange((j,ie)=>{if(j==="SIGNED_OUT"||!(ie&&ie.user)){_.current=null,a(null),t("login");return}if(T.current)return;let K=ie.user.id;_.current!==K&&O(K)});return()=>{try{q.unsubscribe()}catch{}}},[]),(0,ke.useEffect)(()=>{let q=setInterval(()=>i(new Date),2e4);return()=>clearInterval(q)},[]),(0,ke.useEffect)(()=>{if(e!=="app")return;let q=()=>{document.visibilityState!=="hidden"&&k()};window.addEventListener("focus",q),document.addEventListener("visibilitychange",q);let j=setInterval(k,25e3);return()=>{window.removeEventListener("focus",q),document.removeEventListener("visibilitychange",q),clearInterval(j)}},[e]);let U={checkIn:async q=>{let j=await AB(),ie={id:Yo(),employeeId:q,date:ra(0),checkIn:new Date().toISOString(),checkOut:null,loc:j};u(de=>[...de,ie]);let{error:K}=await dt.from("attendance").insert({id:ie.id,employee_id:q,date:ie.date,check_in:ie.checkIn,check_out:null,loc:j});K&&b(K)},checkOut:async q=>{let j=new Date().toISOString();u(K=>K.map(de=>de.id===q?{...de,checkOut:j}:de));let{error:ie}=await dt.from("attendance").update({check_out:j}).eq("id",q);ie&&b(ie)},addLeave:async q=>{let j={id:Yo(),status:"pending",createdAt:new Date().toISOString(),...q};f(K=>[j,...K]);let{error:ie}=await dt.from("leaves").insert({id:j.id,employee_id:j.employeeId,type:j.type,from_date:j.from,to_date:j.to,reason:j.reason,status:j.status,created_at:j.createdAt});ie&&b(ie)},decideLeave:async(q,j)=>{f(K=>K.map(de=>de.id===q?{...de,status:j}:de));let{error:ie}=await dt.from("leaves").update({status:j}).eq("id",q);ie&&b(ie)},addMeeting:async q=>{if(r?.role!=="manager")return;let j={id:Yo(),...q};m(K=>[...K,j]);let{error:ie}=await dt.from("meetings").insert(DB(j));ie&&b(ie)},deleteMeeting:async q=>{if(r?.role!=="manager")return;m(ie=>ie.filter(K=>K.id!==q));let{error:j}=await dt.from("meetings").delete().eq("id",q);j&&b(j)},addLead:async q=>{let j=q.subCategory||"Acquisition",ie=j==="Service"?"request":q.ownerId?"assigned":"new",K={id:Yo(),category:"New Lead",email:"",notes:"",updatedAt:new Date().toISOString(),...q,subCategory:j,stage:ie};p(se=>[K,...se]);let{error:de}=await dt.from("leads").insert(a_(K));de&&b(de)},addLeads:async q=>{let j=q.map(K=>{let de=K.subCategory||"Acquisition",se=de==="Service"?"request":K.ownerId?"assigned":"new";return{id:Yo(),category:"New Lead",email:"",notes:"",updatedAt:new Date().toISOString(),...K,subCategory:de,stage:se}});p(K=>[...j,...K]);let{error:ie}=await dt.from("leads").insert(j.map(a_));ie&&b(ie)},assignLead:async(q,j)=>{let ie=null;if(p(K=>K.map(de=>{if(de.id!==q)return de;let se=de.stage;return(de.subCategory||"Acquisition")!=="Service"&&(j&&de.stage==="new"&&(se="assigned"),j||(se="new")),ie={...de,ownerId:j||null,stage:se,updatedAt:new Date().toISOString()},ie})),ie){let{error:K}=await dt.from("leads").update({owner_id:ie.ownerId,stage:ie.stage,updated_at:ie.updatedAt}).eq("id",q);K&&b(K)}},setLeadCategory:async(q,j)=>{let ie=new Date().toISOString();p(de=>de.map(se=>se.id===q?{...se,category:j,updatedAt:ie}:se));let{error:K}=await dt.from("leads").update({category:j,updated_at:ie}).eq("id",q);K&&b(K)},deleteLead:async q=>{p(ie=>ie.filter(K=>K.id!==q));let{error:j}=await dt.from("leads").delete().eq("id",q);j&&b(j)},moveLead:async(q,j)=>{let ie=new Date().toISOString();p(de=>de.map(se=>se.id===q?{...se,stage:j,updatedAt:ie}:se));let{error:K}=await dt.from("leads").update({stage:j,updated_at:ie}).eq("id",q);K&&b(K)},addEmployee:async q=>{let j=await NB(q);o(ie=>[...ie,j])},updateEmployee:async(q,j)=>{let{password:ie,...K}=j;o(se=>se.map(ge=>ge.id===q?{...ge,...K}:ge));let{error:de}=await dt.from("employees").update(p_(K)).eq("id",q);de&&b(de)},deleteEmployee:async q=>{o(ie=>ie.filter(K=>K.id!==q)),u(ie=>ie.filter(K=>K.employeeId!==q)),f(ie=>ie.filter(K=>K.employeeId!==q));let{error:j}=await dt.from("employees").delete().eq("id",q);j&&b(j)}},B=async()=>{x("");try{await dt.auth.signOut()}catch{}};if(e==="loading")return(0,d.jsx)("div",{style:{minHeight:"100vh",background:I.bg,display:"grid",placeItems:"center",fontFamily:cn},children:(0,d.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:14},children:[(0,d.jsx)("img",{src:Og,alt:"The Simple Trade",width:54,height:54,style:{display:"block",borderRadius:"50%"}}),(0,d.jsx)("div",{style:{color:I.faint,fontSize:13,fontWeight:600},children:"Loading workspace\u2026"})]})});if(e!=="app"||!r)return(0,d.jsx)(aN,{onBootstrap:H,initialError:v});let te={employees:s,attendance:l,leaves:c,meetings:h,leads:g,events:y};return(0,d.jsxs)(d.Fragment,{children:[v&&(0,d.jsx)(nN,{msg:v,onClose:()=>x("")}),r.role==="manager"?(0,d.jsx)(rN,{user:r,db:te,actions:U,now:n,onLogout:B}):(0,d.jsx)(tN,{user:r,db:te,actions:U,now:n,onLogout:B})]})}var A_=zn(xc()),Hg=document.getElementById("root");Hg&&(Hg.innerHTML="",(0,T_.createRoot)(Hg).render((0,A_.jsx)(Ug,{})));})(); /*! Bundled license information: react/cjs/react.production.min.js: (** * @license React * react.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) scheduler/cjs/scheduler.production.min.js: (** * @license React * scheduler.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) react-dom/cjs/react-dom.production.min.js: (** * @license React * react-dom.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) react/cjs/react-jsx-runtime.production.min.js: (** * @license React * react-jsx-runtime.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) xlsx/xlsx.mjs: (*! xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com *) xlsx/xlsx.mjs: (*! sheetjs (C) 2013-present SheetJS -- http://sheetjs.com *) lucide-react/dist/esm/shared/src/utils.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/defaultAttributes.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/Icon.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/createLucideIcon.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/alarm-clock.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/briefcase.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/building-2.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/cake.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/calendar-days.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/calendar-plus.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/chevron-left.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/chevron-right.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/circle-check.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/circle-dot.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/circle-x.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/clock.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/contact.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/credit-card.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/download.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/droplet.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/eye-off.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/eye.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/file-spreadsheet.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/file-text.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/inbox.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/key-round.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/landmark.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/layout-dashboard.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/life-buoy.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/link-2.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/lock.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/log-in.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/log-out.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/mail.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/map-pin.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/menu.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/navigation.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/pencil.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/phone.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/plus.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/search.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/shield-check.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/trash-2.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/trending-up.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/upload.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/user-check.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/user-plus.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/users.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/video.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/icons/x.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) lucide-react/dist/esm/lucide-react.js: (** * @license lucide-react v0.383.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. *) */