heyio 3.1.19 → 3.1.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/routes/schedules.d.ts.map +1 -1
- package/dist/api/routes/schedules.js +20 -0
- package/dist/api/routes/schedules.js.map +1 -1
- package/dist/scheduler/engine.d.ts +3 -0
- package/dist/scheduler/engine.d.ts.map +1 -1
- package/dist/scheduler/engine.js +2 -1
- package/dist/scheduler/engine.js.map +1 -1
- package/node_modules/@io/shared/package.json +1 -1
- package/package.json +1 -1
- package/public/assets/{index-B5A5Nmig.css → index-CnhK3Zuq.css} +1 -1
- package/public/assets/{index-8o486hk9.js → index-DJBKkz8R.js} +28 -28
- package/public/assets/index-DJBKkz8R.js.map +1 -0
- package/public/index.html +2 -2
- package/public/assets/index-8o486hk9.js.map +0 -1
|
@@ -318,12 +318,14 @@ Please change the parent <Route path="${S}"> to <Route path="${S==="/"?"*":`${S}
|
|
|
318
318
|
*
|
|
319
319
|
* This source code is licensed under the ISC license.
|
|
320
320
|
* See the LICENSE file in the root directory of this source tree.
|
|
321
|
-
*/const X4=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],qb=Ue("zap",X4),Uk="/api";let jo=null,Fb=null;function Y4(t){jo=t}function J4(t){Fb=t}function oP(){return(jo==null?void 0:jo())??null}async function fc(t,e){const r=jo==null?void 0:jo(),n={"Content-Type":"application/json",...e==null?void 0:e.headers};r&&(n.Authorization=`Bearer ${r}`);let i=await fetch(`${Uk}${t}`,{...e,headers:n});if(i.status===401&&Fb){const a=await Fb();a&&(n.Authorization=`Bearer ${a}`,i=await fetch(`${Uk}${t}`,{...e,headers:n}))}if(!i.ok){const a=await i.json().catch(()=>({error:i.statusText}));throw new Error(a.error??`Request failed: ${i.status}`)}return i.json()}const Ve={get:t=>fc(t),post:(t,e)=>fc(t,{method:"POST",body:e?JSON.stringify(e):void 0}),patch:(t,e)=>fc(t,{method:"PATCH",body:JSON.stringify(e)}),put:(t,e)=>fc(t,{method:"PUT",body:JSON.stringify(e)}),delete:t=>fc(t,{method:"DELETE"})},sP=N.createContext({timezone:"UTC"});function Z4({children:t}){const[e,r]=N.useState("UTC");return N.useEffect(()=>{Ve.get("/config").then(n=>{n.config.timezone&&r(n.config.timezone)}).catch(()=>{})},[]),y.jsx(sP.Provider,{value:{timezone:e},children:t})}function qa(){return N.useContext(sP).timezone}const Q4=[{label:"UTC",value:"UTC"},{label:"Eastern Time (US)",value:"America/New_York"},{label:"Central Time (US)",value:"America/Chicago"},{label:"Mountain Time (US)",value:"America/Denver"},{label:"Pacific Time (US)",value:"America/Los_Angeles"},{label:"Alaska Time",value:"America/Anchorage"},{label:"Hawaii Time",value:"Pacific/Honolulu"},{label:"London (GMT/BST)",value:"Europe/London"},{label:"Central European",value:"Europe/Berlin"},{label:"Eastern European",value:"Europe/Bucharest"},{label:"India (IST)",value:"Asia/Kolkata"},{label:"China (CST)",value:"Asia/Shanghai"},{label:"Japan (JST)",value:"Asia/Tokyo"},{label:"Australia Eastern",value:"Australia/Sydney"},{label:"New Zealand",value:"Pacific/Auckland"},{label:"São Paulo",value:"America/Sao_Paulo"}];function Ws(t,e,r){if(!t)return"";try{return new Date(t).toLocaleString("en-US",{timeZone:e,month:"short",day:"numeric",hour:"numeric",minute:"2-digit",...r})}catch{return new Date(t).toLocaleString()}}function Qh(t,e,r){if(!t)return"";try{return new Date(t).toLocaleTimeString("en-US",{timeZone:e,hour:"numeric",minute:"2-digit",...r})}catch{return new Date(t).toLocaleTimeString()}}function ez(t,e,r){if(!t)return"";try{return new Date(t).toLocaleDateString("en-US",{timeZone:e,month:"short",day:"numeric",...r})}catch{return new Date(t).toLocaleDateString()}}let Rf=[];const If=new Set;function tz(t){Rf=[t,...Rf].slice(0,50);for(const e of If)e()}function rz(){Rf=[];for(const t of If)t()}function nz(){const[,t]=N.useState(0);return N.useEffect(()=>{const e=()=>t(r=>r+1);return If.add(e),()=>{If.delete(e)}},[]),Rf}function iz(){const[t,e]=N.useState(!1),r=nz(),n=N.useRef(null),[i,a]=N.useState(0),o=qa(),c=r.length-i;N.useEffect(()=>{function d(p){n.current&&!n.current.contains(p.target)&&e(!1)}if(t)return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[t]);function u(){e(!t),t||a(r.length)}return y.jsxs("div",{className:"relative",ref:n,children:[y.jsxs("button",{type:"button",onClick:u,className:"relative p-2 rounded-xl hover:bg-white/[0.05] text-zinc-600 hover:text-zinc-300 transition-colors cursor-pointer",title:"Notifications",children:[y.jsx(I5,{className:"w-3.5 h-3.5"}),c>0&&y.jsx("span",{className:"absolute top-1 right-1 w-2 h-2 rounded-full bg-[#E43A9C]"})]}),t&&y.jsxs("div",{className:"absolute right-0 top-full mt-2 w-80 max-h-96 overflow-y-auto rounded-xl border border-white/[0.07] bg-[#1a1a1a] shadow-2xl z-50",children:[y.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-white/[0.07]",children:[y.jsx("span",{className:"text-xs font-mono text-zinc-300",children:"Notifications"}),r.length>0&&y.jsx("button",{type:"button",onClick:rz,className:"text-[10px] font-mono text-zinc-500 hover:text-zinc-300 cursor-pointer",children:"Clear all"})]}),r.length===0?y.jsx("div",{className:"px-4 py-8 text-center text-zinc-600 text-xs font-mono",children:"No notifications yet"}):y.jsx("div",{className:"divide-y divide-white/[0.04]",children:r.map(d=>y.jsxs("div",{className:"px-4 py-3 hover:bg-white/[0.03]",children:[y.jsx("p",{className:"text-xs text-zinc-300 leading-relaxed",children:d.message}),y.jsx("p",{className:"text-[10px] text-zinc-600 font-mono mt-1",children:Qh(d.timestamp,o)})]},d.id))})]})]})}const az=10,oz=1e3,sz=3e4;function lz(t={}){const[e,r]=N.useState(!1),[n,i]=N.useState(null),[a,o]=N.useState("connecting"),c=N.useRef(null),u=N.useRef(t),d=N.useRef(0),p=N.useRef(null),f=N.useRef(!0),g=N.useRef(!1);u.current=t,N.useEffect(()=>{let w=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`;const b=oP();b&&(w+=`?token=${encodeURIComponent(b)}`);const S=()=>{if(!f.current)return;o(d.current>0?"reconnecting":"connecting");const A=new WebSocket(w);c.current=A,A.onopen=()=>{const O=d.current>0||g.current;d.current=0,g.current=!1,r(!0),o("connected"),O&&console.info("WebSocket reconnected")},A.onmessage=O=>{var j,E,T,P,R,M,J,F;try{const B=JSON.parse(O.data);switch(B.type){case"connected":i(B.connectionId??null);break;case"delta":(E=(j=u.current).onDelta)==null||E.call(j,B.content??"");break;case"message":(P=(T=u.current).onMessage)==null||P.call(T,B.content??"");break;case"event":(M=(R=u.current).onEvent)==null||M.call(R,B);break;case"error":(F=(J=u.current).onError)==null||F.call(J,B.content??"Unknown error");break}}catch{}},A.onclose=()=>{if(c.current=null,r(!1),i(null),!f.current)return;if(g.current||(g.current=!0,console.warn("WebSocket disconnected; attempting to reconnect")),d.current>=az){o("disconnected");return}const O=Math.min(oz*2**d.current,sz);d.current+=1,o("reconnecting"),p.current=setTimeout(S,O)},A.onerror=()=>{A.close()}};return S(),()=>{var A;f.current=!1,p.current&&clearTimeout(p.current),(A=c.current)==null||A.close()}},[]);const v=N.useCallback((x,w="web")=>{var b;((b=c.current)==null?void 0:b.readyState)===WebSocket.OPEN&&c.current.send(JSON.stringify({type:"message",content:x,source:w}))},[]);return{connected:e,connectionId:n,connectionState:a,sendMessage:v}}const lP=N.createContext(null);function cz({children:t}){const[e,r]=N.useState([]),[n,i]=N.useState(""),[a,o]=N.useState(!1),[c,u]=N.useState(!1),d=N.useRef(!1);N.useEffect(()=>{d.current||(d.current=!0,Ve.get("/conversations?limit=50").then(O=>{r(O.messages.map(j=>({...j,timestamp:j.timestamp})))}).catch(()=>{}))},[]);const p=N.useCallback(O=>{u(!1),o(!0),i(O)},[]),f=N.useCallback(O=>{u(!1),o(!1),i(""),r(j=>[...j,{id:crypto.randomUUID(),role:"assistant",content:O,timestamp:new Date().toISOString()}])},[]),g=N.useCallback(O=>{var j,E,T;O.notification&&tz({id:((j=O.event)==null?void 0:j.id)??crypto.randomUUID(),message:O.notification,timestamp:((E=O.event)==null?void 0:E.timestamp)??new Date().toISOString(),eventType:((T=O.event)==null?void 0:T.type)??"unknown"})},[]),v=N.useCallback(()=>{u(!1),o(!1),i("")},[]),{connected:x,sendMessage:w}=lz({onDelta:p,onMessage:f,onEvent:g,onError:v}),b=N.useCallback(O=>{u(!0),w(O)},[w]),S=N.useCallback(O=>{r(j=>[...j,O])},[]),A=N.useCallback(async(O,j)=>{const E=new FormData;E.append("file",O),E.append("messageId",j);const T=oP();if(!(await fetch("/api/attachments",{method:"POST",body:E,headers:T?{Authorization:`Bearer ${T}`}:void 0})).ok)throw new Error("Failed to upload attachment")},[]);return y.jsx(lP.Provider,{value:{messages:e,streaming:n,isStreaming:a,isThinking:c,connected:x,sendChatMessage:b,addUserMessage:S,uploadAttachment:A},children:t})}function cP(){const t=N.useContext(lP);if(!t)throw new Error("useChat must be used within a ChatProvider");return t}function qw(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var zo=qw();function uP(t){zo=t}var So={exec:()=>null};function bs(t){let e=[];return r=>{let n=Math.max(0,Math.min(3,r-1)),i=e[n];return i||(i=t(n),e[n]=i),i}}function st(t,e=""){let r=typeof t=="string"?t:t.source,n={replace:(i,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace(Pr.caret,"$1"),r=r.replace(i,o),n},getRegex:()=>new RegExp(r,e)};return n}var uz=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),Pr={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:bs(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:bs(t=>new RegExp(`^ {0,${t}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:bs(t=>new RegExp(`^ {0,${t}}(?:\`\`\`|~~~)`)),headingBeginRegex:bs(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:bs(t=>new RegExp(`^ {0,${t}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:bs(t=>new RegExp(`^ {0,${t}}>`))},dz=/^(?:[ \t]*(?:\n|$))+/,fz=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,hz=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Ru=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,pz=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Fw=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,dP=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,fP=st(dP).replace(/bull/g,Fw).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),mz=st(dP).replace(/bull/g,Fw).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Hw=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,gz=/^[^\n]+/,Ww=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,yz=st(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Ww).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),vz=st(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Fw).getRegex(),ep="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Gw=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,bz=st("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Gw).replace("tag",ep).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),hP=st(Hw).replace("hr",Ru).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ep).getRegex(),xz=st(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",hP).getRegex(),Kw={blockquote:xz,code:fz,def:yz,fences:hz,heading:pz,hr:Ru,html:bz,lheading:fP,list:vz,newline:dz,paragraph:hP,table:So,text:gz},qk=st("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Ru).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ep).getRegex(),wz={...Kw,lheading:mz,table:qk,paragraph:st(Hw).replace("hr",Ru).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",qk).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ep).getRegex()},_z={...Kw,html:st(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Gw).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:So,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:st(Hw).replace("hr",Ru).replace("heading",` *#{1,6} *[^
|
|
322
|
-
|
|
321
|
+
*/const X4=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],qb=Ue("zap",X4),Uk="/api";let jo=null,Fb=null;function Y4(t){jo=t}function J4(t){Fb=t}function oP(){return(jo==null?void 0:jo())??null}async function fc(t,e){const r=jo==null?void 0:jo(),n={"Content-Type":"application/json",...e==null?void 0:e.headers};r&&(n.Authorization=`Bearer ${r}`);let i=await fetch(`${Uk}${t}`,{...e,headers:n});if(i.status===401&&Fb){const a=await Fb();a&&(n.Authorization=`Bearer ${a}`,i=await fetch(`${Uk}${t}`,{...e,headers:n}))}if(!i.ok){const a=await i.json().catch(()=>({error:i.statusText}));throw new Error(a.error??`Request failed: ${i.status}`)}return i.json()}const Ve={get:t=>fc(t),post:(t,e)=>fc(t,{method:"POST",body:e?JSON.stringify(e):void 0}),patch:(t,e)=>fc(t,{method:"PATCH",body:JSON.stringify(e)}),put:(t,e)=>fc(t,{method:"PUT",body:JSON.stringify(e)}),delete:t=>fc(t,{method:"DELETE"})},sP=N.createContext({timezone:"UTC"});function Z4({children:t}){const[e,r]=N.useState("UTC");return N.useEffect(()=>{Ve.get("/config").then(n=>{n.config.timezone&&r(n.config.timezone)}).catch(()=>{})},[]),y.jsx(sP.Provider,{value:{timezone:e},children:t})}function qa(){return N.useContext(sP).timezone}const Q4=[{label:"UTC",value:"UTC"},{label:"Eastern Time (US)",value:"America/New_York"},{label:"Central Time (US)",value:"America/Chicago"},{label:"Mountain Time (US)",value:"America/Denver"},{label:"Pacific Time (US)",value:"America/Los_Angeles"},{label:"Alaska Time",value:"America/Anchorage"},{label:"Hawaii Time",value:"Pacific/Honolulu"},{label:"London (GMT/BST)",value:"Europe/London"},{label:"Central European",value:"Europe/Berlin"},{label:"Eastern European",value:"Europe/Bucharest"},{label:"India (IST)",value:"Asia/Kolkata"},{label:"China (CST)",value:"Asia/Shanghai"},{label:"Japan (JST)",value:"Asia/Tokyo"},{label:"Australia Eastern",value:"Australia/Sydney"},{label:"New Zealand",value:"Pacific/Auckland"},{label:"São Paulo",value:"America/Sao_Paulo"}];function Ws(t,e,r){if(!t)return"";try{return new Date(t).toLocaleString("en-US",{timeZone:e,month:"short",day:"numeric",hour:"numeric",minute:"2-digit",...r})}catch{return new Date(t).toLocaleString()}}function Qh(t,e,r){if(!t)return"";try{return new Date(t).toLocaleTimeString("en-US",{timeZone:e,hour:"numeric",minute:"2-digit",...r})}catch{return new Date(t).toLocaleTimeString()}}function ez(t,e,r){if(!t)return"";try{return new Date(t).toLocaleDateString("en-US",{timeZone:e,month:"short",day:"numeric",...r})}catch{return new Date(t).toLocaleDateString()}}let Rf=[];const If=new Set;function tz(t){Rf=[t,...Rf].slice(0,50);for(const e of If)e()}function rz(){Rf=[];for(const t of If)t()}function nz(){const[,t]=N.useState(0);return N.useEffect(()=>{const e=()=>t(r=>r+1);return If.add(e),()=>{If.delete(e)}},[]),Rf}function iz(){const[t,e]=N.useState(!1),r=nz(),n=N.useRef(null),[i,a]=N.useState(0),o=qa(),c=r.length-i;N.useEffect(()=>{function d(p){n.current&&!n.current.contains(p.target)&&e(!1)}if(t)return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[t]);function u(){e(!t),t||a(r.length)}return y.jsxs("div",{className:"relative",ref:n,children:[y.jsxs("button",{type:"button",onClick:u,className:"relative p-2 rounded-xl hover:bg-white/[0.05] text-zinc-600 hover:text-zinc-300 transition-colors cursor-pointer",title:"Notifications",children:[y.jsx(I5,{className:"w-3.5 h-3.5"}),c>0&&y.jsx("span",{className:"absolute top-1 right-1 w-2 h-2 rounded-full bg-[#E43A9C]"})]}),t&&y.jsxs("div",{className:"absolute right-0 top-full mt-2 w-80 max-h-96 overflow-y-auto rounded-xl border border-white/[0.07] bg-[#1a1a1a] shadow-2xl z-50",children:[y.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-white/[0.07]",children:[y.jsx("span",{className:"text-xs font-mono text-zinc-300",children:"Notifications"}),r.length>0&&y.jsx("button",{type:"button",onClick:rz,className:"text-[10px] font-mono text-zinc-500 hover:text-zinc-300 cursor-pointer",children:"Clear all"})]}),r.length===0?y.jsx("div",{className:"px-4 py-8 text-center text-zinc-600 text-xs font-mono",children:"No notifications yet"}):y.jsx("div",{className:"divide-y divide-white/[0.04]",children:r.map(d=>y.jsxs("div",{className:"px-4 py-3 hover:bg-white/[0.03]",children:[y.jsx("p",{className:"text-xs text-zinc-300 leading-relaxed",children:d.message}),y.jsx("p",{className:"text-[10px] text-zinc-600 font-mono mt-1",children:Qh(d.timestamp,o)})]},d.id))})]})]})}const az=10,oz=1e3,sz=3e4;function lz(t={}){const[e,r]=N.useState(!1),[n,i]=N.useState(null),[a,o]=N.useState("connecting"),c=N.useRef(null),u=N.useRef(t),d=N.useRef(0),p=N.useRef(null),f=N.useRef(!0),g=N.useRef(!1);u.current=t,N.useEffect(()=>{let w=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`;const b=oP();b&&(w+=`?token=${encodeURIComponent(b)}`);const S=()=>{if(!f.current)return;o(d.current>0?"reconnecting":"connecting");const A=new WebSocket(w);c.current=A,A.onopen=()=>{const O=d.current>0||g.current;d.current=0,g.current=!1,r(!0),o("connected"),O&&console.info("WebSocket reconnected")},A.onmessage=O=>{var j,E,T,P,R,M,J,F;try{const B=JSON.parse(O.data);switch(B.type){case"connected":i(B.connectionId??null);break;case"delta":(E=(j=u.current).onDelta)==null||E.call(j,B.content??"");break;case"message":(P=(T=u.current).onMessage)==null||P.call(T,B.content??"");break;case"event":(M=(R=u.current).onEvent)==null||M.call(R,B);break;case"error":(F=(J=u.current).onError)==null||F.call(J,B.content??"Unknown error");break}}catch{}},A.onclose=()=>{if(c.current=null,r(!1),i(null),!f.current)return;if(g.current||(g.current=!0,console.warn("WebSocket disconnected; attempting to reconnect")),d.current>=az){o("disconnected");return}const O=Math.min(oz*2**d.current,sz);d.current+=1,o("reconnecting"),p.current=setTimeout(S,O)},A.onerror=()=>{A.close()}};return S(),()=>{var A;f.current=!1,p.current&&clearTimeout(p.current),(A=c.current)==null||A.close()}},[]);const v=N.useCallback((x,w="web")=>{var b;((b=c.current)==null?void 0:b.readyState)===WebSocket.OPEN&&c.current.send(JSON.stringify({type:"message",content:x,source:w}))},[]);return{connected:e,connectionId:n,connectionState:a,sendMessage:v}}const lP=N.createContext(null);function cz({children:t}){const[e,r]=N.useState([]),[n,i]=N.useState(""),[a,o]=N.useState(!1),[c,u]=N.useState(!1),d=N.useRef(!1);N.useEffect(()=>{d.current||(d.current=!0,Ve.get("/conversations?limit=50").then(O=>{r(O.messages.map(j=>({...j,timestamp:j.timestamp})))}).catch(()=>{}))},[]);const p=N.useCallback(O=>{u(!1),o(!0),i(O)},[]),f=N.useCallback(O=>{u(!1),o(!1),i(""),r(j=>[...j,{id:crypto.randomUUID(),role:"assistant",content:O,timestamp:new Date().toISOString()}])},[]),g=N.useCallback(O=>{var j,E,T;O.notification&&tz({id:((j=O.event)==null?void 0:j.id)??crypto.randomUUID(),message:O.notification,timestamp:((E=O.event)==null?void 0:E.timestamp)??new Date().toISOString(),eventType:((T=O.event)==null?void 0:T.type)??"unknown"})},[]),v=N.useCallback(()=>{u(!1),o(!1),i("")},[]),{connected:x,sendMessage:w}=lz({onDelta:p,onMessage:f,onEvent:g,onError:v}),b=N.useCallback(O=>{u(!0),w(O)},[w]),S=N.useCallback(O=>{r(j=>[...j,O])},[]),A=N.useCallback(async(O,j)=>{const E=new FormData;E.append("file",O),E.append("messageId",j);const T=oP();if(!(await fetch("/api/attachments",{method:"POST",body:E,headers:T?{Authorization:`Bearer ${T}`}:void 0})).ok)throw new Error("Failed to upload attachment")},[]);return y.jsx(lP.Provider,{value:{messages:e,streaming:n,isStreaming:a,isThinking:c,connected:x,sendChatMessage:b,addUserMessage:S,uploadAttachment:A},children:t})}function cP(){const t=N.useContext(lP);if(!t)throw new Error("useChat must be used within a ChatProvider");return t}var Ag,qk;function uz(){if(qk)return Ag;qk=1;function t(D){return D instanceof Map?D.clear=D.delete=D.set=function(){throw new Error("map is read-only")}:D instanceof Set&&(D.add=D.clear=D.delete=function(){throw new Error("set is read-only")}),Object.freeze(D),Object.getOwnPropertyNames(D).forEach(ne=>{const de=D[ne],Re=typeof de;(Re==="object"||Re==="function")&&!Object.isFrozen(de)&&t(de)}),D}class e{constructor(ne){ne.data===void 0&&(ne.data={}),this.data=ne.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function r(D){return D.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function n(D,...ne){const de=Object.create(null);for(const Re in D)de[Re]=D[Re];return ne.forEach(function(Re){for(const ht in Re)de[ht]=Re[ht]}),de}const i="</span>",a=D=>!!D.scope,o=(D,{prefix:ne})=>{if(D.startsWith("language:"))return D.replace("language:","language-");if(D.includes(".")){const de=D.split(".");return[`${ne}${de.shift()}`,...de.map((Re,ht)=>`${Re}${"_".repeat(ht+1)}`)].join(" ")}return`${ne}${D}`};class c{constructor(ne,de){this.buffer="",this.classPrefix=de.classPrefix,ne.walk(this)}addText(ne){this.buffer+=r(ne)}openNode(ne){if(!a(ne))return;const de=o(ne.scope,{prefix:this.classPrefix});this.span(de)}closeNode(ne){a(ne)&&(this.buffer+=i)}value(){return this.buffer}span(ne){this.buffer+=`<span class="${ne}">`}}const u=(D={})=>{const ne={children:[]};return Object.assign(ne,D),ne};class d{constructor(){this.rootNode=u(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(ne){this.top.children.push(ne)}openNode(ne){const de=u({scope:ne});this.add(de),this.stack.push(de)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(ne){return this.constructor._walk(ne,this.rootNode)}static _walk(ne,de){return typeof de=="string"?ne.addText(de):de.children&&(ne.openNode(de),de.children.forEach(Re=>this._walk(ne,Re)),ne.closeNode(de)),ne}static _collapse(ne){typeof ne!="string"&&ne.children&&(ne.children.every(de=>typeof de=="string")?ne.children=[ne.children.join("")]:ne.children.forEach(de=>{d._collapse(de)}))}}class p extends d{constructor(ne){super(),this.options=ne}addText(ne){ne!==""&&this.add(ne)}startScope(ne){this.openNode(ne)}endScope(){this.closeNode()}__addSublanguage(ne,de){const Re=ne.root;de&&(Re.scope=`language:${de}`),this.add(Re)}toHTML(){return new c(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}}function f(D){return D?typeof D=="string"?D:D.source:null}function g(D){return w("(?=",D,")")}function v(D){return w("(?:",D,")*")}function x(D){return w("(?:",D,")?")}function w(...D){return D.map(de=>f(de)).join("")}function b(D){const ne=D[D.length-1];return typeof ne=="object"&&ne.constructor===Object?(D.splice(D.length-1,1),ne):{}}function S(...D){return"("+(b(D).capture?"":"?:")+D.map(Re=>f(Re)).join("|")+")"}function A(D){return new RegExp(D.toString()+"|").exec("").length-1}function O(D,ne){const de=D&&D.exec(ne);return de&&de.index===0}const j=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;function E(D,{joinWith:ne}){let de=0;return D.map(Re=>{de+=1;const ht=de;let Ke=f(Re),ye="";for(;Ke.length>0;){const we=j.exec(Ke);if(!we){ye+=Ke;break}ye+=Ke.substring(0,we.index),Ke=Ke.substring(we.index+we[0].length),we[0][0]==="\\"&&we[1]?ye+="\\"+String(Number(we[1])+ht):(ye+=we[0],we[0]==="("&&de++)}return ye}).map(Re=>`(${Re})`).join(ne)}const T=/\b\B/,P="[a-zA-Z]\\w*",R="[a-zA-Z_]\\w*",M="\\b\\d+(\\.\\d+)?",J="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",F="\\b(0b[01]+)",B="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",K=(D={})=>{const ne=/^#![ ]*\//;return D.binary&&(D.begin=w(ne,/.*\b/,D.binary,/\b.*/)),n({scope:"meta",begin:ne,end:/$/,relevance:0,"on:begin":(de,Re)=>{de.index!==0&&Re.ignoreMatch()}},D)},W={begin:"\\\\[\\s\\S]",relevance:0},X={scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[W]},Y={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[W]},te={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},H=function(D,ne,de={}){const Re=n({scope:"comment",begin:D,end:ne,contains:[]},de);Re.contains.push({scope:"doctag",begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0});const ht=S("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return Re.contains.push({begin:w(/[ ]+/,"(",ht,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),Re},Q=H("//","$"),U=H("/\\*","\\*/"),I=H("#","$"),$={scope:"number",begin:M,relevance:0},V={scope:"number",begin:J,relevance:0},oe={scope:"number",begin:F,relevance:0},le={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[W,{begin:/\[/,end:/\]/,relevance:0,contains:[W]}]},ve={scope:"title",begin:P,relevance:0},qe={scope:"title",begin:R,relevance:0},xe={begin:"\\.\\s*"+R,relevance:0};var Se=Object.freeze({__proto__:null,APOS_STRING_MODE:X,BACKSLASH_ESCAPE:W,BINARY_NUMBER_MODE:oe,BINARY_NUMBER_RE:F,COMMENT:H,C_BLOCK_COMMENT_MODE:U,C_LINE_COMMENT_MODE:Q,C_NUMBER_MODE:V,C_NUMBER_RE:J,END_SAME_AS_BEGIN:function(D){return Object.assign(D,{"on:begin":(ne,de)=>{de.data._beginMatch=ne[1]},"on:end":(ne,de)=>{de.data._beginMatch!==ne[1]&&de.ignoreMatch()}})},HASH_COMMENT_MODE:I,IDENT_RE:P,MATCH_NOTHING_RE:T,METHOD_GUARD:xe,NUMBER_MODE:$,NUMBER_RE:M,PHRASAL_WORDS_MODE:te,QUOTE_STRING_MODE:Y,REGEXP_MODE:le,RE_STARTERS_RE:B,SHEBANG:K,TITLE_MODE:ve,UNDERSCORE_IDENT_RE:R,UNDERSCORE_TITLE_MODE:qe});function Me(D,ne){D.input[D.index-1]==="."&&ne.ignoreMatch()}function se(D,ne){D.className!==void 0&&(D.scope=D.className,delete D.className)}function tt(D,ne){ne&&D.beginKeywords&&(D.begin="\\b("+D.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",D.__beforeBegin=Me,D.keywords=D.keywords||D.beginKeywords,delete D.beginKeywords,D.relevance===void 0&&(D.relevance=0))}function Fe(D,ne){Array.isArray(D.illegal)&&(D.illegal=S(...D.illegal))}function kt(D,ne){if(D.match){if(D.begin||D.end)throw new Error("begin & end are not supported with match");D.begin=D.match,delete D.match}}function wt(D,ne){D.relevance===void 0&&(D.relevance=1)}const Et=(D,ne)=>{if(!D.beforeMatch)return;if(D.starts)throw new Error("beforeMatch cannot be used with starts");const de=Object.assign({},D);Object.keys(D).forEach(Re=>{delete D[Re]}),D.keywords=de.keywords,D.begin=w(de.beforeMatch,g(de.begin)),D.starts={relevance:0,contains:[Object.assign(de,{endsParent:!0})]},D.relevance=0,delete de.beforeMatch},Sr=["of","and","for","in","not","or","if","then","parent","list","value"],Ut="keyword";function Rr(D,ne,de=Ut){const Re=Object.create(null);return typeof D=="string"?ht(de,D.split(" ")):Array.isArray(D)?ht(de,D):Object.keys(D).forEach(function(Ke){Object.assign(Re,Rr(D[Ke],ne,Ke))}),Re;function ht(Ke,ye){ne&&(ye=ye.map(we=>we.toLowerCase())),ye.forEach(function(we){const je=we.split("|");Re[je[0]]=[Ke,lr(je[0],je[1])]})}}function lr(D,ne){return ne?Number(ne):_t(D)?0:1}function _t(D){return Sr.includes(D.toLowerCase())}const kr={},Ir=D=>{console.error(D)},ni=(D,...ne)=>{console.log(`WARN: ${D}`,...ne)},Ur=(D,ne)=>{kr[`${D}/${ne}`]||(console.log(`Deprecated as of ${D}. ${ne}`),kr[`${D}/${ne}`]=!0)},ii=new Error;function ai(D,ne,{key:de}){let Re=0;const ht=D[de],Ke={},ye={};for(let we=1;we<=ne.length;we++)ye[we+Re]=ht[we],Ke[we+Re]=!0,Re+=A(ne[we-1]);D[de]=ye,D[de]._emit=Ke,D[de]._multi=!0}function aa(D){if(Array.isArray(D.begin)){if(D.skip||D.excludeBegin||D.returnBegin)throw Ir("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),ii;if(typeof D.beginScope!="object"||D.beginScope===null)throw Ir("beginScope must be object"),ii;ai(D,D.begin,{key:"beginScope"}),D.begin=E(D.begin,{joinWith:""})}}function qr(D){if(Array.isArray(D.end)){if(D.skip||D.excludeEnd||D.returnEnd)throw Ir("skip, excludeEnd, returnEnd not compatible with endScope: {}"),ii;if(typeof D.endScope!="object"||D.endScope===null)throw Ir("endScope must be object"),ii;ai(D,D.end,{key:"endScope"}),D.end=E(D.end,{joinWith:""})}}function oi(D){D.scope&&typeof D.scope=="object"&&D.scope!==null&&(D.beginScope=D.scope,delete D.scope)}function si(D){oi(D),typeof D.beginScope=="string"&&(D.beginScope={_wrap:D.beginScope}),typeof D.endScope=="string"&&(D.endScope={_wrap:D.endScope}),aa(D),qr(D)}function Go(D){function ne(ye,we){return new RegExp(f(ye),"m"+(D.case_insensitive?"i":"")+(D.unicodeRegex?"u":"")+(we?"g":""))}class de{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(we,je){je.position=this.position++,this.matchIndexes[this.matchAt]=je,this.regexes.push([je,we]),this.matchAt+=A(we)+1}compile(){this.regexes.length===0&&(this.exec=()=>null);const we=this.regexes.map(je=>je[1]);this.matcherRe=ne(E(we,{joinWith:"|"}),!0),this.lastIndex=0}exec(we){this.matcherRe.lastIndex=this.lastIndex;const je=this.matcherRe.exec(we);if(!je)return null;const ut=je.findIndex((cr,Ai)=>Ai>0&&cr!==void 0),gt=this.matchIndexes[ut];return je.splice(0,ut),Object.assign(je,gt)}}class Re{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(we){if(this.multiRegexes[we])return this.multiRegexes[we];const je=new de;return this.rules.slice(we).forEach(([ut,gt])=>je.addRule(ut,gt)),je.compile(),this.multiRegexes[we]=je,je}resumingScanAtSamePosition(){return this.regexIndex!==0}considerAll(){this.regexIndex=0}addRule(we,je){this.rules.push([we,je]),je.type==="begin"&&this.count++}exec(we){const je=this.getMatcher(this.regexIndex);je.lastIndex=this.lastIndex;let ut=je.exec(we);if(this.resumingScanAtSamePosition()&&!(ut&&ut.index===this.lastIndex)){const gt=this.getMatcher(0);gt.lastIndex=this.lastIndex+1,ut=gt.exec(we)}return ut&&(this.regexIndex+=ut.position+1,this.regexIndex===this.count&&this.considerAll()),ut}}function ht(ye){const we=new Re;return ye.contains.forEach(je=>we.addRule(je.begin,{rule:je,type:"begin"})),ye.terminatorEnd&&we.addRule(ye.terminatorEnd,{type:"end"}),ye.illegal&&we.addRule(ye.illegal,{type:"illegal"}),we}function Ke(ye,we){const je=ye;if(ye.isCompiled)return je;[se,kt,si,Et].forEach(gt=>gt(ye,we)),D.compilerExtensions.forEach(gt=>gt(ye,we)),ye.__beforeBegin=null,[tt,Fe,wt].forEach(gt=>gt(ye,we)),ye.isCompiled=!0;let ut=null;return typeof ye.keywords=="object"&&ye.keywords.$pattern&&(ye.keywords=Object.assign({},ye.keywords),ut=ye.keywords.$pattern,delete ye.keywords.$pattern),ut=ut||/\w+/,ye.keywords&&(ye.keywords=Rr(ye.keywords,D.case_insensitive)),je.keywordPatternRe=ne(ut,!0),we&&(ye.begin||(ye.begin=/\B|\b/),je.beginRe=ne(je.begin),!ye.end&&!ye.endsWithParent&&(ye.end=/\B|\b/),ye.end&&(je.endRe=ne(je.end)),je.terminatorEnd=f(je.end)||"",ye.endsWithParent&&we.terminatorEnd&&(je.terminatorEnd+=(ye.end?"|":"")+we.terminatorEnd)),ye.illegal&&(je.illegalRe=ne(ye.illegal)),ye.contains||(ye.contains=[]),ye.contains=[].concat(...ye.contains.map(function(gt){return Ko(gt==="self"?ye:gt)})),ye.contains.forEach(function(gt){Ke(gt,je)}),ye.starts&&Ke(ye.starts,we),je.matcher=ht(je),je}if(D.compilerExtensions||(D.compilerExtensions=[]),D.contains&&D.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return D.classNameAliases=n(D.classNameAliases||{}),Ke(D)}function Xa(D){return D?D.endsWithParent||Xa(D.starts):!1}function Ko(D){return D.variants&&!D.cachedVariants&&(D.cachedVariants=D.variants.map(function(ne){return n(D,{variants:null},ne)})),D.cachedVariants?D.cachedVariants:Xa(D)?n(D,{starts:D.starts?n(D.starts):null}):Object.isFrozen(D)?n(D):D}var oa="11.11.1";class Ya extends Error{constructor(ne,de){super(ne),this.name="HTMLInjectionError",this.html=de}}const Rn=r,$r=n,sa=Symbol("nomatch"),li=7,hn=function(D){const ne=Object.create(null),de=Object.create(null),Re=[];let ht=!0;const Ke="Could not find the language '{}', did you forget to load/include a language module?",ye={disableAutodetect:!0,name:"Plain text",contains:[]};let we={ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",cssSelector:"pre code",languages:null,__emitter:p};function je(he){return we.noHighlightRe.test(he)}function ut(he){let $e=he.className+" ";$e+=he.parentNode?he.parentNode.className:"";const Xe=we.languageDetectRe.exec($e);if(Xe){const Qe=In(Xe[1]);return Qe||(ni(Ke.replace("{}",Xe[1])),ni("Falling back to no-highlight mode for this block.",he)),Qe?Xe[1]:"no-highlight"}return $e.split(/\s+/).find(Qe=>je(Qe)||In(Qe))}function gt(he,$e,Xe){let Qe="",Gt="";typeof $e=="object"?(Qe=he,Xe=$e.ignoreIllegals,Gt=$e.language):(Ur("10.7.0","highlight(lang, code, ...args) has been deprecated."),Ur("10.7.0",`Please use highlight(code, options) instead.
|
|
322
|
+
https://github.com/highlightjs/highlight.js/issues/2277`),Gt=he,Qe=$e),Xe===void 0&&(Xe=!0);const Dt={code:Qe,language:Gt};Za("before:highlight",Dt);const ci=Dt.result?Dt.result:cr(Dt.language,Dt.code,Xe);return ci.code=Dt.code,Za("after:highlight",ci),ci}function cr(he,$e,Xe,Qe){const Gt=Object.create(null);function Dt(me,Ee){return me.keywords[Ee]}function ci(){if(!Ge.keywords){Kt.addText(yt);return}let me=0;Ge.keywordPatternRe.lastIndex=0;let Ee=Ge.keywordPatternRe.exec(yt),He="";for(;Ee;){He+=yt.substring(me,Ee.index);const rt=mn.case_insensitive?Ee[0].toLowerCase():Ee[0],qt=Dt(Ge,rt);if(qt){const[ur,Hp]=qt;if(Kt.addText(He),He="",Gt[rt]=(Gt[rt]||0)+1,Gt[rt]<=li&&(to+=Hp),ur.startsWith("_"))He+=Ee[0];else{const Zu=mn.classNameAliases[ur]||ur;Lr(Ee[0],Zu)}}else He+=Ee[0];me=Ge.keywordPatternRe.lastIndex,Ee=Ge.keywordPatternRe.exec(yt)}He+=yt.substring(me),Kt.addText(He)}function Yo(){if(yt==="")return;let me=null;if(typeof Ge.subLanguage=="string"){if(!ne[Ge.subLanguage]){Kt.addText(yt);return}me=cr(Ge.subLanguage,yt,!0,Il[Ge.subLanguage]),Il[Ge.subLanguage]=me._top}else me=Ja(yt,Ge.subLanguage.length?Ge.subLanguage:null);Ge.relevance>0&&(to+=me.relevance),Kt.__addSublanguage(me._emitter,me.language)}function Mr(){Ge.subLanguage!=null?Yo():ci(),yt=""}function Lr(me,Ee){me!==""&&(Kt.startScope(Ee),Kt.addText(me),Kt.endScope())}function Qa(me,Ee){let He=1;const rt=Ee.length-1;for(;He<=rt;){if(!me._emit[He]){He++;continue}const qt=mn.classNameAliases[me[He]]||me[He],ur=Ee[He];qt?Lr(ur,qt):(yt=ur,ci(),yt=""),He++}}function la(me,Ee){return me.scope&&typeof me.scope=="string"&&Kt.openNode(mn.classNameAliases[me.scope]||me.scope),me.beginScope&&(me.beginScope._wrap?(Lr(yt,mn.classNameAliases[me.beginScope._wrap]||me.beginScope._wrap),yt=""):me.beginScope._multi&&(Qa(me.beginScope,Ee),yt="")),Ge=Object.create(me,{parent:{value:Ge}}),Ge}function eo(me,Ee,He){let rt=O(me.endRe,He);if(rt){if(me["on:end"]){const qt=new e(me);me["on:end"](Ee,qt),qt.isMatchIgnored&&(rt=!1)}if(rt){for(;me.endsParent&&me.parent;)me=me.parent;return me}}if(me.endsWithParent)return eo(me.parent,Ee,He)}function qp(me){return Ge.matcher.regexIndex===0?(yt+=me[0],1):(da=!0,0)}function Fp(me){const Ee=me[0],He=me.rule,rt=new e(He),qt=[He.__beforeBegin,He["on:begin"]];for(const ur of qt)if(ur&&(ur(me,rt),rt.isMatchIgnored))return qp(Ee);return He.skip?yt+=Ee:(He.excludeBegin&&(yt+=Ee),Mr(),!He.returnBegin&&!He.excludeBegin&&(yt=Ee)),la(He,me),He.returnBegin?0:Ee.length}function Pl(me){const Ee=me[0],He=$e.substring(me.index),rt=eo(Ge,me,He);if(!rt)return sa;const qt=Ge;Ge.endScope&&Ge.endScope._wrap?(Mr(),Lr(Ee,Ge.endScope._wrap)):Ge.endScope&&Ge.endScope._multi?(Mr(),Qa(Ge.endScope,me)):qt.skip?yt+=Ee:(qt.returnEnd||qt.excludeEnd||(yt+=Ee),Mr(),qt.excludeEnd&&(yt=Ee));do Ge.scope&&Kt.closeNode(),!Ge.skip&&!Ge.subLanguage&&(to+=Ge.relevance),Ge=Ge.parent;while(Ge!==rt.parent);return rt.starts&&la(rt.starts,me),qt.returnEnd?0:Ee.length}function Ju(){const me=[];for(let Ee=Ge;Ee!==mn;Ee=Ee.parent)Ee.scope&&me.unshift(Ee.scope);me.forEach(Ee=>Kt.openNode(Ee))}let ca={};function ua(me,Ee){const He=Ee&&Ee[0];if(yt+=me,He==null)return Mr(),0;if(ca.type==="begin"&&Ee.type==="end"&&ca.index===Ee.index&&He===""){if(yt+=$e.slice(Ee.index,Ee.index+1),!ht){const rt=new Error(`0 width match regex (${he})`);throw rt.languageName=he,rt.badRule=ca.rule,rt}return 1}if(ca=Ee,Ee.type==="begin")return Fp(Ee);if(Ee.type==="illegal"&&!Xe){const rt=new Error('Illegal lexeme "'+He+'" for mode "'+(Ge.scope||"<unnamed>")+'"');throw rt.mode=Ge,rt}else if(Ee.type==="end"){const rt=Pl(Ee);if(rt!==sa)return rt}if(Ee.type==="illegal"&&He==="")return yt+=`
|
|
323
|
+
`,1;if(ro>1e5&&ro>Ee.index*3)throw new Error("potential infinite loop, way more iterations than matches");return yt+=He,He.length}const mn=In(he);if(!mn)throw Ir(Ke.replace("{}",he)),new Error('Unknown language: "'+he+'"');const Rl=Go(mn);let lt="",Ge=Qe||Rl;const Il={},Kt=new we.__emitter(we);Ju();let yt="",to=0,ui=0,ro=0,da=!1;try{if(mn.__emitTokens)mn.__emitTokens($e,Kt);else{for(Ge.matcher.considerAll();;){ro++,da?da=!1:Ge.matcher.considerAll(),Ge.matcher.lastIndex=ui;const me=Ge.matcher.exec($e);if(!me)break;const Ee=$e.substring(ui,me.index),He=ua(Ee,me);ui=me.index+He}ua($e.substring(ui))}return Kt.finalize(),lt=Kt.toHTML(),{language:he,value:lt,relevance:to,illegal:!1,_emitter:Kt,_top:Ge}}catch(me){if(me.message&&me.message.includes("Illegal"))return{language:he,value:Rn($e),illegal:!0,relevance:0,_illegalBy:{message:me.message,index:ui,context:$e.slice(ui-100,ui+100),mode:me.mode,resultSoFar:lt},_emitter:Kt};if(ht)return{language:he,value:Rn($e),illegal:!1,relevance:0,errorRaised:me,_emitter:Kt,_top:Ge};throw me}}function Ai(he){const $e={value:Rn(he),illegal:!1,relevance:0,_top:ye,_emitter:new we.__emitter(we)};return $e._emitter.addText(he),$e}function Ja(he,$e){$e=$e||we.languages||Object.keys(ne);const Xe=Ai(he),Qe=$e.filter(In).filter(Yu).map(Mr=>cr(Mr,he,!1));Qe.unshift(Xe);const Gt=Qe.sort((Mr,Lr)=>{if(Mr.relevance!==Lr.relevance)return Lr.relevance-Mr.relevance;if(Mr.language&&Lr.language){if(In(Mr.language).supersetOf===Lr.language)return 1;if(In(Lr.language).supersetOf===Mr.language)return-1}return 0}),[Dt,ci]=Gt,Yo=Dt;return Yo.secondBest=ci,Yo}function zp(he,$e,Xe){const Qe=$e&&de[$e]||Xe;he.classList.add("hljs"),he.classList.add(`language-${Qe}`)}function jl(he){let $e=null;const Xe=ut(he);if(je(Xe))return;if(Za("before:highlightElement",{el:he,language:Xe}),he.dataset.highlighted){console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",he);return}if(he.children.length>0&&(we.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),console.warn("The element with unescaped HTML:"),console.warn(he)),we.throwUnescapedHTML))throw new Ya("One of your code blocks includes unescaped HTML.",he.innerHTML);$e=he;const Qe=$e.textContent,Gt=Xe?gt(Qe,{language:Xe,ignoreIllegals:!0}):Ja(Qe);he.innerHTML=Gt.value,he.dataset.highlighted="yes",zp(he,Xe,Gt.language),he.result={language:Gt.language,re:Gt.relevance,relevance:Gt.relevance},Gt.secondBest&&(he.secondBest={language:Gt.secondBest.language,relevance:Gt.secondBest.relevance}),Za("after:highlightElement",{el:he,result:Gt,text:Qe})}function Bp(he){we=$r(we,he)}const Ti=()=>{Vo(),Ur("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")};function Wu(){Vo(),Ur("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.")}let Cl=!1;function Vo(){function he(){Vo()}if(document.readyState==="loading"){Cl||window.addEventListener("DOMContentLoaded",he,!1),Cl=!0;return}document.querySelectorAll(we.cssSelector).forEach(jl)}function Gu(he,$e){let Xe=null;try{Xe=$e(D)}catch(Qe){if(Ir("Language definition for '{}' could not be registered.".replace("{}",he)),ht)Ir(Qe);else throw Qe;Xe=ye}Xe.name||(Xe.name=he),ne[he]=Xe,Xe.rawDefinition=$e.bind(null,D),Xe.aliases&&Xu(Xe.aliases,{languageName:he})}function Ku(he){delete ne[he];for(const $e of Object.keys(de))de[$e]===he&&delete de[$e]}function Vu(){return Object.keys(ne)}function In(he){return he=(he||"").toLowerCase(),ne[he]||ne[de[he]]}function Xu(he,{languageName:$e}){typeof he=="string"&&(he=[he]),he.forEach(Xe=>{de[Xe.toLowerCase()]=$e})}function Yu(he){const $e=In(he);return $e&&!$e.disableAutodetect}function Lt(he){he["before:highlightBlock"]&&!he["before:highlightElement"]&&(he["before:highlightElement"]=$e=>{he["before:highlightBlock"](Object.assign({block:$e.el},$e))}),he["after:highlightBlock"]&&!he["after:highlightElement"]&&(he["after:highlightElement"]=$e=>{he["after:highlightBlock"](Object.assign({block:$e.el},$e))})}function Up(he){Lt(he),Re.push(he)}function Nl(he){const $e=Re.indexOf(he);$e!==-1&&Re.splice($e,1)}function Za(he,$e){const Xe=he;Re.forEach(function(Qe){Qe[Xe]&&Qe[Xe]($e)})}function Xo(he){return Ur("10.7.0","highlightBlock will be removed entirely in v12.0"),Ur("10.7.0","Please use highlightElement now."),jl(he)}Object.assign(D,{highlight:gt,highlightAuto:Ja,highlightAll:Vo,highlightElement:jl,highlightBlock:Xo,configure:Bp,initHighlighting:Ti,initHighlightingOnLoad:Wu,registerLanguage:Gu,unregisterLanguage:Ku,listLanguages:Vu,getLanguage:In,registerAliases:Xu,autoDetection:Yu,inherit:$r,addPlugin:Up,removePlugin:Nl}),D.debugMode=function(){ht=!1},D.safeMode=function(){ht=!0},D.versionString=oa,D.regex={concat:w,lookahead:g,either:S,optional:x,anyNumberOfTimes:v};for(const he in Se)typeof Se[he]=="object"&&t(Se[he]);return Object.assign(D,Se),D},pn=hn({});return pn.newInstance=()=>hn({}),Ag=pn,pn.HighlightJS=pn,pn.default=pn,Ag}var dz=uz();const Qt=vt(dz),fz=t=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:t.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[t.APOS_STRING_MODE,t.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:t.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),hz=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],pz=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],mz=[...hz,...pz],gz=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),yz=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),vz=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),bz=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();function xz(t){const e=t.regex,r=fz(t),n={begin:/-(webkit|moz|ms|o)-(?=[a-z])/},i="and or not only",a=/@-?\w[\w]*(-\w+)*/,o="[a-zA-Z-][a-zA-Z0-9_-]*",c=[t.APOS_STRING_MODE,t.QUOTE_STRING_MODE];return{name:"CSS",case_insensitive:!0,illegal:/[=|'\$]/,keywords:{keyframePosition:"from to"},classNameAliases:{keyframePosition:"selector-tag"},contains:[r.BLOCK_COMMENT,n,r.CSS_NUMBER_MODE,{className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0},{className:"selector-class",begin:"\\."+o,relevance:0},r.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{begin:":("+yz.join("|")+")"},{begin:":(:)?("+vz.join("|")+")"}]},r.CSS_VARIABLE,{className:"attribute",begin:"\\b("+bz.join("|")+")\\b"},{begin:/:/,end:/[;}{]/,contains:[r.BLOCK_COMMENT,r.HEXCOLOR,r.IMPORTANT,r.CSS_NUMBER_MODE,...c,{begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri"},contains:[...c,{className:"string",begin:/[^)]/,endsWithParent:!0,excludeEnd:!0}]},r.FUNCTION_DISPATCH]},{begin:e.lookahead(/@/),end:"[{;]",relevance:0,illegal:/:/,contains:[{className:"keyword",begin:a},{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{$pattern:/[a-z-]+/,keyword:i,attribute:gz.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...c,r.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+mz.join("|")+")\\b"}]}}function wz(t){const a={keyword:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],type:["bool","byte","complex64","complex128","error","float32","float64","int8","int16","int32","int64","string","uint8","uint16","uint32","uint64","int","uint","uintptr","rune"],literal:["true","false","iota","nil"],built_in:["append","cap","close","complex","copy","imag","len","make","new","panic","print","println","real","recover","delete"]};return{name:"Go",aliases:["golang"],keywords:a,illegal:"</",contains:[t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE,{className:"string",variants:[t.QUOTE_STRING_MODE,t.APOS_STRING_MODE,{begin:"`",end:"`"}]},{className:"number",variants:[{match:/-?\b0[xX]\.[a-fA-F0-9](_?[a-fA-F0-9])*[pP][+-]?\d(_?\d)*i?/,relevance:0},{match:/-?\b0[xX](_?[a-fA-F0-9])+((\.([a-fA-F0-9](_?[a-fA-F0-9])*)?)?[pP][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b0[oO](_?[0-7])*i?/,relevance:0},{match:/-?\.\d(_?\d)*([eE][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b\d(_?\d)*(\.(\d(_?\d)*)?)?([eE][+-]?\d(_?\d)*)?i?/,relevance:0}]},{begin:/:=/},{className:"function",beginKeywords:"func",end:"\\s*(\\{|$)",excludeEnd:!0,contains:[t.TITLE_MODE,{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:a,illegal:/["']/}]}]}}const Fk="[A-Za-z$_][0-9A-Za-z$_]*",_z=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],Sz=["true","false","null","undefined","NaN","Infinity"],uP=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],dP=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],fP=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],kz=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],Ez=[].concat(fP,uP,dP);function hP(t){const e=t.regex,r=(H,{after:Q})=>{const U="</"+H[0].slice(1);return H.input.indexOf(U,Q)!==-1},n=Fk,i={begin:"<>",end:"</>"},a=/<[A-Za-z0-9\\._:-]+\s*\/>/,o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(H,Q)=>{const U=H[0].length+H.index,I=H.input[U];if(I==="<"||I===","){Q.ignoreMatch();return}I===">"&&(r(H,{after:U})||Q.ignoreMatch());let $;const V=H.input.substring(U);if($=V.match(/^\s*=/)){Q.ignoreMatch();return}if(($=V.match(/^\s+extends\s+/))&&$.index===0){Q.ignoreMatch();return}}},c={$pattern:Fk,keyword:_z,literal:Sz,built_in:Ez,"variable.language":kz},u="[0-9](_?[0-9])*",d=`\\.(${u})`,p="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",f={className:"number",variants:[{begin:`(\\b(${p})((${d})|\\.)?|(${d}))[eE][+-]?(${u})\\b`},{begin:`\\b(${p})\\b((${d})\\b|\\.)?|(${d})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},g={className:"subst",begin:"\\$\\{",end:"\\}",keywords:c,contains:[]},v={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,g],subLanguage:"xml"}},x={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,g],subLanguage:"css"}},w={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,g],subLanguage:"graphql"}},b={className:"string",begin:"`",end:"`",contains:[t.BACKSLASH_ESCAPE,g]},A={className:"comment",variants:[t.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:n+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),t.C_BLOCK_COMMENT_MODE,t.C_LINE_COMMENT_MODE]},O=[t.APOS_STRING_MODE,t.QUOTE_STRING_MODE,v,x,w,b,{match:/\$\d+/},f];g.contains=O.concat({begin:/\{/,end:/\}/,keywords:c,contains:["self"].concat(O)});const j=[].concat(A,g.contains),E=j.concat([{begin:/(\s*)\(/,end:/\)/,keywords:c,contains:["self"].concat(j)}]),T={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:c,contains:E},P={variants:[{match:[/class/,/\s+/,n,/\s+/,/extends/,/\s+/,e.concat(n,"(",e.concat(/\./,n),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,n],scope:{1:"keyword",3:"title.class"}}]},R={relevance:0,match:e.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...uP,...dP]}},M={label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},J={variants:[{match:[/function/,/\s+/,n,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[T],illegal:/%/},F={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function B(H){return e.concat("(?!",H.join("|"),")")}const K={match:e.concat(/\b/,B([...fP,"super","import"].map(H=>`${H}\\s*\\(`)),n,e.lookahead(/\s*\(/)),className:"title.function",relevance:0},W={begin:e.concat(/\./,e.lookahead(e.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},X={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},T]},Y="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+t.UNDERSCORE_IDENT_RE+")\\s*=>",te={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,e.lookahead(Y)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[T]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:c,exports:{PARAMS_CONTAINS:E,CLASS_REFERENCE:R},illegal:/#(?![$_A-z])/,contains:[t.SHEBANG({label:"shebang",binary:"node",relevance:5}),M,t.APOS_STRING_MODE,t.QUOTE_STRING_MODE,v,x,w,b,A,{match:/\$\d+/},f,R,{scope:"attr",match:n+e.lookahead(":"),relevance:0},te,{begin:"("+t.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[A,t.REGEXP_MODE,{className:"function",begin:Y,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:t.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:c,contains:E}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:i.begin,end:i.end},{match:a},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:"xml",contains:[{begin:o.begin,end:o.end,skip:!0,contains:["self"]}]}]},J,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+t.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[T,t.inherit(t.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},W,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[T]},K,F,P,X,{match:/\$[(.]/}]}}function Oz(t){const e={className:"attr",begin:/"(\\.|[^\\"\r\n])*"(?=\s*:)/,relevance:1.01},r={match:/[{}[\],:]/,className:"punctuation",relevance:0},n=["true","false","null"],i={scope:"literal",beginKeywords:n.join(" ")};return{name:"JSON",aliases:["jsonc"],keywords:{literal:n},contains:[e,r,t.QUOTE_STRING_MODE,i,t.C_NUMBER_MODE,t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE],illegal:"\\S"}}function pP(t){const e=t.regex,r=new RegExp("[\\p{XID_Start}_]\\p{XID_Continue}*","u"),n=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],c={$pattern:/[A-Za-z]\w+|__\w+__/,keyword:n,built_in:["__import__","abs","all","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"],literal:["__debug__","Ellipsis","False","None","NotImplemented","True"],type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"]},u={className:"meta",begin:/^(>>>|\.\.\.) /},d={className:"subst",begin:/\{/,end:/\}/,keywords:c,illegal:/#/},p={begin:/\{\{/,relevance:0},f={className:"string",contains:[t.BACKSLASH_ESCAPE],variants:[{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,contains:[t.BACKSLASH_ESCAPE,u],relevance:10},{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,contains:[t.BACKSLASH_ESCAPE,u],relevance:10},{begin:/([fF][rR]|[rR][fF]|[fF])'''/,end:/'''/,contains:[t.BACKSLASH_ESCAPE,u,p,d]},{begin:/([fF][rR]|[rR][fF]|[fF])"""/,end:/"""/,contains:[t.BACKSLASH_ESCAPE,u,p,d]},{begin:/([uU]|[rR])'/,end:/'/,relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,end:/"/},{begin:/([fF][rR]|[rR][fF]|[fF])'/,end:/'/,contains:[t.BACKSLASH_ESCAPE,p,d]},{begin:/([fF][rR]|[rR][fF]|[fF])"/,end:/"/,contains:[t.BACKSLASH_ESCAPE,p,d]},t.APOS_STRING_MODE,t.QUOTE_STRING_MODE]},g="[0-9](_?[0-9])*",v=`(\\b(${g}))?\\.(${g})|\\b(${g})\\.`,x=`\\b|${n.join("|")}`,w={className:"number",relevance:0,variants:[{begin:`(\\b(${g})|(${v}))[eE][+-]?(${g})[jJ]?(?=${x})`},{begin:`(${v})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${x})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${x})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${x})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${x})`},{begin:`\\b(${g})[jJ](?=${x})`}]},b={className:"comment",begin:e.lookahead(/# type:/),end:/$/,keywords:c,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},S={className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:c,contains:["self",u,w,f,t.HASH_COMMENT_MODE]}]};return d.contains=[f,w,u],{name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:c,illegal:/(<\/|\?)|=>/,contains:[u,w,{scope:"variable.language",match:/\bself\b/},{beginKeywords:"if",relevance:0},{match:/\bor\b/,scope:"keyword"},f,b,t.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,r],scope:{1:"keyword",3:"title.function"},contains:[S]},{variants:[{match:[/\bclass/,/\s+/,r,/\s*/,/\(\s*/,r,/\s*\)/]},{match:[/\bclass/,/\s+/,r]}],scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[w,S,f]}]}}function Az(t){const e=t.regex,r=/(r#)?/,n=e.concat(r,t.UNDERSCORE_IDENT_RE),i=e.concat(r,t.IDENT_RE),a={className:"title.function.invoke",relevance:0,begin:e.concat(/\b/,/(?!let|for|while|if|else|match\b)/,i,e.lookahead(/\s*\(/))},o="([ui](8|16|32|64|128|size)|f(32|64))?",c=["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","ref","return","self","Self","static","struct","super","trait","true","try","type","typeof","union","unsafe","unsized","use","virtual","where","while","yield"],u=["true","false","Some","None","Ok","Err"],d=["drop ","Copy","Send","Sized","Sync","Drop","Fn","FnMut","FnOnce","ToOwned","Clone","Debug","PartialEq","PartialOrd","Eq","Ord","AsRef","AsMut","Into","From","Default","Iterator","Extend","IntoIterator","DoubleEndedIterator","ExactSizeIterator","SliceConcatExt","ToString","assert!","assert_eq!","bitflags!","bytes!","cfg!","col!","concat!","concat_idents!","debug_assert!","debug_assert_eq!","env!","eprintln!","panic!","file!","format!","format_args!","include_bytes!","include_str!","line!","local_data_key!","module_path!","option_env!","print!","println!","select!","stringify!","try!","unimplemented!","unreachable!","vec!","write!","writeln!","macro_rules!","assert_ne!","debug_assert_ne!"],p=["i8","i16","i32","i64","i128","isize","u8","u16","u32","u64","u128","usize","f32","f64","str","char","bool","Box","Option","Result","String","Vec"];return{name:"Rust",aliases:["rs"],keywords:{$pattern:t.IDENT_RE+"!?",type:p,keyword:c,literal:u,built_in:d},illegal:"</",contains:[t.C_LINE_COMMENT_MODE,t.COMMENT("/\\*","\\*/",{contains:["self"]}),t.inherit(t.QUOTE_STRING_MODE,{begin:/b?"/,illegal:null}),{className:"symbol",begin:/'[a-zA-Z_][a-zA-Z0-9_]*(?!')/},{scope:"string",variants:[{begin:/b?r(#*)"(.|\n)*?"\1(?!#)/},{begin:/b?'/,end:/'/,contains:[{scope:"char.escape",match:/\\('|\w|x\w{2}|u\w{4}|U\w{8})/}]}]},{className:"number",variants:[{begin:"\\b0b([01_]+)"+o},{begin:"\\b0o([0-7_]+)"+o},{begin:"\\b0x([A-Fa-f0-9_]+)"+o},{begin:"\\b(\\d[\\d_]*(\\.[0-9_]+)?([eE][+-]?[0-9_]+)?)"+o}],relevance:0},{begin:[/fn/,/\s+/,n],className:{1:"keyword",3:"title.function"}},{className:"meta",begin:"#!?\\[",end:"\\]",contains:[{className:"string",begin:/"/,end:/"/,contains:[t.BACKSLASH_ESCAPE]}]},{begin:[/let/,/\s+/,/(?:mut\s+)?/,n],className:{1:"keyword",3:"keyword",4:"variable"}},{begin:[/for/,/\s+/,n,/\s+/,/in/],className:{1:"keyword",3:"variable",5:"keyword"}},{begin:[/type/,/\s+/,n],className:{1:"keyword",3:"title.class"}},{begin:[/(?:trait|enum|struct|union|impl|for)/,/\s+/,n],className:{1:"keyword",3:"title.class"}},{begin:t.IDENT_RE+"::",keywords:{keyword:"Self",built_in:d,type:p}},{className:"punctuation",begin:"->"},a]}}function qw(t){return{name:"Shell Session",aliases:["console","shellsession"],contains:[{className:"meta.prompt",begin:/^\s{0,3}[/~\w\d[\]()@-]*[>%$#][ ]?/,starts:{end:/[^\\](?=\s*$)/,subLanguage:"bash"}}]}}const $f="[A-Za-z$_][0-9A-Za-z$_]*",mP=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],gP=["true","false","null","undefined","NaN","Infinity"],yP=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],vP=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],bP=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],xP=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],wP=[].concat(bP,yP,vP);function Tz(t){const e=t.regex,r=(H,{after:Q})=>{const U="</"+H[0].slice(1);return H.input.indexOf(U,Q)!==-1},n=$f,i={begin:"<>",end:"</>"},a=/<[A-Za-z0-9\\._:-]+\s*\/>/,o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(H,Q)=>{const U=H[0].length+H.index,I=H.input[U];if(I==="<"||I===","){Q.ignoreMatch();return}I===">"&&(r(H,{after:U})||Q.ignoreMatch());let $;const V=H.input.substring(U);if($=V.match(/^\s*=/)){Q.ignoreMatch();return}if(($=V.match(/^\s+extends\s+/))&&$.index===0){Q.ignoreMatch();return}}},c={$pattern:$f,keyword:mP,literal:gP,built_in:wP,"variable.language":xP},u="[0-9](_?[0-9])*",d=`\\.(${u})`,p="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",f={className:"number",variants:[{begin:`(\\b(${p})((${d})|\\.)?|(${d}))[eE][+-]?(${u})\\b`},{begin:`\\b(${p})\\b((${d})\\b|\\.)?|(${d})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},g={className:"subst",begin:"\\$\\{",end:"\\}",keywords:c,contains:[]},v={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,g],subLanguage:"xml"}},x={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,g],subLanguage:"css"}},w={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,g],subLanguage:"graphql"}},b={className:"string",begin:"`",end:"`",contains:[t.BACKSLASH_ESCAPE,g]},A={className:"comment",variants:[t.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:n+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),t.C_BLOCK_COMMENT_MODE,t.C_LINE_COMMENT_MODE]},O=[t.APOS_STRING_MODE,t.QUOTE_STRING_MODE,v,x,w,b,{match:/\$\d+/},f];g.contains=O.concat({begin:/\{/,end:/\}/,keywords:c,contains:["self"].concat(O)});const j=[].concat(A,g.contains),E=j.concat([{begin:/(\s*)\(/,end:/\)/,keywords:c,contains:["self"].concat(j)}]),T={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:c,contains:E},P={variants:[{match:[/class/,/\s+/,n,/\s+/,/extends/,/\s+/,e.concat(n,"(",e.concat(/\./,n),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,n],scope:{1:"keyword",3:"title.class"}}]},R={relevance:0,match:e.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...yP,...vP]}},M={label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},J={variants:[{match:[/function/,/\s+/,n,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[T],illegal:/%/},F={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function B(H){return e.concat("(?!",H.join("|"),")")}const K={match:e.concat(/\b/,B([...bP,"super","import"].map(H=>`${H}\\s*\\(`)),n,e.lookahead(/\s*\(/)),className:"title.function",relevance:0},W={begin:e.concat(/\./,e.lookahead(e.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},X={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},T]},Y="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+t.UNDERSCORE_IDENT_RE+")\\s*=>",te={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,e.lookahead(Y)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[T]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:c,exports:{PARAMS_CONTAINS:E,CLASS_REFERENCE:R},illegal:/#(?![$_A-z])/,contains:[t.SHEBANG({label:"shebang",binary:"node",relevance:5}),M,t.APOS_STRING_MODE,t.QUOTE_STRING_MODE,v,x,w,b,A,{match:/\$\d+/},f,R,{scope:"attr",match:n+e.lookahead(":"),relevance:0},te,{begin:"("+t.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[A,t.REGEXP_MODE,{className:"function",begin:Y,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:t.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:c,contains:E}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:i.begin,end:i.end},{match:a},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:"xml",contains:[{begin:o.begin,end:o.end,skip:!0,contains:["self"]}]}]},J,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+t.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[T,t.inherit(t.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},W,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[T]},K,F,P,X,{match:/\$[(.]/}]}}function _P(t){const e=t.regex,r=Tz(t),n=$f,i=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],a={begin:[/namespace/,/\s+/,t.IDENT_RE],beginScope:{1:"keyword",3:"title.class"}},o={beginKeywords:"interface",end:/\{/,excludeEnd:!0,keywords:{keyword:"interface extends",built_in:i},contains:[r.exports.CLASS_REFERENCE]},c={className:"meta",relevance:10,begin:/^\s*['"]use strict['"]/},u=["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"],d={$pattern:$f,keyword:mP.concat(u),literal:gP,built_in:wP.concat(i),"variable.language":xP},p={className:"meta",begin:"@"+n},f=(w,b,S)=>{const A=w.contains.findIndex(O=>O.label===b);if(A===-1)throw new Error("can not find mode to replace");w.contains.splice(A,1,S)};Object.assign(r.keywords,d),r.exports.PARAMS_CONTAINS.push(p);const g=r.contains.find(w=>w.scope==="attr"),v=Object.assign({},g,{match:e.concat(n,e.lookahead(/\s*\?:/))});r.exports.PARAMS_CONTAINS.push([r.exports.CLASS_REFERENCE,g,v]),r.contains=r.contains.concat([p,a,o,v]),f(r,"shebang",t.SHEBANG()),f(r,"use_strict",c);const x=r.contains.find(w=>w.label==="func.def");return x.relevance=0,Object.assign(r,{name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),r}function SP(t){const e=t.regex,r=e.concat(/[\p{L}_]/u,e.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),n=/[\p{L}0-9._:-]+/u,i={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},a={begin:/\s/,contains:[{className:"keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},o=t.inherit(a,{begin:/\(/,end:/\)/}),c=t.inherit(t.APOS_STRING_MODE,{className:"string"}),u=t.inherit(t.QUOTE_STRING_MODE,{className:"string"}),d={endsWithParent:!0,illegal:/</,relevance:0,contains:[{className:"attr",begin:n,relevance:0},{begin:/=\s*/,relevance:0,contains:[{className:"string",endsParent:!0,variants:[{begin:/"/,end:/"/,contains:[i]},{begin:/'/,end:/'/,contains:[i]},{begin:/[^\s"'=<>`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,unicodeRegex:!0,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,relevance:10,contains:[a,u,c,o,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,contains:[a,o,u,c]}]}]},t.COMMENT(/<!--/,/-->/,{relevance:10}),{begin:/<!\[CDATA\[/,end:/\]\]>/,relevance:10},i,{className:"meta",end:/\?>/,variants:[{begin:/<\?xml/,relevance:10,contains:[u]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:"tag",begin:/<style(?=\s|>)/,end:/>/,keywords:{name:"style"},contains:[d],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:/<script(?=\s|>)/,end:/>/,keywords:{name:"script"},contains:[d],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:e.concat(/</,e.lookahead(e.concat(r,e.either(/\/>/,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:r,relevance:0,starts:d}]},{className:"tag",begin:e.concat(/<\//,e.lookahead(e.concat(r,/>/))),contains:[{className:"name",begin:r,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}function kP(t){const e="true false yes no null",r="[\\w#;/?:@&=+$,.~*'()[\\]]+",n={className:"attr",variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},i={className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]},a={className:"string",relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:"char.escape",relevance:0}]},o={className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[t.BACKSLASH_ESCAPE,i]},c=t.inherit(o,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),g={className:"number",begin:"\\b"+"[0-9]{4}(-[0-9][0-9]){0,2}"+"([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?"+"(\\.[0-9]*)?"+"([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?"+"\\b"},v={end:",",endsWithParent:!0,excludeEnd:!0,keywords:e,relevance:0},x={begin:/\{/,end:/\}/,contains:[v],illegal:"\\n",relevance:0},w={begin:"\\[",end:"\\]",contains:[v],illegal:"\\n",relevance:0},b=[n,{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+r},{className:"type",begin:"!<"+r+">"},{className:"type",begin:"!"+r},{className:"type",begin:"!!"+r},{className:"meta",begin:"&"+t.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+t.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},t.HASH_COMMENT_MODE,{beginKeywords:e,keywords:{literal:e}},g,{className:"number",begin:t.C_NUMBER_RE+"\\b",relevance:0},x,w,a,o],S=[...b];return S.pop(),S.push(c),v.contains=S,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:b}}function Fw(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var zo=Fw();function EP(t){zo=t}var So={exec:()=>null};function bs(t){let e=[];return r=>{let n=Math.max(0,Math.min(3,r-1)),i=e[n];return i||(i=t(n),e[n]=i),i}}function st(t,e=""){let r=typeof t=="string"?t:t.source,n={replace:(i,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace(Pr.caret,"$1"),r=r.replace(i,o),n},getRegex:()=>new RegExp(r,e)};return n}var jz=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),Pr={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:bs(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:bs(t=>new RegExp(`^ {0,${t}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:bs(t=>new RegExp(`^ {0,${t}}(?:\`\`\`|~~~)`)),headingBeginRegex:bs(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:bs(t=>new RegExp(`^ {0,${t}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:bs(t=>new RegExp(`^ {0,${t}}>`))},Cz=/^(?:[ \t]*(?:\n|$))+/,Nz=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Pz=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Ru=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Rz=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Hw=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,OP=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,AP=st(OP).replace(/bull/g,Hw).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Iz=st(OP).replace(/bull/g,Hw).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Ww=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,$z=/^[^\n]+/,Gw=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Mz=st(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Gw).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Lz=st(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Hw).getRegex(),ep="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Kw=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Dz=st("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Kw).replace("tag",ep).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),TP=st(Ww).replace("hr",Ru).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ep).getRegex(),zz=st(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",TP).getRegex(),Vw={blockquote:zz,code:Nz,def:Mz,fences:Pz,heading:Rz,hr:Ru,html:Dz,lheading:AP,list:Lz,newline:Cz,paragraph:TP,table:So,text:$z},Hk=st("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Ru).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ep).getRegex(),Bz={...Vw,lheading:Iz,table:Hk,paragraph:st(Ww).replace("hr",Ru).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Hk).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ep).getRegex()},Uz={...Vw,html:st(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Kw).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:So,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:st(Ww).replace("hr",Ru).replace("heading",` *#{1,6} *[^
|
|
324
|
+
]`).replace("lheading",AP).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},qz=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Fz=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,jP=/^( {2,}|\\)\n(?!\s*$)/,Hz=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,bl=/[\p{P}\p{S}]/u,tp=/[\s\p{P}\p{S}]/u,Xw=/[^\s\p{P}\p{S}]/u,Wz=st(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,tp).getRegex(),CP=/(?!~)[\p{P}\p{S}]/u,Gz=/(?!~)[\s\p{P}\p{S}]/u,Kz=/(?:[^\s\p{P}\p{S}]|~)/u,Vz=st(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",jz?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),NP=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Xz=st(NP,"u").replace(/punct/g,bl).getRegex(),Yz=st(NP,"u").replace(/punct/g,CP).getRegex(),PP="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Jz=st(PP,"gu").replace(/notPunctSpace/g,Xw).replace(/punctSpace/g,tp).replace(/punct/g,bl).getRegex(),Zz=st(PP,"gu").replace(/notPunctSpace/g,Kz).replace(/punctSpace/g,Gz).replace(/punct/g,CP).getRegex(),Qz=st("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Xw).replace(/punctSpace/g,tp).replace(/punct/g,bl).getRegex(),eB=st(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,bl).getRegex(),tB="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",rB=st(tB,"gu").replace(/notPunctSpace/g,Xw).replace(/punctSpace/g,tp).replace(/punct/g,bl).getRegex(),nB=st(/\\(punct)/,"gu").replace(/punct/g,bl).getRegex(),iB=st(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),aB=st(Kw).replace("(?:-->|$)","-->").getRegex(),oB=st("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",aB).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Mf=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,sB=st(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Mf).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),RP=st(/^!?\[(label)\]\[(ref)\]/).replace("label",Mf).replace("ref",Gw).getRegex(),IP=st(/^!?\[(ref)\](?:\[\])?/).replace("ref",Gw).getRegex(),lB=st("reflink|nolink(?!\\()","g").replace("reflink",RP).replace("nolink",IP).getRegex(),Wk=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Yw={_backpedal:So,anyPunctuation:nB,autolink:iB,blockSkip:Vz,br:jP,code:Fz,del:So,delLDelim:So,delRDelim:So,emStrongLDelim:Xz,emStrongRDelimAst:Jz,emStrongRDelimUnd:Qz,escape:qz,link:sB,nolink:IP,punctuation:Wz,reflink:RP,reflinkSearch:lB,tag:oB,text:Hz,url:So},cB={...Yw,link:st(/^!?\[(label)\]\((.*?)\)/).replace("label",Mf).getRegex(),reflink:st(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Mf).getRegex()},Hb={...Yw,emStrongRDelimAst:Zz,emStrongLDelim:Yz,delLDelim:eB,delRDelim:rB,url:st(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Wk).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:st(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Wk).getRegex()},uB={...Hb,br:st(jP).replace("{2,}","*").getRegex(),text:st(Hb.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},rf={normal:Vw,gfm:Bz,pedantic:Uz},hc={normal:Yw,gfm:Hb,breaks:uB,pedantic:cB},dB={"&":"&","<":"<",">":">",'"':""","'":"'"},Gk=t=>dB[t];function vi(t,e){if(e){if(Pr.escapeTest.test(t))return t.replace(Pr.escapeReplace,Gk)}else if(Pr.escapeTestNoEncode.test(t))return t.replace(Pr.escapeReplaceNoEncode,Gk);return t}function Kk(t){try{t=encodeURI(t).replace(Pr.percentDecode,"%")}catch{return null}return t}function Vk(t,e){var a;let r=t.replace(Pr.findPipe,(o,c,u)=>{let d=!1,p=c;for(;--p>=0&&u[p]==="\\";)d=!d;return d?"|":" |"}),n=r.split(Pr.splitPipe),i=0;if(n[0].trim()||n.shift(),n.length>0&&!((a=n.at(-1))!=null&&a.trim())&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;i<n.length;i++)n[i]=n[i].trim().replace(Pr.slashPipe,"|");return n}function Aa(t,e,r){let n=t.length;if(n===0)return"";let i=0;for(;i<n&&t.charAt(n-i-1)===e;)i++;return t.slice(0,n-i)}function Xk(t){let e=t.split(`
|
|
323
325
|
`),r=e.length-1;for(;r>=0&&Pr.blankLine.test(e[r]);)r--;return e.length-r<=2?t:e.slice(0,r+1).join(`
|
|
324
|
-
`)}function
|
|
326
|
+
`)}function fB(t,e){if(t.indexOf(e[1])===-1)return-1;let r=0;for(let n=0;n<t.length;n++)if(t[n]==="\\")n++;else if(t[n]===e[0])r++;else if(t[n]===e[1]&&(r--,r<0))return n;return r>0?-2:-1}function hB(t,e=0){let r=e,n="";for(let i of t)if(i===" "){let a=4-r%4;n+=" ".repeat(a),r+=a}else n+=i,r++;return n}function Yk(t,e,r,n,i){let a=e.href,o=e.title||null,c=t[1].replace(i.other.outputLinkReplace,"$1");n.state.inLink=!0;let u={type:t[0].charAt(0)==="!"?"image":"link",raw:r,href:a,title:o,text:c,tokens:n.inlineTokens(c)};return n.state.inLink=!1,u}function pB(t,e,r){let n=t.match(r.other.indentCodeCompensation);if(n===null)return e;let i=n[1];return e.split(`
|
|
325
327
|
`).map(a=>{let o=a.match(r.other.beginningSpace);if(o===null)return a;let[c]=o;return c.length>=i.length?a.slice(i.length):a}).join(`
|
|
326
|
-
`)}var
|
|
328
|
+
`)}var Lf=class{constructor(t){bt(this,"options");bt(this,"rules");bt(this,"lexer");this.options=t||zo}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let r=this.options.pedantic?e[0]:Xk(e[0]),n=r.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:r,codeBlockStyle:"indented",text:n}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let r=e[0],n=pB(r,e[3]||"",this.rules);return{type:"code",raw:r,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:n}}}heading(t){let e=this.rules.block.heading.exec(t);if(e){let r=e[2].trim();if(this.rules.other.endingHash.test(r)){let n=Aa(r,"#");(this.options.pedantic||!n||this.rules.other.endingSpaceChar.test(n))&&(r=n.trim())}return{type:"heading",raw:Aa(e[0],`
|
|
327
329
|
`),depth:e[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(t){let e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:Aa(e[0],`
|
|
328
330
|
`)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let r=Aa(e[0],`
|
|
329
331
|
`).split(`
|
|
@@ -336,19 +338,19 @@ ${p}`:p;let f=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
336
338
|
`),w=this.blockquote(x);a[a.length-1]=w,n=n.substring(0,n.length-v.raw.length)+w.raw,i=i.substring(0,i.length-v.text.length)+w.text;break}else if((g==null?void 0:g.type)==="list"){let v=g,x=v.raw+`
|
|
337
339
|
`+r.join(`
|
|
338
340
|
`),w=this.list(x);a[a.length-1]=w,n=n.substring(0,n.length-g.raw.length)+w.raw,i=i.substring(0,i.length-v.raw.length)+w.raw,r=x.substring(a.at(-1).raw.length).split(`
|
|
339
|
-
`);continue}}return{type:"blockquote",raw:n,tokens:a,text:i}}}list(t){let e=this.rules.block.list.exec(t);if(e){let r=e[1].trim(),n=r.length>1,i={type:"list",raw:"",ordered:n,start:n?+r.slice(0,-1):"",loose:!1,items:[]};r=n?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=n?r:"[*+-]");let a=this.rules.other.listItemRegex(r),o=!1;for(;t;){let u=!1,d="",p="";if(!(e=a.exec(t))||this.rules.block.hr.test(t))break;d=e[0],t=t.substring(d.length);let f=
|
|
341
|
+
`);continue}}return{type:"blockquote",raw:n,tokens:a,text:i}}}list(t){let e=this.rules.block.list.exec(t);if(e){let r=e[1].trim(),n=r.length>1,i={type:"list",raw:"",ordered:n,start:n?+r.slice(0,-1):"",loose:!1,items:[]};r=n?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=n?r:"[*+-]");let a=this.rules.other.listItemRegex(r),o=!1;for(;t;){let u=!1,d="",p="";if(!(e=a.exec(t))||this.rules.block.hr.test(t))break;d=e[0],t=t.substring(d.length);let f=hB(e[2].split(`
|
|
340
342
|
`,1)[0],e[1].length),g=t.split(`
|
|
341
343
|
`,1)[0],v=!f.trim(),x=0;if(this.options.pedantic?(x=2,p=f.trimStart()):v?x=e[1].length+1:(x=f.search(this.rules.other.nonSpaceChar),x=x>4?1:x,p=f.slice(x),x+=e[1].length),v&&this.rules.other.blankLine.test(g)&&(d+=g+`
|
|
342
344
|
`,t=t.substring(g.length+1),u=!0),!u){let w=this.rules.other.nextBulletRegex(x),b=this.rules.other.hrRegex(x),S=this.rules.other.fencesBeginRegex(x),A=this.rules.other.headingBeginRegex(x),O=this.rules.other.htmlBeginRegex(x),j=this.rules.other.blockquoteBeginRegex(x);for(;t;){let E=t.split(`
|
|
343
345
|
`,1)[0],T;if(g=E,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),T=g):T=g.replace(this.rules.other.tabCharGlobal," "),S.test(g)||A.test(g)||O.test(g)||j.test(g)||w.test(g)||b.test(g))break;if(T.search(this.rules.other.nonSpaceChar)>=x||!g.trim())p+=`
|
|
344
346
|
`+T.slice(x);else{if(v||f.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||S.test(f)||A.test(f)||b.test(f))break;p+=`
|
|
345
347
|
`+g}v=!g.trim(),d+=E+`
|
|
346
|
-
`,t=t.substring(E.length+1),f=T.slice(x)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(d)&&(o=!0)),i.items.push({type:"list_item",raw:d,task:!!this.options.gfm&&this.rules.other.listIsTask.test(p),loose:!1,text:p,tokens:[]}),i.raw+=d}let c=i.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let u of i.items){this.lexer.state.top=!1,u.tokens=this.lexer.blockTokens(u.text,[]);let d=u.tokens[0];if(u.task&&((d==null?void 0:d.type)==="text"||(d==null?void 0:d.type)==="paragraph")){u.text=u.text.replace(this.rules.other.listReplaceTask,""),d.raw=d.raw.replace(this.rules.other.listReplaceTask,""),d.text=d.text.replace(this.rules.other.listReplaceTask,"");for(let f=this.lexer.inlineQueue.length-1;f>=0;f--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[f].src)){this.lexer.inlineQueue[f].src=this.lexer.inlineQueue[f].src.replace(this.rules.other.listReplaceTask,"");break}let p=this.rules.other.listTaskCheckbox.exec(u.raw);if(p){let f={type:"checkbox",raw:p[0]+" ",checked:p[0]!=="[ ]"};u.checked=f.checked,i.loose?u.tokens[0]&&["paragraph","text"].includes(u.tokens[0].type)&&"tokens"in u.tokens[0]&&u.tokens[0].tokens?(u.tokens[0].raw=f.raw+u.tokens[0].raw,u.tokens[0].text=f.raw+u.tokens[0].text,u.tokens[0].tokens.unshift(f)):u.tokens.unshift({type:"paragraph",raw:f.raw,text:f.raw,tokens:[f]}):u.tokens.unshift(f)}}else u.task&&(u.task=!1);if(!i.loose){let p=u.tokens.filter(g=>g.type==="space"),f=p.length>0&&p.some(g=>this.rules.other.anyLine.test(g.raw));i.loose=f}}if(i.loose)for(let u of i.items){u.loose=!0;for(let d of u.tokens)d.type==="text"&&(d.type="paragraph")}return i}}html(t){let e=this.rules.block.html.exec(t);if(e){let r=
|
|
347
|
-
`),href:n,title:i}}}table(t){var o;let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let r=
|
|
348
|
+
`,t=t.substring(E.length+1),f=T.slice(x)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(d)&&(o=!0)),i.items.push({type:"list_item",raw:d,task:!!this.options.gfm&&this.rules.other.listIsTask.test(p),loose:!1,text:p,tokens:[]}),i.raw+=d}let c=i.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let u of i.items){this.lexer.state.top=!1,u.tokens=this.lexer.blockTokens(u.text,[]);let d=u.tokens[0];if(u.task&&((d==null?void 0:d.type)==="text"||(d==null?void 0:d.type)==="paragraph")){u.text=u.text.replace(this.rules.other.listReplaceTask,""),d.raw=d.raw.replace(this.rules.other.listReplaceTask,""),d.text=d.text.replace(this.rules.other.listReplaceTask,"");for(let f=this.lexer.inlineQueue.length-1;f>=0;f--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[f].src)){this.lexer.inlineQueue[f].src=this.lexer.inlineQueue[f].src.replace(this.rules.other.listReplaceTask,"");break}let p=this.rules.other.listTaskCheckbox.exec(u.raw);if(p){let f={type:"checkbox",raw:p[0]+" ",checked:p[0]!=="[ ]"};u.checked=f.checked,i.loose?u.tokens[0]&&["paragraph","text"].includes(u.tokens[0].type)&&"tokens"in u.tokens[0]&&u.tokens[0].tokens?(u.tokens[0].raw=f.raw+u.tokens[0].raw,u.tokens[0].text=f.raw+u.tokens[0].text,u.tokens[0].tokens.unshift(f)):u.tokens.unshift({type:"paragraph",raw:f.raw,text:f.raw,tokens:[f]}):u.tokens.unshift(f)}}else u.task&&(u.task=!1);if(!i.loose){let p=u.tokens.filter(g=>g.type==="space"),f=p.length>0&&p.some(g=>this.rules.other.anyLine.test(g.raw));i.loose=f}}if(i.loose)for(let u of i.items){u.loose=!0;for(let d of u.tokens)d.type==="text"&&(d.type="paragraph")}return i}}html(t){let e=this.rules.block.html.exec(t);if(e){let r=Xk(e[0]);return{type:"html",block:!0,raw:r,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:r}}}def(t){let e=this.rules.block.def.exec(t);if(e){let r=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),n=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:r,raw:Aa(e[0],`
|
|
349
|
+
`),href:n,title:i}}}table(t){var o;let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let r=Vk(e[1]),n=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=(o=e[3])!=null&&o.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
348
350
|
`):[],a={type:"table",raw:Aa(e[0],`
|
|
349
|
-
`),header:[],align:[],rows:[]};if(r.length===n.length){for(let c of n)this.rules.other.tableAlignRight.test(c)?a.align.push("right"):this.rules.other.tableAlignCenter.test(c)?a.align.push("center"):this.rules.other.tableAlignLeft.test(c)?a.align.push("left"):a.align.push(null);for(let c=0;c<r.length;c++)a.header.push({text:r[c],tokens:this.lexer.inline(r[c]),header:!0,align:a.align[c]});for(let c of i)a.rows.push(
|
|
351
|
+
`),header:[],align:[],rows:[]};if(r.length===n.length){for(let c of n)this.rules.other.tableAlignRight.test(c)?a.align.push("right"):this.rules.other.tableAlignCenter.test(c)?a.align.push("center"):this.rules.other.tableAlignLeft.test(c)?a.align.push("left"):a.align.push(null);for(let c=0;c<r.length;c++)a.header.push({text:r[c],tokens:this.lexer.inline(r[c]),header:!0,align:a.align[c]});for(let c of i)a.rows.push(Vk(c,a.header.length).map((u,d)=>({text:u,tokens:this.lexer.inline(u),header:!1,align:a.align[d]})));return a}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let r=e[1].trim();return{type:"heading",raw:Aa(e[0],`
|
|
350
352
|
`),depth:e[2].charAt(0)==="="?1:2,text:r,tokens:this.lexer.inline(r)}}}paragraph(t){let e=this.rules.block.paragraph.exec(t);if(e){let r=e[1].charAt(e[1].length-1)===`
|
|
351
|
-
`?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:r,tokens:this.lexer.inline(r)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let r=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let a=Aa(r.slice(0,-1),"\\");if((r.length-a.length)%2===0)return}else{let a=
|
|
353
|
+
`?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:r,tokens:this.lexer.inline(r)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let r=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let a=Aa(r.slice(0,-1),"\\");if((r.length-a.length)%2===0)return}else{let a=fB(e[2],"()");if(a===-2)return;if(a>-1){let o=(e[0].indexOf("!")===0?5:4)+e[1].length+a;e[2]=e[2].substring(0,a),e[0]=e[0].substring(0,o).trim(),e[3]=""}}let n=e[2],i="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(n);a&&(n=a[1],i=a[3])}else i=e[3]?e[3].slice(1,-1):"";return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?n=n.slice(1):n=n.slice(1,-1)),Yk(e,{href:n&&n.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let r;if((r=this.rules.inline.reflink.exec(t))||(r=this.rules.inline.nolink.exec(t))){let n=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=e[n.toLowerCase()];if(!i){let a=r[0].charAt(0);return{type:"text",raw:a,text:a}}return Yk(r,i,r[0],this.lexer,this.rules)}}emStrong(t,e,r=""){let n=this.rules.inline.emStrongLDelim.exec(t);if(!(!n||!n[1]&&!n[2]&&!n[3]&&!n[4]||n[4]&&r.match(this.rules.other.unicodeAlphaNumeric))&&(!(n[1]||n[3])||!r||this.rules.inline.punctuation.exec(r))){let i=[...n[0]].length-1,a,o,c=i,u=0,d=n[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,e=e.slice(-1*t.length+i);(n=d.exec(e))!==null;){if(a=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!a)continue;if(o=[...a].length,n[3]||n[4]){c+=o;continue}else if((n[5]||n[6])&&i%3&&!((i+o)%3)){u+=o;continue}if(c-=o,c>0)continue;o=Math.min(o,o+c+u);let p=[...n[0]][0].length,f=t.slice(0,i+n.index+p+o);if(Math.min(i,o)%2){let v=f.slice(1,-1);return{type:"em",raw:f,text:v,tokens:this.lexer.inlineTokens(v)}}let g=f.slice(2,-2);return{type:"strong",raw:f,text:g,tokens:this.lexer.inlineTokens(g)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let r=e[2].replace(this.rules.other.newLineCharGlobal," "),n=this.rules.other.nonSpaceChar.test(r),i=this.rules.other.startingSpaceChar.test(r)&&this.rules.other.endingSpaceChar.test(r);return n&&i&&(r=r.substring(1,r.length-1)),{type:"codespan",raw:e[0],text:r}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t,e,r=""){let n=this.rules.inline.delLDelim.exec(t);if(n&&(!n[1]||!r||this.rules.inline.punctuation.exec(r))){let i=[...n[0]].length-1,a,o,c=i,u=this.rules.inline.delRDelim;for(u.lastIndex=0,e=e.slice(-1*t.length+i);(n=u.exec(e))!==null;){if(a=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!a||(o=[...a].length,o!==i))continue;if(n[3]||n[4]){c+=o;continue}if(c-=o,c>0)continue;o=Math.min(o,o+c);let d=[...n[0]][0].length,p=t.slice(0,i+n.index+d+o),f=p.slice(i,-i);return{type:"del",raw:p,text:f,tokens:this.lexer.inlineTokens(f)}}}}autolink(t){let e=this.rules.inline.autolink.exec(t);if(e){let r,n;return e[2]==="@"?(r=e[1],n="mailto:"+r):(r=e[1],n=r),{type:"link",raw:e[0],text:r,href:n,tokens:[{type:"text",raw:r,text:r}]}}}url(t){var r;let e;if(e=this.rules.inline.url.exec(t)){let n,i;if(e[2]==="@")n=e[0],i="mailto:"+n;else{let a;do a=e[0],e[0]=((r=this.rules.inline._backpedal.exec(e[0]))==null?void 0:r[0])??"";while(a!==e[0]);n=e[0],e[1]==="www."?i="http://"+e[0]:i=e[0]}return{type:"link",raw:e[0],text:n,href:i,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let r=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:r}}}},Gn=class Wb{constructor(e){bt(this,"tokens");bt(this,"options");bt(this,"state");bt(this,"inlineQueue");bt(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=e||zo,this.options.tokenizer=this.options.tokenizer||new Lf,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let r={other:Pr,block:rf.normal,inline:hc.normal};this.options.pedantic?(r.block=rf.pedantic,r.inline=hc.pedantic):this.options.gfm&&(r.block=rf.gfm,this.options.breaks?r.inline=hc.breaks:r.inline=hc.gfm),this.tokenizer.rules=r}static get rules(){return{block:rf,inline:hc}}static lex(e,r){return new Wb(r).lex(e)}static lexInline(e,r){return new Wb(r).inlineTokens(e)}lex(e){e=e.replace(Pr.carriageReturn,`
|
|
352
354
|
`),this.blockTokens(e,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let n=this.inlineQueue[r];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,r=[],n=!1){var a,o,c;this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(Pr.tabCharGlobal," ").replace(Pr.spaceLine,""));let i=1/0;for(;e;){if(e.length<i)i=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let u;if((o=(a=this.options.extensions)==null?void 0:a.block)!=null&&o.some(p=>(u=p.call({lexer:this},e,r))?(e=e.substring(u.raw.length),r.push(u),!0):!1))continue;if(u=this.tokenizer.space(e)){e=e.substring(u.raw.length);let p=r.at(-1);u.raw.length===1&&p!==void 0?p.raw+=`
|
|
353
355
|
`:r.push(u);continue}if(u=this.tokenizer.code(e)){e=e.substring(u.raw.length);let p=r.at(-1);(p==null?void 0:p.type)==="paragraph"||(p==null?void 0:p.type)==="text"?(p.raw+=(p.raw.endsWith(`
|
|
354
356
|
`)?"":`
|
|
@@ -362,7 +364,7 @@ ${p}`:p;let f=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
362
364
|
`+u.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=p.text):r.push(u),n=d.length!==e.length,e=e.substring(u.raw.length);continue}if(u=this.tokenizer.text(e)){e=e.substring(u.raw.length);let p=r.at(-1);(p==null?void 0:p.type)==="text"?(p.raw+=(p.raw.endsWith(`
|
|
363
365
|
`)?"":`
|
|
364
366
|
`)+u.raw,p.text+=`
|
|
365
|
-
`+u.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=p.text):r.push(u);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,r}inline(e,r=[]){return this.inlineQueue.push({src:e,tokens:r}),r}inlineTokens(e,r=[]){var d,p,f,g,v;this.tokenizer.lexer=this;let n=e,i=null;if(this.tokens.links){let x=Object.keys(this.tokens.links);if(x.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(n))!==null;)x.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(n=n.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(n))!==null;)n=n.slice(0,i.index)+"++"+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let a;for(;(i=this.tokenizer.rules.inline.blockSkip.exec(n))!==null;)a=i[2]?i[2].length:0,n=n.slice(0,i.index+a)+"["+"a".repeat(i[0].length-a-2)+"]"+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=((p=(d=this.options.hooks)==null?void 0:d.emStrongMask)==null?void 0:p.call({lexer:this},n))??n;let o=!1,c="",u=1/0;for(;e;){if(e.length<u)u=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}o||(c=""),o=!1;let x;if((g=(f=this.options.extensions)==null?void 0:f.inline)!=null&&g.some(b=>(x=b.call({lexer:this},e,r))?(e=e.substring(x.raw.length),r.push(x),!0):!1))continue;if(x=this.tokenizer.escape(e)){e=e.substring(x.raw.length),r.push(x);continue}if(x=this.tokenizer.tag(e)){e=e.substring(x.raw.length),r.push(x);continue}if(x=this.tokenizer.link(e)){e=e.substring(x.raw.length),r.push(x);continue}if(x=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(x.raw.length);let b=r.at(-1);x.type==="text"&&(b==null?void 0:b.type)==="text"?(b.raw+=x.raw,b.text+=x.text):r.push(x);continue}if(x=this.tokenizer.emStrong(e,n,c)){e=e.substring(x.raw.length),r.push(x);continue}if(x=this.tokenizer.codespan(e)){e=e.substring(x.raw.length),r.push(x);continue}if(x=this.tokenizer.br(e)){e=e.substring(x.raw.length),r.push(x);continue}if(x=this.tokenizer.del(e,n,c)){e=e.substring(x.raw.length),r.push(x);continue}if(x=this.tokenizer.autolink(e)){e=e.substring(x.raw.length),r.push(x);continue}if(!this.state.inLink&&(x=this.tokenizer.url(e))){e=e.substring(x.raw.length),r.push(x);continue}let w=e;if((v=this.options.extensions)!=null&&v.startInline){let b=1/0,S=e.slice(1),A;this.options.extensions.startInline.forEach(O=>{A=O.call({lexer:this},S),typeof A=="number"&&A>=0&&(b=Math.min(b,A))}),b<1/0&&b>=0&&(w=e.substring(0,b+1))}if(x=this.tokenizer.inlineText(w)){e=e.substring(x.raw.length),x.raw.slice(-1)!=="_"&&(c=x.raw.slice(-1)),o=!0;let b=r.at(-1);(b==null?void 0:b.type)==="text"?(b.raw+=x.raw,b.text+=x.text):r.push(x);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return r}infiniteLoopError(e){let r="Infinite loop on byte: "+e;if(this.options.silent)console.error(r);else throw new Error(r)}},
|
|
367
|
+
`+u.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=p.text):r.push(u);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,r}inline(e,r=[]){return this.inlineQueue.push({src:e,tokens:r}),r}inlineTokens(e,r=[]){var d,p,f,g,v;this.tokenizer.lexer=this;let n=e,i=null;if(this.tokens.links){let x=Object.keys(this.tokens.links);if(x.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(n))!==null;)x.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(n=n.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(n))!==null;)n=n.slice(0,i.index)+"++"+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let a;for(;(i=this.tokenizer.rules.inline.blockSkip.exec(n))!==null;)a=i[2]?i[2].length:0,n=n.slice(0,i.index+a)+"["+"a".repeat(i[0].length-a-2)+"]"+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=((p=(d=this.options.hooks)==null?void 0:d.emStrongMask)==null?void 0:p.call({lexer:this},n))??n;let o=!1,c="",u=1/0;for(;e;){if(e.length<u)u=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}o||(c=""),o=!1;let x;if((g=(f=this.options.extensions)==null?void 0:f.inline)!=null&&g.some(b=>(x=b.call({lexer:this},e,r))?(e=e.substring(x.raw.length),r.push(x),!0):!1))continue;if(x=this.tokenizer.escape(e)){e=e.substring(x.raw.length),r.push(x);continue}if(x=this.tokenizer.tag(e)){e=e.substring(x.raw.length),r.push(x);continue}if(x=this.tokenizer.link(e)){e=e.substring(x.raw.length),r.push(x);continue}if(x=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(x.raw.length);let b=r.at(-1);x.type==="text"&&(b==null?void 0:b.type)==="text"?(b.raw+=x.raw,b.text+=x.text):r.push(x);continue}if(x=this.tokenizer.emStrong(e,n,c)){e=e.substring(x.raw.length),r.push(x);continue}if(x=this.tokenizer.codespan(e)){e=e.substring(x.raw.length),r.push(x);continue}if(x=this.tokenizer.br(e)){e=e.substring(x.raw.length),r.push(x);continue}if(x=this.tokenizer.del(e,n,c)){e=e.substring(x.raw.length),r.push(x);continue}if(x=this.tokenizer.autolink(e)){e=e.substring(x.raw.length),r.push(x);continue}if(!this.state.inLink&&(x=this.tokenizer.url(e))){e=e.substring(x.raw.length),r.push(x);continue}let w=e;if((v=this.options.extensions)!=null&&v.startInline){let b=1/0,S=e.slice(1),A;this.options.extensions.startInline.forEach(O=>{A=O.call({lexer:this},S),typeof A=="number"&&A>=0&&(b=Math.min(b,A))}),b<1/0&&b>=0&&(w=e.substring(0,b+1))}if(x=this.tokenizer.inlineText(w)){e=e.substring(x.raw.length),x.raw.slice(-1)!=="_"&&(c=x.raw.slice(-1)),o=!0;let b=r.at(-1);(b==null?void 0:b.type)==="text"?(b.raw+=x.raw,b.text+=x.text):r.push(x);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return r}infiniteLoopError(e){let r="Infinite loop on byte: "+e;if(this.options.silent)console.error(r);else throw new Error(r)}},Df=class{constructor(e){bt(this,"options");bt(this,"parser");this.options=e||zo}space(e){return""}code({text:e,lang:r,escaped:n}){var o;let i=(o=(r||"").match(Pr.notSpaceStart))==null?void 0:o[0],a=e.replace(Pr.endingNewline,"")+`
|
|
366
368
|
`;return i?'<pre><code class="language-'+vi(i)+'">'+(n?a:vi(a,!0))+`</code></pre>
|
|
367
369
|
`:"<pre><code>"+(n?a:vi(a,!0))+`</code></pre>
|
|
368
370
|
`}blockquote({tokens:e}){return`<blockquote>
|
|
@@ -380,23 +382,23 @@ ${this.parser.parse(e)}</blockquote>
|
|
|
380
382
|
`}tablerow({text:e}){return`<tr>
|
|
381
383
|
${e}</tr>
|
|
382
384
|
`}tablecell(e){let r=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+r+`</${n}>
|
|
383
|
-
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${vi(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:r,tokens:n}){let i=this.parser.parseInline(n),a=
|
|
384
|
-
Please report this to https://github.com/markedjs/marked.`,t){let n="<p>An error occurred:</p><pre>"+vi(r.message+"",!0)+"</pre>";return e?Promise.resolve(n):n}if(e)return Promise.reject(r);throw r}}},Ro=new
|
|
385
|
+
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${vi(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:r,tokens:n}){let i=this.parser.parseInline(n),a=Kk(e);if(a===null)return i;e=a;let o='<a href="'+e+'"';return r&&(o+=' title="'+vi(r)+'"'),o+=">"+i+"</a>",o}image({href:e,title:r,text:n,tokens:i}){i&&(n=this.parser.parseInline(i,this.parser.textRenderer));let a=Kk(e);if(a===null)return vi(n);e=a;let o=`<img src="${e}" alt="${vi(n)}"`;return r&&(o+=` title="${vi(r)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:vi(e.text)}},Jw=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},Kn=class Gb{constructor(e){bt(this,"options");bt(this,"renderer");bt(this,"textRenderer");this.options=e||zo,this.options.renderer=this.options.renderer||new Df,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Jw}static parse(e,r){return new Gb(r).parse(e)}static parseInline(e,r){return new Gb(r).parseInline(e)}parse(e){var n,i;this.renderer.parser=this;let r="";for(let a=0;a<e.length;a++){let o=e[a];if((i=(n=this.options.extensions)==null?void 0:n.renderers)!=null&&i[o.type]){let u=o,d=this.options.extensions.renderers[u.type].call({parser:this},u);if(d!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(u.type)){r+=d||"";continue}}let c=o;switch(c.type){case"space":{r+=this.renderer.space(c);break}case"hr":{r+=this.renderer.hr(c);break}case"heading":{r+=this.renderer.heading(c);break}case"code":{r+=this.renderer.code(c);break}case"table":{r+=this.renderer.table(c);break}case"blockquote":{r+=this.renderer.blockquote(c);break}case"list":{r+=this.renderer.list(c);break}case"checkbox":{r+=this.renderer.checkbox(c);break}case"html":{r+=this.renderer.html(c);break}case"def":{r+=this.renderer.def(c);break}case"paragraph":{r+=this.renderer.paragraph(c);break}case"text":{r+=this.renderer.text(c);break}default:{let u='Token with "'+c.type+'" type was not found.';if(this.options.silent)return console.error(u),"";throw new Error(u)}}}return r}parseInline(e,r=this.renderer){var i,a;this.renderer.parser=this;let n="";for(let o=0;o<e.length;o++){let c=e[o];if((a=(i=this.options.extensions)==null?void 0:i.renderers)!=null&&a[c.type]){let d=this.options.extensions.renderers[c.type].call({parser:this},c);if(d!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(c.type)){n+=d||"";continue}}let u=c;switch(u.type){case"escape":{n+=r.text(u);break}case"html":{n+=r.html(u);break}case"link":{n+=r.link(u);break}case"image":{n+=r.image(u);break}case"checkbox":{n+=r.checkbox(u);break}case"strong":{n+=r.strong(u);break}case"em":{n+=r.em(u);break}case"codespan":{n+=r.codespan(u);break}case"br":{n+=r.br(u);break}case"del":{n+=r.del(u);break}case"text":{n+=r.text(u);break}default:{let d='Token with "'+u.type+'" type was not found.';if(this.options.silent)return console.error(d),"";throw new Error(d)}}}return n}},Af,Ec=(Af=class{constructor(e){bt(this,"options");bt(this,"block");this.options=e||zo}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Gn.lex:Gn.lexInline}provideParser(e=this.block){return e?Kn.parse:Kn.parseInline}},bt(Af,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens","emStrongMask"])),bt(Af,"passThroughHooksRespectAsync",new Set(["preprocess","postprocess","processAllTokens"])),Af),mB=class{constructor(...t){bt(this,"defaults",Fw());bt(this,"options",this.setOptions);bt(this,"parse",this.parseMarkdown(!0));bt(this,"parseInline",this.parseMarkdown(!1));bt(this,"Parser",Kn);bt(this,"Renderer",Df);bt(this,"TextRenderer",Jw);bt(this,"Lexer",Gn);bt(this,"Tokenizer",Lf);bt(this,"Hooks",Ec);this.use(...t)}walkTokens(t,e){var n,i;let r=[];for(let a of t)switch(r=r.concat(e.call(this,a)),a.type){case"table":{let o=a;for(let c of o.header)r=r.concat(this.walkTokens(c.tokens,e));for(let c of o.rows)for(let u of c)r=r.concat(this.walkTokens(u.tokens,e));break}case"list":{let o=a;r=r.concat(this.walkTokens(o.items,e));break}default:{let o=a;(i=(n=this.defaults.extensions)==null?void 0:n.childTokens)!=null&&i[o.type]?this.defaults.extensions.childTokens[o.type].forEach(c=>{let u=o[c].flat(1/0);r=r.concat(this.walkTokens(u,e))}):o.tokens&&(r=r.concat(this.walkTokens(o.tokens,e)))}}return r}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(r=>{let n={...r};if(n.async=this.defaults.async||n.async||!1,r.extensions&&(r.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let a=e.renderers[i.name];a?e.renderers[i.name]=function(...o){let c=i.renderer.apply(this,o);return c===!1&&(c=a.apply(this,o)),c}:e.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=e[i.level];a?a.unshift(i.tokenizer):e[i.level]=[i.tokenizer],i.start&&(i.level==="block"?e.startBlock?e.startBlock.push(i.start):e.startBlock=[i.start]:i.level==="inline"&&(e.startInline?e.startInline.push(i.start):e.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(e.childTokens[i.name]=i.childTokens)}),n.extensions=e),r.renderer){let i=this.defaults.renderer||new Df(this.defaults);for(let a in r.renderer){if(!(a in i))throw new Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let o=a,c=r.renderer[o],u=i[o];i[o]=(...d)=>{let p=c.apply(i,d);return p===!1&&(p=u.apply(i,d)),p||""}}n.renderer=i}if(r.tokenizer){let i=this.defaults.tokenizer||new Lf(this.defaults);for(let a in r.tokenizer){if(!(a in i))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let o=a,c=r.tokenizer[o],u=i[o];i[o]=(...d)=>{let p=c.apply(i,d);return p===!1&&(p=u.apply(i,d)),p}}n.tokenizer=i}if(r.hooks){let i=this.defaults.hooks||new Ec;for(let a in r.hooks){if(!(a in i))throw new Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let o=a,c=r.hooks[o],u=i[o];Ec.passThroughHooks.has(a)?i[o]=d=>{if(this.defaults.async&&Ec.passThroughHooksRespectAsync.has(a))return(async()=>{let f=await c.call(i,d);return u.call(i,f)})();let p=c.call(i,d);return u.call(i,p)}:i[o]=(...d)=>{if(this.defaults.async)return(async()=>{let f=await c.apply(i,d);return f===!1&&(f=await u.apply(i,d)),f})();let p=c.apply(i,d);return p===!1&&(p=u.apply(i,d)),p}}n.hooks=i}if(r.walkTokens){let i=this.defaults.walkTokens,a=r.walkTokens;n.walkTokens=function(o){let c=[];return c.push(a.call(this,o)),i&&(c=c.concat(i.call(this,o))),c}}this.defaults={...this.defaults,...n}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return Gn.lex(t,e??this.defaults)}parser(t,e){return Kn.parse(t,e??this.defaults)}parseMarkdown(t){return(e,r)=>{let n={...r},i={...this.defaults,...n},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&n.async===!1)return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=t),i.async)return(async()=>{let o=i.hooks?await i.hooks.preprocess(e):e,c=await(i.hooks?await i.hooks.provideLexer(t):t?Gn.lex:Gn.lexInline)(o,i),u=i.hooks?await i.hooks.processAllTokens(c):c;i.walkTokens&&await Promise.all(this.walkTokens(u,i.walkTokens));let d=await(i.hooks?await i.hooks.provideParser(t):t?Kn.parse:Kn.parseInline)(u,i);return i.hooks?await i.hooks.postprocess(d):d})().catch(a);try{i.hooks&&(e=i.hooks.preprocess(e));let o=(i.hooks?i.hooks.provideLexer(t):t?Gn.lex:Gn.lexInline)(e,i);i.hooks&&(o=i.hooks.processAllTokens(o)),i.walkTokens&&this.walkTokens(o,i.walkTokens);let c=(i.hooks?i.hooks.provideParser(t):t?Kn.parse:Kn.parseInline)(o,i);return i.hooks&&(c=i.hooks.postprocess(c)),c}catch(o){return a(o)}}}onError(t,e){return r=>{if(r.message+=`
|
|
386
|
+
Please report this to https://github.com/markedjs/marked.`,t){let n="<p>An error occurred:</p><pre>"+vi(r.message+"",!0)+"</pre>";return e?Promise.resolve(n):n}if(e)return Promise.reject(r);throw r}}},Ro=new mB;function nt(t,e){return Ro.parse(t,e)}nt.options=nt.setOptions=function(t){return Ro.setOptions(t),nt.defaults=Ro.defaults,EP(nt.defaults),nt};nt.getDefaults=Fw;nt.defaults=zo;nt.use=function(...t){return Ro.use(...t),nt.defaults=Ro.defaults,EP(nt.defaults),nt};nt.walkTokens=function(t,e){return Ro.walkTokens(t,e)};nt.parseInline=Ro.parseInline;nt.Parser=Kn;nt.parser=Kn.parse;nt.Renderer=Df;nt.TextRenderer=Jw;nt.Lexer=Gn;nt.lexer=Gn.lex;nt.Tokenizer=Lf;nt.Hooks=Ec;nt.parse=nt;nt.options;nt.setOptions;nt.use;nt.walkTokens;nt.parseInline;Kn.parse;Gn.lex;Qt.registerLanguage("javascript",hP);Qt.registerLanguage("js",hP);Qt.registerLanguage("typescript",_P);Qt.registerLanguage("ts",_P);Qt.registerLanguage("python",pP);Qt.registerLanguage("py",pP);Qt.registerLanguage("rust",Az);Qt.registerLanguage("go",wz);Qt.registerLanguage("json",Oz);Qt.registerLanguage("yaml",kP);Qt.registerLanguage("yml",kP);Qt.registerLanguage("shell",qw);Qt.registerLanguage("bash",qw);Qt.registerLanguage("sh",qw);Qt.registerLanguage("html",SP);Qt.registerLanguage("xml",SP);Qt.registerLanguage("css",xz);nt.use({renderer:{heading({tokens:t,depth:e}){const r=t.map(a=>a.raw).join(""),n=`h${e}`;return`<${n} style="background:linear-gradient(135deg, #D83333 0%, #E43A9C 50%, #F041FF 100%);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;font-size:${{1:"1.35em",2:"1.15em",3:"1em",4:"0.9em"}[e]??"1em"};font-weight:600;margin:1.1em 0 0.4em;line-height:1.4;text-transform:none;">${r}</${n}>`},code({text:t,lang:e}){let r;return e&&Qt.getLanguage(e)?r=Qt.highlight(t,{language:e}).value:r=Qt.highlightAuto(t).value,`<pre style="background:#161616;border:1px solid rgba(255,255,255,0.07);border-radius:10px;padding:0.9em 1.1em;overflow-x:auto;margin:0.8em 0;"><code class="hljs" style="background:none;border:none;padding:0;color:#d4d4d8;font-size:0.85em;">${r}</code></pre>`}}});function rp({content:t,className:e=""}){const r=N.useMemo(()=>nt.parse(t),[t]);return y.jsx("div",{className:`prose-io ${e}`,style:{color:"#d4d4d8",fontSize:"0.875rem",lineHeight:"1.7"},dangerouslySetInnerHTML:{__html:r}})}function gB(){const[t,e]=N.useState(!1),[r,n]=N.useState(""),[i,a]=N.useState(null),o=N.useRef(null),c=N.useRef(null),u=N.useRef(null),{messages:d,streaming:p,isStreaming:f,connected:g,sendChatMessage:v,addUserMessage:x,uploadAttachment:w}=cP(),b=N.useMemo(()=>d.slice(-10),[d]);N.useLayoutEffect(()=>{const j=o.current;j&&(j.scrollTop=j.scrollHeight)},[b,p,f,t]);async function S(){const j=r.trim();if(!j&&!i||f)return;const E=crypto.randomUUID(),T=i==null?void 0:i.name,P=[j,T?`Attachment: ${T}`:""].filter(Boolean).join(`
|
|
385
387
|
|
|
386
|
-
`);x({id:E,role:"user",content:j,timestamp:new Date().toISOString(),attachmentName:T}),n(""),a(null),u.current&&(u.current.value=""),c.current&&(c.current.style.height="auto");try{i&&await w(i,E),v(P),e(!0)}catch{}}function A(j){n(j.target.value),c.current&&(c.current.style.height="auto",c.current.style.height=`${Math.min(c.current.scrollHeight,96)}px`)}function O(j){j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),S())}return y.jsxs("div",{className:"fixed bottom-5 right-5 z-50 flex flex-col items-end gap-3",children:[t&&y.jsxs("div",{className:"w-[340px] h-[460px] rounded-2xl border border-white/[0.09] shadow-2xl overflow-hidden flex flex-col",style:{background:"#1c1c1c"},children:[y.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-white/[0.07] flex-shrink-0",style:{background:"linear-gradient(135deg, rgba(216,51,51,0.18) 0%, rgba(240,65,255,0.10) 100%)"},children:[y.jsxs("div",{className:"flex items-center gap-2.5",children:[y.jsx(Ra,{height:20}),y.jsx("span",{className:"text-xl text-white tracking-wider leading-none",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"IO"}),y.jsx("span",{className:"text-[10px] font-mono text-zinc-600 mt-0.5",children:"quick chat"})]}),y.jsx("button",{type:"button",onClick:()=>e(!1),className:"p-1 rounded-lg hover:bg-white/[0.07] text-zinc-600 hover:text-zinc-300 transition-colors cursor-pointer",children:y.jsx(aP,{className:"w-3.5 h-3.5"})})]}),y.jsxs("div",{ref:o,className:"flex-1 overflow-y-auto p-3 space-y-2",children:[b.length===0&&!f?y.jsx("div",{className:"h-full flex items-center justify-center text-center px-6",children:y.jsx("p",{className:"text-xs text-zinc-500",children:"Ask IO anything without leaving this page."})}):b.map(j=>y.jsx("div",{className:`flex ${j.role==="user"?"justify-end":"justify-start"}`,title:j.timestamp,children:y.jsxs("div",{className:`max-w-[85%] ${j.role==="user"?"ml-8":"mr-8"}`,children:[j.attachmentName&&y.jsx("div",{className:"mb-1 rounded-xl border border-white/[0.08] bg-[#1e1e1e] px-3 py-2 text-[11px] font-mono text-zinc-400",children:j.attachmentName}),j.content&&y.jsx("div",{className:j.role==="user"?"bg-gradient-to-br from-[#E43A9C] to-[#D83333] rounded-xl px-3 py-2 text-xs text-white whitespace-pre-wrap":"bg-[#2a2a2a] rounded-xl px-3 py-2 text-xs text-zinc-200",children:j.role==="user"?j.content:y.jsx("div",{className:"prose-io [&_*]:text-xs",dangerouslySetInnerHTML:{__html:nt.parse(j.content)}})})]})},j.id)),f&&y.jsx("div",{className:"flex justify-start",children:y.jsx("div",{className:"max-w-[85%] mr-8 bg-[#2a2a2a] rounded-xl px-3 py-2 text-xs text-zinc-200",children:p?y.jsx("div",{className:"prose-io [&_*]:text-xs",dangerouslySetInnerHTML:{__html:nt.parse(p)}}):y.jsx("div",{className:"flex items-center gap-1.5 py-1",children:[0,120,240].map(j=>y.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#E43A9C] animate-bounce",style:{animationDelay:`${j}ms`}},j))})})})]}),y.jsx("div",{className:"p-2.5 border-t border-white/[0.06]",children:y.jsxs("div",{className:"bg-[#252525] border border-white/[0.08] rounded-xl overflow-hidden transition-colors focus-within:border-[#E43A9C]/30",children:[y.jsx("input",{ref:u,type:"file",className:"hidden",onChange:j=>{var E;return a(((E=j.target.files)==null?void 0:E[0])??null)}}),i&&y.jsxs("div",{className:"px-3 pt-2 text-[10px] font-mono text-zinc-400",children:["Attached: ",i.name]}),y.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-2",children:[y.jsx("button",{type:"button",onClick:()=>{var j;return(j=u.current)==null?void 0:j.click()},className:"p-1 rounded-lg text-zinc-600 hover:text-zinc-300 hover:bg-white/[0.06] transition-colors flex-shrink-0 cursor-pointer",children:y.jsx(tP,{className:"w-3.5 h-3.5"})}),y.jsx("textarea",{ref:c,value:r,onChange:A,onKeyDown:O,placeholder:"Message IO…",rows:1,className:"flex-1 bg-transparent text-xs text-zinc-200 placeholder:text-zinc-700 resize-none focus:outline-none leading-relaxed",style:{minHeight:"18px",maxHeight:"96px",fontFamily:"Inter, sans-serif"}}),y.jsx("button",{type:"button",onClick:()=>void S(),disabled:!r.trim()&&!i||!g&&!f,className:"p-1.5 rounded-lg text-white disabled:opacity-25 disabled:cursor-not-allowed transition-opacity hover:opacity-90 flex-shrink-0 cursor-pointer",style:{background:"linear-gradient(135deg, #D83333, #E43A9C)"},children:f?y.jsx(Jh,{className:"w-3 h-3"}):y.jsx(nP,{className:"w-3 h-3"})})]})]})})]}),y.jsx("button",{type:"button",onClick:()=>e(j=>!j),className:"w-12 h-12 rounded-full primary-btn shadow-lg text-white flex items-center justify-center hover:opacity-95 transition-opacity","aria-label":t?"Close quick chat":"Open quick chat",children:y.jsx(_4,{className:"w-5 h-5"})})]})}function xP(t){var e,r,n="";if(typeof t=="string"||typeof t=="number")n+=t;else if(typeof t=="object")if(Array.isArray(t)){var i=t.length;for(e=0;e<i;e++)t[e]&&(r=xP(t[e]))&&(n&&(n+=" "),n+=r)}else for(r in t)t[r]&&(n&&(n+=" "),n+=r);return n}function ot(){for(var t,e,r=0,n="",i=arguments.length;r<i;r++)(t=arguments[r])&&(e=xP(t))&&(n&&(n+=" "),n+=e);return n}const Zz=(t,e)=>{const r=new Array(t.length+e.length);for(let n=0;n<t.length;n++)r[n]=t[n];for(let n=0;n<e.length;n++)r[t.length+n]=e[n];return r},Qz=(t,e)=>({classGroupId:t,validator:e}),wP=(t=new Map,e=null,r)=>({nextPart:t,validators:e,classGroupId:r}),Df="-",Xk=[],eB="arbitrary..",tB=t=>{const e=nB(t),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=t;return{getClassGroupId:o=>{if(o.startsWith("[")&&o.endsWith("]"))return rB(o);const c=o.split(Df),u=c[0]===""&&c.length>1?1:0;return _P(c,u,e)},getConflictingClassGroupIds:(o,c)=>{if(c){const u=n[o],d=r[o];return u?d?Zz(d,u):u:d||Xk}return r[o]||Xk}}},_P=(t,e,r)=>{if(t.length-e===0)return r.classGroupId;const i=t[e],a=r.nextPart.get(i);if(a){const d=_P(t,e+1,a);if(d)return d}const o=r.validators;if(o===null)return;const c=e===0?t.join(Df):t.slice(e).join(Df),u=o.length;for(let d=0;d<u;d++){const p=o[d];if(p.validator(c))return p.classGroupId}},rB=t=>t.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const e=t.slice(1,-1),r=e.indexOf(":"),n=e.slice(0,r);return n?eB+n:void 0})(),nB=t=>{const{theme:e,classGroups:r}=t;return iB(r,e)},iB=(t,e)=>{const r=wP();for(const n in t){const i=t[n];Jw(i,r,n,e)}return r},Jw=(t,e,r,n)=>{const i=t.length;for(let a=0;a<i;a++){const o=t[a];aB(o,e,r,n)}},aB=(t,e,r,n)=>{if(typeof t=="string"){oB(t,e,r);return}if(typeof t=="function"){sB(t,e,r,n);return}lB(t,e,r,n)},oB=(t,e,r)=>{const n=t===""?e:SP(e,t);n.classGroupId=r},sB=(t,e,r,n)=>{if(cB(t)){Jw(t(n),e,r,n);return}e.validators===null&&(e.validators=[]),e.validators.push(Qz(r,t))},lB=(t,e,r,n)=>{const i=Object.entries(t),a=i.length;for(let o=0;o<a;o++){const[c,u]=i[o];Jw(u,SP(e,c),r,n)}},SP=(t,e)=>{let r=t;const n=e.split(Df),i=n.length;for(let a=0;a<i;a++){const o=n[a];let c=r.nextPart.get(o);c||(c=wP(),r.nextPart.set(o,c)),r=c}return r},cB=t=>"isThemeGetter"in t&&t.isThemeGetter===!0,uB=t=>{if(t<1)return{get:()=>{},set:()=>{}};let e=0,r=Object.create(null),n=Object.create(null);const i=(a,o)=>{r[a]=o,e++,e>t&&(e=0,n=r,r=Object.create(null))};return{get(a){let o=r[a];if(o!==void 0)return o;if((o=n[a])!==void 0)return i(a,o),o},set(a,o){a in r?r[a]=o:i(a,o)}}},Kb="!",Yk=":",dB=[],Jk=(t,e,r,n,i)=>({modifiers:t,hasImportantModifier:e,baseClassName:r,maybePostfixModifierPosition:n,isExternal:i}),fB=t=>{const{prefix:e,experimentalParseClassName:r}=t;let n=i=>{const a=[];let o=0,c=0,u=0,d;const p=i.length;for(let w=0;w<p;w++){const b=i[w];if(o===0&&c===0){if(b===Yk){a.push(i.slice(u,w)),u=w+1;continue}if(b==="/"){d=w;continue}}b==="["?o++:b==="]"?o--:b==="("?c++:b===")"&&c--}const f=a.length===0?i:i.slice(u);let g=f,v=!1;f.endsWith(Kb)?(g=f.slice(0,-1),v=!0):f.startsWith(Kb)&&(g=f.slice(1),v=!0);const x=d&&d>u?d-u:void 0;return Jk(a,v,g,x)};if(e){const i=e+Yk,a=n;n=o=>o.startsWith(i)?a(o.slice(i.length)):Jk(dB,!1,o,void 0,!0)}if(r){const i=n;n=a=>r({className:a,parseClassName:i})}return n},hB=t=>{const e=new Map;return t.orderSensitiveModifiers.forEach((r,n)=>{e.set(r,1e6+n)}),r=>{const n=[];let i=[];for(let a=0;a<r.length;a++){const o=r[a],c=o[0]==="[",u=e.has(o);c||u?(i.length>0&&(i.sort(),n.push(...i),i=[]),n.push(o)):i.push(o)}return i.length>0&&(i.sort(),n.push(...i)),n}},pB=t=>({cache:uB(t.cacheSize),parseClassName:fB(t),sortModifiers:hB(t),postfixLookupClassGroupIds:mB(t),...tB(t)}),mB=t=>{const e=Object.create(null),r=t.postfixLookupClassGroups;if(r)for(let n=0;n<r.length;n++)e[r[n]]=!0;return e},gB=/\s+/,yB=(t,e)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:i,sortModifiers:a,postfixLookupClassGroupIds:o}=e,c=[],u=t.trim().split(gB);let d="";for(let p=u.length-1;p>=0;p-=1){const f=u[p],{isExternal:g,modifiers:v,hasImportantModifier:x,baseClassName:w,maybePostfixModifierPosition:b}=r(f);if(g){d=f+(d.length>0?" "+d:d);continue}let S=!!b,A;if(S){const P=w.substring(0,b);A=n(P);const R=A&&o[A]?n(w):void 0;R&&R!==A&&(A=R,S=!1)}else A=n(w);if(!A){if(!S){d=f+(d.length>0?" "+d:d);continue}if(A=n(w),!A){d=f+(d.length>0?" "+d:d);continue}S=!1}const O=v.length===0?"":v.length===1?v[0]:a(v).join(":"),j=x?O+Kb:O,E=j+A;if(c.indexOf(E)>-1)continue;c.push(E);const T=i(A,S);for(let P=0;P<T.length;++P){const R=T[P];c.push(j+R)}d=f+(d.length>0?" "+d:d)}return d},vB=(...t)=>{let e=0,r,n,i="";for(;e<t.length;)(r=t[e++])&&(n=kP(r))&&(i&&(i+=" "),i+=n);return i},kP=t=>{if(typeof t=="string")return t;let e,r="";for(let n=0;n<t.length;n++)t[n]&&(e=kP(t[n]))&&(r&&(r+=" "),r+=e);return r},bB=(t,...e)=>{let r,n,i,a;const o=u=>{const d=e.reduce((p,f)=>f(p),t());return r=pB(d),n=r.cache.get,i=r.cache.set,a=c,c(u)},c=u=>{const d=n(u);if(d)return d;const p=yB(u,r);return i(u,p),p};return a=o,(...u)=>a(vB(...u))},xB=[],nr=t=>{const e=r=>r[t]||xB;return e.isThemeGetter=!0,e},EP=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,OP=/^\((?:(\w[\w-]*):)?(.+)\)$/i,wB=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,_B=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,SB=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,kB=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,EB=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,OB=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ta=t=>wB.test(t),Ye=t=>!!t&&!Number.isNaN(Number(t)),gi=t=>!!t&&Number.isInteger(Number(t)),Ag=t=>t.endsWith("%")&&Ye(t.slice(0,-1)),Li=t=>_B.test(t),AP=()=>!0,AB=t=>SB.test(t)&&!kB.test(t),Zw=()=>!1,TB=t=>EB.test(t),jB=t=>OB.test(t),CB=t=>!ke(t)&&!Ae(t),NB=t=>t.startsWith("@container")&&(t[10]==="/"&&t[11]!==void 0||t[11]==="s"&&t[16]!==void 0&&t.startsWith("-size/",10)||t[11]==="n"&&t[18]!==void 0&&t.startsWith("-normal/",10)),PB=t=>Fa(t,CP,Zw),ke=t=>EP.test(t),go=t=>Fa(t,NP,AB),Zk=t=>Fa(t,BB,Ye),RB=t=>Fa(t,RP,AP),IB=t=>Fa(t,PP,Zw),Qk=t=>Fa(t,TP,Zw),$B=t=>Fa(t,jP,jB),nf=t=>Fa(t,IP,TB),Ae=t=>OP.test(t),pc=t=>Bo(t,NP),MB=t=>Bo(t,PP),eE=t=>Bo(t,TP),LB=t=>Bo(t,CP),DB=t=>Bo(t,jP),af=t=>Bo(t,IP,!0),zB=t=>Bo(t,RP,!0),Fa=(t,e,r)=>{const n=EP.exec(t);return n?n[1]?e(n[1]):r(n[2]):!1},Bo=(t,e,r=!1)=>{const n=OP.exec(t);return n?n[1]?e(n[1]):r:!1},TP=t=>t==="position"||t==="percentage",jP=t=>t==="image"||t==="url",CP=t=>t==="length"||t==="size"||t==="bg-size",NP=t=>t==="length",BB=t=>t==="number",PP=t=>t==="family-name",RP=t=>t==="number"||t==="weight",IP=t=>t==="shadow",UB=()=>{const t=nr("color"),e=nr("font"),r=nr("text"),n=nr("font-weight"),i=nr("tracking"),a=nr("leading"),o=nr("breakpoint"),c=nr("container"),u=nr("spacing"),d=nr("radius"),p=nr("shadow"),f=nr("inset-shadow"),g=nr("text-shadow"),v=nr("drop-shadow"),x=nr("blur"),w=nr("perspective"),b=nr("aspect"),S=nr("ease"),A=nr("animate"),O=()=>["auto","avoid","all","avoid-page","page","left","right","column"],j=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],E=()=>[...j(),Ae,ke],T=()=>["auto","hidden","clip","visible","scroll"],P=()=>["auto","contain","none"],R=()=>[Ae,ke,u],M=()=>[Ta,"full","auto",...R()],J=()=>[gi,"none","subgrid",Ae,ke],F=()=>["auto",{span:["full",gi,Ae,ke]},gi,Ae,ke],B=()=>[gi,"auto",Ae,ke],K=()=>["auto","min","max","fr",Ae,ke],W=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],X=()=>["start","end","center","stretch","center-safe","end-safe"],Y=()=>["auto",...R()],te=()=>[Ta,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...R()],H=()=>[Ta,"screen","full","dvw","lvw","svw","min","max","fit",...R()],Q=()=>[Ta,"screen","full","lh","dvh","lvh","svh","min","max","fit",...R()],U=()=>[t,Ae,ke],I=()=>[...j(),eE,Qk,{position:[Ae,ke]}],$=()=>["no-repeat",{repeat:["","x","y","space","round"]}],V=()=>["auto","cover","contain",LB,PB,{size:[Ae,ke]}],oe=()=>[Ag,pc,go],le=()=>["","none","full",d,Ae,ke],ve=()=>["",Ye,pc,go],qe=()=>["solid","dashed","dotted","double"],xe=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ae=()=>[Ye,Ag,eE,Qk],Se=()=>["","none",x,Ae,ke],Me=()=>["none",Ye,Ae,ke],se=()=>["none",Ye,Ae,ke],tt=()=>[Ye,Ae,ke],Fe=()=>[Ta,"full",...R()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Li],breakpoint:[Li],color:[AP],container:[Li],"drop-shadow":[Li],ease:["in","out","in-out"],font:[CB],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Li],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Li],shadow:[Li],spacing:["px",Ye],text:[Li],"text-shadow":[Li],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ta,ke,Ae,b]}],container:["container"],"container-type":[{"@container":["","normal","size",Ae,ke]}],"container-named":[NB],columns:[{columns:[Ye,ke,Ae,c]}],"break-after":[{"break-after":O()}],"break-before":[{"break-before":O()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:E()}],overflow:[{overflow:T()}],"overflow-x":[{"overflow-x":T()}],"overflow-y":[{"overflow-y":T()}],overscroll:[{overscroll:P()}],"overscroll-x":[{"overscroll-x":P()}],"overscroll-y":[{"overscroll-y":P()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:M()}],"inset-x":[{"inset-x":M()}],"inset-y":[{"inset-y":M()}],start:[{"inset-s":M(),start:M()}],end:[{"inset-e":M(),end:M()}],"inset-bs":[{"inset-bs":M()}],"inset-be":[{"inset-be":M()}],top:[{top:M()}],right:[{right:M()}],bottom:[{bottom:M()}],left:[{left:M()}],visibility:["visible","invisible","collapse"],z:[{z:[gi,"auto",Ae,ke]}],basis:[{basis:[Ta,"full","auto",c,...R()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Ye,Ta,"auto","initial","none",ke]}],grow:[{grow:["",Ye,Ae,ke]}],shrink:[{shrink:["",Ye,Ae,ke]}],order:[{order:[gi,"first","last","none",Ae,ke]}],"grid-cols":[{"grid-cols":J()}],"col-start-end":[{col:F()}],"col-start":[{"col-start":B()}],"col-end":[{"col-end":B()}],"grid-rows":[{"grid-rows":J()}],"row-start-end":[{row:F()}],"row-start":[{"row-start":B()}],"row-end":[{"row-end":B()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":K()}],"auto-rows":[{"auto-rows":K()}],gap:[{gap:R()}],"gap-x":[{"gap-x":R()}],"gap-y":[{"gap-y":R()}],"justify-content":[{justify:[...W(),"normal"]}],"justify-items":[{"justify-items":[...X(),"normal"]}],"justify-self":[{"justify-self":["auto",...X()]}],"align-content":[{content:["normal",...W()]}],"align-items":[{items:[...X(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...X(),{baseline:["","last"]}]}],"place-content":[{"place-content":W()}],"place-items":[{"place-items":[...X(),"baseline"]}],"place-self":[{"place-self":["auto",...X()]}],p:[{p:R()}],px:[{px:R()}],py:[{py:R()}],ps:[{ps:R()}],pe:[{pe:R()}],pbs:[{pbs:R()}],pbe:[{pbe:R()}],pt:[{pt:R()}],pr:[{pr:R()}],pb:[{pb:R()}],pl:[{pl:R()}],m:[{m:Y()}],mx:[{mx:Y()}],my:[{my:Y()}],ms:[{ms:Y()}],me:[{me:Y()}],mbs:[{mbs:Y()}],mbe:[{mbe:Y()}],mt:[{mt:Y()}],mr:[{mr:Y()}],mb:[{mb:Y()}],ml:[{ml:Y()}],"space-x":[{"space-x":R()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":R()}],"space-y-reverse":["space-y-reverse"],size:[{size:te()}],"inline-size":[{inline:["auto",...H()]}],"min-inline-size":[{"min-inline":["auto",...H()]}],"max-inline-size":[{"max-inline":["none",...H()]}],"block-size":[{block:["auto",...Q()]}],"min-block-size":[{"min-block":["auto",...Q()]}],"max-block-size":[{"max-block":["none",...Q()]}],w:[{w:[c,"screen",...te()]}],"min-w":[{"min-w":[c,"screen","none",...te()]}],"max-w":[{"max-w":[c,"screen","none","prose",{screen:[o]},...te()]}],h:[{h:["screen","lh",...te()]}],"min-h":[{"min-h":["screen","lh","none",...te()]}],"max-h":[{"max-h":["screen","lh",...te()]}],"font-size":[{text:["base",r,pc,go]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[n,zB,RB]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Ag,ke]}],"font-family":[{font:[MB,IB,e]}],"font-features":[{"font-features":[ke]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,Ae,ke]}],"line-clamp":[{"line-clamp":[Ye,"none",Ae,Zk]}],leading:[{leading:[a,...R()]}],"list-image":[{"list-image":["none",Ae,ke]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Ae,ke]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:U()}],"text-color":[{text:U()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...qe(),"wavy"]}],"text-decoration-thickness":[{decoration:[Ye,"from-font","auto",Ae,go]}],"text-decoration-color":[{decoration:U()}],"underline-offset":[{"underline-offset":[Ye,"auto",Ae,ke]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:R()}],"tab-size":[{tab:[gi,Ae,ke]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Ae,ke]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Ae,ke]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:I()}],"bg-repeat":[{bg:$()}],"bg-size":[{bg:V()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},gi,Ae,ke],radial:["",Ae,ke],conic:[gi,Ae,ke]},DB,$B]}],"bg-color":[{bg:U()}],"gradient-from-pos":[{from:oe()}],"gradient-via-pos":[{via:oe()}],"gradient-to-pos":[{to:oe()}],"gradient-from":[{from:U()}],"gradient-via":[{via:U()}],"gradient-to":[{to:U()}],rounded:[{rounded:le()}],"rounded-s":[{"rounded-s":le()}],"rounded-e":[{"rounded-e":le()}],"rounded-t":[{"rounded-t":le()}],"rounded-r":[{"rounded-r":le()}],"rounded-b":[{"rounded-b":le()}],"rounded-l":[{"rounded-l":le()}],"rounded-ss":[{"rounded-ss":le()}],"rounded-se":[{"rounded-se":le()}],"rounded-ee":[{"rounded-ee":le()}],"rounded-es":[{"rounded-es":le()}],"rounded-tl":[{"rounded-tl":le()}],"rounded-tr":[{"rounded-tr":le()}],"rounded-br":[{"rounded-br":le()}],"rounded-bl":[{"rounded-bl":le()}],"border-w":[{border:ve()}],"border-w-x":[{"border-x":ve()}],"border-w-y":[{"border-y":ve()}],"border-w-s":[{"border-s":ve()}],"border-w-e":[{"border-e":ve()}],"border-w-bs":[{"border-bs":ve()}],"border-w-be":[{"border-be":ve()}],"border-w-t":[{"border-t":ve()}],"border-w-r":[{"border-r":ve()}],"border-w-b":[{"border-b":ve()}],"border-w-l":[{"border-l":ve()}],"divide-x":[{"divide-x":ve()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":ve()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...qe(),"hidden","none"]}],"divide-style":[{divide:[...qe(),"hidden","none"]}],"border-color":[{border:U()}],"border-color-x":[{"border-x":U()}],"border-color-y":[{"border-y":U()}],"border-color-s":[{"border-s":U()}],"border-color-e":[{"border-e":U()}],"border-color-bs":[{"border-bs":U()}],"border-color-be":[{"border-be":U()}],"border-color-t":[{"border-t":U()}],"border-color-r":[{"border-r":U()}],"border-color-b":[{"border-b":U()}],"border-color-l":[{"border-l":U()}],"divide-color":[{divide:U()}],"outline-style":[{outline:[...qe(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Ye,Ae,ke]}],"outline-w":[{outline:["",Ye,pc,go]}],"outline-color":[{outline:U()}],shadow:[{shadow:["","none",p,af,nf]}],"shadow-color":[{shadow:U()}],"inset-shadow":[{"inset-shadow":["none",f,af,nf]}],"inset-shadow-color":[{"inset-shadow":U()}],"ring-w":[{ring:ve()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:U()}],"ring-offset-w":[{"ring-offset":[Ye,go]}],"ring-offset-color":[{"ring-offset":U()}],"inset-ring-w":[{"inset-ring":ve()}],"inset-ring-color":[{"inset-ring":U()}],"text-shadow":[{"text-shadow":["none",g,af,nf]}],"text-shadow-color":[{"text-shadow":U()}],opacity:[{opacity:[Ye,Ae,ke]}],"mix-blend":[{"mix-blend":[...xe(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":xe()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Ye]}],"mask-image-linear-from-pos":[{"mask-linear-from":ae()}],"mask-image-linear-to-pos":[{"mask-linear-to":ae()}],"mask-image-linear-from-color":[{"mask-linear-from":U()}],"mask-image-linear-to-color":[{"mask-linear-to":U()}],"mask-image-t-from-pos":[{"mask-t-from":ae()}],"mask-image-t-to-pos":[{"mask-t-to":ae()}],"mask-image-t-from-color":[{"mask-t-from":U()}],"mask-image-t-to-color":[{"mask-t-to":U()}],"mask-image-r-from-pos":[{"mask-r-from":ae()}],"mask-image-r-to-pos":[{"mask-r-to":ae()}],"mask-image-r-from-color":[{"mask-r-from":U()}],"mask-image-r-to-color":[{"mask-r-to":U()}],"mask-image-b-from-pos":[{"mask-b-from":ae()}],"mask-image-b-to-pos":[{"mask-b-to":ae()}],"mask-image-b-from-color":[{"mask-b-from":U()}],"mask-image-b-to-color":[{"mask-b-to":U()}],"mask-image-l-from-pos":[{"mask-l-from":ae()}],"mask-image-l-to-pos":[{"mask-l-to":ae()}],"mask-image-l-from-color":[{"mask-l-from":U()}],"mask-image-l-to-color":[{"mask-l-to":U()}],"mask-image-x-from-pos":[{"mask-x-from":ae()}],"mask-image-x-to-pos":[{"mask-x-to":ae()}],"mask-image-x-from-color":[{"mask-x-from":U()}],"mask-image-x-to-color":[{"mask-x-to":U()}],"mask-image-y-from-pos":[{"mask-y-from":ae()}],"mask-image-y-to-pos":[{"mask-y-to":ae()}],"mask-image-y-from-color":[{"mask-y-from":U()}],"mask-image-y-to-color":[{"mask-y-to":U()}],"mask-image-radial":[{"mask-radial":[Ae,ke]}],"mask-image-radial-from-pos":[{"mask-radial-from":ae()}],"mask-image-radial-to-pos":[{"mask-radial-to":ae()}],"mask-image-radial-from-color":[{"mask-radial-from":U()}],"mask-image-radial-to-color":[{"mask-radial-to":U()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":j()}],"mask-image-conic-pos":[{"mask-conic":[Ye]}],"mask-image-conic-from-pos":[{"mask-conic-from":ae()}],"mask-image-conic-to-pos":[{"mask-conic-to":ae()}],"mask-image-conic-from-color":[{"mask-conic-from":U()}],"mask-image-conic-to-color":[{"mask-conic-to":U()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:I()}],"mask-repeat":[{mask:$()}],"mask-size":[{mask:V()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Ae,ke]}],filter:[{filter:["","none",Ae,ke]}],blur:[{blur:Se()}],brightness:[{brightness:[Ye,Ae,ke]}],contrast:[{contrast:[Ye,Ae,ke]}],"drop-shadow":[{"drop-shadow":["","none",v,af,nf]}],"drop-shadow-color":[{"drop-shadow":U()}],grayscale:[{grayscale:["",Ye,Ae,ke]}],"hue-rotate":[{"hue-rotate":[Ye,Ae,ke]}],invert:[{invert:["",Ye,Ae,ke]}],saturate:[{saturate:[Ye,Ae,ke]}],sepia:[{sepia:["",Ye,Ae,ke]}],"backdrop-filter":[{"backdrop-filter":["","none",Ae,ke]}],"backdrop-blur":[{"backdrop-blur":Se()}],"backdrop-brightness":[{"backdrop-brightness":[Ye,Ae,ke]}],"backdrop-contrast":[{"backdrop-contrast":[Ye,Ae,ke]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Ye,Ae,ke]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Ye,Ae,ke]}],"backdrop-invert":[{"backdrop-invert":["",Ye,Ae,ke]}],"backdrop-opacity":[{"backdrop-opacity":[Ye,Ae,ke]}],"backdrop-saturate":[{"backdrop-saturate":[Ye,Ae,ke]}],"backdrop-sepia":[{"backdrop-sepia":["",Ye,Ae,ke]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":R()}],"border-spacing-x":[{"border-spacing-x":R()}],"border-spacing-y":[{"border-spacing-y":R()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Ae,ke]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Ye,"initial",Ae,ke]}],ease:[{ease:["linear","initial",S,Ae,ke]}],delay:[{delay:[Ye,Ae,ke]}],animate:[{animate:["none",A,Ae,ke]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[w,Ae,ke]}],"perspective-origin":[{"perspective-origin":E()}],rotate:[{rotate:Me()}],"rotate-x":[{"rotate-x":Me()}],"rotate-y":[{"rotate-y":Me()}],"rotate-z":[{"rotate-z":Me()}],scale:[{scale:se()}],"scale-x":[{"scale-x":se()}],"scale-y":[{"scale-y":se()}],"scale-z":[{"scale-z":se()}],"scale-3d":["scale-3d"],skew:[{skew:tt()}],"skew-x":[{"skew-x":tt()}],"skew-y":[{"skew-y":tt()}],transform:[{transform:[Ae,ke,"","none","gpu","cpu"]}],"transform-origin":[{origin:E()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Fe()}],"translate-x":[{"translate-x":Fe()}],"translate-y":[{"translate-y":Fe()}],"translate-z":[{"translate-z":Fe()}],"translate-none":["translate-none"],zoom:[{zoom:[gi,Ae,ke]}],accent:[{accent:U()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:U()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Ae,ke]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":U()}],"scrollbar-track-color":[{"scrollbar-track":U()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":R()}],"scroll-mx":[{"scroll-mx":R()}],"scroll-my":[{"scroll-my":R()}],"scroll-ms":[{"scroll-ms":R()}],"scroll-me":[{"scroll-me":R()}],"scroll-mbs":[{"scroll-mbs":R()}],"scroll-mbe":[{"scroll-mbe":R()}],"scroll-mt":[{"scroll-mt":R()}],"scroll-mr":[{"scroll-mr":R()}],"scroll-mb":[{"scroll-mb":R()}],"scroll-ml":[{"scroll-ml":R()}],"scroll-p":[{"scroll-p":R()}],"scroll-px":[{"scroll-px":R()}],"scroll-py":[{"scroll-py":R()}],"scroll-ps":[{"scroll-ps":R()}],"scroll-pe":[{"scroll-pe":R()}],"scroll-pbs":[{"scroll-pbs":R()}],"scroll-pbe":[{"scroll-pbe":R()}],"scroll-pt":[{"scroll-pt":R()}],"scroll-pr":[{"scroll-pr":R()}],"scroll-pb":[{"scroll-pb":R()}],"scroll-pl":[{"scroll-pl":R()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Ae,ke]}],fill:[{fill:["none",...U()]}],"stroke-w":[{stroke:[Ye,pc,go,Zk]}],stroke:[{stroke:["none",...U()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},qB=bB(UB);function Oc(...t){return qB(ot(t))}function FB({status:t}){const e={connected:"bg-green-500",idle:"bg-green-500",disconnected:"bg-zinc-600",error:"bg-red-500",working:"bg-amber-400",reviewing:"bg-blue-400"}[t],r=t==="connected"||t==="working";return y.jsxs("span",{className:"relative inline-flex items-center justify-center w-2 h-2",children:[r&&y.jsx("span",{className:`absolute inline-flex h-full w-full rounded-full ${e} opacity-40 animate-ping`}),y.jsx("span",{className:`relative inline-flex rounded-full h-2 w-2 ${e}`})]})}function jt({children:t,variant:e="muted",className:r=""}){const n={default:"bg-[#E43A9C]/15 text-[#F041FF] border-[#E43A9C]/20",success:"bg-green-500/15 text-green-400 border-green-500/20",warning:"bg-amber-500/15 text-amber-400 border-amber-500/20",error:"bg-red-500/15 text-red-400 border-red-500/20",info:"bg-blue-500/15 text-blue-400 border-blue-500/20",muted:"bg-white/5 text-zinc-400 border-white/10"}[e];return y.jsx("span",{className:`inline-flex items-center px-2 py-px rounded-full text-[10px] font-mono border ${n} ${r}`,children:t})}function HB({name:t,color:e}){return e?y.jsx("span",{className:"inline-flex items-center px-1.5 py-px rounded text-[10px] font-mono border",style:{background:`${e}15`,color:e,borderColor:`${e}30`},children:t}):y.jsx(jt,{variant:"muted",children:t})}function za({children:t,onClick:e,className:r="",type:n="button",disabled:i=!1}){return y.jsx("button",{type:n,onClick:e,disabled:i,className:`flex items-center gap-1.5 font-mono text-[11px] text-white rounded-lg active:opacity-80 primary-btn cursor-pointer disabled:opacity-50 ${r}`,children:t})}function _i({children:t,onClick:e,className:r=""}){return y.jsx("button",{type:"button",onClick:e,className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg font-mono text-[11px] text-zinc-400 bg-[#252525] hover:bg-[#2e2e2e] hover:text-zinc-100 transition-colors cursor-pointer ${r}`,children:t})}function zf({children:t,onClick:e,className:r=""}){return y.jsx("button",{type:"button",onClick:e,className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg font-mono text-[11px] text-zinc-400 bg-[#252525] hover:bg-red-500/10 hover:text-red-400 transition-colors cursor-pointer ${r}`,children:t})}function WB({children:t,onClick:e,className:r=""}){return y.jsx("button",{type:"button",onClick:e,className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg font-mono text-[11px] text-zinc-400 bg-[#252525] hover:bg-amber-500/10 hover:text-amber-400 transition-colors cursor-pointer ${r}`,children:t})}function Co(t){return t==="connected"||t==="idle"?"success":t==="active"||t==="working"?"warning":t==="reviewing"||t==="in meeting"||t==="planning"||t==="meeting"?"info":t==="error"||t==="failed"?"error":"muted"}function rp(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function GB(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(p){try{d(n.next(p))}catch(f){o(f)}}function u(p){try{d(n.throw(p))}catch(f){o(f)}}function d(p){p.done?a(p.value):i(p.value).then(c,u)}d((n=n.apply(t,e||[])).next())})}const KB=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);class Qw extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n}toJSON(){return{name:this.name,message:this.message,context:this.context}}}class VB extends Qw{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class tE extends Qw{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class rE extends Qw{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Vb;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(Vb||(Vb={}));class XB{constructor(e,{headers:r={},customFetch:n,region:i=Vb.Any}={}){this.url=e,this.headers=r,this.region=i,this.fetch=KB(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return GB(this,arguments,void 0,function*(r,n={}){var i;let a,o;try{const{headers:c,method:u,body:d,signal:p,timeout:f}=n;let g={},{region:v}=n;v||(v=this.region);const x=new URL(`${this.url}/${r}`);v&&v!=="any"&&(g["x-region"]=v,x.searchParams.set("forceFunctionRegion",v));let w;d&&(c&&!Object.prototype.hasOwnProperty.call(c,"Content-Type")||!c)?typeof Blob<"u"&&d instanceof Blob||d instanceof ArrayBuffer?(g["Content-Type"]="application/octet-stream",w=d):typeof d=="string"?(g["Content-Type"]="text/plain",w=d):typeof FormData<"u"&&d instanceof FormData?w=d:(g["Content-Type"]="application/json",w=JSON.stringify(d)):d&&typeof d!="string"&&!(typeof Blob<"u"&&d instanceof Blob)&&!(d instanceof ArrayBuffer)&&!(typeof FormData<"u"&&d instanceof FormData)?w=JSON.stringify(d):w=d;let b=p;f&&(o=new AbortController,a=setTimeout(()=>o.abort(),f),p?(b=o.signal,p.addEventListener("abort",()=>o.abort())):b=o.signal);const S=yield this.fetch(x.toString(),{method:u||"POST",headers:Object.assign(Object.assign(Object.assign({},g),this.headers),c),body:w,signal:b}).catch(E=>{throw new VB(E)}),A=S.headers.get("x-relay-error");if(A&&A==="true")throw new tE(S);if(!S.ok)throw new rE(S);let O=((i=S.headers.get("Content-Type"))!==null&&i!==void 0?i:"text/plain").split(";")[0].trim(),j;return O==="application/json"?j=yield S.json():O==="application/octet-stream"||O==="application/pdf"?j=yield S.blob():O==="text/event-stream"?j=S:O==="multipart/form-data"?j=yield S.formData():j=yield S.text(),{data:j,error:null,response:S}}catch(c){return{data:null,error:c,response:c instanceof rE||c instanceof tE?c.context:void 0}}finally{a&&clearTimeout(a)}})}}const $P=3,nE=t=>Math.min(1e3*2**t,3e4),YB=[520,503],MP=["GET","HEAD","OPTIONS"];var JB=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function iE(t,e){return new Promise(r=>{if(e!=null&&e.aborted){r();return}const n=setTimeout(()=>{e==null||e.removeEventListener("abort",i),r()},t);function i(){clearTimeout(n),r()}e==null||e.addEventListener("abort",i)})}function ZB(t,e,r,n){return!(!n||r>=$P||!MP.includes(t)||!YB.includes(e))}var QB=class{constructor(t){var e,r,n,i,a;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.shouldStripNulls=(n=t.shouldStripNulls)!==null&&n!==void 0?n:!1,this.urlLengthLimit=(i=t.urlLengthLimit)!==null&&i!==void 0?i:8e3,this.retryEnabled=(a=t.retry)!==null&&a!==void 0?a:!0,t.fetch?this.fetch=t.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(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}retry(t){return this.retryEnabled=t,this}then(t,e){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){const o=this.headers.get("Accept");o==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!o||o==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}const n=this.fetch;let a=(async()=>{let o=0;for(;;){const d=new Headers(r.headers);o>0&&d.set("X-Retry-Count",String(o));let p;try{p=await n(r.url.toString(),{method:r.method,headers:d,body:JSON.stringify(r.body,(f,g)=>typeof g=="bigint"?g.toString():g),signal:r.signal})}catch(f){if((f==null?void 0:f.name)==="AbortError"||(f==null?void 0:f.code)==="ABORT_ERR"||!MP.includes(r.method))throw f;if(r.retryEnabled&&o<$P){const g=nE(o);o++,await iE(g,r.signal);continue}throw f}if(ZB(r.method,p.status,o,r.retryEnabled)){var c,u;const f=(c=(u=p.headers)===null||u===void 0?void 0:u.get("Retry-After"))!==null&&c!==void 0?c:null,g=f!==null?Math.max(0,parseInt(f,10)||0)*1e3:nE(o);await p.text(),o++,await iE(g,r.signal);continue}return await r.processResponse(p)}})();return this.shouldThrowOnError||(a=a.catch(o=>{var c;let u="",d="",p="";const f=o==null?void 0:o.cause;if(f){var g,v,x,w;const A=(g=f==null?void 0:f.message)!==null&&g!==void 0?g:"",O=(v=f==null?void 0:f.code)!==null&&v!==void 0?v:"";u=`${(x=o==null?void 0:o.name)!==null&&x!==void 0?x:"FetchError"}: ${o==null?void 0:o.message}`,u+=`
|
|
388
|
+
`);x({id:E,role:"user",content:j,timestamp:new Date().toISOString(),attachmentName:T}),n(""),a(null),u.current&&(u.current.value=""),c.current&&(c.current.style.height="auto");try{i&&await w(i,E),v(P),e(!0)}catch{}}function A(j){n(j.target.value),c.current&&(c.current.style.height="auto",c.current.style.height=`${Math.min(c.current.scrollHeight,96)}px`)}function O(j){j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),S())}return y.jsxs("div",{className:"fixed bottom-5 right-5 z-50 flex flex-col items-end gap-3",children:[t&&y.jsxs("div",{className:"w-[340px] h-[460px] rounded-2xl border border-white/[0.09] shadow-2xl overflow-hidden flex flex-col",style:{background:"#1c1c1c"},children:[y.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-white/[0.07] flex-shrink-0",style:{background:"linear-gradient(135deg, rgba(216,51,51,0.18) 0%, rgba(240,65,255,0.10) 100%)"},children:[y.jsxs("div",{className:"flex items-center gap-2.5",children:[y.jsx(Ra,{height:20}),y.jsx("span",{className:"text-xl text-white tracking-wider leading-none",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"IO"}),y.jsx("span",{className:"text-[10px] font-mono text-zinc-600 mt-0.5",children:"quick chat"})]}),y.jsx("button",{type:"button",onClick:()=>e(!1),className:"p-1 rounded-lg hover:bg-white/[0.07] text-zinc-600 hover:text-zinc-300 transition-colors cursor-pointer",children:y.jsx(aP,{className:"w-3.5 h-3.5"})})]}),y.jsxs("div",{ref:o,className:"flex-1 overflow-y-auto p-3 space-y-2",children:[b.length===0&&!f?y.jsx("div",{className:"h-full flex items-center justify-center text-center px-6",children:y.jsx("p",{className:"text-xs text-zinc-500",children:"Ask IO anything without leaving this page."})}):b.map(j=>y.jsx("div",{className:`flex ${j.role==="user"?"justify-end":"justify-start"}`,title:j.timestamp,children:y.jsxs("div",{className:`max-w-[85%] ${j.role==="user"?"ml-8":"mr-8"}`,children:[j.attachmentName&&y.jsx("div",{className:"mb-1 rounded-xl border border-white/[0.08] bg-[#1e1e1e] px-3 py-2 text-[11px] font-mono text-zinc-400",children:j.attachmentName}),j.content&&y.jsx("div",{className:j.role==="user"?"bg-gradient-to-br from-[#E43A9C] to-[#D83333] rounded-xl px-3 py-2 text-xs text-white whitespace-pre-wrap":"bg-[#2a2a2a] rounded-xl px-3 py-2 text-xs text-zinc-200",children:j.role==="user"?j.content:y.jsx("div",{className:"prose-io [&_*]:text-xs",dangerouslySetInnerHTML:{__html:nt.parse(j.content)}})})]})},j.id)),f&&y.jsx("div",{className:"flex justify-start",children:y.jsx("div",{className:"max-w-[85%] mr-8 bg-[#2a2a2a] rounded-xl px-3 py-2 text-xs text-zinc-200",children:p?y.jsx("div",{className:"prose-io [&_*]:text-xs",dangerouslySetInnerHTML:{__html:nt.parse(p)}}):y.jsx("div",{className:"flex items-center gap-1.5 py-1",children:[0,120,240].map(j=>y.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#E43A9C] animate-bounce",style:{animationDelay:`${j}ms`}},j))})})})]}),y.jsx("div",{className:"p-2.5 border-t border-white/[0.06]",children:y.jsxs("div",{className:"bg-[#252525] border border-white/[0.08] rounded-xl overflow-hidden transition-colors focus-within:border-[#E43A9C]/30",children:[y.jsx("input",{ref:u,type:"file",className:"hidden",onChange:j=>{var E;return a(((E=j.target.files)==null?void 0:E[0])??null)}}),i&&y.jsxs("div",{className:"px-3 pt-2 text-[10px] font-mono text-zinc-400",children:["Attached: ",i.name]}),y.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-2",children:[y.jsx("button",{type:"button",onClick:()=>{var j;return(j=u.current)==null?void 0:j.click()},className:"p-1 rounded-lg text-zinc-600 hover:text-zinc-300 hover:bg-white/[0.06] transition-colors flex-shrink-0 cursor-pointer",children:y.jsx(tP,{className:"w-3.5 h-3.5"})}),y.jsx("textarea",{ref:c,value:r,onChange:A,onKeyDown:O,placeholder:"Message IO…",rows:1,className:"flex-1 bg-transparent text-xs text-zinc-200 placeholder:text-zinc-700 resize-none focus:outline-none leading-relaxed",style:{minHeight:"18px",maxHeight:"96px",fontFamily:"Inter, sans-serif"}}),y.jsx("button",{type:"button",onClick:()=>void S(),disabled:!r.trim()&&!i||!g&&!f,className:"p-1.5 rounded-lg text-white disabled:opacity-25 disabled:cursor-not-allowed transition-opacity hover:opacity-90 flex-shrink-0 cursor-pointer",style:{background:"linear-gradient(135deg, #D83333, #E43A9C)"},children:f?y.jsx(Jh,{className:"w-3 h-3"}):y.jsx(nP,{className:"w-3 h-3"})})]})]})})]}),y.jsx("button",{type:"button",onClick:()=>e(j=>!j),className:"w-12 h-12 rounded-full primary-btn shadow-lg text-white flex items-center justify-center hover:opacity-95 transition-opacity","aria-label":t?"Close quick chat":"Open quick chat",children:y.jsx(_4,{className:"w-5 h-5"})})]})}function $P(t){var e,r,n="";if(typeof t=="string"||typeof t=="number")n+=t;else if(typeof t=="object")if(Array.isArray(t)){var i=t.length;for(e=0;e<i;e++)t[e]&&(r=$P(t[e]))&&(n&&(n+=" "),n+=r)}else for(r in t)t[r]&&(n&&(n+=" "),n+=r);return n}function ot(){for(var t,e,r=0,n="",i=arguments.length;r<i;r++)(t=arguments[r])&&(e=$P(t))&&(n&&(n+=" "),n+=e);return n}const yB=(t,e)=>{const r=new Array(t.length+e.length);for(let n=0;n<t.length;n++)r[n]=t[n];for(let n=0;n<e.length;n++)r[t.length+n]=e[n];return r},vB=(t,e)=>({classGroupId:t,validator:e}),MP=(t=new Map,e=null,r)=>({nextPart:t,validators:e,classGroupId:r}),zf="-",Jk=[],bB="arbitrary..",xB=t=>{const e=_B(t),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=t;return{getClassGroupId:o=>{if(o.startsWith("[")&&o.endsWith("]"))return wB(o);const c=o.split(zf),u=c[0]===""&&c.length>1?1:0;return LP(c,u,e)},getConflictingClassGroupIds:(o,c)=>{if(c){const u=n[o],d=r[o];return u?d?yB(d,u):u:d||Jk}return r[o]||Jk}}},LP=(t,e,r)=>{if(t.length-e===0)return r.classGroupId;const i=t[e],a=r.nextPart.get(i);if(a){const d=LP(t,e+1,a);if(d)return d}const o=r.validators;if(o===null)return;const c=e===0?t.join(zf):t.slice(e).join(zf),u=o.length;for(let d=0;d<u;d++){const p=o[d];if(p.validator(c))return p.classGroupId}},wB=t=>t.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const e=t.slice(1,-1),r=e.indexOf(":"),n=e.slice(0,r);return n?bB+n:void 0})(),_B=t=>{const{theme:e,classGroups:r}=t;return SB(r,e)},SB=(t,e)=>{const r=MP();for(const n in t){const i=t[n];Zw(i,r,n,e)}return r},Zw=(t,e,r,n)=>{const i=t.length;for(let a=0;a<i;a++){const o=t[a];kB(o,e,r,n)}},kB=(t,e,r,n)=>{if(typeof t=="string"){EB(t,e,r);return}if(typeof t=="function"){OB(t,e,r,n);return}AB(t,e,r,n)},EB=(t,e,r)=>{const n=t===""?e:DP(e,t);n.classGroupId=r},OB=(t,e,r,n)=>{if(TB(t)){Zw(t(n),e,r,n);return}e.validators===null&&(e.validators=[]),e.validators.push(vB(r,t))},AB=(t,e,r,n)=>{const i=Object.entries(t),a=i.length;for(let o=0;o<a;o++){const[c,u]=i[o];Zw(u,DP(e,c),r,n)}},DP=(t,e)=>{let r=t;const n=e.split(zf),i=n.length;for(let a=0;a<i;a++){const o=n[a];let c=r.nextPart.get(o);c||(c=MP(),r.nextPart.set(o,c)),r=c}return r},TB=t=>"isThemeGetter"in t&&t.isThemeGetter===!0,jB=t=>{if(t<1)return{get:()=>{},set:()=>{}};let e=0,r=Object.create(null),n=Object.create(null);const i=(a,o)=>{r[a]=o,e++,e>t&&(e=0,n=r,r=Object.create(null))};return{get(a){let o=r[a];if(o!==void 0)return o;if((o=n[a])!==void 0)return i(a,o),o},set(a,o){a in r?r[a]=o:i(a,o)}}},Kb="!",Zk=":",CB=[],Qk=(t,e,r,n,i)=>({modifiers:t,hasImportantModifier:e,baseClassName:r,maybePostfixModifierPosition:n,isExternal:i}),NB=t=>{const{prefix:e,experimentalParseClassName:r}=t;let n=i=>{const a=[];let o=0,c=0,u=0,d;const p=i.length;for(let w=0;w<p;w++){const b=i[w];if(o===0&&c===0){if(b===Zk){a.push(i.slice(u,w)),u=w+1;continue}if(b==="/"){d=w;continue}}b==="["?o++:b==="]"?o--:b==="("?c++:b===")"&&c--}const f=a.length===0?i:i.slice(u);let g=f,v=!1;f.endsWith(Kb)?(g=f.slice(0,-1),v=!0):f.startsWith(Kb)&&(g=f.slice(1),v=!0);const x=d&&d>u?d-u:void 0;return Qk(a,v,g,x)};if(e){const i=e+Zk,a=n;n=o=>o.startsWith(i)?a(o.slice(i.length)):Qk(CB,!1,o,void 0,!0)}if(r){const i=n;n=a=>r({className:a,parseClassName:i})}return n},PB=t=>{const e=new Map;return t.orderSensitiveModifiers.forEach((r,n)=>{e.set(r,1e6+n)}),r=>{const n=[];let i=[];for(let a=0;a<r.length;a++){const o=r[a],c=o[0]==="[",u=e.has(o);c||u?(i.length>0&&(i.sort(),n.push(...i),i=[]),n.push(o)):i.push(o)}return i.length>0&&(i.sort(),n.push(...i)),n}},RB=t=>({cache:jB(t.cacheSize),parseClassName:NB(t),sortModifiers:PB(t),postfixLookupClassGroupIds:IB(t),...xB(t)}),IB=t=>{const e=Object.create(null),r=t.postfixLookupClassGroups;if(r)for(let n=0;n<r.length;n++)e[r[n]]=!0;return e},$B=/\s+/,MB=(t,e)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:i,sortModifiers:a,postfixLookupClassGroupIds:o}=e,c=[],u=t.trim().split($B);let d="";for(let p=u.length-1;p>=0;p-=1){const f=u[p],{isExternal:g,modifiers:v,hasImportantModifier:x,baseClassName:w,maybePostfixModifierPosition:b}=r(f);if(g){d=f+(d.length>0?" "+d:d);continue}let S=!!b,A;if(S){const P=w.substring(0,b);A=n(P);const R=A&&o[A]?n(w):void 0;R&&R!==A&&(A=R,S=!1)}else A=n(w);if(!A){if(!S){d=f+(d.length>0?" "+d:d);continue}if(A=n(w),!A){d=f+(d.length>0?" "+d:d);continue}S=!1}const O=v.length===0?"":v.length===1?v[0]:a(v).join(":"),j=x?O+Kb:O,E=j+A;if(c.indexOf(E)>-1)continue;c.push(E);const T=i(A,S);for(let P=0;P<T.length;++P){const R=T[P];c.push(j+R)}d=f+(d.length>0?" "+d:d)}return d},LB=(...t)=>{let e=0,r,n,i="";for(;e<t.length;)(r=t[e++])&&(n=zP(r))&&(i&&(i+=" "),i+=n);return i},zP=t=>{if(typeof t=="string")return t;let e,r="";for(let n=0;n<t.length;n++)t[n]&&(e=zP(t[n]))&&(r&&(r+=" "),r+=e);return r},DB=(t,...e)=>{let r,n,i,a;const o=u=>{const d=e.reduce((p,f)=>f(p),t());return r=RB(d),n=r.cache.get,i=r.cache.set,a=c,c(u)},c=u=>{const d=n(u);if(d)return d;const p=MB(u,r);return i(u,p),p};return a=o,(...u)=>a(LB(...u))},zB=[],nr=t=>{const e=r=>r[t]||zB;return e.isThemeGetter=!0,e},BP=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,UP=/^\((?:(\w[\w-]*):)?(.+)\)$/i,BB=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,UB=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,qB=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,FB=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,HB=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,WB=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ta=t=>BB.test(t),Ye=t=>!!t&&!Number.isNaN(Number(t)),gi=t=>!!t&&Number.isInteger(Number(t)),Tg=t=>t.endsWith("%")&&Ye(t.slice(0,-1)),Li=t=>UB.test(t),qP=()=>!0,GB=t=>qB.test(t)&&!FB.test(t),Qw=()=>!1,KB=t=>HB.test(t),VB=t=>WB.test(t),XB=t=>!ke(t)&&!Ae(t),YB=t=>t.startsWith("@container")&&(t[10]==="/"&&t[11]!==void 0||t[11]==="s"&&t[16]!==void 0&&t.startsWith("-size/",10)||t[11]==="n"&&t[18]!==void 0&&t.startsWith("-normal/",10)),JB=t=>Fa(t,WP,Qw),ke=t=>BP.test(t),go=t=>Fa(t,GP,GB),eE=t=>Fa(t,a6,Ye),ZB=t=>Fa(t,VP,qP),QB=t=>Fa(t,KP,Qw),tE=t=>Fa(t,FP,Qw),e6=t=>Fa(t,HP,VB),nf=t=>Fa(t,XP,KB),Ae=t=>UP.test(t),pc=t=>Bo(t,GP),t6=t=>Bo(t,KP),rE=t=>Bo(t,FP),r6=t=>Bo(t,WP),n6=t=>Bo(t,HP),af=t=>Bo(t,XP,!0),i6=t=>Bo(t,VP,!0),Fa=(t,e,r)=>{const n=BP.exec(t);return n?n[1]?e(n[1]):r(n[2]):!1},Bo=(t,e,r=!1)=>{const n=UP.exec(t);return n?n[1]?e(n[1]):r:!1},FP=t=>t==="position"||t==="percentage",HP=t=>t==="image"||t==="url",WP=t=>t==="length"||t==="size"||t==="bg-size",GP=t=>t==="length",a6=t=>t==="number",KP=t=>t==="family-name",VP=t=>t==="number"||t==="weight",XP=t=>t==="shadow",o6=()=>{const t=nr("color"),e=nr("font"),r=nr("text"),n=nr("font-weight"),i=nr("tracking"),a=nr("leading"),o=nr("breakpoint"),c=nr("container"),u=nr("spacing"),d=nr("radius"),p=nr("shadow"),f=nr("inset-shadow"),g=nr("text-shadow"),v=nr("drop-shadow"),x=nr("blur"),w=nr("perspective"),b=nr("aspect"),S=nr("ease"),A=nr("animate"),O=()=>["auto","avoid","all","avoid-page","page","left","right","column"],j=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],E=()=>[...j(),Ae,ke],T=()=>["auto","hidden","clip","visible","scroll"],P=()=>["auto","contain","none"],R=()=>[Ae,ke,u],M=()=>[Ta,"full","auto",...R()],J=()=>[gi,"none","subgrid",Ae,ke],F=()=>["auto",{span:["full",gi,Ae,ke]},gi,Ae,ke],B=()=>[gi,"auto",Ae,ke],K=()=>["auto","min","max","fr",Ae,ke],W=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],X=()=>["start","end","center","stretch","center-safe","end-safe"],Y=()=>["auto",...R()],te=()=>[Ta,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...R()],H=()=>[Ta,"screen","full","dvw","lvw","svw","min","max","fit",...R()],Q=()=>[Ta,"screen","full","lh","dvh","lvh","svh","min","max","fit",...R()],U=()=>[t,Ae,ke],I=()=>[...j(),rE,tE,{position:[Ae,ke]}],$=()=>["no-repeat",{repeat:["","x","y","space","round"]}],V=()=>["auto","cover","contain",r6,JB,{size:[Ae,ke]}],oe=()=>[Tg,pc,go],le=()=>["","none","full",d,Ae,ke],ve=()=>["",Ye,pc,go],qe=()=>["solid","dashed","dotted","double"],xe=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ae=()=>[Ye,Tg,rE,tE],Se=()=>["","none",x,Ae,ke],Me=()=>["none",Ye,Ae,ke],se=()=>["none",Ye,Ae,ke],tt=()=>[Ye,Ae,ke],Fe=()=>[Ta,"full",...R()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Li],breakpoint:[Li],color:[qP],container:[Li],"drop-shadow":[Li],ease:["in","out","in-out"],font:[XB],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Li],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Li],shadow:[Li],spacing:["px",Ye],text:[Li],"text-shadow":[Li],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Ta,ke,Ae,b]}],container:["container"],"container-type":[{"@container":["","normal","size",Ae,ke]}],"container-named":[YB],columns:[{columns:[Ye,ke,Ae,c]}],"break-after":[{"break-after":O()}],"break-before":[{"break-before":O()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:E()}],overflow:[{overflow:T()}],"overflow-x":[{"overflow-x":T()}],"overflow-y":[{"overflow-y":T()}],overscroll:[{overscroll:P()}],"overscroll-x":[{"overscroll-x":P()}],"overscroll-y":[{"overscroll-y":P()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:M()}],"inset-x":[{"inset-x":M()}],"inset-y":[{"inset-y":M()}],start:[{"inset-s":M(),start:M()}],end:[{"inset-e":M(),end:M()}],"inset-bs":[{"inset-bs":M()}],"inset-be":[{"inset-be":M()}],top:[{top:M()}],right:[{right:M()}],bottom:[{bottom:M()}],left:[{left:M()}],visibility:["visible","invisible","collapse"],z:[{z:[gi,"auto",Ae,ke]}],basis:[{basis:[Ta,"full","auto",c,...R()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Ye,Ta,"auto","initial","none",ke]}],grow:[{grow:["",Ye,Ae,ke]}],shrink:[{shrink:["",Ye,Ae,ke]}],order:[{order:[gi,"first","last","none",Ae,ke]}],"grid-cols":[{"grid-cols":J()}],"col-start-end":[{col:F()}],"col-start":[{"col-start":B()}],"col-end":[{"col-end":B()}],"grid-rows":[{"grid-rows":J()}],"row-start-end":[{row:F()}],"row-start":[{"row-start":B()}],"row-end":[{"row-end":B()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":K()}],"auto-rows":[{"auto-rows":K()}],gap:[{gap:R()}],"gap-x":[{"gap-x":R()}],"gap-y":[{"gap-y":R()}],"justify-content":[{justify:[...W(),"normal"]}],"justify-items":[{"justify-items":[...X(),"normal"]}],"justify-self":[{"justify-self":["auto",...X()]}],"align-content":[{content:["normal",...W()]}],"align-items":[{items:[...X(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...X(),{baseline:["","last"]}]}],"place-content":[{"place-content":W()}],"place-items":[{"place-items":[...X(),"baseline"]}],"place-self":[{"place-self":["auto",...X()]}],p:[{p:R()}],px:[{px:R()}],py:[{py:R()}],ps:[{ps:R()}],pe:[{pe:R()}],pbs:[{pbs:R()}],pbe:[{pbe:R()}],pt:[{pt:R()}],pr:[{pr:R()}],pb:[{pb:R()}],pl:[{pl:R()}],m:[{m:Y()}],mx:[{mx:Y()}],my:[{my:Y()}],ms:[{ms:Y()}],me:[{me:Y()}],mbs:[{mbs:Y()}],mbe:[{mbe:Y()}],mt:[{mt:Y()}],mr:[{mr:Y()}],mb:[{mb:Y()}],ml:[{ml:Y()}],"space-x":[{"space-x":R()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":R()}],"space-y-reverse":["space-y-reverse"],size:[{size:te()}],"inline-size":[{inline:["auto",...H()]}],"min-inline-size":[{"min-inline":["auto",...H()]}],"max-inline-size":[{"max-inline":["none",...H()]}],"block-size":[{block:["auto",...Q()]}],"min-block-size":[{"min-block":["auto",...Q()]}],"max-block-size":[{"max-block":["none",...Q()]}],w:[{w:[c,"screen",...te()]}],"min-w":[{"min-w":[c,"screen","none",...te()]}],"max-w":[{"max-w":[c,"screen","none","prose",{screen:[o]},...te()]}],h:[{h:["screen","lh",...te()]}],"min-h":[{"min-h":["screen","lh","none",...te()]}],"max-h":[{"max-h":["screen","lh",...te()]}],"font-size":[{text:["base",r,pc,go]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[n,i6,ZB]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Tg,ke]}],"font-family":[{font:[t6,QB,e]}],"font-features":[{"font-features":[ke]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,Ae,ke]}],"line-clamp":[{"line-clamp":[Ye,"none",Ae,eE]}],leading:[{leading:[a,...R()]}],"list-image":[{"list-image":["none",Ae,ke]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Ae,ke]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:U()}],"text-color":[{text:U()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...qe(),"wavy"]}],"text-decoration-thickness":[{decoration:[Ye,"from-font","auto",Ae,go]}],"text-decoration-color":[{decoration:U()}],"underline-offset":[{"underline-offset":[Ye,"auto",Ae,ke]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:R()}],"tab-size":[{tab:[gi,Ae,ke]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Ae,ke]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Ae,ke]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:I()}],"bg-repeat":[{bg:$()}],"bg-size":[{bg:V()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},gi,Ae,ke],radial:["",Ae,ke],conic:[gi,Ae,ke]},n6,e6]}],"bg-color":[{bg:U()}],"gradient-from-pos":[{from:oe()}],"gradient-via-pos":[{via:oe()}],"gradient-to-pos":[{to:oe()}],"gradient-from":[{from:U()}],"gradient-via":[{via:U()}],"gradient-to":[{to:U()}],rounded:[{rounded:le()}],"rounded-s":[{"rounded-s":le()}],"rounded-e":[{"rounded-e":le()}],"rounded-t":[{"rounded-t":le()}],"rounded-r":[{"rounded-r":le()}],"rounded-b":[{"rounded-b":le()}],"rounded-l":[{"rounded-l":le()}],"rounded-ss":[{"rounded-ss":le()}],"rounded-se":[{"rounded-se":le()}],"rounded-ee":[{"rounded-ee":le()}],"rounded-es":[{"rounded-es":le()}],"rounded-tl":[{"rounded-tl":le()}],"rounded-tr":[{"rounded-tr":le()}],"rounded-br":[{"rounded-br":le()}],"rounded-bl":[{"rounded-bl":le()}],"border-w":[{border:ve()}],"border-w-x":[{"border-x":ve()}],"border-w-y":[{"border-y":ve()}],"border-w-s":[{"border-s":ve()}],"border-w-e":[{"border-e":ve()}],"border-w-bs":[{"border-bs":ve()}],"border-w-be":[{"border-be":ve()}],"border-w-t":[{"border-t":ve()}],"border-w-r":[{"border-r":ve()}],"border-w-b":[{"border-b":ve()}],"border-w-l":[{"border-l":ve()}],"divide-x":[{"divide-x":ve()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":ve()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...qe(),"hidden","none"]}],"divide-style":[{divide:[...qe(),"hidden","none"]}],"border-color":[{border:U()}],"border-color-x":[{"border-x":U()}],"border-color-y":[{"border-y":U()}],"border-color-s":[{"border-s":U()}],"border-color-e":[{"border-e":U()}],"border-color-bs":[{"border-bs":U()}],"border-color-be":[{"border-be":U()}],"border-color-t":[{"border-t":U()}],"border-color-r":[{"border-r":U()}],"border-color-b":[{"border-b":U()}],"border-color-l":[{"border-l":U()}],"divide-color":[{divide:U()}],"outline-style":[{outline:[...qe(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Ye,Ae,ke]}],"outline-w":[{outline:["",Ye,pc,go]}],"outline-color":[{outline:U()}],shadow:[{shadow:["","none",p,af,nf]}],"shadow-color":[{shadow:U()}],"inset-shadow":[{"inset-shadow":["none",f,af,nf]}],"inset-shadow-color":[{"inset-shadow":U()}],"ring-w":[{ring:ve()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:U()}],"ring-offset-w":[{"ring-offset":[Ye,go]}],"ring-offset-color":[{"ring-offset":U()}],"inset-ring-w":[{"inset-ring":ve()}],"inset-ring-color":[{"inset-ring":U()}],"text-shadow":[{"text-shadow":["none",g,af,nf]}],"text-shadow-color":[{"text-shadow":U()}],opacity:[{opacity:[Ye,Ae,ke]}],"mix-blend":[{"mix-blend":[...xe(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":xe()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Ye]}],"mask-image-linear-from-pos":[{"mask-linear-from":ae()}],"mask-image-linear-to-pos":[{"mask-linear-to":ae()}],"mask-image-linear-from-color":[{"mask-linear-from":U()}],"mask-image-linear-to-color":[{"mask-linear-to":U()}],"mask-image-t-from-pos":[{"mask-t-from":ae()}],"mask-image-t-to-pos":[{"mask-t-to":ae()}],"mask-image-t-from-color":[{"mask-t-from":U()}],"mask-image-t-to-color":[{"mask-t-to":U()}],"mask-image-r-from-pos":[{"mask-r-from":ae()}],"mask-image-r-to-pos":[{"mask-r-to":ae()}],"mask-image-r-from-color":[{"mask-r-from":U()}],"mask-image-r-to-color":[{"mask-r-to":U()}],"mask-image-b-from-pos":[{"mask-b-from":ae()}],"mask-image-b-to-pos":[{"mask-b-to":ae()}],"mask-image-b-from-color":[{"mask-b-from":U()}],"mask-image-b-to-color":[{"mask-b-to":U()}],"mask-image-l-from-pos":[{"mask-l-from":ae()}],"mask-image-l-to-pos":[{"mask-l-to":ae()}],"mask-image-l-from-color":[{"mask-l-from":U()}],"mask-image-l-to-color":[{"mask-l-to":U()}],"mask-image-x-from-pos":[{"mask-x-from":ae()}],"mask-image-x-to-pos":[{"mask-x-to":ae()}],"mask-image-x-from-color":[{"mask-x-from":U()}],"mask-image-x-to-color":[{"mask-x-to":U()}],"mask-image-y-from-pos":[{"mask-y-from":ae()}],"mask-image-y-to-pos":[{"mask-y-to":ae()}],"mask-image-y-from-color":[{"mask-y-from":U()}],"mask-image-y-to-color":[{"mask-y-to":U()}],"mask-image-radial":[{"mask-radial":[Ae,ke]}],"mask-image-radial-from-pos":[{"mask-radial-from":ae()}],"mask-image-radial-to-pos":[{"mask-radial-to":ae()}],"mask-image-radial-from-color":[{"mask-radial-from":U()}],"mask-image-radial-to-color":[{"mask-radial-to":U()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":j()}],"mask-image-conic-pos":[{"mask-conic":[Ye]}],"mask-image-conic-from-pos":[{"mask-conic-from":ae()}],"mask-image-conic-to-pos":[{"mask-conic-to":ae()}],"mask-image-conic-from-color":[{"mask-conic-from":U()}],"mask-image-conic-to-color":[{"mask-conic-to":U()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:I()}],"mask-repeat":[{mask:$()}],"mask-size":[{mask:V()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Ae,ke]}],filter:[{filter:["","none",Ae,ke]}],blur:[{blur:Se()}],brightness:[{brightness:[Ye,Ae,ke]}],contrast:[{contrast:[Ye,Ae,ke]}],"drop-shadow":[{"drop-shadow":["","none",v,af,nf]}],"drop-shadow-color":[{"drop-shadow":U()}],grayscale:[{grayscale:["",Ye,Ae,ke]}],"hue-rotate":[{"hue-rotate":[Ye,Ae,ke]}],invert:[{invert:["",Ye,Ae,ke]}],saturate:[{saturate:[Ye,Ae,ke]}],sepia:[{sepia:["",Ye,Ae,ke]}],"backdrop-filter":[{"backdrop-filter":["","none",Ae,ke]}],"backdrop-blur":[{"backdrop-blur":Se()}],"backdrop-brightness":[{"backdrop-brightness":[Ye,Ae,ke]}],"backdrop-contrast":[{"backdrop-contrast":[Ye,Ae,ke]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Ye,Ae,ke]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Ye,Ae,ke]}],"backdrop-invert":[{"backdrop-invert":["",Ye,Ae,ke]}],"backdrop-opacity":[{"backdrop-opacity":[Ye,Ae,ke]}],"backdrop-saturate":[{"backdrop-saturate":[Ye,Ae,ke]}],"backdrop-sepia":[{"backdrop-sepia":["",Ye,Ae,ke]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":R()}],"border-spacing-x":[{"border-spacing-x":R()}],"border-spacing-y":[{"border-spacing-y":R()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Ae,ke]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Ye,"initial",Ae,ke]}],ease:[{ease:["linear","initial",S,Ae,ke]}],delay:[{delay:[Ye,Ae,ke]}],animate:[{animate:["none",A,Ae,ke]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[w,Ae,ke]}],"perspective-origin":[{"perspective-origin":E()}],rotate:[{rotate:Me()}],"rotate-x":[{"rotate-x":Me()}],"rotate-y":[{"rotate-y":Me()}],"rotate-z":[{"rotate-z":Me()}],scale:[{scale:se()}],"scale-x":[{"scale-x":se()}],"scale-y":[{"scale-y":se()}],"scale-z":[{"scale-z":se()}],"scale-3d":["scale-3d"],skew:[{skew:tt()}],"skew-x":[{"skew-x":tt()}],"skew-y":[{"skew-y":tt()}],transform:[{transform:[Ae,ke,"","none","gpu","cpu"]}],"transform-origin":[{origin:E()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Fe()}],"translate-x":[{"translate-x":Fe()}],"translate-y":[{"translate-y":Fe()}],"translate-z":[{"translate-z":Fe()}],"translate-none":["translate-none"],zoom:[{zoom:[gi,Ae,ke]}],accent:[{accent:U()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:U()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Ae,ke]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":U()}],"scrollbar-track-color":[{"scrollbar-track":U()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":R()}],"scroll-mx":[{"scroll-mx":R()}],"scroll-my":[{"scroll-my":R()}],"scroll-ms":[{"scroll-ms":R()}],"scroll-me":[{"scroll-me":R()}],"scroll-mbs":[{"scroll-mbs":R()}],"scroll-mbe":[{"scroll-mbe":R()}],"scroll-mt":[{"scroll-mt":R()}],"scroll-mr":[{"scroll-mr":R()}],"scroll-mb":[{"scroll-mb":R()}],"scroll-ml":[{"scroll-ml":R()}],"scroll-p":[{"scroll-p":R()}],"scroll-px":[{"scroll-px":R()}],"scroll-py":[{"scroll-py":R()}],"scroll-ps":[{"scroll-ps":R()}],"scroll-pe":[{"scroll-pe":R()}],"scroll-pbs":[{"scroll-pbs":R()}],"scroll-pbe":[{"scroll-pbe":R()}],"scroll-pt":[{"scroll-pt":R()}],"scroll-pr":[{"scroll-pr":R()}],"scroll-pb":[{"scroll-pb":R()}],"scroll-pl":[{"scroll-pl":R()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Ae,ke]}],fill:[{fill:["none",...U()]}],"stroke-w":[{stroke:[Ye,pc,go,eE]}],stroke:[{stroke:["none",...U()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},s6=DB(o6);function Oc(...t){return s6(ot(t))}function l6({status:t}){const e={connected:"bg-green-500",idle:"bg-green-500",disconnected:"bg-zinc-600",error:"bg-red-500",working:"bg-amber-400",reviewing:"bg-blue-400"}[t],r=t==="connected"||t==="working";return y.jsxs("span",{className:"relative inline-flex items-center justify-center w-2 h-2",children:[r&&y.jsx("span",{className:`absolute inline-flex h-full w-full rounded-full ${e} opacity-40 animate-ping`}),y.jsx("span",{className:`relative inline-flex rounded-full h-2 w-2 ${e}`})]})}function jt({children:t,variant:e="muted",className:r=""}){const n={default:"bg-[#E43A9C]/15 text-[#F041FF] border-[#E43A9C]/20",success:"bg-green-500/15 text-green-400 border-green-500/20",warning:"bg-amber-500/15 text-amber-400 border-amber-500/20",error:"bg-red-500/15 text-red-400 border-red-500/20",info:"bg-blue-500/15 text-blue-400 border-blue-500/20",muted:"bg-white/5 text-zinc-400 border-white/10"}[e];return y.jsx("span",{className:`inline-flex items-center px-2 py-px rounded-full text-[10px] font-mono border ${n} ${r}`,children:t})}function c6({name:t,color:e}){return e?y.jsx("span",{className:"inline-flex items-center px-1.5 py-px rounded text-[10px] font-mono border",style:{background:`${e}15`,color:e,borderColor:`${e}30`},children:t}):y.jsx(jt,{variant:"muted",children:t})}function za({children:t,onClick:e,className:r="",type:n="button",disabled:i=!1}){return y.jsx("button",{type:n,onClick:e,disabled:i,className:`flex items-center gap-1.5 font-mono text-[11px] text-white rounded-lg active:opacity-80 primary-btn cursor-pointer disabled:opacity-50 ${r}`,children:t})}function _i({children:t,onClick:e,className:r=""}){return y.jsx("button",{type:"button",onClick:e,className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg font-mono text-[11px] text-zinc-400 bg-[#252525] hover:bg-[#2e2e2e] hover:text-zinc-100 transition-colors cursor-pointer ${r}`,children:t})}function Bf({children:t,onClick:e,className:r=""}){return y.jsx("button",{type:"button",onClick:e,className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg font-mono text-[11px] text-zinc-400 bg-[#252525] hover:bg-red-500/10 hover:text-red-400 transition-colors cursor-pointer ${r}`,children:t})}function u6({children:t,onClick:e,className:r=""}){return y.jsx("button",{type:"button",onClick:e,className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg font-mono text-[11px] text-zinc-400 bg-[#252525] hover:bg-amber-500/10 hover:text-amber-400 transition-colors cursor-pointer ${r}`,children:t})}function Co(t){return t==="connected"||t==="idle"?"success":t==="active"||t==="working"?"warning":t==="reviewing"||t==="in meeting"||t==="planning"||t==="meeting"?"info":t==="error"||t==="failed"?"error":"muted"}function np(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function d6(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(p){try{d(n.next(p))}catch(f){o(f)}}function u(p){try{d(n.throw(p))}catch(f){o(f)}}function d(p){p.done?a(p.value):i(p.value).then(c,u)}d((n=n.apply(t,e||[])).next())})}const f6=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);class e1 extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n}toJSON(){return{name:this.name,message:this.message,context:this.context}}}class h6 extends e1{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class nE extends e1{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class iE extends e1{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Vb;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(Vb||(Vb={}));class p6{constructor(e,{headers:r={},customFetch:n,region:i=Vb.Any}={}){this.url=e,this.headers=r,this.region=i,this.fetch=f6(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return d6(this,arguments,void 0,function*(r,n={}){var i;let a,o;try{const{headers:c,method:u,body:d,signal:p,timeout:f}=n;let g={},{region:v}=n;v||(v=this.region);const x=new URL(`${this.url}/${r}`);v&&v!=="any"&&(g["x-region"]=v,x.searchParams.set("forceFunctionRegion",v));let w;d&&(c&&!Object.prototype.hasOwnProperty.call(c,"Content-Type")||!c)?typeof Blob<"u"&&d instanceof Blob||d instanceof ArrayBuffer?(g["Content-Type"]="application/octet-stream",w=d):typeof d=="string"?(g["Content-Type"]="text/plain",w=d):typeof FormData<"u"&&d instanceof FormData?w=d:(g["Content-Type"]="application/json",w=JSON.stringify(d)):d&&typeof d!="string"&&!(typeof Blob<"u"&&d instanceof Blob)&&!(d instanceof ArrayBuffer)&&!(typeof FormData<"u"&&d instanceof FormData)?w=JSON.stringify(d):w=d;let b=p;f&&(o=new AbortController,a=setTimeout(()=>o.abort(),f),p?(b=o.signal,p.addEventListener("abort",()=>o.abort())):b=o.signal);const S=yield this.fetch(x.toString(),{method:u||"POST",headers:Object.assign(Object.assign(Object.assign({},g),this.headers),c),body:w,signal:b}).catch(E=>{throw new h6(E)}),A=S.headers.get("x-relay-error");if(A&&A==="true")throw new nE(S);if(!S.ok)throw new iE(S);let O=((i=S.headers.get("Content-Type"))!==null&&i!==void 0?i:"text/plain").split(";")[0].trim(),j;return O==="application/json"?j=yield S.json():O==="application/octet-stream"||O==="application/pdf"?j=yield S.blob():O==="text/event-stream"?j=S:O==="multipart/form-data"?j=yield S.formData():j=yield S.text(),{data:j,error:null,response:S}}catch(c){return{data:null,error:c,response:c instanceof iE||c instanceof nE?c.context:void 0}}finally{a&&clearTimeout(a)}})}}const YP=3,aE=t=>Math.min(1e3*2**t,3e4),m6=[520,503],JP=["GET","HEAD","OPTIONS"];var g6=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function oE(t,e){return new Promise(r=>{if(e!=null&&e.aborted){r();return}const n=setTimeout(()=>{e==null||e.removeEventListener("abort",i),r()},t);function i(){clearTimeout(n),r()}e==null||e.addEventListener("abort",i)})}function y6(t,e,r,n){return!(!n||r>=YP||!JP.includes(t)||!m6.includes(e))}var v6=class{constructor(t){var e,r,n,i,a;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.shouldStripNulls=(n=t.shouldStripNulls)!==null&&n!==void 0?n:!1,this.urlLengthLimit=(i=t.urlLengthLimit)!==null&&i!==void 0?i:8e3,this.retryEnabled=(a=t.retry)!==null&&a!==void 0?a:!0,t.fetch?this.fetch=t.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(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}retry(t){return this.retryEnabled=t,this}then(t,e){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){const o=this.headers.get("Accept");o==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!o||o==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}const n=this.fetch;let a=(async()=>{let o=0;for(;;){const d=new Headers(r.headers);o>0&&d.set("X-Retry-Count",String(o));let p;try{p=await n(r.url.toString(),{method:r.method,headers:d,body:JSON.stringify(r.body,(f,g)=>typeof g=="bigint"?g.toString():g),signal:r.signal})}catch(f){if((f==null?void 0:f.name)==="AbortError"||(f==null?void 0:f.code)==="ABORT_ERR"||!JP.includes(r.method))throw f;if(r.retryEnabled&&o<YP){const g=aE(o);o++,await oE(g,r.signal);continue}throw f}if(y6(r.method,p.status,o,r.retryEnabled)){var c,u;const f=(c=(u=p.headers)===null||u===void 0?void 0:u.get("Retry-After"))!==null&&c!==void 0?c:null,g=f!==null?Math.max(0,parseInt(f,10)||0)*1e3:aE(o);await p.text(),o++,await oE(g,r.signal);continue}return await r.processResponse(p)}})();return this.shouldThrowOnError||(a=a.catch(o=>{var c;let u="",d="",p="";const f=o==null?void 0:o.cause;if(f){var g,v,x,w;const A=(g=f==null?void 0:f.message)!==null&&g!==void 0?g:"",O=(v=f==null?void 0:f.code)!==null&&v!==void 0?v:"";u=`${(x=o==null?void 0:o.name)!==null&&x!==void 0?x:"FetchError"}: ${o==null?void 0:o.message}`,u+=`
|
|
387
389
|
|
|
388
390
|
Caused by: ${(w=f==null?void 0:f.name)!==null&&w!==void 0?w:"Error"}: ${A}`,O&&(u+=` (${O})`),f!=null&&f.stack&&(u+=`
|
|
389
|
-
${f.stack}`)}else{var b;u=(b=o==null?void 0:o.stack)!==null&&b!==void 0?b:""}const S=this.url.toString().length;return(o==null?void 0:o.name)==="AbortError"||(o==null?void 0:o.code)==="ABORT_ERR"?(p="",d="Request was aborted (timeout or manual cancellation)",S>this.urlLengthLimit&&(d+=`. Note: Your request URL is ${S} 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==null?void 0:f.name)==="HeadersOverflowError"||(f==null?void 0:f.code)==="UND_ERR_HEADERS_OVERFLOW")&&(p="",d="HTTP headers exceeded server limits (typically 16KB)",S>this.urlLengthLimit&&(d+=`. Your request URL is ${S} 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:`${(c=o==null?void 0:o.name)!==null&&c!==void 0?c:"FetchError"}: ${o==null?void 0:o.message}`,details:u,hint:d,code:p},data:null,count:null,status:0,statusText:""}})),a.then(t,e)}async processResponse(t){var e=this;let r=null,n=null,i=null,a=t.status,o=t.statusText;if(t.ok){var c,u;if(e.method!=="HEAD"){var d;const g=await t.text();g===""||(e.headers.get("Accept")==="text/csv"||e.headers.get("Accept")&&(!((d=e.headers.get("Accept"))===null||d===void 0)&&d.includes("application/vnd.pgrst.plan+text"))?n=g:n=JSON.parse(g))}const p=(c=e.headers.get("Prefer"))===null||c===void 0?void 0:c.match(/count=(exact|planned|estimated)/),f=(u=t.headers.get("content-range"))===null||u===void 0?void 0:u.split("/");p&&f&&f.length>1&&(i=parseInt(f[1])),e.isMaybeSingle&&Array.isArray(n)&&(n.length>1?(r={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,i=null,a=406,o="Not Acceptable"):n.length===1?n=n[0]:n=null)}else{const p=await t.text();try{r=JSON.parse(p),Array.isArray(r)&&t.status===404&&(n=[],r=null,a=200,o="OK")}catch{t.status===404&&p===""?(a=204,o="No Content"):r={message:p}}if(r&&e.shouldThrowOnError)throw new JB(r)}return{success:r===null,error:r,data:n,count:i,status:a,statusText:o}}returns(){return this}overrideTypes(){return this}},e6=class extends QB{select(t){let e=!1;const r=(t??"*").split("").map(n=>/\s/.test(n)&&!e?"":(n==='"'&&(e=!e),n)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:n,referencedTable:i=n}={}){const a=i?`${i}.order`:"order",o=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){const n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:n=r}={}){const i=typeof n>"u"?"offset":`${n}.offset`,a=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(i,`${t}`),this.url.searchParams.set(a,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:n=!1,wal:i=!1,format:a="text"}={}){var o;const c=[t?"analyze":null,e?"verbose":null,r?"settings":null,n?"buffers":null,i?"wal":null].filter(Boolean).join("|"),u=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${a}; for="${u}"; options=${c};`),a==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}};const aE=new RegExp("[,()]");var Cs=class extends e6{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){const r=Array.from(new Set(e)).map(n=>typeof n=="string"&&aE.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){const r=Array.from(new Set(e)).map(n=>typeof n=="string"&&aE.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:n}={}){let i="";n==="plain"?i="pl":n==="phrase"?i="ph":n==="websearch"&&(i="w");const a=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${i}fts${a}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){const n=r?`${r}.or`:"or";return this.url.searchParams.append(n,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},t6=class{constructor(t,{headers:e={},schema:r,fetch:n,urlLengthLimit:i=8e3,retry:a}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=n,this.urlLengthLimit=i,this.retry=a}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){const{head:r=!1,count:n}=e??{},i=r?"HEAD":"GET";let a=!1;const o=(t??"*").split("").map(d=>/\s/.test(d)&&!a?"":(d==='"'&&(a=!a),d)).join(""),{url:c,headers:u}=this.cloneRequestState();return c.searchParams.set("select",o),n&&u.append("Prefer",`count=${n}`),new Cs({method:i,url:c,headers:u,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(t,{count:e,defaultToNull:r=!0}={}){var n;const i="POST",{url:a,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),r||o.append("Prefer","missing=default"),Array.isArray(t)){const c=t.reduce((u,d)=>u.concat(Object.keys(d)),[]);if(c.length>0){const u=[...new Set(c)].map(d=>`"${d}"`);a.searchParams.set("columns",u.join(","))}}return new Cs({method:i,url:a,headers:o,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:n,defaultToNull:i=!0}={}){var a;const o="POST",{url:c,headers:u}=this.cloneRequestState();if(u.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&c.searchParams.set("on_conflict",e),n&&u.append("Prefer",`count=${n}`),i||u.append("Prefer","missing=default"),Array.isArray(t)){const d=t.reduce((p,f)=>p.concat(Object.keys(f)),[]);if(d.length>0){const p=[...new Set(d)].map(f=>`"${f}"`);c.searchParams.set("columns",p.join(","))}}return new Cs({method:o,url:c,headers:u,schema:this.schema,body:t,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(t,{count:e}={}){var r;const n="PATCH",{url:i,headers:a}=this.cloneRequestState();return e&&a.append("Prefer",`count=${e}`),new Cs({method:n,url:i,headers:a,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:t}={}){var e;const r="DELETE",{url:n,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new Cs({method:r,url:n,headers:i,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function qc(t){"@babel/helpers - typeof";return qc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},qc(t)}function r6(t,e){if(qc(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(qc(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function n6(t){var e=r6(t,"string");return qc(e)=="symbol"?e:e+""}function i6(t,e,r){return(e=n6(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function oE(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function of(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?oE(Object(r),!0).forEach(function(n){i6(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):oE(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var a6=class LP{constructor(e,{headers:r={},schema:n,fetch:i,timeout:a,urlLengthLimit:o=8e3,retry:c}={}){this.url=e,this.headers=new Headers(r),this.schemaName=n,this.urlLengthLimit=o;const u=i??globalThis.fetch;a!==void 0&&a>0?this.fetch=(d,p)=>{const f=new AbortController,g=setTimeout(()=>f.abort(),a),v=p==null?void 0:p.signal;if(v){if(v.aborted)return clearTimeout(g),u(d,p);const x=()=>{clearTimeout(g),f.abort()};return v.addEventListener("abort",x,{once:!0}),u(d,of(of({},p),{},{signal:f.signal})).finally(()=>{clearTimeout(g),v.removeEventListener("abort",x)})}return u(d,of(of({},p),{},{signal:f.signal})).finally(()=>clearTimeout(g))}:this.fetch=u,this.retry=c}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new t6(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(e){return new LP(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,r={},{head:n=!1,get:i=!1,count:a}={}){var o;let c;const u=new URL(`${this.url}/rpc/${e}`);let d;const p=v=>v!==null&&typeof v=="object"&&(!Array.isArray(v)||v.some(p)),f=n&&Object.values(r).some(p);f?(c="POST",d=r):n||i?(c=n?"HEAD":"GET",Object.entries(r).filter(([v,x])=>x!==void 0).map(([v,x])=>[v,Array.isArray(x)?`{${x.join(",")}}`:`${x}`]).forEach(([v,x])=>{u.searchParams.append(v,x)})):(c="POST",d=r);const g=new Headers(this.headers);return f?g.set("Prefer",a?`count=${a},return=minimal`:"return=minimal"):a&&g.set("Prefer",`count=${a}`),new Cs({method:c,url:u,headers:g,schema:this.schemaName,body:d,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};class o6{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",wsConstructor:WebSocket};const r=globalThis;if(typeof globalThis<"u"&&typeof r.WebSocket<"u")return{type:"native",wsConstructor:r.WebSocket};const n=typeof global<"u"?global:void 0;if(n&&typeof n.WebSocket<"u")return{type:"native",wsConstructor:n.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"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const i=globalThis.process;if(i){const a=i.versions;if(a&&a.node){const o=a.node,c=parseInt(o.replace(/^v/,"").split(".")[0]);return c>=22?typeof globalThis.WebSocket<"u"?{type:"native",wsConstructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${c} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${c} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
|
|
391
|
+
${f.stack}`)}else{var b;u=(b=o==null?void 0:o.stack)!==null&&b!==void 0?b:""}const S=this.url.toString().length;return(o==null?void 0:o.name)==="AbortError"||(o==null?void 0:o.code)==="ABORT_ERR"?(p="",d="Request was aborted (timeout or manual cancellation)",S>this.urlLengthLimit&&(d+=`. Note: Your request URL is ${S} 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==null?void 0:f.name)==="HeadersOverflowError"||(f==null?void 0:f.code)==="UND_ERR_HEADERS_OVERFLOW")&&(p="",d="HTTP headers exceeded server limits (typically 16KB)",S>this.urlLengthLimit&&(d+=`. Your request URL is ${S} 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:`${(c=o==null?void 0:o.name)!==null&&c!==void 0?c:"FetchError"}: ${o==null?void 0:o.message}`,details:u,hint:d,code:p},data:null,count:null,status:0,statusText:""}})),a.then(t,e)}async processResponse(t){var e=this;let r=null,n=null,i=null,a=t.status,o=t.statusText;if(t.ok){var c,u;if(e.method!=="HEAD"){var d;const g=await t.text();g===""||(e.headers.get("Accept")==="text/csv"||e.headers.get("Accept")&&(!((d=e.headers.get("Accept"))===null||d===void 0)&&d.includes("application/vnd.pgrst.plan+text"))?n=g:n=JSON.parse(g))}const p=(c=e.headers.get("Prefer"))===null||c===void 0?void 0:c.match(/count=(exact|planned|estimated)/),f=(u=t.headers.get("content-range"))===null||u===void 0?void 0:u.split("/");p&&f&&f.length>1&&(i=parseInt(f[1])),e.isMaybeSingle&&Array.isArray(n)&&(n.length>1?(r={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,i=null,a=406,o="Not Acceptable"):n.length===1?n=n[0]:n=null)}else{const p=await t.text();try{r=JSON.parse(p),Array.isArray(r)&&t.status===404&&(n=[],r=null,a=200,o="OK")}catch{t.status===404&&p===""?(a=204,o="No Content"):r={message:p}}if(r&&e.shouldThrowOnError)throw new g6(r)}return{success:r===null,error:r,data:n,count:i,status:a,statusText:o}}returns(){return this}overrideTypes(){return this}},b6=class extends v6{select(t){let e=!1;const r=(t??"*").split("").map(n=>/\s/.test(n)&&!e?"":(n==='"'&&(e=!e),n)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:n,referencedTable:i=n}={}){const a=i?`${i}.order`:"order",o=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){const n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:n=r}={}){const i=typeof n>"u"?"offset":`${n}.offset`,a=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(i,`${t}`),this.url.searchParams.set(a,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:n=!1,wal:i=!1,format:a="text"}={}){var o;const c=[t?"analyze":null,e?"verbose":null,r?"settings":null,n?"buffers":null,i?"wal":null].filter(Boolean).join("|"),u=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${a}; for="${u}"; options=${c};`),a==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}};const sE=new RegExp("[,()]");var Cs=class extends b6{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){const r=Array.from(new Set(e)).map(n=>typeof n=="string"&&sE.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){const r=Array.from(new Set(e)).map(n=>typeof n=="string"&&sE.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:n}={}){let i="";n==="plain"?i="pl":n==="phrase"?i="ph":n==="websearch"&&(i="w");const a=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${i}fts${a}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){const n=r?`${r}.or`:"or";return this.url.searchParams.append(n,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},x6=class{constructor(t,{headers:e={},schema:r,fetch:n,urlLengthLimit:i=8e3,retry:a}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=n,this.urlLengthLimit=i,this.retry=a}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){const{head:r=!1,count:n}=e??{},i=r?"HEAD":"GET";let a=!1;const o=(t??"*").split("").map(d=>/\s/.test(d)&&!a?"":(d==='"'&&(a=!a),d)).join(""),{url:c,headers:u}=this.cloneRequestState();return c.searchParams.set("select",o),n&&u.append("Prefer",`count=${n}`),new Cs({method:i,url:c,headers:u,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(t,{count:e,defaultToNull:r=!0}={}){var n;const i="POST",{url:a,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),r||o.append("Prefer","missing=default"),Array.isArray(t)){const c=t.reduce((u,d)=>u.concat(Object.keys(d)),[]);if(c.length>0){const u=[...new Set(c)].map(d=>`"${d}"`);a.searchParams.set("columns",u.join(","))}}return new Cs({method:i,url:a,headers:o,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:n,defaultToNull:i=!0}={}){var a;const o="POST",{url:c,headers:u}=this.cloneRequestState();if(u.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&c.searchParams.set("on_conflict",e),n&&u.append("Prefer",`count=${n}`),i||u.append("Prefer","missing=default"),Array.isArray(t)){const d=t.reduce((p,f)=>p.concat(Object.keys(f)),[]);if(d.length>0){const p=[...new Set(d)].map(f=>`"${f}"`);c.searchParams.set("columns",p.join(","))}}return new Cs({method:o,url:c,headers:u,schema:this.schema,body:t,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(t,{count:e}={}){var r;const n="PATCH",{url:i,headers:a}=this.cloneRequestState();return e&&a.append("Prefer",`count=${e}`),new Cs({method:n,url:i,headers:a,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:t}={}){var e;const r="DELETE",{url:n,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new Cs({method:r,url:n,headers:i,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function qc(t){"@babel/helpers - typeof";return qc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},qc(t)}function w6(t,e){if(qc(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(qc(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function _6(t){var e=w6(t,"string");return qc(e)=="symbol"?e:e+""}function S6(t,e,r){return(e=_6(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function lE(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function of(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?lE(Object(r),!0).forEach(function(n){S6(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):lE(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var k6=class ZP{constructor(e,{headers:r={},schema:n,fetch:i,timeout:a,urlLengthLimit:o=8e3,retry:c}={}){this.url=e,this.headers=new Headers(r),this.schemaName=n,this.urlLengthLimit=o;const u=i??globalThis.fetch;a!==void 0&&a>0?this.fetch=(d,p)=>{const f=new AbortController,g=setTimeout(()=>f.abort(),a),v=p==null?void 0:p.signal;if(v){if(v.aborted)return clearTimeout(g),u(d,p);const x=()=>{clearTimeout(g),f.abort()};return v.addEventListener("abort",x,{once:!0}),u(d,of(of({},p),{},{signal:f.signal})).finally(()=>{clearTimeout(g),v.removeEventListener("abort",x)})}return u(d,of(of({},p),{},{signal:f.signal})).finally(()=>clearTimeout(g))}:this.fetch=u,this.retry=c}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new x6(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(e){return new ZP(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,r={},{head:n=!1,get:i=!1,count:a}={}){var o;let c;const u=new URL(`${this.url}/rpc/${e}`);let d;const p=v=>v!==null&&typeof v=="object"&&(!Array.isArray(v)||v.some(p)),f=n&&Object.values(r).some(p);f?(c="POST",d=r):n||i?(c=n?"HEAD":"GET",Object.entries(r).filter(([v,x])=>x!==void 0).map(([v,x])=>[v,Array.isArray(x)?`{${x.join(",")}}`:`${x}`]).forEach(([v,x])=>{u.searchParams.append(v,x)})):(c="POST",d=r);const g=new Headers(this.headers);return f?g.set("Prefer",a?`count=${a},return=minimal`:"return=minimal"):a&&g.set("Prefer",`count=${a}`),new Cs({method:c,url:u,headers:g,schema:this.schemaName,body:d,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};class E6{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",wsConstructor:WebSocket};const r=globalThis;if(typeof globalThis<"u"&&typeof r.WebSocket<"u")return{type:"native",wsConstructor:r.WebSocket};const n=typeof global<"u"?global:void 0;if(n&&typeof n.WebSocket<"u")return{type:"native",wsConstructor:n.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"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const i=globalThis.process;if(i){const a=i.versions;if(a&&a.node){const o=a.node,c=parseInt(o.replace(/^v/,"").split(".")[0]);return c>=22?typeof globalThis.WebSocket<"u"?{type:"native",wsConstructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${c} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${c} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
|
|
390
392
|
import ws from "ws"
|
|
391
393
|
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(){const e=this.detectEnvironment();if(e.wsConstructor)return e.wsConstructor;let r=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(r+=`
|
|
392
394
|
|
|
393
|
-
Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const s6="2.106.2",l6=`realtime-js/${s6}`,c6="1.0.0",DP="2.0.0",u6=DP,d6=1e4,f6=100,Ca={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},zP={close:"phx_close",error:"phx_error",join:"phx_join",leave:"phx_leave",access_token:"access_token"},Xb={connecting:"connecting",closing:"closing",closed:"closed"};class h6{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,n;const i=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,i)}_encodeJsonUserBroadcastPush(e){var r,n;const i=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:{},o=new TextEncoder().encode(JSON.stringify(i)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,r,n){var i,a;const o=e.topic,c=(i=e.ref)!==null&&i!==void 0?i:"",u=(a=e.join_ref)!==null&&a!==void 0?a:"",d=e.payload.event,p=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},f=Object.keys(p).length===0?"":JSON.stringify(p);if(u.length>255)throw new Error(`joinRef length ${u.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`ref length ${c.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`userEvent length ${d.length} exceeds maximum of 255`);if(f.length>255)throw new Error(`metadata length ${f.length} exceeds maximum of 255`);const g=this.USER_BROADCAST_PUSH_META_LENGTH+u.length+c.length+o.length+d.length+f.length,v=new ArrayBuffer(this.HEADER_LENGTH+g);let x=new DataView(v),w=0;x.setUint8(w++,this.KINDS.userBroadcastPush),x.setUint8(w++,u.length),x.setUint8(w++,c.length),x.setUint8(w++,o.length),x.setUint8(w++,d.length),x.setUint8(w++,f.length),x.setUint8(w++,r),Array.from(u,S=>x.setUint8(w++,S.charCodeAt(0))),Array.from(c,S=>x.setUint8(w++,S.charCodeAt(0))),Array.from(o,S=>x.setUint8(w++,S.charCodeAt(0))),Array.from(d,S=>x.setUint8(w++,S.charCodeAt(0))),Array.from(f,S=>x.setUint8(w++,S.charCodeAt(0)));var b=new Uint8Array(v.byteLength+n.byteLength);return b.set(new Uint8Array(v),0),b.set(new Uint8Array(n),v.byteLength),b.buffer}decode(e,r){if(this._isArrayBuffer(e)){let n=this._binaryDecode(e);return r(n)}if(typeof e=="string"){const n=JSON.parse(e),[i,a,o,c,u]=n;return r({join_ref:i,ref:a,topic:o,event:c,payload:u})}return r({})}_binaryDecode(e){const r=new DataView(e),n=r.getUint8(0),i=new TextDecoder;switch(n){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,r,i)}}_decodeUserBroadcast(e,r,n){const i=r.getUint8(1),a=r.getUint8(2),o=r.getUint8(3),c=r.getUint8(4);let u=this.HEADER_LENGTH+4;const d=n.decode(e.slice(u,u+i));u=u+i;const p=n.decode(e.slice(u,u+a));u=u+a;const f=n.decode(e.slice(u,u+o));u=u+o;const g=e.slice(u,e.byteLength),v=c===this.JSON_ENCODING?JSON.parse(n.decode(g)):g,x={type:this.BROADCAST_EVENT,event:p,payload:v};return o>0&&(x.meta=JSON.parse(f)),{join_ref:null,ref:null,topic:d,event:this.BROADCAST_EVENT,payload:x}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e==null?void 0:e.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([n])=>r.includes(n)))}}var At;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(At||(At={}));const sE=(t,e,r={})=>{var n;const i=(n=r.skipTypes)!==null&&n!==void 0?n:[];return e?Object.keys(e).reduce((a,o)=>(a[o]=p6(o,t,e,i),a),{}):{}},p6=(t,e,r,n)=>{const i=e.find(c=>c.name===t),a=i==null?void 0:i.type,o=r[t];return a&&!n.includes(a)?BP(a,o):Yb(o)},BP=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return v6(e,r)}switch(t){case At.bool:return m6(e);case At.float4:case At.float8:case At.int2:case At.int4:case At.int8:case At.numeric:case At.oid:return g6(e);case At.json:case At.jsonb:return y6(e);case At.timestamp:return b6(e);case At.abstime:case At.date:case At.daterange:case At.int4range:case At.int8range:case At.money:case At.reltime:case At.text:case At.time:case At.timestamptz:case At.timetz:case At.tsrange:case At.tstzrange:return Yb(e);default:return Yb(e)}},Yb=t=>t,m6=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},g6=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},y6=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},v6=(t,e)=>{if(typeof t!="string")return t;const r=t.length-1,n=t[r];if(t[0]==="{"&&n==="}"){let a;const o=t.slice(1,r);try{a=JSON.parse("["+o+"]")}catch{a=o?o.split(","):[]}return a.map(c=>BP(e,c))}return t},b6=t=>typeof t=="string"?t.replace(" ","T"):t,UP=t=>{const e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var Pc=t=>typeof t=="function"?t:function(){return t},x6=typeof self<"u"?self:null,Ns=typeof window<"u"?window:null,bi=x6||Ns||globalThis,w6="2.0.0",_6=1e4,S6=1e3,xi={connecting:0,open:1,closing:2,closed:3},Xr={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Bi={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Jb={longpoll:"longpoll",websocket:"websocket"},k6={complete:4},Zb="base64url.bearer.phx.",sf=class{constructor(t,e,r,n){this.channel=t,this.event=e,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=n,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(t){this.timeout=t,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(n=>n.status===t).forEach(n=>n.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},qP=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},E6=class{constructor(t,e,r){this.state=Xr.closed,this.topic=t,this.params=Pc(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new sf(this,Bi.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new qP(()=>{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=Xr.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(n=>n.send()),this.pushBuffer=[]}),this.joinPush.receive("error",n=>{this.state=Xr.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=Xr.closed,this.socket.remove(this)}),this.onError(n=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.isJoining()&&this.joinPush.reset(),this.state=Xr.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 sf(this,Bi.leave,Pc({}),this.timeout).send(),this.state=Xr.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(Bi.reply,(n,i)=>{this.trigger(this.replyEventName(i),n)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Xr.closed,this.bindings=[]}onClose(t){this.on(Bi.close,t)}onError(t){return this.on(Bi.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let n=new sf(this,t,function(){return e},r);return this.canPush()?n.send():(n.startTimeout(),this.pushBuffer.push(n)),n}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Xr.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(Bi.close,"leave")},r=new sf(this,Bi.leave,Pc({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return!0}isMember(t,e,r,n){return this.topic!==t?!1:n&&n!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:n}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Xr.joining,this.joinPush.resend(t))}trigger(t,e,r,n){let i=this.onMessage(t,e,r,n);if(e&&!i)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let a=this.bindings.filter(o=>o.event===t&&this.filterBindings(o,e,r));for(let o=0;o<a.length;o++)a[o].callback(i,r,n||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===Xr.closed}isErrored(){return this.state===Xr.errored}isJoined(){return this.state===Xr.joined}isJoining(){return this.state===Xr.joining}isLeaving(){return this.state===Xr.leaving}},Bf=class{static request(t,e,r,n,i,a,o){if(bi.XDomainRequest){let c=new bi.XDomainRequest;return this.xdomainRequest(c,t,e,n,i,a,o)}else if(bi.XMLHttpRequest){let c=new bi.XMLHttpRequest;return this.xhrRequest(c,t,e,r,n,i,a,o)}else{if(bi.fetch&&bi.AbortController)return this.fetchRequest(t,e,r,n,i,a,o);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,n,i,a,o){let c={method:t,headers:r,body:n},u=null;return i&&(u=new AbortController,setTimeout(()=>u.abort(),i),c.signal=u.signal),bi.fetch(e,c).then(d=>d.text()).then(d=>this.parseJSON(d)).then(d=>o&&o(d)).catch(d=>{d.name==="AbortError"&&a?a():o&&o(null)}),u}static xdomainRequest(t,e,r,n,i,a,o){return t.timeout=i,t.open(e,r),t.onload=()=>{let c=this.parseJSON(t.responseText);o&&o(c)},a&&(t.ontimeout=a),t.onprogress=()=>{},t.send(n),t}static xhrRequest(t,e,r,n,i,a,o,c){t.open(e,r,!0),t.timeout=a;for(let[u,d]of Object.entries(n))t.setRequestHeader(u,d);return t.onerror=()=>c&&c(null),t.onreadystatechange=()=>{if(t.readyState===k6.complete&&c){let u=this.parseJSON(t.responseText);c(u)}},o&&(t.ontimeout=o),t.send(i),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let i=e?`${e}[${n}]`:n,a=t[n];typeof a=="object"?r.push(this.serialize(a,i)):r.push(encodeURIComponent(i)+"="+encodeURIComponent(a))}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return`${t}${r}${this.serialize(e)}`}},O6=t=>{let e="",r=new Uint8Array(t),n=r.byteLength;for(let i=0;i<n;i++)e+=String.fromCharCode(r[i]);return btoa(e)},xs=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(Zb)&&(this.authToken=atob(e[1].slice(Zb.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=xi.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+Jb.websocket),"$1/"+Jb.longpoll)}endpointURL(){return Bf.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=xi.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===xi.open||this.readyState===xi.connecting}poll(){const t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:n,messages:i}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=n}else r=0;switch(r){case 200:i.forEach(a=>{setTimeout(()=>this.onmessage({data:a}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=xi.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}})}send(t){typeof t!="string"&&(t=O6(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},t.join(`
|
|
394
|
-
`),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(t,e,r){for(let i of this.reqs)i.abort();this.readyState=xi.closed;let n=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",n)):this.onclose(n)}ajax(t,e,r,n,i){let a,o=()=>{this.reqs.delete(a),n()};a=Bf.request(t,this.endpointURL(),e,r,this.timeout,o,c=>{this.reqs.delete(a),this.isActive()&&i(c)}),this.reqs.add(a)}},A6=class Ac{constructor(e,r={}){let n=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(n.state,i=>{let{onJoin:a,onLeave:o,onSync:c}=this.caller;this.joinRef=this.channel.joinRef(),this.state=Ac.syncState(this.state,i,a,o),this.pendingDiffs.forEach(u=>{this.state=Ac.syncDiff(this.state,u,a,o)}),this.pendingDiffs=[],c()}),this.channel.on(n.diff,i=>{let{onJoin:a,onLeave:o,onSync:c}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=Ac.syncDiff(this.state,i,a,o),c())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return Ac.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,n,i){let a=this.clone(e),o={},c={};return this.map(a,(u,d)=>{r[u]||(c[u]=d)}),this.map(r,(u,d)=>{let p=a[u];if(p){let f=d.metas.map(w=>w.phx_ref),g=p.metas.map(w=>w.phx_ref),v=d.metas.filter(w=>g.indexOf(w.phx_ref)<0),x=p.metas.filter(w=>f.indexOf(w.phx_ref)<0);v.length>0&&(o[u]=d,o[u].metas=v),x.length>0&&(c[u]=this.clone(p),c[u].metas=x)}else o[u]=d}),this.syncDiff(a,{joins:o,leaves:c},n,i)}static syncDiff(e,r,n,i){let{joins:a,leaves:o}=this.clone(r);return n||(n=function(){}),i||(i=function(){}),this.map(a,(c,u)=>{let d=e[c];if(e[c]=this.clone(u),d){let p=e[c].metas.map(g=>g.phx_ref),f=d.metas.filter(g=>p.indexOf(g.phx_ref)<0);e[c].metas.unshift(...f)}n(c,d,u)}),this.map(o,(c,u)=>{let d=e[c];if(!d)return;let p=u.metas.map(f=>f.phx_ref);d.metas=d.metas.filter(f=>p.indexOf(f.phx_ref)<0),i(c,d,u),d.metas.length===0&&delete e[c]}),e}static list(e,r){return r||(r=function(n,i){return i}),this.map(e,(n,i)=>r(n,i))}static map(e,r){return Object.getOwnPropertyNames(e).map(n=>r(n,e[n]))}static clone(e){return JSON.parse(JSON.stringify(e))}},lf={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,n,i,a,o]=JSON.parse(t);return e({join_ref:r,ref:n,topic:i,event:a,payload:o})}},binaryEncode(t){let{join_ref:e,ref:r,event:n,topic:i,payload:a}=t,o=this.META_LENGTH+e.length+r.length+i.length+n.length,c=new ArrayBuffer(this.HEADER_LENGTH+o),u=new DataView(c),d=0;u.setUint8(d++,this.KINDS.push),u.setUint8(d++,e.length),u.setUint8(d++,r.length),u.setUint8(d++,i.length),u.setUint8(d++,n.length),Array.from(e,f=>u.setUint8(d++,f.charCodeAt(0))),Array.from(r,f=>u.setUint8(d++,f.charCodeAt(0))),Array.from(i,f=>u.setUint8(d++,f.charCodeAt(0))),Array.from(n,f=>u.setUint8(d++,f.charCodeAt(0)));var p=new Uint8Array(c.byteLength+a.byteLength);return p.set(new Uint8Array(c),0),p.set(new Uint8Array(a),c.byteLength),p.buffer},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),n=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,n);case this.KINDS.reply:return this.decodeReply(t,e,n);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,n)}},decodePush(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),a=e.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,c=r.decode(t.slice(o,o+n));o=o+n;let u=r.decode(t.slice(o,o+i));o=o+i;let d=r.decode(t.slice(o,o+a));o=o+a;let p=t.slice(o,t.byteLength);return{join_ref:c,ref:null,topic:u,event:d,payload:p}},decodeReply(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),a=e.getUint8(3),o=e.getUint8(4),c=this.HEADER_LENGTH+this.META_LENGTH,u=r.decode(t.slice(c,c+n));c=c+n;let d=r.decode(t.slice(c,c+i));c=c+i;let p=r.decode(t.slice(c,c+a));c=c+a;let f=r.decode(t.slice(c,c+o));c=c+o;let g=t.slice(c,t.byteLength),v={status:f,response:g};return{join_ref:u,ref:d,topic:p,event:Bi.reply,payload:v}},decodeBroadcast(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),a=this.HEADER_LENGTH+2,o=r.decode(t.slice(a,a+n));a=a+n;let c=r.decode(t.slice(a,a+i));a=a+i;let u=t.slice(a,t.byteLength);return{join_ref:null,ref:null,topic:o,event:c,payload:u}}},T6=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||_6,this.transport=e.transport||bi.WebSocket||xs,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null;let r=null;try{r=bi&&bi.sessionStorage}catch{}this.sessionStore=e.sessionStorage||r,this.establishedConnections=0,this.defaultEncoder=lf.encode.bind(lf),this.defaultDecoder=lf.decode.bind(lf),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==xs?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let n=null;Ns&&Ns.addEventListener&&(Ns.addEventListener("pagehide",i=>{this.conn&&(this.disconnect(),n=this.connectClock)}),Ns.addEventListener("pageshow",i=>{n===this.connectClock&&(n=null,this.connect())}),Ns.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=i=>e.rejoinAfterMs?e.rejoinAfterMs(i):[1e3,2e3,5e3][i-1]||1e4,this.reconnectAfterMs=i=>e.reconnectAfterMs?e.reconnectAfterMs(i):[10,50,100,150,200,250,500,1e3,2e3][i-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(i,a,o)=>{console.log(`${i}: ${a}`,o)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=Pc(e.params||{}),this.endPoint=`${t}/${Jb.websocket}`,this.vsn=e.vsn||w6,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new qP(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken}getLongPollTransport(){return xs}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=Bf.appendParams(Bf.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,t&&t()},e,r)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Pc(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==xs?this.connectWithFallback(xs,this.longPollFallbackMs):this.transportConnect())}log(t,e,r){this.logger&&this.logger(t,e,r)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let n=this.onMessage(i=>{i.ref===e&&(this.off([n]),t(Date.now()-r))});return!0}transportName(t){switch(t){case xs:return"LongPoll";default:return t.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${Zb}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=!1,n=!0,i,a,o=this.transportName(t),c=u=>{this.log("transport",`falling back to ${o}...`,u),this.off([i,a]),n=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${o}`))return c("memorized");this.fallbackTimer=setTimeout(c,e),a=this.onError(u=>{this.log("transport","error",u),n&&!r&&(clearTimeout(this.fallbackTimer),c(u))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!n){let u=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${u}`,"true"),this.log("transport",`established ${u} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(c,e),this.ping(u=>{this.log("transport","connected to primary after",u),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(new Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),S6,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,r){if(!this.conn)return t&&t();const n=this.conn;this.waitForBufferDone(n,()=>{e?n.close(e,r||""):n.close(),this.waitForSocketClosed(n,()=>{this.conn===n&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1)},150*r)}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===xi.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1)},150*r)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(t),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport","error",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError(t)}triggerChanError(t){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(Bi.error,t)})}connectionState(){switch(this.conn&&this.conn.readyState){case xi.connecting:return"connecting";case xi.open:return"open";case xi.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1)}channel(t,e={}){let r=new E6(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:n,ref:i,join_ref:a}=t;this.log("push",`${e} ${r} (${a}, ${i})`,n)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:n,payload:i,ref:a,join_ref:o}=e;if(a&&a===this.pendingHeartbeatRef){const c=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(i.status==="ok"?"ok":"error",c)}catch(u){this.log("error","error in heartbeat callback",u)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${i.status||""} ${r} ${n} ${a&&"("+a+")"||""}`.trim(),i);for(let c=0;c<this.channels.length;c++){const u=this.channels[c];u.isMember(r,n,i,o)&&u.trigger(n,i,a,o)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,n])=>{try{n(...e)}catch(i){this.log("error",`error in ${t} callback`,i)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};class Rc{constructor(e,r){const n=C6(r);this.presence=new A6(e.getChannel(),n),this.presence.onJoin((i,a,o)=>{const c=Rc.onJoinPayload(i,a,o);e.getChannel().trigger("presence",c)}),this.presence.onLeave((i,a,o)=>{const c=Rc.onLeavePayload(i,a,o);e.getChannel().trigger("presence",c)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return Rc.transformState(this.presence.state)}static transformState(e){return e=j6(e),Object.getOwnPropertyNames(e).reduce((r,n)=>{const i=e[n];return r[n]=Cf(i),r},{})}static onJoinPayload(e,r,n){const i=lE(r),a=Cf(n);return{event:"join",key:e,currentPresences:i,newPresences:a}}static onLeavePayload(e,r,n){const i=lE(r),a=Cf(n);return{event:"leave",key:e,currentPresences:i,leftPresences:a}}}function Cf(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function j6(t){return JSON.parse(JSON.stringify(t))}function C6(t){return(t==null?void 0:t.events)&&{events:t.events}}function lE(t){return t!=null&&t.metas?Cf(t):[]}var cE;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(cE||(cE={}));class N6{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new Rc(this.channel.channelAdapter,r)}}function P6(t){if(t instanceof Error)return t;if(typeof t=="string")return new Error(t);if(t&&typeof t=="object"){const e=t;if(typeof e.code=="number"){const r=typeof e.reason=="string"&&e.reason?` (${e.reason})`:"";return new Error(`socket closed: ${e.code}${r}`,{cause:t})}return new Error("channel error: transport failure",{cause:t})}return new Error("channel error: connection lost")}class R6{constructor(e,r,n){const i=I6(n);this.channel=e.getSocket().channel(r,i),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,r,n){let i;try{i=this.channel.push(e,r,n)}catch{throw new Error(`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>f6){const a=this.channel.pushBuffer.shift();a.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${a.event}`,a.payload())}return i}updateJoinPayload(e){const r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===Ca.joined}isJoined(){return this.state===Ca.joined}isJoining(){return this.state===Ca.joining}isClosed(){return this.state===Ca.closed}isLeaving(){return this.state===Ca.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}function I6(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var uE;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(uE||(uE={}));var Is;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(Is||(Is={}));var Ui;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(Ui||(Ui={}));class Ic{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},n){var i,a;if(this.topic=e,this.params=r,this.socket=n,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new R6(this.socket.socketAdapter,e,this.params),this.presence=new N6(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=UP(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((a=(i=this.params.config)===null||i===void 0?void 0:i.broadcast)===null||a===void 0)&&a.replay))throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,r=this.timeout){var n,i,a;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:o,presence:c,private:u}}=this.params,d=(i=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(v=>v.filter))!==null&&i!==void 0?i:[],p=!!this.bindings[Is.PRESENCE]&&this.bindings[Is.PRESENCE].length>0||((a=this.params.config.presence)===null||a===void 0?void 0:a.enabled)===!0,f={},g={broadcast:o,presence:Object.assign(Object.assign({},c),{enabled:p}),postgres_changes:d,private:u};this.socket.accessTokenValue&&(f.access_token=this.socket.accessTokenValue),this._onError(v=>{e==null||e(Ui.CHANNEL_ERROR,P6(v))}),this._onClose(()=>e==null?void 0:e(Ui.CLOSED)),this.updateJoinPayload(Object.assign({config:g},f)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:v})=>{if(this.socket._isManualToken()||this.socket.setAuth(),v===void 0){e==null||e(Ui.SUBSCRIBED);return}this._updatePostgresBindings(v,e)}).receive("error",v=>{this.state=Ca.errored;const x=Object.values(v).join(", ")||"error";e==null||e(Ui.CHANNEL_ERROR,new Error(x,{cause:v}))}).receive("timeout",()=>{e==null||e(Ui.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var n;const i=this.bindings.postgres_changes,a=(n=i==null?void 0:i.length)!==null&&n!==void 0?n:0,o=[];for(let c=0;c<a;c++){const u=i[c],{filter:{event:d,schema:p,table:f,filter:g}}=u,v=e&&e[c];if(v&&v.event===d&&Ic.isFilterValueEqual(v.schema,p)&&Ic.isFilterValueEqual(v.table,f)&&Ic.isFilterValueEqual(v.filter,g))o.push(Object.assign(Object.assign({},u),{id:v.id}));else{this.unsubscribe(),this.state=Ca.errored,r==null||r(Ui.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=o,this.state!=Ca.errored&&r&&r(Ui.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,n){const i=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),a=e===Is.PRESENCE||e===Is.POSTGRES_CHANGES;if(i&&a)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,r,n)}async httpSend(e,r,n={}){var i;if(r==null)return Promise.reject(new Error("Payload is required for httpSend()"));const a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);const o={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},c=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(i=n.timeout)!==null&&i!==void 0?i:this.timeout);if(c.status===202)return{success:!0};let u=c.statusText;try{const d=await c.json();u=d.error||d.message||u}catch{}return Promise.reject(new Error(u))}async send(e,r={}){var n,i;if(!this.channelAdapter.canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:a,payload:o}=e,c={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(c.Authorization=`Bearer ${this.socket.accessTokenValue}`);const u={method:"POST",headers:c,body:JSON.stringify({messages:[{topic:this.subTopic,event:a,payload:o,private:this.private}]})};try{const d=await this._fetchWithTimeout(this.broadcastEndpointURL,u,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((i=d.body)===null||i===void 0?void 0:i.cancel()),d.ok?"ok":"error"}catch(d){return d instanceof Error&&d.name==="AbortError"?"timed out":"error"}}else return new Promise(a=>{var o,c,u;const d=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((u=(c=(o=this.params)===null||o===void 0?void 0:o.config)===null||c===void 0?void 0:c.broadcast)===null||u===void 0)&&u.ack)&&a("ok"),d.receive("ok",()=>a("ok")),d.receive("error",()=>a("error")),d.receive("timeout",()=>a("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,n){const i=new AbortController,a=setTimeout(()=>i.abort(),n),o=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:i.signal}));return clearTimeout(a),o}_on(e,r,n){const i=e.toLocaleLowerCase(),a=this.channelAdapter.on(e,n),o={type:i,filter:r,callback:n,ref:a};return this.bindings[i]?this.bindings[i].push(o):this.bindings[i]=[o],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,n)=>{var i,a,o,c,u,d,p;const f=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(f,n))return!1;const g=(i=this.bindings[f])===null||i===void 0?void 0:i.find(v=>v.ref===e.ref);if(!g)return!0;if(["broadcast","presence","postgres_changes"].includes(f))if("id"in g){const v=g.id,x=(a=g.filter)===null||a===void 0?void 0:a.event;return v&&((o=r.ids)===null||o===void 0?void 0:o.includes(v))&&(x==="*"||(x==null?void 0:x.toLocaleLowerCase())===((c=r.data)===null||c===void 0?void 0:c.type.toLocaleLowerCase()))}else{const v=(d=(u=g==null?void 0:g.filter)===null||u===void 0?void 0:u.event)===null||d===void 0?void 0:d.toLocaleLowerCase();return v==="*"||v===((p=r==null?void 0:r.event)===null||p===void 0?void 0:p.toLocaleLowerCase())}else return g.type.toLocaleLowerCase()===f})}_notThisChannelEvent(e,r){const{close:n,error:i,leave:a,join:o}=zP;return r&&[n,i,a,o].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,n)=>{if(typeof r=="object"&&"ids"in r){const i=r.data,{schema:a,table:o,commit_timestamp:c,type:u,errors:d}=i;return Object.assign(Object.assign({},{schema:a,table:o,commit_timestamp:c,eventType:u,new:{},old:{},errors:d}),this._getPayloadRecords(i))}return r})}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(const r in e.bindings)for(const n of e.bindings[r])this._on(n.type,n.filter,n.callback)}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=sE(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=sE(e.columns,e.old_record)),r}}class $6{constructor(e,r){this.socket=new T6(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,n,i=1e4){return new Promise(a=>{setTimeout(()=>a("timeout"),i),this.socket.disconnect(()=>{e(),a("ok")},r,n)})}push(e){this.socket.push(e)}log(e,r,n){this.socket.log(e,r,n)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==Xb.connecting}isDisconnecting(){return this.socket.connectionState()==Xb.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const dE={HEARTBEAT_INTERVAL:25e3},M6=[1e3,2e3,5e3,1e4],L6=1e4;function D6(){const t=new Map;return{get length(){return t.size},clear(){t.clear()},getItem(e){return t.has(e)?t.get(e):null},key(e){var r;return(r=Array.from(t.keys())[e])!==null&&r!==void 0?r:null},removeItem(e){t.delete(e)},setItem(e,r){t.set(e,String(r))}}}function z6(){try{if(typeof globalThis<"u"&&globalThis.sessionStorage)return globalThis.sessionStorage}catch{}return D6()}const B6=`
|
|
395
|
+
Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const O6="2.106.2",A6=`realtime-js/${O6}`,T6="1.0.0",QP="2.0.0",j6=QP,C6=1e4,N6=100,Ca={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},eR={close:"phx_close",error:"phx_error",join:"phx_join",leave:"phx_leave",access_token:"access_token"},Xb={connecting:"connecting",closing:"closing",closed:"closed"};class P6{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,n;const i=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,i)}_encodeJsonUserBroadcastPush(e){var r,n;const i=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:{},o=new TextEncoder().encode(JSON.stringify(i)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,r,n){var i,a;const o=e.topic,c=(i=e.ref)!==null&&i!==void 0?i:"",u=(a=e.join_ref)!==null&&a!==void 0?a:"",d=e.payload.event,p=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},f=Object.keys(p).length===0?"":JSON.stringify(p);if(u.length>255)throw new Error(`joinRef length ${u.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`ref length ${c.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`userEvent length ${d.length} exceeds maximum of 255`);if(f.length>255)throw new Error(`metadata length ${f.length} exceeds maximum of 255`);const g=this.USER_BROADCAST_PUSH_META_LENGTH+u.length+c.length+o.length+d.length+f.length,v=new ArrayBuffer(this.HEADER_LENGTH+g);let x=new DataView(v),w=0;x.setUint8(w++,this.KINDS.userBroadcastPush),x.setUint8(w++,u.length),x.setUint8(w++,c.length),x.setUint8(w++,o.length),x.setUint8(w++,d.length),x.setUint8(w++,f.length),x.setUint8(w++,r),Array.from(u,S=>x.setUint8(w++,S.charCodeAt(0))),Array.from(c,S=>x.setUint8(w++,S.charCodeAt(0))),Array.from(o,S=>x.setUint8(w++,S.charCodeAt(0))),Array.from(d,S=>x.setUint8(w++,S.charCodeAt(0))),Array.from(f,S=>x.setUint8(w++,S.charCodeAt(0)));var b=new Uint8Array(v.byteLength+n.byteLength);return b.set(new Uint8Array(v),0),b.set(new Uint8Array(n),v.byteLength),b.buffer}decode(e,r){if(this._isArrayBuffer(e)){let n=this._binaryDecode(e);return r(n)}if(typeof e=="string"){const n=JSON.parse(e),[i,a,o,c,u]=n;return r({join_ref:i,ref:a,topic:o,event:c,payload:u})}return r({})}_binaryDecode(e){const r=new DataView(e),n=r.getUint8(0),i=new TextDecoder;switch(n){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,r,i)}}_decodeUserBroadcast(e,r,n){const i=r.getUint8(1),a=r.getUint8(2),o=r.getUint8(3),c=r.getUint8(4);let u=this.HEADER_LENGTH+4;const d=n.decode(e.slice(u,u+i));u=u+i;const p=n.decode(e.slice(u,u+a));u=u+a;const f=n.decode(e.slice(u,u+o));u=u+o;const g=e.slice(u,e.byteLength),v=c===this.JSON_ENCODING?JSON.parse(n.decode(g)):g,x={type:this.BROADCAST_EVENT,event:p,payload:v};return o>0&&(x.meta=JSON.parse(f)),{join_ref:null,ref:null,topic:d,event:this.BROADCAST_EVENT,payload:x}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e==null?void 0:e.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([n])=>r.includes(n)))}}var At;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(At||(At={}));const cE=(t,e,r={})=>{var n;const i=(n=r.skipTypes)!==null&&n!==void 0?n:[];return e?Object.keys(e).reduce((a,o)=>(a[o]=R6(o,t,e,i),a),{}):{}},R6=(t,e,r,n)=>{const i=e.find(c=>c.name===t),a=i==null?void 0:i.type,o=r[t];return a&&!n.includes(a)?tR(a,o):Yb(o)},tR=(t,e)=>{if(t.charAt(0)==="_"){const r=t.slice(1,t.length);return L6(e,r)}switch(t){case At.bool:return I6(e);case At.float4:case At.float8:case At.int2:case At.int4:case At.int8:case At.numeric:case At.oid:return $6(e);case At.json:case At.jsonb:return M6(e);case At.timestamp:return D6(e);case At.abstime:case At.date:case At.daterange:case At.int4range:case At.int8range:case At.money:case At.reltime:case At.text:case At.time:case At.timestamptz:case At.timetz:case At.tsrange:case At.tstzrange:return Yb(e);default:return Yb(e)}},Yb=t=>t,I6=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}},$6=t=>{if(typeof t=="string"){const e=parseFloat(t);if(!Number.isNaN(e))return e}return t},M6=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},L6=(t,e)=>{if(typeof t!="string")return t;const r=t.length-1,n=t[r];if(t[0]==="{"&&n==="}"){let a;const o=t.slice(1,r);try{a=JSON.parse("["+o+"]")}catch{a=o?o.split(","):[]}return a.map(c=>tR(e,c))}return t},D6=t=>typeof t=="string"?t.replace(" ","T"):t,rR=t=>{const e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};var Pc=t=>typeof t=="function"?t:function(){return t},z6=typeof self<"u"?self:null,Ns=typeof window<"u"?window:null,bi=z6||Ns||globalThis,B6="2.0.0",U6=1e4,q6=1e3,xi={connecting:0,open:1,closing:2,closed:3},Xr={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Bi={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Jb={longpoll:"longpoll",websocket:"websocket"},F6={complete:4},Zb="base64url.bearer.phx.",sf=class{constructor(t,e,r,n){this.channel=t,this.event=e,this.payload=r||function(){return{}},this.receivedResp=null,this.timeout=n,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(t){this.timeout=t,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(n=>n.status===t).forEach(n=>n.callback(e))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e})}},nR=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},H6=class{constructor(t,e,r){this.state=Xr.closed,this.topic=t,this.params=Pc(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new sf(this,Bi.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new nR(()=>{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=Xr.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(n=>n.send()),this.pushBuffer=[]}),this.joinPush.receive("error",n=>{this.state=Xr.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=Xr.closed,this.socket.remove(this)}),this.onError(n=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.isJoining()&&this.joinPush.reset(),this.state=Xr.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 sf(this,Bi.leave,Pc({}),this.timeout).send(),this.state=Xr.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(Bi.reply,(n,i)=>{this.trigger(this.replyEventName(i),n)})}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Xr.closed,this.bindings=[]}onClose(t){this.on(Bi.close,t)}onError(t){return this.on(Bi.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let n=new sf(this,t,function(){return e},r);return this.canPush()?n.send():(n.startTimeout(),this.pushBuffer.push(n)),n}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Xr.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(Bi.close,"leave")},r=new sf(this,Bi.leave,Pc({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return!0}isMember(t,e,r,n){return this.topic!==t?!1:n&&n!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:n}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Xr.joining,this.joinPush.resend(t))}trigger(t,e,r,n){let i=this.onMessage(t,e,r,n);if(e&&!i)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let a=this.bindings.filter(o=>o.event===t&&this.filterBindings(o,e,r));for(let o=0;o<a.length;o++)a[o].callback(i,r,n||this.joinRef())}replyEventName(t){return`chan_reply_${t}`}isClosed(){return this.state===Xr.closed}isErrored(){return this.state===Xr.errored}isJoined(){return this.state===Xr.joined}isJoining(){return this.state===Xr.joining}isLeaving(){return this.state===Xr.leaving}},Uf=class{static request(t,e,r,n,i,a,o){if(bi.XDomainRequest){let c=new bi.XDomainRequest;return this.xdomainRequest(c,t,e,n,i,a,o)}else if(bi.XMLHttpRequest){let c=new bi.XMLHttpRequest;return this.xhrRequest(c,t,e,r,n,i,a,o)}else{if(bi.fetch&&bi.AbortController)return this.fetchRequest(t,e,r,n,i,a,o);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,n,i,a,o){let c={method:t,headers:r,body:n},u=null;return i&&(u=new AbortController,setTimeout(()=>u.abort(),i),c.signal=u.signal),bi.fetch(e,c).then(d=>d.text()).then(d=>this.parseJSON(d)).then(d=>o&&o(d)).catch(d=>{d.name==="AbortError"&&a?a():o&&o(null)}),u}static xdomainRequest(t,e,r,n,i,a,o){return t.timeout=i,t.open(e,r),t.onload=()=>{let c=this.parseJSON(t.responseText);o&&o(c)},a&&(t.ontimeout=a),t.onprogress=()=>{},t.send(n),t}static xhrRequest(t,e,r,n,i,a,o,c){t.open(e,r,!0),t.timeout=a;for(let[u,d]of Object.entries(n))t.setRequestHeader(u,d);return t.onerror=()=>c&&c(null),t.onreadystatechange=()=>{if(t.readyState===F6.complete&&c){let u=this.parseJSON(t.responseText);c(u)}},o&&(t.ontimeout=o),t.send(i),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let i=e?`${e}[${n}]`:n,a=t[n];typeof a=="object"?r.push(this.serialize(a,i)):r.push(encodeURIComponent(i)+"="+encodeURIComponent(a))}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return`${t}${r}${this.serialize(e)}`}},W6=t=>{let e="",r=new Uint8Array(t),n=r.byteLength;for(let i=0;i<n;i++)e+=String.fromCharCode(r[i]);return btoa(e)},xs=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(Zb)&&(this.authToken=atob(e[1].slice(Zb.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=xi.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+Jb.websocket),"$1/"+Jb.longpoll)}endpointURL(){return Uf.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=xi.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===xi.open||this.readyState===xi.connecting}poll(){const t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:n,messages:i}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=n}else r=0;switch(r){case 200:i.forEach(a=>{setTimeout(()=>this.onmessage({data:a}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=xi.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}})}send(t){typeof t!="string"&&(t=W6(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(t){this.awaitingBatchAck=!0,this.ajax("POST",{"Content-Type":"application/x-ndjson"},t.join(`
|
|
396
|
+
`),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=!1,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",!1)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[])})}close(t,e,r){for(let i of this.reqs)i.abort();this.readyState=xi.closed;let n=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",n)):this.onclose(n)}ajax(t,e,r,n,i){let a,o=()=>{this.reqs.delete(a),n()};a=Uf.request(t,this.endpointURL(),e,r,this.timeout,o,c=>{this.reqs.delete(a),this.isActive()&&i(c)}),this.reqs.add(a)}},G6=class Ac{constructor(e,r={}){let n=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(n.state,i=>{let{onJoin:a,onLeave:o,onSync:c}=this.caller;this.joinRef=this.channel.joinRef(),this.state=Ac.syncState(this.state,i,a,o),this.pendingDiffs.forEach(u=>{this.state=Ac.syncDiff(this.state,u,a,o)}),this.pendingDiffs=[],c()}),this.channel.on(n.diff,i=>{let{onJoin:a,onLeave:o,onSync:c}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=Ac.syncDiff(this.state,i,a,o),c())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(e){return Ac.list(this.state,e)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,n,i){let a=this.clone(e),o={},c={};return this.map(a,(u,d)=>{r[u]||(c[u]=d)}),this.map(r,(u,d)=>{let p=a[u];if(p){let f=d.metas.map(w=>w.phx_ref),g=p.metas.map(w=>w.phx_ref),v=d.metas.filter(w=>g.indexOf(w.phx_ref)<0),x=p.metas.filter(w=>f.indexOf(w.phx_ref)<0);v.length>0&&(o[u]=d,o[u].metas=v),x.length>0&&(c[u]=this.clone(p),c[u].metas=x)}else o[u]=d}),this.syncDiff(a,{joins:o,leaves:c},n,i)}static syncDiff(e,r,n,i){let{joins:a,leaves:o}=this.clone(r);return n||(n=function(){}),i||(i=function(){}),this.map(a,(c,u)=>{let d=e[c];if(e[c]=this.clone(u),d){let p=e[c].metas.map(g=>g.phx_ref),f=d.metas.filter(g=>p.indexOf(g.phx_ref)<0);e[c].metas.unshift(...f)}n(c,d,u)}),this.map(o,(c,u)=>{let d=e[c];if(!d)return;let p=u.metas.map(f=>f.phx_ref);d.metas=d.metas.filter(f=>p.indexOf(f.phx_ref)<0),i(c,d,u),d.metas.length===0&&delete e[c]}),e}static list(e,r){return r||(r=function(n,i){return i}),this.map(e,(n,i)=>r(n,i))}static map(e,r){return Object.getOwnPropertyNames(e).map(n=>r(n,e[n]))}static clone(e){return JSON.parse(JSON.stringify(e))}},lf={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,n,i,a,o]=JSON.parse(t);return e({join_ref:r,ref:n,topic:i,event:a,payload:o})}},binaryEncode(t){let{join_ref:e,ref:r,event:n,topic:i,payload:a}=t,o=this.META_LENGTH+e.length+r.length+i.length+n.length,c=new ArrayBuffer(this.HEADER_LENGTH+o),u=new DataView(c),d=0;u.setUint8(d++,this.KINDS.push),u.setUint8(d++,e.length),u.setUint8(d++,r.length),u.setUint8(d++,i.length),u.setUint8(d++,n.length),Array.from(e,f=>u.setUint8(d++,f.charCodeAt(0))),Array.from(r,f=>u.setUint8(d++,f.charCodeAt(0))),Array.from(i,f=>u.setUint8(d++,f.charCodeAt(0))),Array.from(n,f=>u.setUint8(d++,f.charCodeAt(0)));var p=new Uint8Array(c.byteLength+a.byteLength);return p.set(new Uint8Array(c),0),p.set(new Uint8Array(a),c.byteLength),p.buffer},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),n=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,n);case this.KINDS.reply:return this.decodeReply(t,e,n);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,n)}},decodePush(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),a=e.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,c=r.decode(t.slice(o,o+n));o=o+n;let u=r.decode(t.slice(o,o+i));o=o+i;let d=r.decode(t.slice(o,o+a));o=o+a;let p=t.slice(o,t.byteLength);return{join_ref:c,ref:null,topic:u,event:d,payload:p}},decodeReply(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),a=e.getUint8(3),o=e.getUint8(4),c=this.HEADER_LENGTH+this.META_LENGTH,u=r.decode(t.slice(c,c+n));c=c+n;let d=r.decode(t.slice(c,c+i));c=c+i;let p=r.decode(t.slice(c,c+a));c=c+a;let f=r.decode(t.slice(c,c+o));c=c+o;let g=t.slice(c,t.byteLength),v={status:f,response:g};return{join_ref:u,ref:d,topic:p,event:Bi.reply,payload:v}},decodeBroadcast(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),a=this.HEADER_LENGTH+2,o=r.decode(t.slice(a,a+n));a=a+n;let c=r.decode(t.slice(a,a+i));a=a+i;let u=t.slice(a,t.byteLength);return{join_ref:null,ref:null,topic:o,event:c,payload:u}}},K6=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||U6,this.transport=e.transport||bi.WebSocket||xs,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null;let r=null;try{r=bi&&bi.sessionStorage}catch{}this.sessionStore=e.sessionStorage||r,this.establishedConnections=0,this.defaultEncoder=lf.encode.bind(lf),this.defaultDecoder=lf.decode.bind(lf),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==xs?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let n=null;Ns&&Ns.addEventListener&&(Ns.addEventListener("pagehide",i=>{this.conn&&(this.disconnect(),n=this.connectClock)}),Ns.addEventListener("pageshow",i=>{n===this.connectClock&&(n=null,this.connect())}),Ns.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??!0,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=i=>e.rejoinAfterMs?e.rejoinAfterMs(i):[1e3,2e3,5e3][i-1]||1e4,this.reconnectAfterMs=i=>e.reconnectAfterMs?e.reconnectAfterMs(i):[10,50,100,150,200,250,500,1e3,2e3][i-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(i,a,o)=>{console.log(`${i}: ${a}`,o)}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=Pc(e.params||{}),this.endPoint=`${t}/${Jb.websocket}`,this.vsn=e.vsn||B6,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new nR(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=e.authToken}getLongPollTransport(){return xs}replaceTransport(t){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=Uf.appendParams(Uf.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,t&&t()},e,r)}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Pc(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==xs?this.connectWithFallback(xs,this.longPollFallbackMs):this.transportConnect())}log(t,e,r){this.logger&&this.logger(t,e,r)}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t}ping(t){if(!this.isConnected())return!1;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let n=this.onMessage(i=>{i.ref===e&&(this.off([n]),t(Date.now()-r))});return!0}transportName(t){switch(t){case xs:return"LongPoll";default:return t.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let t;this.authToken&&(t=["phoenix",`${Zb}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e)}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=!1,n=!0,i,a,o=this.transportName(t),c=u=>{this.log("transport",`falling back to ${o}...`,u),this.off([i,a]),n=!1,this.replaceTransport(t),this.transportConnect()};if(this.getSession(`phx:fallback:${o}`))return c("memorized");this.fallbackTimer=setTimeout(c,e),a=this.onError(u=>{this.log("transport","error",u),n&&!r&&(clearTimeout(this.fallbackTimer),c(u))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=!0,!n){let u=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${u}`,"true"),this.log("transport",`established ${u} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(c,e),this.ping(u=>{this.log("transport","connected to primary after",u),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this.triggerChanError(new Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),q6,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(t,e,r){if(!this.conn)return t&&t();const n=this.conn;this.waitForBufferDone(n,()=>{e?n.close(e,r||""):n.close(),this.waitForSocketClosed(n,()=>{this.conn===n&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t()})})}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1)},150*r)}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===xi.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1)},150*r)}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(t),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t)}onConnError(t){this.hasLogger()&&this.log("transport","error",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError(t)}triggerChanError(t){this.channels.forEach(e=>{e.isErrored()||e.isLeaving()||e.isClosed()||e.trigger(Bi.error,t)})}connectionState(){switch(this.conn&&this.conn.readyState){case xi.connecting:return"connecting";case xi.open:return"open";case xi.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t)}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1)}channel(t,e={}){let r=new H6(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:n,ref:i,join_ref:a}=t;this.log("push",`${e} ${r} (${a}, ${i})`,n)}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)))}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:n,payload:i,ref:a,join_ref:o}=e;if(a&&a===this.pendingHeartbeatRef){const c=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(i.status==="ok"?"ok":"error",c)}catch(u){this.log("error","error in heartbeat callback",u)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${i.status||""} ${r} ${n} ${a&&"("+a+")"||""}`.trim(),i);for(let c=0;c<this.channels.length;c++){const u=this.channels[c];u.isMember(r,n,i,o)&&u.trigger(n,i,a,o)}this.triggerStateCallbacks("message",e)})}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,n])=>{try{n(...e)}catch(i){this.log("error",`error in ${t} callback`,i)}})}catch(r){this.log("error",`error triggering ${t} callbacks`,r)}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave())}};class Rc{constructor(e,r){const n=X6(r);this.presence=new G6(e.getChannel(),n),this.presence.onJoin((i,a,o)=>{const c=Rc.onJoinPayload(i,a,o);e.getChannel().trigger("presence",c)}),this.presence.onLeave((i,a,o)=>{const c=Rc.onLeavePayload(i,a,o);e.getChannel().trigger("presence",c)}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"})})}get state(){return Rc.transformState(this.presence.state)}static transformState(e){return e=V6(e),Object.getOwnPropertyNames(e).reduce((r,n)=>{const i=e[n];return r[n]=Cf(i),r},{})}static onJoinPayload(e,r,n){const i=uE(r),a=Cf(n);return{event:"join",key:e,currentPresences:i,newPresences:a}}static onLeavePayload(e,r,n){const i=uE(r),a=Cf(n);return{event:"leave",key:e,currentPresences:i,leftPresences:a}}}function Cf(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function V6(t){return JSON.parse(JSON.stringify(t))}function X6(t){return(t==null?void 0:t.events)&&{events:t.events}}function uE(t){return t!=null&&t.metas?Cf(t):[]}var dE;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(dE||(dE={}));class Y6{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new Rc(this.channel.channelAdapter,r)}}function J6(t){if(t instanceof Error)return t;if(typeof t=="string")return new Error(t);if(t&&typeof t=="object"){const e=t;if(typeof e.code=="number"){const r=typeof e.reason=="string"&&e.reason?` (${e.reason})`:"";return new Error(`socket closed: ${e.code}${r}`,{cause:t})}return new Error("channel error: transport failure",{cause:t})}return new Error("channel error: connection lost")}class Z6{constructor(e,r,n){const i=Q6(n);this.channel=e.getSocket().channel(r,i),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,r,n){let i;try{i=this.channel.push(e,r,n)}catch{throw new Error(`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>N6){const a=this.channel.pushBuffer.shift();a.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${a.event}`,a.payload())}return i}updateJoinPayload(e){const r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e)}canPush(){return this.socket.isConnected()&&this.state===Ca.joined}isJoined(){return this.state===Ca.joined}isJoining(){return this.state===Ca.joining}isClosed(){return this.state===Ca.closed}isLeaving(){return this.state===Ca.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}}function Q6(t){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config)}}var fE;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(fE||(fE={}));var Is;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(Is||(Is={}));var Ui;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(Ui||(Ui={}));class Ic{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},n){var i,a;if(this.topic=e,this.params=r,this.socket=n,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},r.config),this.channelAdapter=new Z6(this.socket.socketAdapter,e,this.params),this.presence=new Y6(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=rR(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((a=(i=this.params.config)===null||i===void 0?void 0:i.broadcast)===null||a===void 0)&&a.replay))throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,r=this.timeout){var n,i,a;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:o,presence:c,private:u}}=this.params,d=(i=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(v=>v.filter))!==null&&i!==void 0?i:[],p=!!this.bindings[Is.PRESENCE]&&this.bindings[Is.PRESENCE].length>0||((a=this.params.config.presence)===null||a===void 0?void 0:a.enabled)===!0,f={},g={broadcast:o,presence:Object.assign(Object.assign({},c),{enabled:p}),postgres_changes:d,private:u};this.socket.accessTokenValue&&(f.access_token=this.socket.accessTokenValue),this._onError(v=>{e==null||e(Ui.CHANNEL_ERROR,J6(v))}),this._onClose(()=>e==null?void 0:e(Ui.CLOSED)),this.updateJoinPayload(Object.assign({config:g},f)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:v})=>{if(this.socket._isManualToken()||this.socket.setAuth(),v===void 0){e==null||e(Ui.SUBSCRIBED);return}this._updatePostgresBindings(v,e)}).receive("error",v=>{this.state=Ca.errored;const x=Object.values(v).join(", ")||"error";e==null||e(Ui.CHANNEL_ERROR,new Error(x,{cause:v}))}).receive("timeout",()=>{e==null||e(Ui.TIMED_OUT)})}return this}_updatePostgresBindings(e,r){var n;const i=this.bindings.postgres_changes,a=(n=i==null?void 0:i.length)!==null&&n!==void 0?n:0,o=[];for(let c=0;c<a;c++){const u=i[c],{filter:{event:d,schema:p,table:f,filter:g}}=u,v=e&&e[c];if(v&&v.event===d&&Ic.isFilterValueEqual(v.schema,p)&&Ic.isFilterValueEqual(v.table,f)&&Ic.isFilterValueEqual(v.filter,g))o.push(Object.assign(Object.assign({},u),{id:v.id}));else{this.unsubscribe(),this.state=Ca.errored,r==null||r(Ui.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=o,this.state!=Ca.errored&&r&&r(Ui.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,n){const i=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),a=e===Is.PRESENCE||e===Is.POSTGRES_CHANGES;if(i&&a)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,r,n)}async httpSend(e,r,n={}){var i;if(r==null)return Promise.reject(new Error("Payload is required for httpSend()"));const a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);const o={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},c=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(i=n.timeout)!==null&&i!==void 0?i:this.timeout);if(c.status===202)return{success:!0};let u=c.statusText;try{const d=await c.json();u=d.error||d.message||u}catch{}return Promise.reject(new Error(u))}async send(e,r={}){var n,i;if(!this.channelAdapter.canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:a,payload:o}=e,c={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(c.Authorization=`Bearer ${this.socket.accessTokenValue}`);const u={method:"POST",headers:c,body:JSON.stringify({messages:[{topic:this.subTopic,event:a,payload:o,private:this.private}]})};try{const d=await this._fetchWithTimeout(this.broadcastEndpointURL,u,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((i=d.body)===null||i===void 0?void 0:i.cancel()),d.ok?"ok":"error"}catch(d){return d instanceof Error&&d.name==="AbortError"?"timed out":"error"}}else return new Promise(a=>{var o,c,u;const d=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((u=(c=(o=this.params)===null||o===void 0?void 0:o.config)===null||c===void 0?void 0:c.broadcast)===null||u===void 0)&&u.ack)&&a("ok"),d.receive("ok",()=>a("ok")),d.receive("error",()=>a("error")),d.receive("timeout",()=>a("timed out"))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,r,n){const i=new AbortController,a=setTimeout(()=>i.abort(),n),o=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:i.signal}));return clearTimeout(a),o}_on(e,r,n){const i=e.toLocaleLowerCase(),a=this.channelAdapter.on(e,n),o={type:i,filter:r,callback:n,ref:a};return this.bindings[i]?this.bindings[i].push(o):this.bindings[i]=[o],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,n)=>{var i,a,o,c,u,d,p;const f=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(f,n))return!1;const g=(i=this.bindings[f])===null||i===void 0?void 0:i.find(v=>v.ref===e.ref);if(!g)return!0;if(["broadcast","presence","postgres_changes"].includes(f))if("id"in g){const v=g.id,x=(a=g.filter)===null||a===void 0?void 0:a.event;return v&&((o=r.ids)===null||o===void 0?void 0:o.includes(v))&&(x==="*"||(x==null?void 0:x.toLocaleLowerCase())===((c=r.data)===null||c===void 0?void 0:c.type.toLocaleLowerCase()))}else{const v=(d=(u=g==null?void 0:g.filter)===null||u===void 0?void 0:u.event)===null||d===void 0?void 0:d.toLocaleLowerCase();return v==="*"||v===((p=r==null?void 0:r.event)===null||p===void 0?void 0:p.toLocaleLowerCase())}else return g.type.toLocaleLowerCase()===f})}_notThisChannelEvent(e,r){const{close:n,error:i,leave:a,join:o}=eR;return r&&[n,i,a,o].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,n)=>{if(typeof r=="object"&&"ids"in r){const i=r.data,{schema:a,table:o,commit_timestamp:c,type:u,errors:d}=i;return Object.assign(Object.assign({},{schema:a,table:o,commit_timestamp:c,eventType:u,new:{},old:{},errors:d}),this._getPayloadRecords(i))}return r})}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(const r in e.bindings)for(const n of e.bindings[r])this._on(n.type,n.filter,n.callback)}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_getPayloadRecords(e){const r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=cE(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=cE(e.columns,e.old_record)),r}}class e8{constructor(e,r){this.socket=new K6(e,r)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,r,n,i=1e4){return new Promise(a=>{setTimeout(()=>a("timeout"),i),this.socket.disconnect(()=>{e(),a("ok")},r,n)})}push(e){this.socket.push(e)}log(e,r,n){this.socket.log(e,r,n)}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==Xb.connecting}isDisconnecting(){return this.socket.connectionState()==Xb.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const hE={HEARTBEAT_INTERVAL:25e3},t8=[1e3,2e3,5e3,1e4],r8=1e4;function n8(){const t=new Map;return{get length(){return t.size},clear(){t.clear()},getItem(e){return t.has(e)?t.get(e):null},key(e){var r;return(r=Array.from(t.keys())[e])!==null&&r!==void 0?r:null},removeItem(e){t.delete(e)},setItem(e,r){t.set(e,String(r))}}}function i8(){try{if(typeof globalThis<"u"&&globalThis.sessionStorage)return globalThis.sessionStorage}catch{}return n8()}const a8=`
|
|
395
397
|
addEventListener("message", (e) => {
|
|
396
398
|
if (e.data.event === "start") {
|
|
397
399
|
setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
|
|
398
400
|
}
|
|
399
|
-
});`;class
|
|
401
|
+
});`;class o8{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,r){var n;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 P6,this._manuallySetToken=!1,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=a=>a?(...o)=>a(...o):(...o)=>fetch(...o),!(!((n=r==null?void 0:r.params)===null||n===void 0)&&n.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;const i=this._initializeOptions(r);this.socketAdapter=new e8(e,i),this.httpEndpoint=rR(e),this.fetch=this._resolveFetch(r==null?void 0:r.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){const r=e.message;throw r.includes("Node.js")?new Error(`${r}
|
|
400
402
|
|
|
401
403
|
To use Realtime in Node.js, you need to provide a WebSocket implementation:
|
|
402
404
|
|
|
@@ -409,9 +411,9 @@ Option 2: Install and provide the "ws" package:
|
|
|
409
411
|
const client = new RealtimeClient(url, {
|
|
410
412
|
...options,
|
|
411
413
|
transport: ws
|
|
412
|
-
})`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this._cancelPendingDisconnect(),this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){const r=await e.unsubscribe();return r==="ok"&&e.teardown(),r}async removeAllChannels(){const e=this.channels.map(async n=>{const i=await n.unsubscribe();return n.teardown(),i}),r=await Promise.all(e);return await this.disconnect(),r}log(e,r,n){this.socketAdapter.log(e,r,n)}connectionState(){return this.socketAdapter.connectionState()||Xb.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){const n=`realtime:${e}`,i=this.getChannels().find(a=>a.topic===n);if(i)return i;{const a=new Ic(`realtime:${e}`,r,this);return this._cancelPendingDisconnect(),this.channels.push(a),a}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic),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(e=null){let r,n=!1;if(e)r=e,n=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(i){this.log("error","Error fetching access token from callback",i),r=this.accessTokenValue}else r=this.accessTokenValue;n?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(i=>{const a={access_token:r,version:l6};r&&i.updateJoinPayload(a),i.joinedOnce&&i.channelAdapter.isJoined()&&i.channelAdapter.push(zP.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,n)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,n)}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let r;if(e)r=e;else{const n=new Blob([B6],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}_initializeOptions(e){var r,n,i,a,o,c,u,d,p,f,g,v;this.worker=(r=e==null?void 0:e.worker)!==null&&r!==void 0?r:!1,this.accessToken=(n=e==null?void 0:e.accessToken)!==null&&n!==void 0?n:null;const x={};x.timeout=(i=e==null?void 0:e.timeout)!==null&&i!==void 0?i:d6,x.heartbeatIntervalMs=(a=e==null?void 0:e.heartbeatIntervalMs)!==null&&a!==void 0?a:dE.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=(o=e==null?void 0:e.disconnectOnEmptyChannelsAfterMs)!==null&&o!==void 0?o:2*((c=e==null?void 0:e.heartbeatIntervalMs)!==null&&c!==void 0?c:dE.HEARTBEAT_INTERVAL),x.transport=(u=e==null?void 0:e.transport)!==null&&u!==void 0?u:o6.getWebSocketConstructor(),x.params=e==null?void 0:e.params,x.logger=e==null?void 0:e.logger,x.heartbeatCallback=this._wrapHeartbeatCallback(e==null?void 0:e.heartbeatCallback),x.sessionStorage=(d=e==null?void 0:e.sessionStorage)!==null&&d!==void 0?d:z6(),x.reconnectAfterMs=(p=e==null?void 0:e.reconnectAfterMs)!==null&&p!==void 0?p:(A=>M6[A-1]||L6);let w,b;const S=(f=e==null?void 0:e.vsn)!==null&&f!==void 0?f:u6;switch(S){case c6:w=(A,O)=>O(JSON.stringify(A)),b=(A,O)=>O(JSON.parse(A));break;case DP:w=this.serializer.encode.bind(this.serializer),b=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${x.vsn}`)}if(x.vsn=S,x.encode=(g=e==null?void 0:e.encode)!==null&&g!==void 0?g:w,x.decode=(v=e==null?void 0:e.decode)!==null&&v!==void 0?v:b,x.beforeReconnect=this._reconnectAuth.bind(this),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,x.params=Object.assign(Object.assign({},x.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl,x.autoSendHeartbeat=!this.worker}return x}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var Fc=class extends Error{constructor(t,e){var r;super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&((r=e.icebergType)==null?void 0:r.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function q6(t,e,r){const n=new URL(e,t);if(r)for(const[i,a]of Object.entries(r))a!==void 0&&n.searchParams.set(i,a);return n.toString()}async function F6(t){return!t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function H6(t){const e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:n,query:i,body:a,headers:o}){const c=q6(t.baseUrl,n,i),u=await F6(t.auth),d=await e(c,{method:r,headers:{...a?{"Content-Type":"application/json"}:{},...u,...o},body:a?JSON.stringify(a):void 0}),p=await d.text(),f=(d.headers.get("content-type")||"").includes("application/json"),g=f&&p?JSON.parse(p):p;if(!d.ok){const v=f?g:void 0,x=v==null?void 0:v.error;throw new Fc((x==null?void 0:x.message)??`Request failed with status ${d.status}`,{status:d.status,icebergType:x==null?void 0:x.type,icebergCode:x==null?void 0:x.code,details:v})}return{status:d.status,headers:d.headers,data:g}}}}function cf(t){return t.join("")}var W6=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:cf(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(n=>({namespace:n}))}async createNamespace(t,e){const r={namespace:t.namespace,properties:e==null?void 0:e.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${cf(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${cf(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${cf(t.namespace)}`}),!0}catch(e){if(e instanceof Fc&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof Fc&&r.status===409)return;throw r}}};function ws(t){return t.join("")}var G6=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r}async listTables(t){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ws(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){const r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${ws(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){const r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${ws(t.namespace)}/tables/${t.name}`,body:e});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${ws(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String((e==null?void 0:e.purge)??!1)}})}async loadTable(t){const e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ws(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){const e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${ws(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof Fc&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof Fc&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},K6=class{constructor(t){var n;let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);const r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=H6({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=(n=t.accessDelegation)==null?void 0:n.join(","),this.namespaceOps=new W6(this.client,e),this.tableOps=new G6(this.client,e,this.accessDelegation)}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t)}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e)}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};function Hc(t){"@babel/helpers - typeof";return Hc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Hc(t)}function V6(t,e){if(Hc(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(Hc(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function X6(t){var e=V6(t,"string");return Hc(e)=="symbol"?e:e+""}function Y6(t,e,r){return(e=X6(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function fE(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function Be(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?fE(Object(r),!0).forEach(function(n){Y6(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):fE(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var np=class extends Error{constructor(t,e="storage",r,n){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=n}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};function ip(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var Qb=class extends np{constructor(t,e,r,n="storage"){super(t,n,e,r),this.name=n==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return Be({},super.toJSON())}},FP=class extends np{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};function Uf(t,e,r){const n=Be({},t),i=e.toLowerCase();for(const a of Object.keys(n))a.toLowerCase()===i&&delete n[a];return n[i]=r,n}function J6(t){const e={};for(const[r,n]of Object.entries(t))e[r.toLowerCase()]=n;return e}const Z6=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Q6=t=>{if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},ex=t=>{if(Array.isArray(t))return t.map(r=>ex(r));if(typeof t=="function"||t!==Object(t))return t;const e={};return Object.entries(t).forEach(([r,n])=>{const i=r.replace(/([-_][a-z])/gi,a=>a.toUpperCase().replace(/[-_]/g,""));e[i]=ex(n)}),e},e8=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t),hE=t=>{if(typeof t=="object"&&t!==null){const e=t;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error;if(typeof e.error=="object"&&e.error!==null){const r=e.error;if(typeof r.message=="string")return r.message}}return JSON.stringify(t)},t8=async(t,e,r,n)=>{if(t!==null&&typeof t=="object"&&"json"in t&&typeof t.json=="function"){const i=t;let a=parseInt(String(i.status),10);Number.isFinite(a)||(a=500),i.json().then(o=>{const c=(o==null?void 0:o.statusCode)||(o==null?void 0:o.code)||a+"";e(new Qb(hE(o),a,c,n))}).catch(()=>{const o=a+"";e(new Qb(i.statusText||`HTTP ${a} error`,a,o,n))})}else e(new FP(hE(t),t,n))},r8=(t,e,r,n)=>{const i={method:t,headers:(e==null?void 0:e.headers)||{}};if(t==="GET"||t==="HEAD"||!n)return Be(Be({},i),r);if(Q6(n)){var a;const o=(e==null?void 0:e.headers)||{};let c;for(const[u,d]of Object.entries(o))u.toLowerCase()==="content-type"&&(c=d);i.headers=Uf(o,"Content-Type",(a=c)!==null&&a!==void 0?a:"application/json"),i.body=JSON.stringify(n)}else i.body=n;return e!=null&&e.duplex&&(i.duplex=e.duplex),Be(Be({},i),r)};async function mc(t,e,r,n,i,a,o){return new Promise((c,u)=>{t(r,r8(e,n,i,a)).then(d=>{if(!d.ok)throw d;if(n!=null&&n.noResolveJson)return d;if(o==="vectors"){const p=d.headers.get("content-type");if(d.headers.get("content-length")==="0"||d.status===204)return{};if(!p||!p.includes("application/json"))return{}}return d.json()}).then(d=>c(d)).catch(d=>t8(d,u,n,o))})}function HP(t="storage"){return{get:async(e,r,n,i)=>mc(e,"GET",r,n,i,void 0,t),post:async(e,r,n,i,a)=>mc(e,"POST",r,i,a,n,t),put:async(e,r,n,i,a)=>mc(e,"PUT",r,i,a,n,t),head:async(e,r,n,i)=>mc(e,"HEAD",r,Be(Be({},n),{},{noResolveJson:!0}),i,void 0,t),remove:async(e,r,n,i,a)=>mc(e,"DELETE",r,i,a,n,t)}}const n8=HP("storage"),{get:Wc,post:Fn,put:tx,head:i8,remove:e1}=n8,cn=HP("vectors");var xl=class{constructor(t,e={},r,n="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=J6(e),this.fetch=Z6(r),this.namespace=n}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=Uf(this.headers,t,e),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(ip(r))return{data:null,error:r};throw r}}};let WP;WP=Symbol.toStringTag;var a8=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[WP]="StreamDownloadBuilder",this.promise=null}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ip(e))return{data:null,error:e};throw e}}};let GP;GP=Symbol.toStringTag;var o8=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[GP]="BlobDownloadBuilder",this.promise=null}asStream(){return new a8(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ip(e))return{data:null,error:e};throw e}}};const s8={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},pE={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var l8=class extends xl{constructor(t,e={},r,n){super(t,e,n,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,n){var i=this;return i.handleOperation(async()=>{let a;const o=Be(Be({},pE),n);let c=Be(Be({},i.headers),t==="POST"&&{"x-upsert":String(o.upsert)});const u=o.metadata;if(typeof Blob<"u"&&r instanceof Blob?(a=new FormData,a.append("cacheControl",o.cacheControl),u&&a.append("metadata",i.encodeMetadata(u)),a.append("",r)):typeof FormData<"u"&&r instanceof FormData?(a=r,a.has("cacheControl")||a.append("cacheControl",o.cacheControl),u&&!a.has("metadata")&&a.append("metadata",i.encodeMetadata(u))):(a=r,c["cache-control"]=`max-age=${o.cacheControl}`,c["content-type"]=o.contentType,u&&(c["x-metadata"]=i.toBase64(i.encodeMetadata(u))),(typeof ReadableStream<"u"&&a instanceof ReadableStream||a&&typeof a=="object"&&"pipe"in a&&typeof a.pipe=="function")&&!o.duplex&&(o.duplex="half")),n!=null&&n.headers)for(const[g,v]of Object.entries(n.headers))c=Uf(c,g,v);const d=i._removeEmptyFolders(e),p=i._getFinalPath(d),f=await(t=="PUT"?tx:Fn)(i.fetch,`${i.url}/object/${p}`,a,Be({headers:c},o!=null&&o.duplex?{duplex:o.duplex}:{}));return{path:d,id:f.Id,fullPath:f.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,n){var i=this;const a=i._removeEmptyFolders(t),o=i._getFinalPath(a),c=new URL(i.url+`/object/upload/sign/${o}`);return c.searchParams.set("token",e),i.handleOperation(async()=>{let u;const d=Be(Be({},pE),n);let p=Be(Be({},i.headers),{"x-upsert":String(d.upsert)});const f=d.metadata;if(typeof Blob<"u"&&r instanceof Blob?(u=new FormData,u.append("cacheControl",d.cacheControl),f&&u.append("metadata",i.encodeMetadata(f)),u.append("",r)):typeof FormData<"u"&&r instanceof FormData?(u=r,u.has("cacheControl")||u.append("cacheControl",d.cacheControl),f&&!u.has("metadata")&&u.append("metadata",i.encodeMetadata(f))):(u=r,p["cache-control"]=`max-age=${d.cacheControl}`,p["content-type"]=d.contentType,f&&(p["x-metadata"]=i.toBase64(i.encodeMetadata(f))),(typeof ReadableStream<"u"&&u instanceof ReadableStream||u&&typeof u=="object"&&"pipe"in u&&typeof u.pipe=="function")&&!d.duplex&&(d.duplex="half")),n!=null&&n.headers)for(const[g,v]of Object.entries(n.headers))p=Uf(p,g,v);return{path:a,fullPath:(await tx(i.fetch,c.toString(),u,Be({headers:p},d!=null&&d.duplex?{duplex:d.duplex}:{}))).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let n=r._getFinalPath(t);const i=Be({},r.headers);e!=null&&e.upsert&&(i["x-upsert"]="true");const a=await Fn(r.fetch,`${r.url}/object/upload/sign/${n}`,{},{headers:i}),o=new URL(r.url+a.url),c=o.searchParams.get("token");if(!c)throw new np("No token returned by API");return{signedUrl:o.toString(),path:t,token:c}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var n=this;return n.handleOperation(async()=>await Fn(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r==null?void 0:r.destinationBucket},{headers:n.headers}))}async copy(t,e,r){var n=this;return n.handleOperation(async()=>({path:(await Fn(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r==null?void 0:r.destinationBucket},{headers:n.headers})).Key}))}async createSignedUrl(t,e,r){var n=this;return n.handleOperation(async()=>{let i=n._getFinalPath(t);const a=typeof(r==null?void 0:r.transform)=="object"&&r.transform!==null&&Object.keys(r.transform).length>0;let o=await Fn(n.fetch,`${n.url}/object/sign/${i}`,Be({expiresIn:e},a?{transform:r.transform}:{}),{headers:n.headers});const c=new URLSearchParams;r!=null&&r.download&&c.set("download",r.download===!0?"":r.download),(r==null?void 0:r.cacheNonce)!=null&&c.set("cacheNonce",String(r.cacheNonce));const u=c.toString();return{signedUrl:encodeURI(`${n.url}${o.signedURL}${u?`&${u}`:""}`)}})}async createSignedUrls(t,e,r){var n=this;return n.handleOperation(async()=>{const i=await Fn(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:e,paths:t},{headers:n.headers}),a=new URLSearchParams;r!=null&&r.download&&a.set("download",r.download===!0?"":r.download),(r==null?void 0:r.cacheNonce)!=null&&a.set("cacheNonce",String(r.cacheNonce));const o=a.toString();return i.map(c=>Be(Be({},c),{},{signedUrl:c.signedURL?encodeURI(`${n.url}${c.signedURL}${o?`&${o}`:""}`):null}))})}download(t,e,r){const n=typeof(e==null?void 0:e.transform)=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image/authenticated":"object",i=new URLSearchParams;e!=null&&e.transform&&this.applyTransformOptsToQuery(i,e.transform),(e==null?void 0:e.cacheNonce)!=null&&i.set("cacheNonce",String(e.cacheNonce));const a=i.toString(),o=this._getFinalPath(t),c=()=>Wc(this.fetch,`${this.url}/${n}/${o}${a?`?${a}`:""}`,{headers:this.headers,noResolveJson:!0},r);return new o8(c,this.shouldThrowOnError)}async info(t){var e=this;const r=e._getFinalPath(t);return e.handleOperation(async()=>ex(await Wc(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;const r=e._getFinalPath(t);try{return await i8(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(i){if(e.shouldThrowOnError)throw i;if(ip(i)){var n;const a=i instanceof Qb?i.status:i instanceof FP?(n=i.originalError)===null||n===void 0?void 0:n.status:void 0;if(a!==void 0&&[400,404].includes(a))return{data:!1,error:i}}throw i}}getPublicUrl(t,e){const r=this._getFinalPath(t),n=new URLSearchParams;e!=null&&e.download&&n.set("download",e.download===!0?"":e.download),e!=null&&e.transform&&this.applyTransformOptsToQuery(n,e.transform),(e==null?void 0:e.cacheNonce)!=null&&n.set("cacheNonce",String(e.cacheNonce));const i=n.toString(),a=typeof(e==null?void 0:e.transform)=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}`)+(i?`?${i}`:"")}}}async remove(t){var e=this;return e.handleOperation(async()=>await e1(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var n=this;return n.handleOperation(async()=>{const i=Be(Be(Be({},s8),e),{},{prefix:t||""});return await Fn(n.fetch,`${n.url}/object/list/${n.bucketId}`,i,{headers:n.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{const n=Be({},t);return await Fn(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,n,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(t,e){return e.width&&t.set("width",e.width.toString()),e.height&&t.set("height",e.height.toString()),e.resize&&t.set("resize",e.resize),e.format&&t.set("format",e.format),e.quality&&t.set("quality",e.quality.toString()),t}};const c8="2.106.2",Iu={"X-Client-Info":`storage-js/${c8}`};var u8=class extends xl{constructor(t,e={},r,n){const i=new URL(t);n!=null&&n.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase."));const a=i.href.replace(/\/$/,""),o=Be(Be({},Iu),e);super(a,o,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=e.listBucketOptionsToQueryString(t);return await Wc(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Wc(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await Fn(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await tx(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await Fn(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await e1(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){const e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},d8=class extends xl{constructor(t,e={},r){const n=t.replace(/\/$/,""),i=Be(Be({},Iu),e);super(n,i,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Fn(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=new URLSearchParams;(t==null?void 0:t.limit)!==void 0&&r.set("limit",t.limit.toString()),(t==null?void 0:t.offset)!==void 0&&r.set("offset",t.offset.toString()),t!=null&&t.sortColumn&&r.set("sortColumn",t.sortColumn),t!=null&&t.sortOrder&&r.set("sortOrder",t.sortOrder),t!=null&&t.search&&r.set("search",t.search);const n=r.toString(),i=n?`${e.url}/bucket?${n}`:`${e.url}/bucket`;return await Wc(e.fetch,i,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await e1(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!e8(t))throw new np("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const r=new K6({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(r,{get(i,a){const o=i[a];return typeof o!="function"?o:async(...c)=>{try{return{data:await o.apply(i,c),error:null}}catch(u){if(n)throw u;return{data:null,error:u}}}}})}},f8=class extends xl{constructor(t,e={},r){const n=t.replace(/\/$/,""),i=Be(Be({},Iu),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await cn.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await cn.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},h8=class extends xl{constructor(t,e={},r){const n=t.replace(/\/$/,""),i=Be(Be({},Iu),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},p8=class extends xl{constructor(t,e={},r){const n=t.replace(/\/$/,""),i=Be(Be({},Iu),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},m8=class extends p8{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new g8(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},g8=class extends f8{constructor(t,e,r,n){super(t,e,n),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,Be(Be({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,Be(Be({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new y8(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},y8=class extends h8{constructor(t,e,r,n,i){super(t,e,i),this.vectorBucketName=r,this.indexName=n}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,Be(Be({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,Be(Be({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,Be(Be({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,Be(Be({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,Be(Be({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},v8=class extends u8{constructor(t,e={},r,n){super(t,e,r,n)}from(t){return new l8(this.url,this.headers,t,this.fetch)}get vectors(){return new m8(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new d8(this.url+"/iceberg",this.headers,this.fetch)}};const KP="2.106.2",Ps=30*1e3,rx=3,Tg=rx*Ps,b8="http://localhost:9999",x8="supabase.auth.token",w8={"X-Client-Info":`gotrue-js/${KP}`},nx="X-Supabase-Api-Version",VP={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},_8=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,S8=600*1e3;class Gs extends Error{constructor(e,r,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}}function be(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class k8 extends Gs{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n}}function E8(t){return be(t)&&t.name==="AuthApiError"}class Xn extends Gs{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class ta extends Gs{constructor(e,r,n,i){super(e,n,i),this.name=r,this.status=n}}class pr extends ta{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function uf(t){return be(t)&&t.name==="AuthSessionMissingError"}class _s extends ta{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class df extends ta{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class ff extends ta{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}function O8(t){return be(t)&&t.name==="AuthImplicitGrantRedirectError"}class mE extends ta{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class A8 extends ta{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")}}class ix extends ta{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function jg(t){return be(t)&&t.name==="AuthRetryableFetchError"}class gE extends ta{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}}class ax extends ta{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const qf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),yE=`
|
|
413
|
-
\r=`.split(""),T8=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<yE.length;e+=1)t[yE[e].charCodeAt(0)]=-2;for(let e=0;e<qf.length;e+=1)t[qf[e].charCodeAt(0)]=e;return t})();function vE(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){const n=e.queue>>e.queuedBits-6&63;r(qf[n]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const n=e.queue>>e.queuedBits-6&63;r(qf[n]),e.queuedBits-=6}}function XP(t,e,r){const n=T8[t];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function bE(t){const e=[],r=o=>{e.push(String.fromCodePoint(o))},n={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},a=o=>{N8(o,n,r)};for(let o=0;o<t.length;o+=1)XP(t.charCodeAt(o),i,a);return e.join("")}function j8(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function C8(t,e){for(let r=0;r<t.length;r+=1){let n=t.charCodeAt(r);if(n>55295&&n<=56319){const i=(n-55296)*1024&65535;n=(t.charCodeAt(r+1)-56320&65535|i)+65536,r+=1}j8(n,e)}}function N8(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let n=1;n<6;n+=1)if((t>>7-n&1)===0){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function zs(t){const e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i)};for(let i=0;i<t.length;i+=1)XP(t.charCodeAt(i),r,n);return new Uint8Array(e)}function P8(t){const e=[];return C8(t,r=>e.push(r)),new Uint8Array(e)}function ko(t){const e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i)};return t.forEach(i=>vE(i,r,n)),vE(null,r,n),e.join("")}function R8(t){return Math.round(Date.now()/1e3)+t}function I8(){return Symbol("auth-callback")}const xr=()=>typeof window<"u"&&typeof document<"u",yo={tested:!1,writable:!1},YP=()=>{if(!xr())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(yo.tested)return yo.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),yo.tested=!0,yo.writable=!0}catch{yo.tested=!0,yo.writable=!1}return yo.writable};function $8(t){const e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((i,a)=>{e[a]=i})}catch{}return r.searchParams.forEach((n,i)=>{e[i]=n}),e}const JP=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),M8=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Rs=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},vo=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return null}},br=async(t,e)=>{await t.removeItem(e)};class ap{constructor(){this.promise=new ap.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}ap.promiseConstructor=Promise;function hf(t){const e=t.split(".");if(e.length!==3)throw new ax("Invalid JWT structure");for(let n=0;n<e.length;n++)if(!_8.test(e[n]))throw new ax("JWT not in base64url format");return{header:JSON.parse(bE(e[0])),payload:JSON.parse(bE(e[1])),signature:zs(e[2]),raw:{header:e[0],payload:e[1]}}}async function L8(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function D8(t,e){return new Promise((n,i)=>{(async()=>{for(let a=0;a<1/0;a++)try{const o=await t(a);if(!e(a,null,o)){n(o);return}}catch(o){if(!e(a,o)){i(o);return}}})()})}function z8(t){return("0"+t.toString(16)).substr(-2)}function B8(){const e=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length;let i="";for(let a=0;a<56;a++)i+=r.charAt(Math.floor(Math.random()*n));return i}return crypto.getRandomValues(e),Array.from(e,z8).join("")}async function U8(t){const r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r),i=new Uint8Array(n);return Array.from(i).map(a=>String.fromCharCode(a)).join("")}async function q8(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;const r=await U8(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ss(t,e,r=!1){const n=B8();let i=n;r&&(i+="/recovery"),await Rs(t,`${e}-code-verifier`,i);const a=await q8(n);return[a,n===a?"plain":"s256"]}const F8=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function H8(t){const e=t.headers.get(nx);if(!e||!e.match(F8))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function W8(t){if(!t)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function G8(t){switch(t){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const K8=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Di(t){if(!K8.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function qn(t){if(!t.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 Cg(){const t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){const n=r.toString();if(n==="Symbol(Symbol.toPrimitive)"||n==="Symbol(Symbol.toStringTag)"||n==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function V8(t,e){return new Proxy(t,{get:(r,n,i)=>{if(n==="__isInsecureUserWarningProxy")return!0;if(typeof n=="symbol"){const a=n.toString();if(a==="Symbol(Symbol.toPrimitive)"||a==="Symbol(Symbol.toStringTag)"||a==="Symbol(util.inspect.custom)"||a==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,n,i)}return!e.value&&typeof n=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(r,n,i)}})}function xE(t){return JSON.parse(JSON.stringify(t))}const xo=t=>{if(typeof t=="object"&&t!==null){const e=t;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error}return JSON.stringify(t)},X8=[502,503,504,520,521,522,523,524,530];async function wE(t){var e;if(!M8(t))throw new ix(xo(t),0);if(X8.includes(t.status))throw new ix(xo(t),t.status);let r;try{r=await t.json()}catch(a){throw new Xn(xo(a),a)}let n;const i=H8(t);if(i&&i.getTime()>=VP["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new gE(xo(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new pr}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((a,o)=>a&&typeof o=="string",!0))throw new gE(xo(r),t.status,r.weak_password.reasons);throw new k8(xo(r),t.status||500,n)}const Y8=(t,e,r,n)=>{const i={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),i.body=JSON.stringify(n),Object.assign(Object.assign({},i),r))};async function Ne(t,e,r,n){var i;const a=Object.assign({},n==null?void 0:n.headers);a[nx]||(a[nx]=VP["2024-01-01"].name),n!=null&&n.jwt&&(a.Authorization=`Bearer ${n.jwt}`);const o=(i=n==null?void 0:n.query)!==null&&i!==void 0?i:{};n!=null&&n.redirectTo&&(o.redirect_to=n.redirectTo);const c=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",u=await J8(t,e,r+c,{headers:a,noResolveJson:n==null?void 0:n.noResolveJson},{},n==null?void 0:n.body);return n!=null&&n.xform?n==null?void 0:n.xform(u):{data:Object.assign({},u),error:null}}async function J8(t,e,r,n,i,a){const o=Y8(e,n,i,a);let c;try{c=await t(r,Object.assign({},o))}catch(u){throw console.error(u),new ix(xo(u),0)}if(c.ok||await wE(c),n!=null&&n.noResolveJson)return c;try{return await c.json()}catch(u){await wE(u)}}function On(t){var e;let r=null;eU(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=R8(t.expires_in)));const n=(e=t.user)!==null&&e!==void 0?e:typeof(t==null?void 0:t.id)=="string"?t:null;return{data:{session:r,user:n},error:null}}function _E(t){const e=On(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",!0)&&(e.data.weak_password=t.weak_password),e}function Na(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Z8(t){return{data:t,error:null}}function Q8(t){const{action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:a}=t,o=rp(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),c={action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:a},u=Object.assign({},o);return{data:{properties:c,user:u},error:null}}function SE(t){return t}function eU(t){return!!t.access_token&&!!t.refresh_token&&!!t.expires_in}const Ng=["global","local","others"];class tU{_encodePathSegment(e){if(e==="."||e==="..")throw new Gs("Invalid path segment");return encodeURIComponent(e)}constructor({url:e="",headers:r={},fetch:n,experimental:i}){this.url=e,this.headers=r,this.fetch=JP(n),this.experimental=i??{},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(e,r=Ng[0]){if(Ng.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Ng.join(", ")}`);try{return await Ne(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(be(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,r={}){try{return await Ne(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Na})}catch(n){if(be(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{const{options:r}=e,n=rp(e,["options"]),i=Object.assign(Object.assign({},n),r);return"newEmail"in n&&(i.new_email=n==null?void 0:n.newEmail,delete i.newEmail),await Ne(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:Q8,redirectTo:r==null?void 0:r.redirectTo})}catch(r){if(be(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await Ne(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Na})}catch(r){if(be(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,n,i,a,o,c,u;try{const d={nextPage:null,lastPage:0,total:0},p=await Ne(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e==null?void 0:e.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(a=(i=e==null?void 0:e.perPage)===null||i===void 0?void 0:i.toString())!==null&&a!==void 0?a:""},xform:SE});if(p.error)throw p.error;const f=await p.json(),g=(o=p.headers.get("x-total-count"))!==null&&o!==void 0?o:0,v=(u=(c=p.headers.get("link"))===null||c===void 0?void 0:c.split(","))!==null&&u!==void 0?u:[];return v.length>0&&(v.forEach(x=>{const w=parseInt(x.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(x.split(";")[1].split("=")[1]);d[`${b}Page`]=w}),d.total=parseInt(g)),{data:Object.assign(Object.assign({},f),d),error:null}}catch(d){if(be(d))return{data:{users:[]},error:d};throw d}}async getUserById(e){Di(e);try{return await Ne(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Na})}catch(r){if(be(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){Di(e);try{return await Ne(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Na})}catch(n){if(be(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,r=!1){Di(e);try{return await Ne(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Na})}catch(n){if(be(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){Di(e.userId);try{const{data:r,error:n}=await Ne(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:r,error:n}}catch(r){if(be(r))return{data:null,error:r};throw r}}async _deleteFactor(e){Di(e.userId),Di(e.id);try{return{data:await Ne(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(be(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,n,i,a,o,c,u;try{const d={nextPage:null,lastPage:0,total:0},p=await Ne(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e==null?void 0:e.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(a=(i=e==null?void 0:e.perPage)===null||i===void 0?void 0:i.toString())!==null&&a!==void 0?a:""},xform:SE});if(p.error)throw p.error;const f=await p.json(),g=(o=p.headers.get("x-total-count"))!==null&&o!==void 0?o:0,v=(u=(c=p.headers.get("link"))===null||c===void 0?void 0:c.split(","))!==null&&u!==void 0?u:[];return v.length>0&&(v.forEach(x=>{const w=parseInt(x.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(x.split(";")[1].split("=")[1]);d[`${b}Page`]=w}),d.total=parseInt(g)),{data:Object.assign(Object.assign({},f),d),error:null}}catch(d){if(be(d))return{data:{clients:[]},error:d};throw d}}async _createOAuthClient(e){try{return await Ne(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(be(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{const r=this._encodePathSegment(e);return await Ne(this.fetch,"GET",`${this.url}/admin/oauth/clients/${r}`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(r){if(be(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{const n=this._encodePathSegment(e);return await Ne(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${n}`,{body:r,headers:this.headers,xform:i=>({data:i,error:null})})}catch(n){if(be(n))return{data:null,error:n};throw n}}async _deleteOAuthClient(e){try{const r=this._encodePathSegment(e);return await Ne(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${r}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(be(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{const r=this._encodePathSegment(e);return await Ne(this.fetch,"POST",`${this.url}/admin/oauth/clients/${r}/regenerate_secret`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(r){if(be(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{const r={};return e!=null&&e.type&&(r.type=e.type),await Ne(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:n=>{var i;return{data:{providers:(i=n==null?void 0:n.providers)!==null&&i!==void 0?i:[]},error:null}}})}catch(r){if(be(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await Ne(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(be(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{const r=this._encodePathSegment(e);return await Ne(this.fetch,"GET",`${this.url}/admin/custom-providers/${r}`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(r){if(be(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{const n=this._encodePathSegment(e);return await Ne(this.fetch,"PUT",`${this.url}/admin/custom-providers/${n}`,{body:r,headers:this.headers,xform:i=>({data:i,error:null})})}catch(n){if(be(n))return{data:null,error:n};throw n}}async _deleteCustomProvider(e){try{const r=this._encodePathSegment(e);return await Ne(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${r}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(be(r))return{data:null,error:r};throw r}}async _adminListPasskeys(e){qn(this.experimental),Di(e.userId);try{return await Ne(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(be(r))return{data:null,error:r};throw r}}async _adminDeletePasskey(e){qn(this.experimental),Di(e.userId),Di(e.passkeyId);try{return await Ne(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(be(r))return{data:null,error:r};throw r}}}function kE(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}const yi={debug:!!(globalThis&&YP()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class ZP extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class EE extends ZP{}async function rU(t,e,r){yi.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const n=new globalThis.AbortController;let i;e>0&&(i=setTimeout(()=>{n.abort(),yi.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async a=>{if(a){clearTimeout(i),yi.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,a.name);try{return await r()}finally{yi.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,a.name)}}else{if(e===0)throw yi.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new EE(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(yi.debug)try{const o=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(o,null," "))}catch(o){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",o)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),clearTimeout(i),await r()}})}catch(a){if(e>0&&clearTimeout(i),a!==null&&typeof a=="object"&&"name"in a&&a.name==="AbortError"&&e>0){if(n.signal.aborted)return yi.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,{mode:"exclusive",steal:!0},async o=>{if(o){yi.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,o.name);try{return await r()}finally{yi.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,o.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw yi.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new EE(`Lock "${t}" was released because another request stole it`)}throw a}}function nU(){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 QP(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function iU(t){return parseInt(t,16)}function aU(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}function oU(t){var e;const{chainId:r,domain:n,expirationTime:i,issuedAt:a=new Date,nonce:o,notBefore:c,requestId:u,resources:d,scheme:p,uri:f,version:g}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!f)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(g!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${g}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
|
|
414
|
-
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}const v=
|
|
414
|
+
})`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this._cancelPendingDisconnect(),this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,r)}getChannels(){return this.channels}async removeChannel(e){const r=await e.unsubscribe();return r==="ok"&&e.teardown(),r}async removeAllChannels(){const e=this.channels.map(async n=>{const i=await n.unsubscribe();return n.teardown(),i}),r=await Promise.all(e);return await this.disconnect(),r}log(e,r,n){this.socketAdapter.log(e,r,n)}connectionState(){return this.socketAdapter.connectionState()||Xb.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){const n=`realtime:${e}`,i=this.getChannels().find(a=>a.topic===n);if(i)return i;{const a=new Ic(`realtime:${e}`,r,this);return this._cancelPendingDisconnect(),this.channels.push(a),a}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic),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(e=null){let r,n=!1;if(e)r=e,n=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(i){this.log("error","Error fetching access token from callback",i),r=this.accessTokenValue}else r=this.accessTokenValue;n?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(i=>{const a={access_token:r,version:A6};r&&i.updateJoinPayload(a),i.joinedOnce&&i.channelAdapter.isJoined()&&i.channelAdapter.push(eR.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(r,n)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,n)}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_workerObjectUrl(e){let r;if(e)r=e;else{const n=new Blob([a8],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}_initializeOptions(e){var r,n,i,a,o,c,u,d,p,f,g,v;this.worker=(r=e==null?void 0:e.worker)!==null&&r!==void 0?r:!1,this.accessToken=(n=e==null?void 0:e.accessToken)!==null&&n!==void 0?n:null;const x={};x.timeout=(i=e==null?void 0:e.timeout)!==null&&i!==void 0?i:C6,x.heartbeatIntervalMs=(a=e==null?void 0:e.heartbeatIntervalMs)!==null&&a!==void 0?a:hE.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=(o=e==null?void 0:e.disconnectOnEmptyChannelsAfterMs)!==null&&o!==void 0?o:2*((c=e==null?void 0:e.heartbeatIntervalMs)!==null&&c!==void 0?c:hE.HEARTBEAT_INTERVAL),x.transport=(u=e==null?void 0:e.transport)!==null&&u!==void 0?u:E6.getWebSocketConstructor(),x.params=e==null?void 0:e.params,x.logger=e==null?void 0:e.logger,x.heartbeatCallback=this._wrapHeartbeatCallback(e==null?void 0:e.heartbeatCallback),x.sessionStorage=(d=e==null?void 0:e.sessionStorage)!==null&&d!==void 0?d:i8(),x.reconnectAfterMs=(p=e==null?void 0:e.reconnectAfterMs)!==null&&p!==void 0?p:(A=>t8[A-1]||r8);let w,b;const S=(f=e==null?void 0:e.vsn)!==null&&f!==void 0?f:j6;switch(S){case T6:w=(A,O)=>O(JSON.stringify(A)),b=(A,O)=>O(JSON.parse(A));break;case QP:w=this.serializer.encode.bind(this.serializer),b=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${x.vsn}`)}if(x.vsn=S,x.encode=(g=e==null?void 0:e.encode)!==null&&g!==void 0?g:w,x.decode=(v=e==null?void 0:e.decode)!==null&&v!==void 0?v:b,x.beforeReconnect=this._reconnectAuth.bind(this),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,x.params=Object.assign(Object.assign({},x.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl,x.autoSendHeartbeat=!this.worker}return x}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}var Fc=class extends Error{constructor(t,e){var r;super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&((r=e.icebergType)==null?void 0:r.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function s8(t,e,r){const n=new URL(e,t);if(r)for(const[i,a]of Object.entries(r))a!==void 0&&n.searchParams.set(i,a);return n.toString()}async function l8(t){return!t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function c8(t){const e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:n,query:i,body:a,headers:o}){const c=s8(t.baseUrl,n,i),u=await l8(t.auth),d=await e(c,{method:r,headers:{...a?{"Content-Type":"application/json"}:{},...u,...o},body:a?JSON.stringify(a):void 0}),p=await d.text(),f=(d.headers.get("content-type")||"").includes("application/json"),g=f&&p?JSON.parse(p):p;if(!d.ok){const v=f?g:void 0,x=v==null?void 0:v.error;throw new Fc((x==null?void 0:x.message)??`Request failed with status ${d.status}`,{status:d.status,icebergType:x==null?void 0:x.type,icebergCode:x==null?void 0:x.code,details:v})}return{status:d.status,headers:d.headers,data:g}}}}function cf(t){return t.join("")}var u8=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){const e=t?{parent:cf(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(n=>({namespace:n}))}async createNamespace(t,e){const r={namespace:t.namespace,properties:e==null?void 0:e.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${cf(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${cf(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${cf(t.namespace)}`}),!0}catch(e){if(e instanceof Fc&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof Fc&&r.status===409)return;throw r}}};function ws(t){return t.join("")}var d8=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r}async listTables(t){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ws(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){const r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${ws(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){const r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${ws(t.namespace)}/tables/${t.name}`,body:e});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${ws(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String((e==null?void 0:e.purge)??!1)}})}async loadTable(t){const e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ws(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){const e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${ws(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof Fc&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof Fc&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},f8=class{constructor(t){var n;let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);const r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=c8({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=(n=t.accessDelegation)==null?void 0:n.join(","),this.namespaceOps=new u8(this.client,e),this.tableOps=new d8(this.client,e,this.accessDelegation)}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t)}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e)}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};function Hc(t){"@babel/helpers - typeof";return Hc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Hc(t)}function h8(t,e){if(Hc(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(Hc(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function p8(t){var e=h8(t,"string");return Hc(e)=="symbol"?e:e+""}function m8(t,e,r){return(e=p8(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function pE(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function Be(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?pE(Object(r),!0).forEach(function(n){m8(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):pE(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var ip=class extends Error{constructor(t,e="storage",r,n){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=n}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};function ap(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var Qb=class extends ip{constructor(t,e,r,n="storage"){super(t,n,e,r),this.name=n==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return Be({},super.toJSON())}},iR=class extends ip{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};function qf(t,e,r){const n=Be({},t),i=e.toLowerCase();for(const a of Object.keys(n))a.toLowerCase()===i&&delete n[a];return n[i]=r,n}function g8(t){const e={};for(const[r,n]of Object.entries(t))e[r.toLowerCase()]=n;return e}const y8=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),v8=t=>{if(typeof t!="object"||t===null)return!1;const e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},ex=t=>{if(Array.isArray(t))return t.map(r=>ex(r));if(typeof t=="function"||t!==Object(t))return t;const e={};return Object.entries(t).forEach(([r,n])=>{const i=r.replace(/([-_][a-z])/gi,a=>a.toUpperCase().replace(/[-_]/g,""));e[i]=ex(n)}),e},b8=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t),mE=t=>{if(typeof t=="object"&&t!==null){const e=t;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error;if(typeof e.error=="object"&&e.error!==null){const r=e.error;if(typeof r.message=="string")return r.message}}return JSON.stringify(t)},x8=async(t,e,r,n)=>{if(t!==null&&typeof t=="object"&&"json"in t&&typeof t.json=="function"){const i=t;let a=parseInt(String(i.status),10);Number.isFinite(a)||(a=500),i.json().then(o=>{const c=(o==null?void 0:o.statusCode)||(o==null?void 0:o.code)||a+"";e(new Qb(mE(o),a,c,n))}).catch(()=>{const o=a+"";e(new Qb(i.statusText||`HTTP ${a} error`,a,o,n))})}else e(new iR(mE(t),t,n))},w8=(t,e,r,n)=>{const i={method:t,headers:(e==null?void 0:e.headers)||{}};if(t==="GET"||t==="HEAD"||!n)return Be(Be({},i),r);if(v8(n)){var a;const o=(e==null?void 0:e.headers)||{};let c;for(const[u,d]of Object.entries(o))u.toLowerCase()==="content-type"&&(c=d);i.headers=qf(o,"Content-Type",(a=c)!==null&&a!==void 0?a:"application/json"),i.body=JSON.stringify(n)}else i.body=n;return e!=null&&e.duplex&&(i.duplex=e.duplex),Be(Be({},i),r)};async function mc(t,e,r,n,i,a,o){return new Promise((c,u)=>{t(r,w8(e,n,i,a)).then(d=>{if(!d.ok)throw d;if(n!=null&&n.noResolveJson)return d;if(o==="vectors"){const p=d.headers.get("content-type");if(d.headers.get("content-length")==="0"||d.status===204)return{};if(!p||!p.includes("application/json"))return{}}return d.json()}).then(d=>c(d)).catch(d=>x8(d,u,n,o))})}function aR(t="storage"){return{get:async(e,r,n,i)=>mc(e,"GET",r,n,i,void 0,t),post:async(e,r,n,i,a)=>mc(e,"POST",r,i,a,n,t),put:async(e,r,n,i,a)=>mc(e,"PUT",r,i,a,n,t),head:async(e,r,n,i)=>mc(e,"HEAD",r,Be(Be({},n),{},{noResolveJson:!0}),i,void 0,t),remove:async(e,r,n,i,a)=>mc(e,"DELETE",r,i,a,n,t)}}const _8=aR("storage"),{get:Wc,post:Fn,put:tx,head:S8,remove:t1}=_8,cn=aR("vectors");var xl=class{constructor(t,e={},r,n="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=g8(e),this.fetch=y8(r),this.namespace=n}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=qf(this.headers,t,e),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(ap(r))return{data:null,error:r};throw r}}};let oR;oR=Symbol.toStringTag;var k8=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[oR]="StreamDownloadBuilder",this.promise=null}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ap(e))return{data:null,error:e};throw e}}};let sR;sR=Symbol.toStringTag;var E8=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[sR]="BlobDownloadBuilder",this.promise=null}asStream(){return new k8(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ap(e))return{data:null,error:e};throw e}}};const O8={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},gE={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var A8=class extends xl{constructor(t,e={},r,n){super(t,e,n,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,n){var i=this;return i.handleOperation(async()=>{let a;const o=Be(Be({},gE),n);let c=Be(Be({},i.headers),t==="POST"&&{"x-upsert":String(o.upsert)});const u=o.metadata;if(typeof Blob<"u"&&r instanceof Blob?(a=new FormData,a.append("cacheControl",o.cacheControl),u&&a.append("metadata",i.encodeMetadata(u)),a.append("",r)):typeof FormData<"u"&&r instanceof FormData?(a=r,a.has("cacheControl")||a.append("cacheControl",o.cacheControl),u&&!a.has("metadata")&&a.append("metadata",i.encodeMetadata(u))):(a=r,c["cache-control"]=`max-age=${o.cacheControl}`,c["content-type"]=o.contentType,u&&(c["x-metadata"]=i.toBase64(i.encodeMetadata(u))),(typeof ReadableStream<"u"&&a instanceof ReadableStream||a&&typeof a=="object"&&"pipe"in a&&typeof a.pipe=="function")&&!o.duplex&&(o.duplex="half")),n!=null&&n.headers)for(const[g,v]of Object.entries(n.headers))c=qf(c,g,v);const d=i._removeEmptyFolders(e),p=i._getFinalPath(d),f=await(t=="PUT"?tx:Fn)(i.fetch,`${i.url}/object/${p}`,a,Be({headers:c},o!=null&&o.duplex?{duplex:o.duplex}:{}));return{path:d,id:f.Id,fullPath:f.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,n){var i=this;const a=i._removeEmptyFolders(t),o=i._getFinalPath(a),c=new URL(i.url+`/object/upload/sign/${o}`);return c.searchParams.set("token",e),i.handleOperation(async()=>{let u;const d=Be(Be({},gE),n);let p=Be(Be({},i.headers),{"x-upsert":String(d.upsert)});const f=d.metadata;if(typeof Blob<"u"&&r instanceof Blob?(u=new FormData,u.append("cacheControl",d.cacheControl),f&&u.append("metadata",i.encodeMetadata(f)),u.append("",r)):typeof FormData<"u"&&r instanceof FormData?(u=r,u.has("cacheControl")||u.append("cacheControl",d.cacheControl),f&&!u.has("metadata")&&u.append("metadata",i.encodeMetadata(f))):(u=r,p["cache-control"]=`max-age=${d.cacheControl}`,p["content-type"]=d.contentType,f&&(p["x-metadata"]=i.toBase64(i.encodeMetadata(f))),(typeof ReadableStream<"u"&&u instanceof ReadableStream||u&&typeof u=="object"&&"pipe"in u&&typeof u.pipe=="function")&&!d.duplex&&(d.duplex="half")),n!=null&&n.headers)for(const[g,v]of Object.entries(n.headers))p=qf(p,g,v);return{path:a,fullPath:(await tx(i.fetch,c.toString(),u,Be({headers:p},d!=null&&d.duplex?{duplex:d.duplex}:{}))).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let n=r._getFinalPath(t);const i=Be({},r.headers);e!=null&&e.upsert&&(i["x-upsert"]="true");const a=await Fn(r.fetch,`${r.url}/object/upload/sign/${n}`,{},{headers:i}),o=new URL(r.url+a.url),c=o.searchParams.get("token");if(!c)throw new ip("No token returned by API");return{signedUrl:o.toString(),path:t,token:c}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var n=this;return n.handleOperation(async()=>await Fn(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r==null?void 0:r.destinationBucket},{headers:n.headers}))}async copy(t,e,r){var n=this;return n.handleOperation(async()=>({path:(await Fn(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r==null?void 0:r.destinationBucket},{headers:n.headers})).Key}))}async createSignedUrl(t,e,r){var n=this;return n.handleOperation(async()=>{let i=n._getFinalPath(t);const a=typeof(r==null?void 0:r.transform)=="object"&&r.transform!==null&&Object.keys(r.transform).length>0;let o=await Fn(n.fetch,`${n.url}/object/sign/${i}`,Be({expiresIn:e},a?{transform:r.transform}:{}),{headers:n.headers});const c=new URLSearchParams;r!=null&&r.download&&c.set("download",r.download===!0?"":r.download),(r==null?void 0:r.cacheNonce)!=null&&c.set("cacheNonce",String(r.cacheNonce));const u=c.toString();return{signedUrl:encodeURI(`${n.url}${o.signedURL}${u?`&${u}`:""}`)}})}async createSignedUrls(t,e,r){var n=this;return n.handleOperation(async()=>{const i=await Fn(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:e,paths:t},{headers:n.headers}),a=new URLSearchParams;r!=null&&r.download&&a.set("download",r.download===!0?"":r.download),(r==null?void 0:r.cacheNonce)!=null&&a.set("cacheNonce",String(r.cacheNonce));const o=a.toString();return i.map(c=>Be(Be({},c),{},{signedUrl:c.signedURL?encodeURI(`${n.url}${c.signedURL}${o?`&${o}`:""}`):null}))})}download(t,e,r){const n=typeof(e==null?void 0:e.transform)=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image/authenticated":"object",i=new URLSearchParams;e!=null&&e.transform&&this.applyTransformOptsToQuery(i,e.transform),(e==null?void 0:e.cacheNonce)!=null&&i.set("cacheNonce",String(e.cacheNonce));const a=i.toString(),o=this._getFinalPath(t),c=()=>Wc(this.fetch,`${this.url}/${n}/${o}${a?`?${a}`:""}`,{headers:this.headers,noResolveJson:!0},r);return new E8(c,this.shouldThrowOnError)}async info(t){var e=this;const r=e._getFinalPath(t);return e.handleOperation(async()=>ex(await Wc(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;const r=e._getFinalPath(t);try{return await S8(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(i){if(e.shouldThrowOnError)throw i;if(ap(i)){var n;const a=i instanceof Qb?i.status:i instanceof iR?(n=i.originalError)===null||n===void 0?void 0:n.status:void 0;if(a!==void 0&&[400,404].includes(a))return{data:!1,error:i}}throw i}}getPublicUrl(t,e){const r=this._getFinalPath(t),n=new URLSearchParams;e!=null&&e.download&&n.set("download",e.download===!0?"":e.download),e!=null&&e.transform&&this.applyTransformOptsToQuery(n,e.transform),(e==null?void 0:e.cacheNonce)!=null&&n.set("cacheNonce",String(e.cacheNonce));const i=n.toString(),a=typeof(e==null?void 0:e.transform)=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}`)+(i?`?${i}`:"")}}}async remove(t){var e=this;return e.handleOperation(async()=>await t1(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var n=this;return n.handleOperation(async()=>{const i=Be(Be(Be({},O8),e),{},{prefix:t||""});return await Fn(n.fetch,`${n.url}/object/list/${n.bucketId}`,i,{headers:n.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{const n=Be({},t);return await Fn(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,n,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(t,e){return e.width&&t.set("width",e.width.toString()),e.height&&t.set("height",e.height.toString()),e.resize&&t.set("resize",e.resize),e.format&&t.set("format",e.format),e.quality&&t.set("quality",e.quality.toString()),t}};const T8="2.106.2",Iu={"X-Client-Info":`storage-js/${T8}`};var j8=class extends xl{constructor(t,e={},r,n){const i=new URL(t);n!=null&&n.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase."));const a=i.href.replace(/\/$/,""),o=Be(Be({},Iu),e);super(a,o,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=e.listBucketOptionsToQueryString(t);return await Wc(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Wc(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await Fn(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await tx(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await Fn(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await t1(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){const e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},C8=class extends xl{constructor(t,e={},r){const n=t.replace(/\/$/,""),i=Be(Be({},Iu),e);super(n,i,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Fn(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{const r=new URLSearchParams;(t==null?void 0:t.limit)!==void 0&&r.set("limit",t.limit.toString()),(t==null?void 0:t.offset)!==void 0&&r.set("offset",t.offset.toString()),t!=null&&t.sortColumn&&r.set("sortColumn",t.sortColumn),t!=null&&t.sortOrder&&r.set("sortOrder",t.sortOrder),t!=null&&t.search&&r.set("search",t.search);const n=r.toString(),i=n?`${e.url}/bucket?${n}`:`${e.url}/bucket`;return await Wc(e.fetch,i,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await t1(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!b8(t))throw new ip("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const r=new f8({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(r,{get(i,a){const o=i[a];return typeof o!="function"?o:async(...c)=>{try{return{data:await o.apply(i,c),error:null}}catch(u){if(n)throw u;return{data:null,error:u}}}}})}},N8=class extends xl{constructor(t,e={},r){const n=t.replace(/\/$/,""),i=Be(Be({},Iu),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await cn.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await cn.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},P8=class extends xl{constructor(t,e={},r){const n=t.replace(/\/$/,""),i=Be(Be({},Iu),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},R8=class extends xl{constructor(t,e={},r){const n=t.replace(/\/$/,""),i=Be(Be({},Iu),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await cn.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},I8=class extends R8{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new $8(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},$8=class extends N8{constructor(t,e,r,n){super(t,e,n),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,Be(Be({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,Be(Be({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new M8(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},M8=class extends P8{constructor(t,e,r,n,i){super(t,e,i),this.vectorBucketName=r,this.indexName=n}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,Be(Be({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,Be(Be({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,Be(Be({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,Be(Be({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,Be(Be({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},L8=class extends j8{constructor(t,e={},r,n){super(t,e,r,n)}from(t){return new A8(this.url,this.headers,t,this.fetch)}get vectors(){return new I8(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new C8(this.url+"/iceberg",this.headers,this.fetch)}};const lR="2.106.2",Ps=30*1e3,rx=3,jg=rx*Ps,D8="http://localhost:9999",z8="supabase.auth.token",B8={"X-Client-Info":`gotrue-js/${lR}`},nx="X-Supabase-Api-Version",cR={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},U8=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,q8=600*1e3;class Gs extends Error{constructor(e,r,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}}function be(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}class F8 extends Gs{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n}}function H8(t){return be(t)&&t.name==="AuthApiError"}class Xn extends Gs{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}}class ta extends Gs{constructor(e,r,n,i){super(e,n,i),this.name=r,this.status=n}}class pr extends ta{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function uf(t){return be(t)&&t.name==="AuthSessionMissingError"}class _s extends ta{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class df extends ta{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class ff extends ta{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}function W8(t){return be(t)&&t.name==="AuthImplicitGrantRedirectError"}class yE extends ta{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class G8 extends ta{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")}}class ix extends ta{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}}function Cg(t){return be(t)&&t.name==="AuthRetryableFetchError"}class vE extends ta{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}}class ax extends ta{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Ff="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),bE=`
|
|
415
|
+
\r=`.split(""),K8=(()=>{const t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<bE.length;e+=1)t[bE[e].charCodeAt(0)]=-2;for(let e=0;e<Ff.length;e+=1)t[Ff[e].charCodeAt(0)]=e;return t})();function xE(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){const n=e.queue>>e.queuedBits-6&63;r(Ff[n]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const n=e.queue>>e.queuedBits-6&63;r(Ff[n]),e.queuedBits-=6}}function uR(t,e,r){const n=K8[t];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function wE(t){const e=[],r=o=>{e.push(String.fromCodePoint(o))},n={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},a=o=>{Y8(o,n,r)};for(let o=0;o<t.length;o+=1)uR(t.charCodeAt(o),i,a);return e.join("")}function V8(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function X8(t,e){for(let r=0;r<t.length;r+=1){let n=t.charCodeAt(r);if(n>55295&&n<=56319){const i=(n-55296)*1024&65535;n=(t.charCodeAt(r+1)-56320&65535|i)+65536,r+=1}V8(n,e)}}function Y8(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let n=1;n<6;n+=1)if((t>>7-n&1)===0){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function zs(t){const e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i)};for(let i=0;i<t.length;i+=1)uR(t.charCodeAt(i),r,n);return new Uint8Array(e)}function J8(t){const e=[];return X8(t,r=>e.push(r)),new Uint8Array(e)}function ko(t){const e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i)};return t.forEach(i=>xE(i,r,n)),xE(null,r,n),e.join("")}function Z8(t){return Math.round(Date.now()/1e3)+t}function Q8(){return Symbol("auth-callback")}const xr=()=>typeof window<"u"&&typeof document<"u",yo={tested:!1,writable:!1},dR=()=>{if(!xr())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(yo.tested)return yo.writable;const t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),yo.tested=!0,yo.writable=!0}catch{yo.tested=!0,yo.writable=!1}return yo.writable};function eU(t){const e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((i,a)=>{e[a]=i})}catch{}return r.searchParams.forEach((n,i)=>{e[i]=n}),e}const fR=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),tU=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",Rs=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))},vo=async(t,e)=>{const r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return null}},br=async(t,e)=>{await t.removeItem(e)};class op{constructor(){this.promise=new op.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}}op.promiseConstructor=Promise;function hf(t){const e=t.split(".");if(e.length!==3)throw new ax("Invalid JWT structure");for(let n=0;n<e.length;n++)if(!U8.test(e[n]))throw new ax("JWT not in base64url format");return{header:JSON.parse(wE(e[0])),payload:JSON.parse(wE(e[1])),signature:zs(e[2]),raw:{header:e[0],payload:e[1]}}}async function rU(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function nU(t,e){return new Promise((n,i)=>{(async()=>{for(let a=0;a<1/0;a++)try{const o=await t(a);if(!e(a,null,o)){n(o);return}}catch(o){if(!e(a,o)){i(o);return}}})()})}function iU(t){return("0"+t.toString(16)).substr(-2)}function aU(){const e=new Uint32Array(56);if(typeof crypto>"u"){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length;let i="";for(let a=0;a<56;a++)i+=r.charAt(Math.floor(Math.random()*n));return i}return crypto.getRandomValues(e),Array.from(e,iU).join("")}async function oU(t){const r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r),i=new Uint8Array(n);return Array.from(i).map(a=>String.fromCharCode(a)).join("")}async function sU(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;const r=await oU(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Ss(t,e,r=!1){const n=aU();let i=n;r&&(i+="/recovery"),await Rs(t,`${e}-code-verifier`,i);const a=await sU(n);return[a,n===a?"plain":"s256"]}const lU=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function cU(t){const e=t.headers.get(nx);if(!e||!e.match(lU))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function uU(t){if(!t)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function dU(t){switch(t){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const fU=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Di(t){if(!fU.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function qn(t){if(!t.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 Ng(){const t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){const n=r.toString();if(n==="Symbol(Symbol.toPrimitive)"||n==="Symbol(Symbol.toStringTag)"||n==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function hU(t,e){return new Proxy(t,{get:(r,n,i)=>{if(n==="__isInsecureUserWarningProxy")return!0;if(typeof n=="symbol"){const a=n.toString();if(a==="Symbol(Symbol.toPrimitive)"||a==="Symbol(Symbol.toStringTag)"||a==="Symbol(util.inspect.custom)"||a==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,n,i)}return!e.value&&typeof n=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(r,n,i)}})}function _E(t){return JSON.parse(JSON.stringify(t))}const xo=t=>{if(typeof t=="object"&&t!==null){const e=t;if(typeof e.msg=="string")return e.msg;if(typeof e.message=="string")return e.message;if(typeof e.error_description=="string")return e.error_description;if(typeof e.error=="string")return e.error}return JSON.stringify(t)},pU=[502,503,504,520,521,522,523,524,530];async function SE(t){var e;if(!tU(t))throw new ix(xo(t),0);if(pU.includes(t.status))throw new ix(xo(t),t.status);let r;try{r=await t.json()}catch(a){throw new Xn(xo(a),a)}let n;const i=cU(t);if(i&&i.getTime()>=cR["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new vE(xo(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new pr}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((a,o)=>a&&typeof o=="string",!0))throw new vE(xo(r),t.status,r.weak_password.reasons);throw new F8(xo(r),t.status||500,n)}const mU=(t,e,r,n)=>{const i={method:t,headers:(e==null?void 0:e.headers)||{}};return t==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),i.body=JSON.stringify(n),Object.assign(Object.assign({},i),r))};async function Ne(t,e,r,n){var i;const a=Object.assign({},n==null?void 0:n.headers);a[nx]||(a[nx]=cR["2024-01-01"].name),n!=null&&n.jwt&&(a.Authorization=`Bearer ${n.jwt}`);const o=(i=n==null?void 0:n.query)!==null&&i!==void 0?i:{};n!=null&&n.redirectTo&&(o.redirect_to=n.redirectTo);const c=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",u=await gU(t,e,r+c,{headers:a,noResolveJson:n==null?void 0:n.noResolveJson},{},n==null?void 0:n.body);return n!=null&&n.xform?n==null?void 0:n.xform(u):{data:Object.assign({},u),error:null}}async function gU(t,e,r,n,i,a){const o=mU(e,n,i,a);let c;try{c=await t(r,Object.assign({},o))}catch(u){throw console.error(u),new ix(xo(u),0)}if(c.ok||await SE(c),n!=null&&n.noResolveJson)return c;try{return await c.json()}catch(u){await SE(u)}}function On(t){var e;let r=null;bU(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=Z8(t.expires_in)));const n=(e=t.user)!==null&&e!==void 0?e:typeof(t==null?void 0:t.id)=="string"?t:null;return{data:{session:r,user:n},error:null}}function kE(t){const e=On(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",!0)&&(e.data.weak_password=t.weak_password),e}function Na(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function yU(t){return{data:t,error:null}}function vU(t){const{action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:a}=t,o=np(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),c={action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:a},u=Object.assign({},o);return{data:{properties:c,user:u},error:null}}function EE(t){return t}function bU(t){return!!t.access_token&&!!t.refresh_token&&!!t.expires_in}const Pg=["global","local","others"];class xU{_encodePathSegment(e){if(e==="."||e==="..")throw new Gs("Invalid path segment");return encodeURIComponent(e)}constructor({url:e="",headers:r={},fetch:n,experimental:i}){this.url=e,this.headers=r,this.fetch=fR(n),this.experimental=i??{},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(e,r=Pg[0]){if(Pg.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Pg.join(", ")}`);try{return await Ne(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(be(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,r={}){try{return await Ne(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Na})}catch(n){if(be(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{const{options:r}=e,n=np(e,["options"]),i=Object.assign(Object.assign({},n),r);return"newEmail"in n&&(i.new_email=n==null?void 0:n.newEmail,delete i.newEmail),await Ne(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:vU,redirectTo:r==null?void 0:r.redirectTo})}catch(r){if(be(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await Ne(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Na})}catch(r){if(be(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,n,i,a,o,c,u;try{const d={nextPage:null,lastPage:0,total:0},p=await Ne(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e==null?void 0:e.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(a=(i=e==null?void 0:e.perPage)===null||i===void 0?void 0:i.toString())!==null&&a!==void 0?a:""},xform:EE});if(p.error)throw p.error;const f=await p.json(),g=(o=p.headers.get("x-total-count"))!==null&&o!==void 0?o:0,v=(u=(c=p.headers.get("link"))===null||c===void 0?void 0:c.split(","))!==null&&u!==void 0?u:[];return v.length>0&&(v.forEach(x=>{const w=parseInt(x.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(x.split(";")[1].split("=")[1]);d[`${b}Page`]=w}),d.total=parseInt(g)),{data:Object.assign(Object.assign({},f),d),error:null}}catch(d){if(be(d))return{data:{users:[]},error:d};throw d}}async getUserById(e){Di(e);try{return await Ne(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Na})}catch(r){if(be(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){Di(e);try{return await Ne(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Na})}catch(n){if(be(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,r=!1){Di(e);try{return await Ne(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Na})}catch(n){if(be(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){Di(e.userId);try{const{data:r,error:n}=await Ne(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:r,error:n}}catch(r){if(be(r))return{data:null,error:r};throw r}}async _deleteFactor(e){Di(e.userId),Di(e.id);try{return{data:await Ne(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(be(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,n,i,a,o,c,u;try{const d={nextPage:null,lastPage:0,total:0},p=await Ne(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e==null?void 0:e.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(a=(i=e==null?void 0:e.perPage)===null||i===void 0?void 0:i.toString())!==null&&a!==void 0?a:""},xform:EE});if(p.error)throw p.error;const f=await p.json(),g=(o=p.headers.get("x-total-count"))!==null&&o!==void 0?o:0,v=(u=(c=p.headers.get("link"))===null||c===void 0?void 0:c.split(","))!==null&&u!==void 0?u:[];return v.length>0&&(v.forEach(x=>{const w=parseInt(x.split(";")[0].split("=")[1].substring(0,1)),b=JSON.parse(x.split(";")[1].split("=")[1]);d[`${b}Page`]=w}),d.total=parseInt(g)),{data:Object.assign(Object.assign({},f),d),error:null}}catch(d){if(be(d))return{data:{clients:[]},error:d};throw d}}async _createOAuthClient(e){try{return await Ne(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(be(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{const r=this._encodePathSegment(e);return await Ne(this.fetch,"GET",`${this.url}/admin/oauth/clients/${r}`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(r){if(be(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{const n=this._encodePathSegment(e);return await Ne(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${n}`,{body:r,headers:this.headers,xform:i=>({data:i,error:null})})}catch(n){if(be(n))return{data:null,error:n};throw n}}async _deleteOAuthClient(e){try{const r=this._encodePathSegment(e);return await Ne(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${r}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(be(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{const r=this._encodePathSegment(e);return await Ne(this.fetch,"POST",`${this.url}/admin/oauth/clients/${r}/regenerate_secret`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(r){if(be(r))return{data:null,error:r};throw r}}async _listCustomProviders(e){try{const r={};return e!=null&&e.type&&(r.type=e.type),await Ne(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:n=>{var i;return{data:{providers:(i=n==null?void 0:n.providers)!==null&&i!==void 0?i:[]},error:null}}})}catch(r){if(be(r))return{data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await Ne(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(be(r))return{data:null,error:r};throw r}}async _getCustomProvider(e){try{const r=this._encodePathSegment(e);return await Ne(this.fetch,"GET",`${this.url}/admin/custom-providers/${r}`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(r){if(be(r))return{data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{const n=this._encodePathSegment(e);return await Ne(this.fetch,"PUT",`${this.url}/admin/custom-providers/${n}`,{body:r,headers:this.headers,xform:i=>({data:i,error:null})})}catch(n){if(be(n))return{data:null,error:n};throw n}}async _deleteCustomProvider(e){try{const r=this._encodePathSegment(e);return await Ne(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${r}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(be(r))return{data:null,error:r};throw r}}async _adminListPasskeys(e){qn(this.experimental),Di(e.userId);try{return await Ne(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(be(r))return{data:null,error:r};throw r}}async _adminDeletePasskey(e){qn(this.experimental),Di(e.userId),Di(e.passkeyId);try{return await Ne(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(be(r))return{data:null,error:r};throw r}}}function OE(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}const yi={debug:!!(globalThis&&dR()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class hR extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class AE extends hR{}async function wU(t,e,r){yi.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);const n=new globalThis.AbortController;let i;e>0&&(i=setTimeout(()=>{n.abort(),yi.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async a=>{if(a){clearTimeout(i),yi.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,a.name);try{return await r()}finally{yi.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,a.name)}}else{if(e===0)throw yi.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new AE(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(yi.debug)try{const o=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(o,null," "))}catch(o){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",o)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),clearTimeout(i),await r()}})}catch(a){if(e>0&&clearTimeout(i),a!==null&&typeof a=="object"&&"name"in a&&a.name==="AbortError"&&e>0){if(n.signal.aborted)return yi.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,{mode:"exclusive",steal:!0},async o=>{if(o){yi.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,o.name);try{return await r()}finally{yi.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,o.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw yi.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new AE(`Lock "${t}" was released because another request stole it`)}throw a}}function _U(){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 pR(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function SU(t){return parseInt(t,16)}function kU(t){const e=new TextEncoder().encode(t);return"0x"+Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}function EU(t){var e;const{chainId:r,domain:n,expirationTime:i,issuedAt:a=new Date,nonce:o,notBefore:c,requestId:u,resources:d,scheme:p,uri:f,version:g}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!f)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(g!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${g}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
|
|
416
|
+
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}const v=pR(t.address),x=p?`${p}://${n}`:n,w=t.statement?`${t.statement}
|
|
415
417
|
`:"",b=`${x} wants you to sign in with your Ethereum account:
|
|
416
418
|
${v}
|
|
417
419
|
|
|
@@ -425,13 +427,11 @@ Not Before: ${c.toISOString()}`),u&&(S+=`
|
|
|
425
427
|
Request ID: ${u}`),d){let A=`
|
|
426
428
|
Resources:`;for(const O of d){if(!O||typeof O!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${O}`);A+=`
|
|
427
429
|
- ${O}`}S+=A}return`${b}
|
|
428
|
-
${S}`}class Zt extends Error{constructor({message:e,code:r,cause:n,name:i}){var a;super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=(a=i??(n instanceof Error?n.name:void 0))!==null&&a!==void 0?a:"Unknown Error",this.code=r}toJSON(){return{name:this.name,message:this.message,code:this.code}}}class Ff extends Zt{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function sU({error:t,options:e}){var r,n,i;const{publicKey:a}=e;if(!a)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new Zt({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=a.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new Zt({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((n=a.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new Zt({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((i=a.authenticatorSelection)===null||i===void 0?void 0:i.userVerification)==="required")return new Zt({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new Zt({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new Zt({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return a.pubKeyCredParams.filter(c=>c.type==="public-key").length===0?new Zt({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new Zt({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){const o=window.location.hostname;if(eR(o)){if(a.rp.id!==o)return new Zt({message:`The RP ID "${a.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Zt({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(a.user.id.byteLength<1||a.user.id.byteLength>64)return new Zt({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new Zt({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new Zt({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function lU({error:t,options:e}){const{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new Zt({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new Zt({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const n=window.location.hostname;if(eR(n)){if(r.rpId!==n)return new Zt({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Zt({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new Zt({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new Zt({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class cU{createNewAbortSignal(){if(this.controller){const r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const ox=new cU;function OE(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);const{challenge:e,user:r,excludeCredentials:n}=t,i=rp(t,["challenge","user","excludeCredentials"]),a=zs(e).buffer,o=Object.assign(Object.assign({},r),{id:zs(r.id).buffer}),c=Object.assign(Object.assign({},i),{challenge:a,user:o});if(n&&n.length>0){c.excludeCredentials=new Array(n.length);for(let u=0;u<n.length;u++){const d=n[u];c.excludeCredentials[u]=Object.assign(Object.assign({},d),{id:zs(d.id).buffer,type:d.type||"public-key",transports:d.transports})}}return c}function AE(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);const{challenge:e,allowCredentials:r}=t,n=rp(t,["challenge","allowCredentials"]),i=zs(e).buffer,a=Object.assign(Object.assign({},n),{challenge:i});if(r&&r.length>0){a.allowCredentials=new Array(r.length);for(let o=0;o<r.length;o++){const c=r[o];a.allowCredentials[o]=Object.assign(Object.assign({},c),{id:zs(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return a}function TE(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t;return{id:t.id,rawId:t.id,response:{attestationObject:ko(new Uint8Array(t.response.attestationObject)),clientDataJSON:ko(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function jE(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t,n=t.getClientExtensionResults(),i=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:ko(new Uint8Array(i.authenticatorData)),clientDataJSON:ko(new Uint8Array(i.clientDataJSON)),signature:ko(new Uint8Array(i.signature)),userHandle:i.userHandle?ko(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function eR(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Hf(){var t,e;return!!(xr()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator==null?void 0:navigator.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.get)=="function")}async function tR(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ff("Browser returned unexpected credential type",e)}:{data:null,error:new Ff("Empty credential response",e)}}catch(e){return{data:null,error:sU({error:e,options:t})}}}async function rR(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ff("Browser returned unexpected credential type",e)}:{data:null,error:new Ff("Empty credential response",e)}}catch(e){return{data:null,error:lU({error:e,options:t})}}}const uU={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},dU={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Wf(...t){const e=i=>i!==null&&typeof i=="object"&&!Array.isArray(i),r=i=>i instanceof ArrayBuffer||ArrayBuffer.isView(i),n={};for(const i of t)if(i)for(const a in i){const o=i[a];if(o!==void 0)if(Array.isArray(o))n[a]=o;else if(r(o))n[a]=o;else if(e(o)){const c=n[a];e(c)?n[a]=Wf(c,o):n[a]=Wf(o)}else n[a]=o}return n}function fU(t,e){return Wf(uU,t,e||{})}function hU(t,e){return Wf(dU,t,e||{})}class pU{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:n,signal:i},a){var o;try{const{data:c,error:u}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!c)return{data:null,error:u};const d=i??ox.createNewAbortSignal();if(c.webauthn.type==="create"){const{user:p}=c.webauthn.credential_options.publicKey;if(!p.name){const f=n;if(f)p.name=`${p.id}:${f}`;else{const v=(await this.client.getUser()).data.user,x=((o=v==null?void 0:v.user_metadata)===null||o===void 0?void 0:o.name)||(v==null?void 0:v.email)||(v==null?void 0:v.id)||"User";p.name=`${p.id}:${x}`}}p.displayName||(p.displayName=p.name)}switch(c.webauthn.type){case"create":{const p=fU(c.webauthn.credential_options.publicKey,a==null?void 0:a.create),{data:f,error:g}=await tR({publicKey:p,signal:d});return f?{data:{factorId:e,challengeId:c.id,webauthn:{type:c.webauthn.type,credential_response:f}},error:null}:{data:null,error:g}}case"request":{const p=hU(c.webauthn.credential_options.publicKey,a==null?void 0:a.request),{data:f,error:g}=await rR(Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:p,signal:d}));return f?{data:{factorId:e,challengeId:c.id,webauthn:{type:c.webauthn.type,credential_response:f}},error:null}:{data:null,error:g}}}}catch(c){return be(c)?{data:null,error:c}:{data:null,error:new Xn("Unexpected error in challenge",c)}}}async _verify({challengeId:e,factorId:r,webauthn:n}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},a){if(!r)return{data:null,error:new Gs("rpId is required for WebAuthn authentication")};try{if(!Hf())return{data:null,error:new Xn("Browser does not support WebAuthn",null)};const{data:o,error:c}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:n},signal:i},{request:a});if(!o)return{data:null,error:c};const{webauthn:u}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:u.type,rpId:r,rpOrigins:n,credential_response:u.credential_response}})}catch(o){return be(o)?{data:null,error:o}:{data:null,error:new Xn("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},a){if(!r)return{data:null,error:new Gs("rpId is required for WebAuthn registration")};try{if(!Hf())return{data:null,error:new Xn("Browser does not support WebAuthn",null)};const{data:o,error:c}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(p=>{var f;return(f=p.data)===null||f===void 0?void 0:f.all.find(g=>g.factor_type==="webauthn"&&g.friendly_name===e&&g.status!=="unverified")}).then(p=>p?this.client.mfa.unenroll({factorId:p==null?void 0:p.id}):void 0),{data:null,error:c};const{data:u,error:d}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:r,rpOrigins:n},signal:i},{create:a});return u?this._verify({factorId:o.id,challengeId:u.challengeId,webauthn:{rpId:r,rpOrigins:n,type:u.webauthn.type,credential_response:u.webauthn.credential_response}}):{data:null,error:d}}catch(o){return be(o)?{data:null,error:o}:{data:null,error:new Xn("Unexpected error in register",o)}}}}nU();const mU={url:b8,storageKey:x8,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:w8,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};async function CE(t,e,r){return await r()}const ks={};class Gc{get jwks(){var e,r;return(r=(e=ks[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){ks[this.storageKey]=Object.assign(Object.assign({},ks[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=ks[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){ks[this.storageKey]=Object.assign(Object.assign({},ks[this.storageKey]),{cachedAt:e})}constructor(e){var r,n,i,a;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const o=Object.assign(Object.assign({},mU),e);if(this.storageKey=o.storageKey,this.instanceID=(r=Gc.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,Gc.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!o.debug,typeof o.debug=="function"&&(this.logger=o.debug),this.instanceID>0&&xr()){const c=`${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(c),this.logDebugMessages&&console.trace(c)}if(this.persistSession=o.persistSession,this.autoRefreshToken=o.autoRefreshToken,this.experimental=(n=o.experimental)!==null&&n!==void 0?n:{},this.admin=new tU({url:o.url,headers:o.headers,fetch:o.fetch,experimental:this.experimental}),this.url=o.url,this.headers=o.headers,this.fetch=JP(o.fetch),this.lock=o.lock||CE,this.detectSessionInUrl=o.detectSessionInUrl,this.flowType=o.flowType,this.hasCustomAuthorizationHeader=o.hasCustomAuthorizationHeader,this.throwOnError=o.throwOnError,this.lockAcquireTimeout=o.lockAcquireTimeout,o.lock?this.lock=o.lock:this.persistSession&&xr()&&(!((i=globalThis==null?void 0:globalThis.navigator)===null||i===void 0)&&i.locks)?this.lock=rU:this.lock=CE,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 pU(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?(o.storage?this.storage=o.storage:YP()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=kE(this.memoryStorage)),o.userStorage&&(this.userStorage=o.userStorage)):(this.memoryStorage={},this.storage=kE(this.memoryStorage)),xr()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(c){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",c)}(a=this.broadcastChannel)===null||a===void 0||a.addEventListener("message",async c=>{this._debug("received broadcast notification from other tab or client",c);try{await this._notifyAllSubscribers(c.data.event,c.data.session,!1)}catch(u){this._debug("#broadcastChannel","error",u)}})}o.skipAutoInitialize||this.initialize().catch(c=>{this._debug("#initialize()","error",c)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${KP}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},n="none";if(xr()&&(r=$8(window.location.href),this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce")),xr()&&this.detectSessionInUrl&&n!=="none"){const{data:i,error:a}=await this._getSessionFromURL(r,n);if(a){if(this._debug("#_initialize()","error detecting session from URL",a),O8(a)){const u=(e=a.details)===null||e===void 0?void 0:e.code;if(u==="identity_already_exists"||u==="identity_not_found"||u==="single_identity_not_deletable")return{error:a}}return{error:a}}const{session:o,redirectType:c}=i;return this._debug("#_initialize()","detected session in URL",o,"redirect type",c),await this._saveSession(o),setTimeout(async()=>{c==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return be(r)?this._returnResult({error:r}):this._returnResult({error:new Xn("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,n,i;try{const a=await Ne(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(i=e==null?void 0:e.options)===null||i===void 0?void 0:i.captchaToken}},xform:On}),{data:o,error:c}=a;if(c||!o)return this._returnResult({data:{user:null,session:null},error:c});const u=o.session,d=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",u)),this._returnResult({data:{user:d,session:u},error:null})}catch(a){if(be(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signUp(e){var r,n,i;try{let a;if("email"in e){const{email:p,password:f,options:g}=e;let v=null,x=null;this.flowType==="pkce"&&([v,x]=await Ss(this.storage,this.storageKey)),a=await Ne(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:g==null?void 0:g.emailRedirectTo,body:{email:p,password:f,data:(r=g==null?void 0:g.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken},code_challenge:v,code_challenge_method:x},xform:On})}else if("phone"in e){const{phone:p,password:f,options:g}=e;a=await Ne(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:p,password:f,data:(n=g==null?void 0:g.data)!==null&&n!==void 0?n:{},channel:(i=g==null?void 0:g.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken}},xform:On})}else throw new df("You must provide either an email or phone number and a password");const{data:o,error:c}=a;if(c||!o)return await br(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:c});const u=o.session,d=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",u)),this._returnResult({data:{user:d,session:u},error:null})}catch(a){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithPassword(e){try{let r;if("email"in e){const{email:a,password:o,options:c}=e;r=await Ne(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:a,password:o,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken}},xform:_E})}else if("phone"in e){const{phone:a,password:o,options:c}=e;r=await Ne(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:a,password:o,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken}},xform:_E})}else throw new df("You must provide either an email or phone number and a password");const{data:n,error:i}=r;if(i)return this._returnResult({data:{user:null,session:null},error:i});if(!n||!n.session||!n.user){const a=new _s;return this._returnResult({data:{user:null,session:null},error:a})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:i})}catch(r){if(be(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,n,i,a;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(a=e.options)===null||a===void 0?void 0:a.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,n,i,a,o,c,u,d,p,f,g;let v,x;if("message"in e)v=e.message,x=e.signature;else{const{chain:w,wallet:b,statement:S,options:A}=e;let O;if(xr())if(typeof b=="object")O=b;else{const M=window;if("ethereum"in M&&typeof M.ethereum=="object"&&"request"in M.ethereum&&typeof M.ethereum.request=="function")O=M.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 b!="object"||!(A!=null&&A.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");O=b}const j=new URL((r=A==null?void 0:A.url)!==null&&r!==void 0?r:window.location.href),E=await O.request({method:"eth_requestAccounts"}).then(M=>M).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!E||E.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const T=QP(E[0]);let P=(n=A==null?void 0:A.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!P){const M=await O.request({method:"eth_chainId"});P=iU(M)}const R={domain:j.host,address:T,statement:S,uri:j.href,version:"1",chainId:P,nonce:(i=A==null?void 0:A.signInWithEthereum)===null||i===void 0?void 0:i.nonce,issuedAt:(o=(a=A==null?void 0:A.signInWithEthereum)===null||a===void 0?void 0:a.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(c=A==null?void 0:A.signInWithEthereum)===null||c===void 0?void 0:c.expirationTime,notBefore:(u=A==null?void 0:A.signInWithEthereum)===null||u===void 0?void 0:u.notBefore,requestId:(d=A==null?void 0:A.signInWithEthereum)===null||d===void 0?void 0:d.requestId,resources:(p=A==null?void 0:A.signInWithEthereum)===null||p===void 0?void 0:p.resources};v=oU(R),x=await O.request({method:"personal_sign",params:[aU(v),T]})}try{const{data:w,error:b}=await Ne(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:v,signature:x},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(g=e.options)===null||g===void 0?void 0:g.captchaToken}}:null),xform:On});if(b)throw b;if(!w||!w.session||!w.user){const S=new _s;return this._returnResult({data:{user:null,session:null},error:S})}return w.session&&(await this._saveSession(w.session),await this._notifyAllSubscribers("SIGNED_IN",w.session)),this._returnResult({data:Object.assign({},w),error:b})}catch(w){if(be(w))return this._returnResult({data:{user:null,session:null},error:w});throw w}}async signInWithSolana(e){var r,n,i,a,o,c,u,d,p,f,g,v;let x,w;if("message"in e)x=e.message,w=e.signature;else{const{chain:b,wallet:S,statement:A,options:O}=e;let j;if(xr())if(typeof S=="object")j=S;else{const T=window;if("solana"in T&&typeof T.solana=="object"&&("signIn"in T.solana&&typeof T.solana.signIn=="function"||"signMessage"in T.solana&&typeof T.solana.signMessage=="function"))j=T.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 S!="object"||!(O!=null&&O.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");j=S}const E=new URL((r=O==null?void 0:O.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in j&&j.signIn){const T=await j.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},O==null?void 0:O.signInWithSolana),{version:"1",domain:E.host,uri:E.href}),A?{statement:A}:null));let P;if(Array.isArray(T)&&T[0]&&typeof T[0]=="object")P=T[0];else if(T&&typeof T=="object"&&"signedMessage"in T&&"signature"in T)P=T;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in P&&"signature"in P&&(typeof P.signedMessage=="string"||P.signedMessage instanceof Uint8Array)&&P.signature instanceof Uint8Array)x=typeof P.signedMessage=="string"?P.signedMessage:new TextDecoder().decode(P.signedMessage),w=P.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in j)||typeof j.signMessage!="function"||!("publicKey"in j)||typeof j!="object"||!j.publicKey||!("toBase58"in j.publicKey)||typeof j.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");x=[`${E.host} wants you to sign in with your Solana account:`,j.publicKey.toBase58(),...A?["",A,""]:[""],"Version: 1",`URI: ${E.href}`,`Issued At: ${(i=(n=O==null?void 0:O.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()}`,...!((a=O==null?void 0:O.signInWithSolana)===null||a===void 0)&&a.notBefore?[`Not Before: ${O.signInWithSolana.notBefore}`]:[],...!((o=O==null?void 0:O.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${O.signInWithSolana.expirationTime}`]:[],...!((c=O==null?void 0:O.signInWithSolana)===null||c===void 0)&&c.chainId?[`Chain ID: ${O.signInWithSolana.chainId}`]:[],...!((u=O==null?void 0:O.signInWithSolana)===null||u===void 0)&&u.nonce?[`Nonce: ${O.signInWithSolana.nonce}`]:[],...!((d=O==null?void 0:O.signInWithSolana)===null||d===void 0)&&d.requestId?[`Request ID: ${O.signInWithSolana.requestId}`]:[],...!((f=(p=O==null?void 0:O.signInWithSolana)===null||p===void 0?void 0:p.resources)===null||f===void 0)&&f.length?["Resources",...O.signInWithSolana.resources.map(P=>`- ${P}`)]:[]].join(`
|
|
429
|
-
`);const T=await j.signMessage(new TextEncoder().encode(x),"utf8");if(!T||!(T instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");w=T}}try{const{data:b,error:S}=await Ne(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:x,signature:ko(w)},!((g=e.options)===null||g===void 0)&&g.captchaToken?{gotrue_meta_security:{captcha_token:(v=e.options)===null||v===void 0?void 0:v.captchaToken}}:null),xform:On});if(S)throw S;if(!b||!b.session||!b.user){const A=new _s;return this._returnResult({data:{user:null,session:null},error:A})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:S})}catch(b){if(be(b))return this._returnResult({data:{user:null,session:null},error:b});throw b}}async _exchangeCodeForSession(e){const r=await vo(this.storage,`${this.storageKey}-code-verifier`),[n,i]=(r??"").split("/");try{if(!n&&this.flowType==="pkce")throw new A8;const{data:a,error:o}=await Ne(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:On});if(await br(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!a||!a.session||!a.user){const c=new _s;return this._returnResult({data:{user:null,session:null,redirectType:null},error:c})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers(i==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",a.session)),this._returnResult({data:Object.assign(Object.assign({},a),{redirectType:i??null}),error:o})}catch(a){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(a))return this._returnResult({data:{user:null,session:null,redirectType:null},error:a});throw a}}async signInWithIdToken(e){try{const{options:r,provider:n,token:i,access_token:a,nonce:o}=e,c=await Ne(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:i,access_token:a,nonce:o,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:On}),{data:u,error:d}=c;if(d)return this._returnResult({data:{user:null,session:null},error:d});if(!u||!u.session||!u.user){const p=new _s;return this._returnResult({data:{user:null,session:null},error:p})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("SIGNED_IN",u.session)),this._returnResult({data:u,error:d})}catch(r){if(be(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,n,i,a,o;try{if("email"in e){const{email:c,options:u}=e;let d=null,p=null;this.flowType==="pkce"&&([d,p]=await Ss(this.storage,this.storageKey));const{error:f}=await Ne(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:c,data:(r=u==null?void 0:u.data)!==null&&r!==void 0?r:{},create_user:(n=u==null?void 0:u.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken},code_challenge:d,code_challenge_method:p},redirectTo:u==null?void 0:u.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:f})}if("phone"in e){const{phone:c,options:u}=e,{data:d,error:p}=await Ne(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:c,data:(i=u==null?void 0:u.data)!==null&&i!==void 0?i:{},create_user:(a=u==null?void 0:u.shouldCreateUser)!==null&&a!==void 0?a:!0,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken},channel:(o=u==null?void 0:u.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:d==null?void 0:d.message_id},error:p})}throw new df("You must provide either an email or phone number.")}catch(c){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(c))return this._returnResult({data:{user:null,session:null},error:c});throw c}}async verifyOtp(e){var r,n;try{let i,a;"options"in e&&(i=(r=e.options)===null||r===void 0?void 0:r.redirectTo,a=(n=e.options)===null||n===void 0?void 0:n.captchaToken);const{data:o,error:c}=await Ne(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:a}}),redirectTo:i,xform:On});if(c)throw c;if(!o)throw new Error("An error occurred on token verification.");const u=o.session,d=o.user;return u!=null&&u.access_token&&(await this._saveSession(u),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",u)),this._returnResult({data:{user:d,session:u},error:null})}catch(i){if(be(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithSSO(e){var r,n,i,a,o;try{let c=null,u=null;this.flowType==="pkce"&&([c,u]=await Ss(this.storage,this.storageKey));const d=await Ne(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((i=e==null?void 0:e.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:c,code_challenge_method:u}),headers:this.headers,xform:Z8});return!((a=d.data)===null||a===void 0)&&a.url&&xr()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(d.data.url),this._returnResult(d)}catch(c){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(c))return this._returnResult({data:null,error:c});throw c}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;if(n)throw n;if(!r)throw new pr;const{error:i}=await Ne(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:i})})}catch(e){if(be(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:n,type:i,options:a}=e,{error:o}=await Ne(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:i,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},redirectTo:a==null?void 0:a.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){const{phone:n,type:i,options:a}=e,{data:o,error:c}=await Ne(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:i,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:c})}throw new df("You must provide either an email or phone number and a type")}catch(r){if(be(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const n=r();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){const i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await vo(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const n=e.expires_at?e.expires_at*1e3-Date.now()<Tg:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){const o=await vo(this.userStorage,this.storageKey+"-user");o!=null&&o.user?e.user=o.user:e.user=Cg()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const o={value:this.suppressGetSessionWarning};e.user=V8(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:i,error:a}=await this._callRefreshToken(e.refresh_token);return a?this._returnResult({data:{session:null},error:a}):this._returnResult({data:{session:i},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await Ne(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Na}):await this._useSession(async r=>{var n,i,a;const{data:o,error:c}=r;if(c)throw c;return!(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new pr}:await Ne(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(a=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&a!==void 0?a:void 0,xform:Na})})}catch(r){if(be(r))return uf(r)&&(await this._removeSession(),await br(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async n=>{const{data:i,error:a}=n;if(a)throw a;if(!i.session)throw new pr;const o=i.session;let c=null,u=null;this.flowType==="pkce"&&e.email!=null&&([c,u]=await Ss(this.storage,this.storageKey));const{data:d,error:p}=await Ne(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:c,code_challenge_method:u}),jwt:o.access_token,xform:Na});if(p)throw p;return o.user=d.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new pr;const r=Date.now()/1e3;let n=r,i=!0,a=null;const{payload:o}=hf(e.access_token);if(o.exp&&(n=o.exp,i=n<=r),i){const{data:c,error:u}=await this._callRefreshToken(e.refresh_token);if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c)return{data:{user:null,session:null},error:null};a=c}else{const{data:c,error:u}=await this._getUser(e.access_token);if(u)return this._returnResult({data:{user:null,session:null},error:u});a={access_token:e.access_token,refresh_token:e.refresh_token,user:c.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(a),await this._notifyAllSubscribers("SIGNED_IN",a)}return this._returnResult({data:{user:a.user,session:a},error:null})}catch(r){if(be(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var n;if(!e){const{data:o,error:c}=r;if(c)throw c;e=(n=o.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new pr;const{data:i,error:a}=await this._callRefreshToken(e.refresh_token);return a?this._returnResult({data:{user:null,session:null},error:a}):i?this._returnResult({data:{user:i.user,session:i},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(be(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var n;try{if(!xr())throw new ff("No browser detected.");if(e.error||e.error_description||e.error_code)throw new ff(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new mE("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new ff("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new mE("No code detected.");const{data:O,error:j}=await this._exchangeCodeForSession(e.code);if(j)throw j;const E=new URL(window.location.href);return E.searchParams.delete("code"),window.history.replaceState(window.history.state,"",E.toString()),{data:{session:O.session,redirectType:(n=O.redirectType)!==null&&n!==void 0?n:null},error:null}}const{provider_token:i,provider_refresh_token:a,access_token:o,refresh_token:c,expires_in:u,expires_at:d,token_type:p}=e;if(!o||!u||!c||!p)throw new ff("No session defined in URL");const f=Math.round(Date.now()/1e3),g=parseInt(u);let v=f+g;d&&(v=parseInt(d));const x=v-f;x*1e3<=Ps&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${x}s, should have been closer to ${g}s`);const w=v-g;f-w>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",w,v,f):f-w<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",w,v,f);const{data:b,error:S}=await this._getUser(o);if(S)throw S;const A={provider_token:i,provider_refresh_token:a,access_token:o,expires_in:g,expires_at:v,refresh_token:c,token_type:p,user:b.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:A,redirectType:e.type},error:null})}catch(i){if(be(i))return this._returnResult({data:{session:null,redirectType:null},error:i});throw i}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){const r=await vo(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var n;const{data:i,error:a}=r;if(a&&!uf(a))return this._returnResult({error:a});const o=(n=i.session)===null||n===void 0?void 0:n.access_token;if(o){const{error:c}=await this.admin.signOut(o,e);if(c&&!(E8(c)&&(c.status===404||c.status===401||c.status===403)||uf(c)))return this._returnResult({error:c})}return e!=="others"&&(await this._removeSession(),await br(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=I8(),n={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async r=>{var n,i;try{const{data:{session:a},error:o}=r;if(o)throw o;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",a)),this._debug("INITIAL_SESSION","callback id",e,"session",a)}catch(a){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",a),uf(a)?console.warn(a):console.error(a)}})}async resetPasswordForEmail(e,r={}){let n=null,i=null;this.flowType==="pkce"&&([n,i]=await Ss(this.storage,this.storageKey,!0));try{return await Ne(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:i,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(a){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(a))return this._returnResult({data:null,error:a});throw a}}async getUserIdentities(){var e;try{const{data:r,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{const{data:n,error:i}=await this._useSession(async a=>{var o,c,u,d,p;const{data:f,error:g}=a;if(g)throw g;const v=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(c=e.options)===null||c===void 0?void 0:c.scopes,queryParams:(u=e.options)===null||u===void 0?void 0:u.queryParams,skipBrowserRedirect:!0});return await Ne(this.fetch,"GET",v,{headers:this.headers,jwt:(p=(d=f.session)===null||d===void 0?void 0:d.access_token)!==null&&p!==void 0?p:void 0})});if(i)throw i;return xr()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n==null?void 0:n.url),this._returnResult({data:{provider:e.provider,url:n==null?void 0:n.url},error:null})}catch(n){if(be(n))return this._returnResult({data:{provider:e.provider,url:null},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var n;try{const{error:i,data:{session:a}}=r;if(i)throw i;const{options:o,provider:c,token:u,access_token:d,nonce:p}=e,f=await Ne(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=a==null?void 0:a.access_token)!==null&&n!==void 0?n:void 0,body:{provider:c,id_token:u,access_token:d,nonce:p,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:On}),{data:g,error:v}=f;return v?this._returnResult({data:{user:null,session:null},error:v}):!g||!g.session||!g.user?this._returnResult({data:{user:null,session:null},error:new _s}):(g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("USER_UPDATED",g.session)),this._returnResult({data:g,error:v}))}catch(i){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var n,i;const{data:a,error:o}=r;if(o)throw o;return await Ne(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(n=a.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0})})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{const n=Date.now();return await D8(async i=>(i>0&&await L8(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await Ne(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:On})),(i,a)=>{const o=200*Math.pow(2,i);return a&&jg(a)&&Date.now()+o-n<Ps})}catch(n){if(this._debug(r,"error",n),be(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",n),xr()&&!r.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,r;const n="#_recoverAndRefresh()";this._debug(n,"begin");try{const i=await vo(this.storage,this.storageKey);if(i&&this.userStorage){let o=await vo(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:i.user},await Rs(this.userStorage,this.storageKey+"-user",o)),i.user=(e=o==null?void 0:o.user)!==null&&e!==void 0?e:Cg()}else if(i&&!i.user&&!i.user){const o=await vo(this.storage,this.storageKey+"-user");o&&(o!=null&&o.user)?(i.user=o.user,await br(this.storage,this.storageKey+"-user"),await Rs(this.storage,this.storageKey,i)):i.user=Cg()}if(this._debug(n,"session from storage",i),!this._isValidSession(i)){this._debug(n,"session is not valid"),i!==null&&await this._removeSession();return}const a=((r=i.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Tg;if(this._debug(n,`session has${a?"":" not"} expired with margin of ${Tg}s`),a){if(this.autoRefreshToken&&i.refresh_token){const{error:o}=await this._callRefreshToken(i.refresh_token);o&&(console.error(o),jg(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(i.user&&i.user.__isUserNotAvailableProxy===!0)try{const{data:o,error:c}=await this._getUser(i.access_token);!c&&(o!=null&&o.user)?(i.user=o.user,await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)):this._debug(n,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(n,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",i)}catch(i){this._debug(n,"error",i),console.error(i);return}finally{this._debug(n,"end")}}async _callRefreshToken(e){var r,n;if(!e)throw new pr;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new ap;const{data:a,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!a.session)throw new pr;await this._saveSession(a.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",a.session);const c={data:a.session,error:null};return this.refreshingDeferred.resolve(c),c}catch(a){if(this._debug(i,"error",a),be(a)){const o={data:null,error:a};return jg(a)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(a),a}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,r,n=!0){const i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",r,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:r});const a=[],o=Array.from(this.stateChangeEmitters.values()).map(async c=>{try{await c.callback(e,r)}catch(u){a.push(u)}});if(await Promise.all(o),a.length>0){for(let c=0;c<a.length;c+=1)console.error(a[c]);throw a[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await br(this.storage,`${this.storageKey}-code-verifier`);const r=Object.assign({},e),n=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!n&&r.user&&await Rs(this.userStorage,this.storageKey+"-user",{user:r.user});const i=Object.assign({},r);delete i.user;const a=xE(i);await Rs(this.storage,this.storageKey,a)}else{const i=xE(r);await Rs(this.storage,this.storageKey,i)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await br(this.storage,this.storageKey),await br(this.storage,this.storageKey+"-code-verifier"),await br(this.storage,this.storageKey+"-user"),this.userStorage&&await br(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&xr()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),Ps);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const 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()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const i=Math.floor((n.expires_at*1e3-e)/Ps);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Ps}ms, refresh threshold is ${rx} ticks`),i<=rx&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof ZP)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!xr()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,n){const i=[`provider=${encodeURIComponent(r)}`];if(n!=null&&n.redirectTo&&i.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n!=null&&n.scopes&&i.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){const[a,o]=await Ss(this.storage,this.storageKey),c=new URLSearchParams({code_challenge:`${encodeURIComponent(a)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(c.toString())}if(n!=null&&n.queryParams){const a=new URLSearchParams(n.queryParams);i.push(a.toString())}return n!=null&&n.skipBrowserRedirect&&i.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var n;const{data:i,error:a}=r;return a?this._returnResult({data:null,error:a}):await Ne(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var n,i;const{data:a,error:o}=r;if(o)return this._returnResult({data:null,error:o});const c=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:u,error:d}=await Ne(this.fetch,"POST",`${this.url}/factors`,{body:c,headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token});return d?this._returnResult({data:null,error:d}):(e.factorType==="totp"&&u.type==="totp"&&(!((i=u==null?void 0:u.totp)===null||i===void 0)&&i.qr_code)&&(u.totp.qr_code=`data:image/svg+xml;utf-8,${u.totp.qr_code}`),this._returnResult({data:u,error:null}))})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;const{data:i,error:a}=r;if(a)return this._returnResult({data:null,error:a});const o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?TE(e.webauthn.credential_response):jE(e.webauthn.credential_response)})}:{code:e.code}),{data:c,error:u}=await Ne(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=i==null?void 0: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)+c.expires_in},c)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",c),this._returnResult({data:c,error:u}))})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;const{data:i,error:a}=r;if(a)return this._returnResult({data:null,error:a});const o=await Ne(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;const{data:c}=o;if(c.type!=="webauthn")return{data:c,error:null};switch(c.webauthn.type){case"create":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:OE(c.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:AE(c.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){const{data:r,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:n}=await this.getUser();if(n)return{data:null,error:n};const i={all:[],phone:[],totp:[],webauthn:[]};for(const a of(e=r==null?void 0:r.factors)!==null&&e!==void 0?e:[])i.all.push(a),a.status==="verified"&&i[a.factor_type].push(a);return{data:i,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,n,i,a;if(e)try{const{payload:v}=hf(e);let x=null;v.aal&&(x=v.aal);let w=x;const{data:{user:b},error:S}=await this.getUser(e);if(S)return this._returnResult({data:null,error:S});((n=(r=b==null?void 0:b.factors)===null||r===void 0?void 0:r.filter(j=>j.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(w="aal2");const O=v.amr||[];return{data:{currentLevel:x,nextLevel:w,currentAuthenticationMethods:O},error:null}}catch(v){if(be(v))return this._returnResult({data:null,error:v});throw v}const{data:{session:o},error:c}=await this.getSession();if(c)return this._returnResult({data:null,error:c});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:u}=hf(o.access_token);let d=null;u.aal&&(d=u.aal);let p=d;((a=(i=o.user.factors)===null||i===void 0?void 0:i.filter(v=>v.status==="verified"))!==null&&a!==void 0?a:[]).length>0&&(p="aal2");const g=u.amr||[];return{data:{currentLevel:d,nextLevel:p,currentAuthenticationMethods:g},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?await Ne(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:a=>({data:a,error:null})}):this._returnResult({data:null,error:new pr})})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async n=>{const{data:{session:i},error:a}=n;if(a)return this._returnResult({data:null,error:a});if(!i)return this._returnResult({data:null,error:new pr});const o=await Ne(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"approve"},xform:c=>({data:c,error:null})});return o.data&&o.data.redirect_url&&xr()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(n){if(be(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,r){try{return await this._useSession(async n=>{const{data:{session:i},error:a}=n;if(a)return this._returnResult({data:null,error:a});if(!i)return this._returnResult({data:null,error:new pr});const o=await Ne(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"deny"},xform:c=>({data:c,error:null})});return o.data&&o.data.redirect_url&&xr()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(n){if(be(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;return n?this._returnResult({data:null,error:n}):r?await Ne(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new pr})})}catch(e){if(be(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?(await Ne(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new pr})})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(c=>c.kid===e);if(n)return n;const i=Date.now();if(n=this.jwks.keys.find(c=>c.kid===e),n&&this.jwks_cached_at+S8>i)return n;const{data:a,error:o}=await Ne(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!a.keys||a.keys.length===0||(this.jwks=a,this.jwks_cached_at=i,n=a.keys.find(c=>c.kid===e),!n)?null:n}async getClaims(e,r={}){try{let n=e;if(!n){const{data:v,error:x}=await this.getSession();if(x||!v.session)return this._returnResult({data:null,error:x});n=v.session.access_token}const{header:i,payload:a,signature:o,raw:{header:c,payload:u}}=hf(n);r!=null&&r.allowExpired||W8(a.exp);const d=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,r!=null&&r.keys?{keys:r.keys}:r==null?void 0:r.jwks);if(!d){const{error:v}=await this.getUser(n);if(v)throw v;return{data:{claims:a,header:i,signature:o},error:null}}const p=G8(i.alg),f=await crypto.subtle.importKey("jwk",d,p,!0,["verify"]);if(!await crypto.subtle.verify(p,f,o,P8(`${c}.${u}`)))throw new ax("Invalid JWT signature");return{data:{claims:a,header:i,signature:o},error:null}}catch(n){if(be(n))return this._returnResult({data:null,error:n});throw n}}async signInWithPasskey(e){var r,n,i;qn(this.experimental);try{if(!Hf())return this._returnResult({data:null,error:new Xn("Browser does not support WebAuthn",null)});const{data:a,error:o}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.captchaToken}});if(o||!a)return this._returnResult({data:null,error:o});const c=AE(a.options),u=(i=(n=e==null?void 0:e.options)===null||n===void 0?void 0:n.signal)!==null&&i!==void 0?i:ox.createNewAbortSignal(),{data:d,error:p}=await rR({publicKey:c,signal:u});if(p||!d)return this._returnResult({data:null,error:p??new Xn("WebAuthn ceremony failed",null)});const f=jE(d);return this._verifyPasskeyAuthentication({challengeId:a.challenge_id,credential:f})}catch(a){if(be(a))return this._returnResult({data:null,error:a});throw a}}async registerPasskey(e){var r,n;qn(this.experimental);try{if(!Hf())return this._returnResult({data:null,error:new Xn("Browser does not support WebAuthn",null)});const{data:i,error:a}=await this._startPasskeyRegistration();if(a||!i)return this._returnResult({data:null,error:a});const o=OE(i.options),c=(n=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.signal)!==null&&n!==void 0?n:ox.createNewAbortSignal(),{data:u,error:d}=await tR({publicKey:o,signal:c});if(d||!u)return this._returnResult({data:null,error:d??new Xn("WebAuthn ceremony failed",null)});const p=TE(u);return this._verifyPasskeyRegistration({challengeId:i.challenge_id,credential:p})}catch(i){if(be(i))return this._returnResult({data:null,error:i});throw i}}async _startPasskeyRegistration(){qn(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;if(n)return this._returnResult({data:null,error:n});if(!r)return this._returnResult({data:null,error:new pr});const{data:i,error:a}=await Ne(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:r.access_token,body:{}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(e){if(be(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){qn(this.experimental);try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new pr});const{data:a,error:o}=await Ne(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:n.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:a,error:null})})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;qn(this.experimental);try{const{data:n,error:i}=await Ne(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.captchaToken}}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})}catch(n){if(be(n))return this._returnResult({data:null,error:n});throw n}}async _verifyPasskeyAuthentication(e){qn(this.experimental);try{const{data:r,error:n}=await Ne(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:On});return n?this._returnResult({data:null,error:n}):(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:r,error:null}))}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){qn(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;if(n)return this._returnResult({data:null,error:n});if(!r)return this._returnResult({data:null,error:new pr});const{data:i,error:a}=await Ne(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:o=>({data:o,error:null})});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(e){if(be(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){qn(this.experimental);try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new pr});const{data:a,error:o}=await Ne(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:n.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:a,error:null})})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){qn(this.experimental);try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new pr});const{error:a}=await Ne(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:n.access_token,noResolveJson:!0});return a?this._returnResult({data:null,error:a}):this._returnResult({data:null,error:null})})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}}Gc.nextInstanceID={};const gU=Gc,yU="2.106.2";let Tc="";typeof Deno<"u"?Tc="deno":typeof document<"u"?Tc="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Tc="react-native":Tc="node";const vU={"X-Client-Info":`supabase-js-${Tc}/${yU}`},bU={headers:vU},xU={schema:"public"},wU={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},_U={},SU={enabled:!1,respectSamplingDecision:!0};function kU(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(p){try{d(n.next(p))}catch(f){o(f)}}function u(p){try{d(n.throw(p))}catch(f){o(f)}}function d(p){p.done?a(p.value):i(p.value).then(c,u)}d((n=n.apply(t,[])).next())})}let Pg=null;const EU="@opentelemetry/api";function OU(){return Pg===null&&(Pg=import(EU).catch(()=>null)),Pg}function AU(){return kU(this,void 0,void 0,function*(){try{const t=yield OU();if(!t||!t.propagation||!t.context)return null;const e={};t.propagation.inject(t.context.active(),e);const r=e.traceparent;return r?{traceparent:r,tracestate:e.tracestate,baggage:e.baggage}:null}catch{return null}})}function TU(t){if(!t||typeof t!="string")return null;const e=t.split("-");if(e.length!==4)return null;const[r,n,i,a]=e;if(r.length!==2||n.length!==32||i.length!==16||a.length!==2)return null;const o=/^[0-9a-f]+$/i;return!o.test(r)||!o.test(n)||!o.test(i)||!o.test(a)||n==="00000000000000000000000000000000"||i==="0000000000000000"?null:{version:r,traceId:n,parentId:i,traceFlags:a,isSampled:(parseInt(a,16)&1)===1}}function jU(t,e){if(!t||!e||e.length===0)return!1;let r;if(t instanceof URL)r=t;else try{r=new URL(t)}catch{return!1}for(const n of e)try{if(typeof n=="string"){if(CU(r.hostname,n))return!0}else if(n instanceof RegExp){if(n.test(r.hostname))return!0}else if(typeof n=="function"&&n(r))return!0}catch{continue}return!1}function CU(t,e){if(e===t)return!0;if(e.startsWith("*.")){const r=e.slice(2);if(t.endsWith(r)&&(t===r||t.endsWith("."+r)))return!0}return!1}function NU(t){const e=[];try{const r=new URL(t);e.push(r.hostname)}catch{}return e.push("*.supabase.co","*.supabase.in"),e.push("localhost","127.0.0.1","[::1]"),e}function Kc(t){"@babel/helpers - typeof";return Kc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Kc(t)}function PU(t,e){if(Kc(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(Kc(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function RU(t){var e=PU(t,"string");return Kc(e)=="symbol"?e:e+""}function IU(t,e,r){return(e=RU(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function NE(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function Ht(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?NE(Object(r),!0).forEach(function(n){IU(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):NE(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}const $U=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),MU=()=>Headers,LU=(t,e,r,n,i)=>{const a=$U(n),o=MU(),c=(i==null?void 0:i.enabled)===!0,u=(i==null?void 0:i.respectSamplingDecision)!==!1,d=c?NU(e):null;return async(p,f)=>{var g;const v=(g=await r())!==null&&g!==void 0?g:t;let x=new o(f==null?void 0:f.headers);if(x.has("apikey")||x.set("apikey",t),x.has("Authorization")||x.set("Authorization",`Bearer ${v}`),d){const w=await DU(p,d,u);w&&(w.traceparent&&!x.has("traceparent")&&x.set("traceparent",w.traceparent),w.tracestate&&!x.has("tracestate")&&x.set("tracestate",w.tracestate),w.baggage&&!x.has("baggage")&&x.set("baggage",w.baggage))}return a(p,Ht(Ht({},f),{},{headers:x}))}};async function DU(t,e,r){if(!jU(typeof t=="string"||t instanceof URL?t:t.url,e))return null;const n=await AU();if(!n||!n.traceparent)return null;if(r){const i=TU(n.traceparent);if(i&&!i.isSampled)return null}return n}function PE(t){return typeof t=="boolean"?{enabled:t}:t}function zU(t){return t.endsWith("/")?t:t+"/"}function BU(t,e){var r,n,i,a,o,c;const{db:u,auth:d,realtime:p,global:f}=t,{db:g,auth:v,realtime:x,global:w}=e,b=PE(t.tracePropagation),S=PE(e.tracePropagation),A={db:Ht(Ht({},g),u),auth:Ht(Ht({},v),d),realtime:Ht(Ht({},x),p),storage:{},global:Ht(Ht(Ht({},w),f),{},{headers:Ht(Ht({},(r=w==null?void 0:w.headers)!==null&&r!==void 0?r:{}),(n=f==null?void 0:f.headers)!==null&&n!==void 0?n:{})}),tracePropagation:{enabled:(i=(a=b==null?void 0:b.enabled)!==null&&a!==void 0?a:S==null?void 0:S.enabled)!==null&&i!==void 0?i:!1,respectSamplingDecision:(o=(c=b==null?void 0:b.respectSamplingDecision)!==null&&c!==void 0?c:S==null?void 0:S.respectSamplingDecision)!==null&&o!==void 0?o:!0},accessToken:async()=>""};return t.accessToken?A.accessToken=t.accessToken:delete A.accessToken,A}function UU(t){const e=t==null?void 0:t.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(zU(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var qU=class extends gU{constructor(t){super(t)}},FU=class{constructor(t,e,r){var n,i;this.supabaseUrl=t,this.supabaseKey=e;const a=UU(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const o=`sb-${a.hostname.split(".")[0]}-auth-token`,c={db:xU,realtime:_U,auth:Ht(Ht({},wU),{},{storageKey:o}),global:bU,tracePropagation:SU},u=BU(r??{},c);if(this.settings=u,this.storageKey=(n=u.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(i=u.global.headers)!==null&&i!==void 0?i:{},u.accessToken)this.accessToken=u.accessToken,this.auth=new Proxy({},{get:(p,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 d;this.auth=this._initSupabaseAuthClient((d=u.auth)!==null&&d!==void 0?d:{},this.headers,u.global.fetch)}this.fetch=LU(e,t,this._getAccessToken.bind(this),u.global.fetch,u.tracePropagation),this.realtime=this._initRealtimeClient(Ht({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},u.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(p=>this.realtime.setAuth(p)).catch(p=>console.warn("Failed to set initial Realtime auth token:",p)),this.rest=new a6(new URL("rest/v1",a).href,{headers:this.headers,schema:u.db.schema,fetch:this.fetch,timeout:u.db.timeout,urlLengthLimit:u.db.urlLengthLimit}),this.storage=new v8(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),u.accessToken||this._listenForAuthEvents()}get functions(){return new XB(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();const{data:n}=await t.auth.getSession();return(e=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,storageKey:a,flowType:o,lock:c,debug:u,throwOnError:d,experimental:p,lockAcquireTimeout:f,skipAutoInitialize:g},v,x){const w={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new qU({url:this.authUrl.href,headers:Ht(Ht({},w),v),storageKey:a,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,flowType:o,lock:c,debug:u,throwOnError:d,experimental:p,fetch:x,lockAcquireTimeout:f,skipAutoInitialize:g,hasCustomAuthorizationHeader:Object.keys(this.headers).some(b=>b.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new U6(this.realtimeUrl.href,Ht(Ht({},t),{},{params:Ht(Ht({},{apikey:this.supabaseKey}),t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const HU=(t,e,r)=>new FU(t,e,r);function WU(){if(typeof window<"u")return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}WU()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const nR=N.createContext({session:null,supabase:null,loading:!0,signIn:async()=>({error:"Not initialized"}),signOut:async()=>{}});function op(){return N.useContext(nR)}function GU({children:t}){const[e,r]=N.useState(null),[n,i]=N.useState(null),[a,o]=N.useState(!0),c=N.useRef(null);N.useEffect(()=>{Y4(()=>{var f;return((f=c.current)==null?void 0:f.access_token)??null})},[]);const u=N.useRef(null);N.useEffect(()=>{J4(async()=>{const f=u.current;if(!f)return null;const{data:g,error:v}=await f.auth.refreshSession();return v||!g.session?null:(c.current=g.session,i(g.session),g.session.access_token)})},[]),N.useEffect(()=>{Ve.get("/config").then(({config:f})=>{if(f.supabase.projectUrl&&f.supabase.anonKey){const g=HU(f.supabase.projectUrl,f.supabase.anonKey);r(g),u.current=g,g.auth.getSession().then(({data:x})=>{c.current=x.session,i(x.session),o(!1)});const{data:{subscription:v}}=g.auth.onAuthStateChange((x,w)=>{c.current=w,i(w)});return()=>v.unsubscribe()}o(!1)}).catch(()=>{o(!1)})},[]);async function d(f,g){if(!e)return{error:"Supabase not configured"};const{error:v}=await e.auth.signInWithPassword({email:f,password:g});return{error:(v==null?void 0:v.message)??null}}async function p(){e&&(await e.auth.signOut(),c.current=null,i(null))}return y.jsx(nR.Provider,{value:{session:n,supabase:e,loading:a,signIn:d,signOut:p},children:t})}const KU=[{to:"/squads",icon:Zh,label:"Squads"},{to:"/skills",icon:qb,label:"Skills"},{to:"/schedules",icon:B5,label:"Schedules"},{to:"/wiki",icon:XN,label:"Wiki"},{to:"/usage",icon:q5,label:"Usage"}],VU=[{to:"/",icon:zw,label:"Chat"},{to:"/feed",icon:Bb,label:"Inbox"},{to:"/settings",icon:z4,label:"Settings"}];function RE({to:t,icon:e,label:r,collapsed:n,badge:i}){return y.jsxs(GN,{to:t,end:t==="/",title:n?r:void 0,className:({isActive:a})=>Oc("w-full flex items-center gap-2.5 px-2 py-2 rounded-xl text-[11px] font-mono transition-colors cursor-pointer relative",n?"justify-center":"",a?"text-[#E43A9C]":"text-zinc-600 hover:text-zinc-300 hover:bg-white/[0.04]"),style:({isActive:a})=>a?{background:"rgba(228,58,156,0.1)"}:void 0,children:[y.jsx(e,{className:"w-3.5 h-3.5 flex-shrink-0"}),!n&&r,i!=null&&i>0&&y.jsx("span",{className:"absolute top-1 right-1 min-w-[14px] h-[14px] flex items-center justify-center rounded-full bg-[#E43A9C] text-[9px] text-white font-mono px-1",children:i>99?"99+":i})]})}function XU(){const[t,e]=N.useState(!1),[r,n]=N.useState("..."),[i,a]=N.useState(0),{supabase:o}=op();return N.useEffect(()=>{let c=!0;Ve.get("/version").then(({version:d})=>{c&&n(d)}).catch(()=>{c&&n("unknown")}),Ve.get("/inbox/unread-count").then(({count:d})=>{c&&a(d)}).catch(()=>{});const u=setInterval(()=>{Ve.get("/inbox/unread-count").then(({count:d})=>{c&&a(d)}).catch(()=>{})},3e4);return()=>{c=!1,clearInterval(u)}},[]),y.jsxs("div",{className:"flex h-screen overflow-hidden bg-background relative",children:[y.jsxs("div",{className:Oc("flex-shrink-0 flex flex-col border-r border-white/[0.06] bg-[#181818] transition-all duration-200",t?"w-[52px]":"w-[210px]"),children:[y.jsx("div",{className:Oc("h-[52px] flex items-center border-b border-white/[0.06] flex-shrink-0",t?"justify-center px-3":"justify-between pl-4 pr-3"),children:t?y.jsx(Ra,{height:26}):y.jsxs("div",{className:"flex items-center gap-2.5",children:[y.jsx(Ra,{height:26}),y.jsx("span",{className:"text-2xl text-white tracking-wider leading-none",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"IO"})]})}),y.jsx("nav",{className:"flex-1 py-2 px-1.5 space-y-0.5 overflow-y-auto",children:KU.map(c=>y.jsx(RE,{collapsed:t,...c},c.to))}),y.jsxs("div",{className:"flex-shrink-0 border-t border-white/[0.06]",children:[y.jsx("div",{className:"py-1.5 px-1.5 space-y-0.5",children:VU.map(c=>y.jsx(RE,{collapsed:t,badge:c.to==="/feed"?i:void 0,...c},c.to))}),y.jsxs("div",{className:"border-t border-white/[0.05] py-1.5 px-1.5 space-y-0.5",children:[y.jsxs("a",{href:`https://github.com/michaeljolley/io/releases/tag/v${r}`,target:"_blank",rel:"noreferrer",title:"GitHub",className:Oc("flex items-center gap-2.5 px-2 py-2 rounded-xl text-[11px] font-mono text-zinc-600 hover:text-zinc-300 hover:bg-white/[0.04] transition-colors cursor-pointer",t&&"justify-center"),children:[y.jsx(f4,{className:"w-3.5 h-3.5 flex-shrink-0"}),!t&&y.jsxs("span",{className:"text-zinc-700",children:["v",r]})]}),y.jsx("button",{type:"button",onClick:()=>e(!t),title:t?"Expand sidebar":"Collapse sidebar",className:Oc("w-full flex items-center gap-2.5 px-2 py-2 rounded-xl text-[11px] font-mono text-zinc-600 hover:text-zinc-300 hover:bg-white/[0.04] transition-colors cursor-pointer",t&&"justify-center"),children:t?y.jsx(Mw,{className:"w-3.5 h-3.5 flex-shrink-0"}):y.jsx(vl,{className:"w-3.5 h-3.5 flex-shrink-0"})})]})]})]}),y.jsxs("div",{className:"flex flex-col flex-1 min-w-0 overflow-hidden",children:[y.jsxs("div",{className:"h-[52px] flex-shrink-0 flex items-center justify-between px-4 border-b border-white/[0.06] bg-[#181818]",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx(FB,{status:"connected"}),y.jsx("span",{className:"text-[11px] font-mono text-green-400",children:"connected"})]}),y.jsxs("div",{className:"flex items-center gap-1.5",children:[y.jsx(iz,{}),o&&y.jsx("button",{type:"button",onClick:()=>o.auth.signOut(),className:"p-2 rounded-xl hover:bg-white/[0.05] text-zinc-600 hover:text-zinc-300 transition-colors cursor-pointer",title:"Sign out",children:y.jsx(x4,{className:"w-3.5 h-3.5"})})]})]}),y.jsxs("main",{className:"flex-1 overflow-hidden flex flex-col min-h-0 relative",children:[y.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",style:{zIndex:0},children:[y.jsx("div",{className:"orb orb-pink"}),y.jsx("div",{className:"orb orb-gray"})]}),y.jsx(yD,{})]})]})]})}function YU(){const{session:t}=op(),e=qa(),{messages:r,streaming:n,isStreaming:i,isThinking:a,sendChatMessage:o,addUserMessage:c,uploadAttachment:u}=cP(),[d,p]=N.useState(""),[f,g]=N.useState(null),[v,x]=N.useState(null),w=N.useRef(null),b=N.useRef(null),S=N.useRef(null);N.useLayoutEffect(()=>{const E=w.current;E&&(E.scrollTop=E.scrollHeight)},[r,n,a]);async function A(){const E=d.trim();if(!E&&!f||i||a)return;const T=crypto.randomUUID(),P=f==null?void 0:f.name,R=[E,P?`Attachment: ${P}`:""].filter(Boolean).join(`
|
|
430
|
+
${S}`}class Zt extends Error{constructor({message:e,code:r,cause:n,name:i}){var a;super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=(a=i??(n instanceof Error?n.name:void 0))!==null&&a!==void 0?a:"Unknown Error",this.code=r}toJSON(){return{name:this.name,message:this.message,code:this.code}}}class Hf extends Zt{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function OU({error:t,options:e}){var r,n,i;const{publicKey:a}=e;if(!a)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new Zt({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=a.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new Zt({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((n=a.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new Zt({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((i=a.authenticatorSelection)===null||i===void 0?void 0:i.userVerification)==="required")return new Zt({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new Zt({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new Zt({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return a.pubKeyCredParams.filter(c=>c.type==="public-key").length===0?new Zt({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new Zt({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){const o=window.location.hostname;if(mR(o)){if(a.rp.id!==o)return new Zt({message:`The RP ID "${a.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Zt({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(a.user.id.byteLength<1||a.user.id.byteLength>64)return new Zt({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new Zt({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new Zt({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function AU({error:t,options:e}){const{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new Zt({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new Zt({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const n=window.location.hostname;if(mR(n)){if(r.rpId!==n)return new Zt({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new Zt({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new Zt({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new Zt({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class TU{createNewAbortSignal(){if(this.controller){const r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const ox=new TU;function TE(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);const{challenge:e,user:r,excludeCredentials:n}=t,i=np(t,["challenge","user","excludeCredentials"]),a=zs(e).buffer,o=Object.assign(Object.assign({},r),{id:zs(r.id).buffer}),c=Object.assign(Object.assign({},i),{challenge:a,user:o});if(n&&n.length>0){c.excludeCredentials=new Array(n.length);for(let u=0;u<n.length;u++){const d=n[u];c.excludeCredentials[u]=Object.assign(Object.assign({},d),{id:zs(d.id).buffer,type:d.type||"public-key",transports:d.transports})}}return c}function jE(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);const{challenge:e,allowCredentials:r}=t,n=np(t,["challenge","allowCredentials"]),i=zs(e).buffer,a=Object.assign(Object.assign({},n),{challenge:i});if(r&&r.length>0){a.allowCredentials=new Array(r.length);for(let o=0;o<r.length;o++){const c=r[o];a.allowCredentials[o]=Object.assign(Object.assign({},c),{id:zs(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return a}function CE(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t;return{id:t.id,rawId:t.id,response:{attestationObject:ko(new Uint8Array(t.response.attestationObject)),clientDataJSON:ko(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function NE(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t,n=t.getClientExtensionResults(),i=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:ko(new Uint8Array(i.authenticatorData)),clientDataJSON:ko(new Uint8Array(i.clientDataJSON)),signature:ko(new Uint8Array(i.signature)),userHandle:i.userHandle?ko(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function mR(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Wf(){var t,e;return!!(xr()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator==null?void 0:navigator.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.get)=="function")}async function gR(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Hf("Browser returned unexpected credential type",e)}:{data:null,error:new Hf("Empty credential response",e)}}catch(e){return{data:null,error:OU({error:e,options:t})}}}async function yR(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Hf("Browser returned unexpected credential type",e)}:{data:null,error:new Hf("Empty credential response",e)}}catch(e){return{data:null,error:AU({error:e,options:t})}}}const jU={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},CU={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Gf(...t){const e=i=>i!==null&&typeof i=="object"&&!Array.isArray(i),r=i=>i instanceof ArrayBuffer||ArrayBuffer.isView(i),n={};for(const i of t)if(i)for(const a in i){const o=i[a];if(o!==void 0)if(Array.isArray(o))n[a]=o;else if(r(o))n[a]=o;else if(e(o)){const c=n[a];e(c)?n[a]=Gf(c,o):n[a]=Gf(o)}else n[a]=o}return n}function NU(t,e){return Gf(jU,t,e||{})}function PU(t,e){return Gf(CU,t,e||{})}class RU{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:n,signal:i},a){var o;try{const{data:c,error:u}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!c)return{data:null,error:u};const d=i??ox.createNewAbortSignal();if(c.webauthn.type==="create"){const{user:p}=c.webauthn.credential_options.publicKey;if(!p.name){const f=n;if(f)p.name=`${p.id}:${f}`;else{const v=(await this.client.getUser()).data.user,x=((o=v==null?void 0:v.user_metadata)===null||o===void 0?void 0:o.name)||(v==null?void 0:v.email)||(v==null?void 0:v.id)||"User";p.name=`${p.id}:${x}`}}p.displayName||(p.displayName=p.name)}switch(c.webauthn.type){case"create":{const p=NU(c.webauthn.credential_options.publicKey,a==null?void 0:a.create),{data:f,error:g}=await gR({publicKey:p,signal:d});return f?{data:{factorId:e,challengeId:c.id,webauthn:{type:c.webauthn.type,credential_response:f}},error:null}:{data:null,error:g}}case"request":{const p=PU(c.webauthn.credential_options.publicKey,a==null?void 0:a.request),{data:f,error:g}=await yR(Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:p,signal:d}));return f?{data:{factorId:e,challengeId:c.id,webauthn:{type:c.webauthn.type,credential_response:f}},error:null}:{data:null,error:g}}}}catch(c){return be(c)?{data:null,error:c}:{data:null,error:new Xn("Unexpected error in challenge",c)}}}async _verify({challengeId:e,factorId:r,webauthn:n}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},a){if(!r)return{data:null,error:new Gs("rpId is required for WebAuthn authentication")};try{if(!Wf())return{data:null,error:new Xn("Browser does not support WebAuthn",null)};const{data:o,error:c}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:n},signal:i},{request:a});if(!o)return{data:null,error:c};const{webauthn:u}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:u.type,rpId:r,rpOrigins:n,credential_response:u.credential_response}})}catch(o){return be(o)?{data:null,error:o}:{data:null,error:new Xn("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},a){if(!r)return{data:null,error:new Gs("rpId is required for WebAuthn registration")};try{if(!Wf())return{data:null,error:new Xn("Browser does not support WebAuthn",null)};const{data:o,error:c}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(p=>{var f;return(f=p.data)===null||f===void 0?void 0:f.all.find(g=>g.factor_type==="webauthn"&&g.friendly_name===e&&g.status!=="unverified")}).then(p=>p?this.client.mfa.unenroll({factorId:p==null?void 0:p.id}):void 0),{data:null,error:c};const{data:u,error:d}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:r,rpOrigins:n},signal:i},{create:a});return u?this._verify({factorId:o.id,challengeId:u.challengeId,webauthn:{rpId:r,rpOrigins:n,type:u.webauthn.type,credential_response:u.webauthn.credential_response}}):{data:null,error:d}}catch(o){return be(o)?{data:null,error:o}:{data:null,error:new Xn("Unexpected error in register",o)}}}}_U();const IU={url:D8,storageKey:z8,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:B8,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};async function PE(t,e,r){return await r()}const ks={};class Gc{get jwks(){var e,r;return(r=(e=ks[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){ks[this.storageKey]=Object.assign(Object.assign({},ks[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=ks[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){ks[this.storageKey]=Object.assign(Object.assign({},ks[this.storageKey]),{cachedAt:e})}constructor(e){var r,n,i,a;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const o=Object.assign(Object.assign({},IU),e);if(this.storageKey=o.storageKey,this.instanceID=(r=Gc.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,Gc.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!o.debug,typeof o.debug=="function"&&(this.logger=o.debug),this.instanceID>0&&xr()){const c=`${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(c),this.logDebugMessages&&console.trace(c)}if(this.persistSession=o.persistSession,this.autoRefreshToken=o.autoRefreshToken,this.experimental=(n=o.experimental)!==null&&n!==void 0?n:{},this.admin=new xU({url:o.url,headers:o.headers,fetch:o.fetch,experimental:this.experimental}),this.url=o.url,this.headers=o.headers,this.fetch=fR(o.fetch),this.lock=o.lock||PE,this.detectSessionInUrl=o.detectSessionInUrl,this.flowType=o.flowType,this.hasCustomAuthorizationHeader=o.hasCustomAuthorizationHeader,this.throwOnError=o.throwOnError,this.lockAcquireTimeout=o.lockAcquireTimeout,o.lock?this.lock=o.lock:this.persistSession&&xr()&&(!((i=globalThis==null?void 0:globalThis.navigator)===null||i===void 0)&&i.locks)?this.lock=wU:this.lock=PE,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 RU(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?(o.storage?this.storage=o.storage:dR()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=OE(this.memoryStorage)),o.userStorage&&(this.userStorage=o.userStorage)):(this.memoryStorage={},this.storage=OE(this.memoryStorage)),xr()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(c){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",c)}(a=this.broadcastChannel)===null||a===void 0||a.addEventListener("message",async c=>{this._debug("received broadcast notification from other tab or client",c);try{await this._notifyAllSubscribers(c.data.event,c.data.session,!1)}catch(u){this._debug("#broadcastChannel","error",u)}})}o.skipAutoInitialize||this.initialize().catch(c=>{this._debug("#initialize()","error",c)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${lR}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},n="none";if(xr()&&(r=eU(window.location.href),this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce")),xr()&&this.detectSessionInUrl&&n!=="none"){const{data:i,error:a}=await this._getSessionFromURL(r,n);if(a){if(this._debug("#_initialize()","error detecting session from URL",a),W8(a)){const u=(e=a.details)===null||e===void 0?void 0:e.code;if(u==="identity_already_exists"||u==="identity_not_found"||u==="single_identity_not_deletable")return{error:a}}return{error:a}}const{session:o,redirectType:c}=i;return this._debug("#_initialize()","detected session in URL",o,"redirect type",c),await this._saveSession(o),setTimeout(async()=>{c==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return be(r)?this._returnResult({error:r}):this._returnResult({error:new Xn("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,n,i;try{const a=await Ne(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(i=e==null?void 0:e.options)===null||i===void 0?void 0:i.captchaToken}},xform:On}),{data:o,error:c}=a;if(c||!o)return this._returnResult({data:{user:null,session:null},error:c});const u=o.session,d=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",u)),this._returnResult({data:{user:d,session:u},error:null})}catch(a){if(be(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signUp(e){var r,n,i;try{let a;if("email"in e){const{email:p,password:f,options:g}=e;let v=null,x=null;this.flowType==="pkce"&&([v,x]=await Ss(this.storage,this.storageKey)),a=await Ne(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:g==null?void 0:g.emailRedirectTo,body:{email:p,password:f,data:(r=g==null?void 0:g.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken},code_challenge:v,code_challenge_method:x},xform:On})}else if("phone"in e){const{phone:p,password:f,options:g}=e;a=await Ne(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:p,password:f,data:(n=g==null?void 0:g.data)!==null&&n!==void 0?n:{},channel:(i=g==null?void 0:g.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken}},xform:On})}else throw new df("You must provide either an email or phone number and a password");const{data:o,error:c}=a;if(c||!o)return await br(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:c});const u=o.session,d=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",u)),this._returnResult({data:{user:d,session:u},error:null})}catch(a){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithPassword(e){try{let r;if("email"in e){const{email:a,password:o,options:c}=e;r=await Ne(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:a,password:o,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken}},xform:kE})}else if("phone"in e){const{phone:a,password:o,options:c}=e;r=await Ne(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:a,password:o,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken}},xform:kE})}else throw new df("You must provide either an email or phone number and a password");const{data:n,error:i}=r;if(i)return this._returnResult({data:{user:null,session:null},error:i});if(!n||!n.session||!n.user){const a=new _s;return this._returnResult({data:{user:null,session:null},error:a})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:i})}catch(r){if(be(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,n,i,a;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(a=e.options)===null||a===void 0?void 0:a.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,n,i,a,o,c,u,d,p,f,g;let v,x;if("message"in e)v=e.message,x=e.signature;else{const{chain:w,wallet:b,statement:S,options:A}=e;let O;if(xr())if(typeof b=="object")O=b;else{const M=window;if("ethereum"in M&&typeof M.ethereum=="object"&&"request"in M.ethereum&&typeof M.ethereum.request=="function")O=M.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 b!="object"||!(A!=null&&A.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");O=b}const j=new URL((r=A==null?void 0:A.url)!==null&&r!==void 0?r:window.location.href),E=await O.request({method:"eth_requestAccounts"}).then(M=>M).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!E||E.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const T=pR(E[0]);let P=(n=A==null?void 0:A.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!P){const M=await O.request({method:"eth_chainId"});P=SU(M)}const R={domain:j.host,address:T,statement:S,uri:j.href,version:"1",chainId:P,nonce:(i=A==null?void 0:A.signInWithEthereum)===null||i===void 0?void 0:i.nonce,issuedAt:(o=(a=A==null?void 0:A.signInWithEthereum)===null||a===void 0?void 0:a.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(c=A==null?void 0:A.signInWithEthereum)===null||c===void 0?void 0:c.expirationTime,notBefore:(u=A==null?void 0:A.signInWithEthereum)===null||u===void 0?void 0:u.notBefore,requestId:(d=A==null?void 0:A.signInWithEthereum)===null||d===void 0?void 0:d.requestId,resources:(p=A==null?void 0:A.signInWithEthereum)===null||p===void 0?void 0:p.resources};v=EU(R),x=await O.request({method:"personal_sign",params:[kU(v),T]})}try{const{data:w,error:b}=await Ne(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:v,signature:x},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(g=e.options)===null||g===void 0?void 0:g.captchaToken}}:null),xform:On});if(b)throw b;if(!w||!w.session||!w.user){const S=new _s;return this._returnResult({data:{user:null,session:null},error:S})}return w.session&&(await this._saveSession(w.session),await this._notifyAllSubscribers("SIGNED_IN",w.session)),this._returnResult({data:Object.assign({},w),error:b})}catch(w){if(be(w))return this._returnResult({data:{user:null,session:null},error:w});throw w}}async signInWithSolana(e){var r,n,i,a,o,c,u,d,p,f,g,v;let x,w;if("message"in e)x=e.message,w=e.signature;else{const{chain:b,wallet:S,statement:A,options:O}=e;let j;if(xr())if(typeof S=="object")j=S;else{const T=window;if("solana"in T&&typeof T.solana=="object"&&("signIn"in T.solana&&typeof T.solana.signIn=="function"||"signMessage"in T.solana&&typeof T.solana.signMessage=="function"))j=T.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 S!="object"||!(O!=null&&O.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");j=S}const E=new URL((r=O==null?void 0:O.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in j&&j.signIn){const T=await j.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},O==null?void 0:O.signInWithSolana),{version:"1",domain:E.host,uri:E.href}),A?{statement:A}:null));let P;if(Array.isArray(T)&&T[0]&&typeof T[0]=="object")P=T[0];else if(T&&typeof T=="object"&&"signedMessage"in T&&"signature"in T)P=T;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in P&&"signature"in P&&(typeof P.signedMessage=="string"||P.signedMessage instanceof Uint8Array)&&P.signature instanceof Uint8Array)x=typeof P.signedMessage=="string"?P.signedMessage:new TextDecoder().decode(P.signedMessage),w=P.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in j)||typeof j.signMessage!="function"||!("publicKey"in j)||typeof j!="object"||!j.publicKey||!("toBase58"in j.publicKey)||typeof j.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");x=[`${E.host} wants you to sign in with your Solana account:`,j.publicKey.toBase58(),...A?["",A,""]:[""],"Version: 1",`URI: ${E.href}`,`Issued At: ${(i=(n=O==null?void 0:O.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()}`,...!((a=O==null?void 0:O.signInWithSolana)===null||a===void 0)&&a.notBefore?[`Not Before: ${O.signInWithSolana.notBefore}`]:[],...!((o=O==null?void 0:O.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${O.signInWithSolana.expirationTime}`]:[],...!((c=O==null?void 0:O.signInWithSolana)===null||c===void 0)&&c.chainId?[`Chain ID: ${O.signInWithSolana.chainId}`]:[],...!((u=O==null?void 0:O.signInWithSolana)===null||u===void 0)&&u.nonce?[`Nonce: ${O.signInWithSolana.nonce}`]:[],...!((d=O==null?void 0:O.signInWithSolana)===null||d===void 0)&&d.requestId?[`Request ID: ${O.signInWithSolana.requestId}`]:[],...!((f=(p=O==null?void 0:O.signInWithSolana)===null||p===void 0?void 0:p.resources)===null||f===void 0)&&f.length?["Resources",...O.signInWithSolana.resources.map(P=>`- ${P}`)]:[]].join(`
|
|
431
|
+
`);const T=await j.signMessage(new TextEncoder().encode(x),"utf8");if(!T||!(T instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");w=T}}try{const{data:b,error:S}=await Ne(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:x,signature:ko(w)},!((g=e.options)===null||g===void 0)&&g.captchaToken?{gotrue_meta_security:{captcha_token:(v=e.options)===null||v===void 0?void 0:v.captchaToken}}:null),xform:On});if(S)throw S;if(!b||!b.session||!b.user){const A=new _s;return this._returnResult({data:{user:null,session:null},error:A})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:S})}catch(b){if(be(b))return this._returnResult({data:{user:null,session:null},error:b});throw b}}async _exchangeCodeForSession(e){const r=await vo(this.storage,`${this.storageKey}-code-verifier`),[n,i]=(r??"").split("/");try{if(!n&&this.flowType==="pkce")throw new G8;const{data:a,error:o}=await Ne(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:On});if(await br(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!a||!a.session||!a.user){const c=new _s;return this._returnResult({data:{user:null,session:null,redirectType:null},error:c})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers(i==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",a.session)),this._returnResult({data:Object.assign(Object.assign({},a),{redirectType:i??null}),error:o})}catch(a){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(a))return this._returnResult({data:{user:null,session:null,redirectType:null},error:a});throw a}}async signInWithIdToken(e){try{const{options:r,provider:n,token:i,access_token:a,nonce:o}=e,c=await Ne(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:i,access_token:a,nonce:o,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:On}),{data:u,error:d}=c;if(d)return this._returnResult({data:{user:null,session:null},error:d});if(!u||!u.session||!u.user){const p=new _s;return this._returnResult({data:{user:null,session:null},error:p})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("SIGNED_IN",u.session)),this._returnResult({data:u,error:d})}catch(r){if(be(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,n,i,a,o;try{if("email"in e){const{email:c,options:u}=e;let d=null,p=null;this.flowType==="pkce"&&([d,p]=await Ss(this.storage,this.storageKey));const{error:f}=await Ne(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:c,data:(r=u==null?void 0:u.data)!==null&&r!==void 0?r:{},create_user:(n=u==null?void 0:u.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken},code_challenge:d,code_challenge_method:p},redirectTo:u==null?void 0:u.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:f})}if("phone"in e){const{phone:c,options:u}=e,{data:d,error:p}=await Ne(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:c,data:(i=u==null?void 0:u.data)!==null&&i!==void 0?i:{},create_user:(a=u==null?void 0:u.shouldCreateUser)!==null&&a!==void 0?a:!0,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken},channel:(o=u==null?void 0:u.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:d==null?void 0:d.message_id},error:p})}throw new df("You must provide either an email or phone number.")}catch(c){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(c))return this._returnResult({data:{user:null,session:null},error:c});throw c}}async verifyOtp(e){var r,n;try{let i,a;"options"in e&&(i=(r=e.options)===null||r===void 0?void 0:r.redirectTo,a=(n=e.options)===null||n===void 0?void 0:n.captchaToken);const{data:o,error:c}=await Ne(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:a}}),redirectTo:i,xform:On});if(c)throw c;if(!o)throw new Error("An error occurred on token verification.");const u=o.session,d=o.user;return u!=null&&u.access_token&&(await this._saveSession(u),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",u)),this._returnResult({data:{user:d,session:u},error:null})}catch(i){if(be(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithSSO(e){var r,n,i,a,o;try{let c=null,u=null;this.flowType==="pkce"&&([c,u]=await Ss(this.storage,this.storageKey));const d=await Ne(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((i=e==null?void 0:e.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:c,code_challenge_method:u}),headers:this.headers,xform:yU});return!((a=d.data)===null||a===void 0)&&a.url&&xr()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(d.data.url),this._returnResult(d)}catch(c){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(c))return this._returnResult({data:null,error:c});throw c}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;if(n)throw n;if(!r)throw new pr;const{error:i}=await Ne(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:i})})}catch(e){if(be(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:n,type:i,options:a}=e,{error:o}=await Ne(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:i,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},redirectTo:a==null?void 0:a.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){const{phone:n,type:i,options:a}=e,{data:o,error:c}=await Ne(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:i,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:c})}throw new df("You must provide either an email or phone number and a type")}catch(r){if(be(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const n=r();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){const i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length)}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await vo(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const n=e.expires_at?e.expires_at*1e3-Date.now()<jg:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){const o=await vo(this.userStorage,this.storageKey+"-user");o!=null&&o.user?e.user=o.user:e.user=Ng()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const o={value:this.suppressGetSessionWarning};e.user=hU(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:i,error:a}=await this._callRefreshToken(e.refresh_token);return a?this._returnResult({data:{session:null},error:a}):this._returnResult({data:{session:i},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await Ne(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Na}):await this._useSession(async r=>{var n,i,a;const{data:o,error:c}=r;if(c)throw c;return!(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new pr}:await Ne(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(a=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&a!==void 0?a:void 0,xform:Na})})}catch(r){if(be(r))return uf(r)&&(await this._removeSession(),await br(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async n=>{const{data:i,error:a}=n;if(a)throw a;if(!i.session)throw new pr;const o=i.session;let c=null,u=null;this.flowType==="pkce"&&e.email!=null&&([c,u]=await Ss(this.storage,this.storageKey));const{data:d,error:p}=await Ne(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:c,code_challenge_method:u}),jwt:o.access_token,xform:Na});if(p)throw p;return o.user=d.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new pr;const r=Date.now()/1e3;let n=r,i=!0,a=null;const{payload:o}=hf(e.access_token);if(o.exp&&(n=o.exp,i=n<=r),i){const{data:c,error:u}=await this._callRefreshToken(e.refresh_token);if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c)return{data:{user:null,session:null},error:null};a=c}else{const{data:c,error:u}=await this._getUser(e.access_token);if(u)return this._returnResult({data:{user:null,session:null},error:u});a={access_token:e.access_token,refresh_token:e.refresh_token,user:c.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(a),await this._notifyAllSubscribers("SIGNED_IN",a)}return this._returnResult({data:{user:a.user,session:a},error:null})}catch(r){if(be(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var n;if(!e){const{data:o,error:c}=r;if(c)throw c;e=(n=o.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new pr;const{data:i,error:a}=await this._callRefreshToken(e.refresh_token);return a?this._returnResult({data:{user:null,session:null},error:a}):i?this._returnResult({data:{user:i.user,session:i},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(be(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var n;try{if(!xr())throw new ff("No browser detected.");if(e.error||e.error_description||e.error_code)throw new ff(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new yE("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new ff("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new yE("No code detected.");const{data:O,error:j}=await this._exchangeCodeForSession(e.code);if(j)throw j;const E=new URL(window.location.href);return E.searchParams.delete("code"),window.history.replaceState(window.history.state,"",E.toString()),{data:{session:O.session,redirectType:(n=O.redirectType)!==null&&n!==void 0?n:null},error:null}}const{provider_token:i,provider_refresh_token:a,access_token:o,refresh_token:c,expires_in:u,expires_at:d,token_type:p}=e;if(!o||!u||!c||!p)throw new ff("No session defined in URL");const f=Math.round(Date.now()/1e3),g=parseInt(u);let v=f+g;d&&(v=parseInt(d));const x=v-f;x*1e3<=Ps&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${x}s, should have been closer to ${g}s`);const w=v-g;f-w>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",w,v,f):f-w<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",w,v,f);const{data:b,error:S}=await this._getUser(o);if(S)throw S;const A={provider_token:i,provider_refresh_token:a,access_token:o,expires_in:g,expires_at:v,refresh_token:c,token_type:p,user:b.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:A,redirectType:e.type},error:null})}catch(i){if(be(i))return this._returnResult({data:{session:null,redirectType:null},error:i});throw i}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){const r=await vo(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var n;const{data:i,error:a}=r;if(a&&!uf(a))return this._returnResult({error:a});const o=(n=i.session)===null||n===void 0?void 0:n.access_token;if(o){const{error:c}=await this.admin.signOut(o,e);if(c&&!(H8(c)&&(c.status===404||c.status===401||c.status===403)||uf(c)))return this._returnResult({error:c})}return e!=="others"&&(await this._removeSession(),await br(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=Q8(),n={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async r=>{var n,i;try{const{data:{session:a},error:o}=r;if(o)throw o;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",a)),this._debug("INITIAL_SESSION","callback id",e,"session",a)}catch(a){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",a),uf(a)?console.warn(a):console.error(a)}})}async resetPasswordForEmail(e,r={}){let n=null,i=null;this.flowType==="pkce"&&([n,i]=await Ss(this.storage,this.storageKey,!0));try{return await Ne(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:i,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(a){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(a))return this._returnResult({data:null,error:a});throw a}}async getUserIdentities(){var e;try{const{data:r,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{const{data:n,error:i}=await this._useSession(async a=>{var o,c,u,d,p;const{data:f,error:g}=a;if(g)throw g;const v=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(c=e.options)===null||c===void 0?void 0:c.scopes,queryParams:(u=e.options)===null||u===void 0?void 0:u.queryParams,skipBrowserRedirect:!0});return await Ne(this.fetch,"GET",v,{headers:this.headers,jwt:(p=(d=f.session)===null||d===void 0?void 0:d.access_token)!==null&&p!==void 0?p:void 0})});if(i)throw i;return xr()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n==null?void 0:n.url),this._returnResult({data:{provider:e.provider,url:n==null?void 0:n.url},error:null})}catch(n){if(be(n))return this._returnResult({data:{provider:e.provider,url:null},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var n;try{const{error:i,data:{session:a}}=r;if(i)throw i;const{options:o,provider:c,token:u,access_token:d,nonce:p}=e,f=await Ne(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=a==null?void 0:a.access_token)!==null&&n!==void 0?n:void 0,body:{provider:c,id_token:u,access_token:d,nonce:p,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:On}),{data:g,error:v}=f;return v?this._returnResult({data:{user:null,session:null},error:v}):!g||!g.session||!g.user?this._returnResult({data:{user:null,session:null},error:new _s}):(g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("USER_UPDATED",g.session)),this._returnResult({data:g,error:v}))}catch(i){if(await br(this.storage,`${this.storageKey}-code-verifier`),be(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var n,i;const{data:a,error:o}=r;if(o)throw o;return await Ne(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(n=a.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0})})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{const n=Date.now();return await nU(async i=>(i>0&&await rU(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await Ne(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:On})),(i,a)=>{const o=200*Math.pow(2,i);return a&&Cg(a)&&Date.now()+o-n<Ps})}catch(n){if(this._debug(r,"error",n),be(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",n),xr()&&!r.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,r;const n="#_recoverAndRefresh()";this._debug(n,"begin");try{const i=await vo(this.storage,this.storageKey);if(i&&this.userStorage){let o=await vo(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:i.user},await Rs(this.userStorage,this.storageKey+"-user",o)),i.user=(e=o==null?void 0:o.user)!==null&&e!==void 0?e:Ng()}else if(i&&!i.user&&!i.user){const o=await vo(this.storage,this.storageKey+"-user");o&&(o!=null&&o.user)?(i.user=o.user,await br(this.storage,this.storageKey+"-user"),await Rs(this.storage,this.storageKey,i)):i.user=Ng()}if(this._debug(n,"session from storage",i),!this._isValidSession(i)){this._debug(n,"session is not valid"),i!==null&&await this._removeSession();return}const a=((r=i.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<jg;if(this._debug(n,`session has${a?"":" not"} expired with margin of ${jg}s`),a){if(this.autoRefreshToken&&i.refresh_token){const{error:o}=await this._callRefreshToken(i.refresh_token);o&&(console.error(o),Cg(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(i.user&&i.user.__isUserNotAvailableProxy===!0)try{const{data:o,error:c}=await this._getUser(i.access_token);!c&&(o!=null&&o.user)?(i.user=o.user,await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)):this._debug(n,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(n,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",i)}catch(i){this._debug(n,"error",i),console.error(i);return}finally{this._debug(n,"end")}}async _callRefreshToken(e){var r,n;if(!e)throw new pr;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new op;const{data:a,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!a.session)throw new pr;await this._saveSession(a.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",a.session);const c={data:a.session,error:null};return this.refreshingDeferred.resolve(c),c}catch(a){if(this._debug(i,"error",a),be(a)){const o={data:null,error:a};return Cg(a)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(a),a}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,r,n=!0){const i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",r,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:r});const a=[],o=Array.from(this.stateChangeEmitters.values()).map(async c=>{try{await c.callback(e,r)}catch(u){a.push(u)}});if(await Promise.all(o),a.length>0){for(let c=0;c<a.length;c+=1)console.error(a[c]);throw a[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await br(this.storage,`${this.storageKey}-code-verifier`);const r=Object.assign({},e),n=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!n&&r.user&&await Rs(this.userStorage,this.storageKey+"-user",{user:r.user});const i=Object.assign({},r);delete i.user;const a=_E(i);await Rs(this.storage,this.storageKey,a)}else{const i=_E(r);await Rs(this.storage,this.storageKey,i)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await br(this.storage,this.storageKey),await br(this.storage,this.storageKey+"-code-verifier"),await br(this.storage,this.storageKey+"-user"),this.userStorage&&await br(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&xr()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),Ps);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const 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()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const i=Math.floor((n.expires_at*1e3-e)/Ps);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${Ps}ms, refresh threshold is ${rx} ticks`),i<=rx&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof hR)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!xr()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,n){const i=[`provider=${encodeURIComponent(r)}`];if(n!=null&&n.redirectTo&&i.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n!=null&&n.scopes&&i.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){const[a,o]=await Ss(this.storage,this.storageKey),c=new URLSearchParams({code_challenge:`${encodeURIComponent(a)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(c.toString())}if(n!=null&&n.queryParams){const a=new URLSearchParams(n.queryParams);i.push(a.toString())}return n!=null&&n.skipBrowserRedirect&&i.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var n;const{data:i,error:a}=r;return a?this._returnResult({data:null,error:a}):await Ne(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var n,i;const{data:a,error:o}=r;if(o)return this._returnResult({data:null,error:o});const c=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:u,error:d}=await Ne(this.fetch,"POST",`${this.url}/factors`,{body:c,headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token});return d?this._returnResult({data:null,error:d}):(e.factorType==="totp"&&u.type==="totp"&&(!((i=u==null?void 0:u.totp)===null||i===void 0)&&i.qr_code)&&(u.totp.qr_code=`data:image/svg+xml;utf-8,${u.totp.qr_code}`),this._returnResult({data:u,error:null}))})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;const{data:i,error:a}=r;if(a)return this._returnResult({data:null,error:a});const o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?CE(e.webauthn.credential_response):NE(e.webauthn.credential_response)})}:{code:e.code}),{data:c,error:u}=await Ne(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=i==null?void 0: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)+c.expires_in},c)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",c),this._returnResult({data:c,error:u}))})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;const{data:i,error:a}=r;if(a)return this._returnResult({data:null,error:a});const o=await Ne(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;const{data:c}=o;if(c.type!=="webauthn")return{data:c,error:null};switch(c.webauthn.type){case"create":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:TE(c.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:jE(c.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){const{data:r,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:n}=await this.getUser();if(n)return{data:null,error:n};const i={all:[],phone:[],totp:[],webauthn:[]};for(const a of(e=r==null?void 0:r.factors)!==null&&e!==void 0?e:[])i.all.push(a),a.status==="verified"&&i[a.factor_type].push(a);return{data:i,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,n,i,a;if(e)try{const{payload:v}=hf(e);let x=null;v.aal&&(x=v.aal);let w=x;const{data:{user:b},error:S}=await this.getUser(e);if(S)return this._returnResult({data:null,error:S});((n=(r=b==null?void 0:b.factors)===null||r===void 0?void 0:r.filter(j=>j.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(w="aal2");const O=v.amr||[];return{data:{currentLevel:x,nextLevel:w,currentAuthenticationMethods:O},error:null}}catch(v){if(be(v))return this._returnResult({data:null,error:v});throw v}const{data:{session:o},error:c}=await this.getSession();if(c)return this._returnResult({data:null,error:c});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:u}=hf(o.access_token);let d=null;u.aal&&(d=u.aal);let p=d;((a=(i=o.user.factors)===null||i===void 0?void 0:i.filter(v=>v.status==="verified"))!==null&&a!==void 0?a:[]).length>0&&(p="aal2");const g=u.amr||[];return{data:{currentLevel:d,nextLevel:p,currentAuthenticationMethods:g},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?await Ne(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:a=>({data:a,error:null})}):this._returnResult({data:null,error:new pr})})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async n=>{const{data:{session:i},error:a}=n;if(a)return this._returnResult({data:null,error:a});if(!i)return this._returnResult({data:null,error:new pr});const o=await Ne(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"approve"},xform:c=>({data:c,error:null})});return o.data&&o.data.redirect_url&&xr()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(n){if(be(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,r){try{return await this._useSession(async n=>{const{data:{session:i},error:a}=n;if(a)return this._returnResult({data:null,error:a});if(!i)return this._returnResult({data:null,error:new pr});const o=await Ne(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"deny"},xform:c=>({data:c,error:null})});return o.data&&o.data.redirect_url&&xr()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(n){if(be(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;return n?this._returnResult({data:null,error:n}):r?await Ne(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new pr})})}catch(e){if(be(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?(await Ne(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new pr})})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(c=>c.kid===e);if(n)return n;const i=Date.now();if(n=this.jwks.keys.find(c=>c.kid===e),n&&this.jwks_cached_at+q8>i)return n;const{data:a,error:o}=await Ne(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!a.keys||a.keys.length===0||(this.jwks=a,this.jwks_cached_at=i,n=a.keys.find(c=>c.kid===e),!n)?null:n}async getClaims(e,r={}){try{let n=e;if(!n){const{data:v,error:x}=await this.getSession();if(x||!v.session)return this._returnResult({data:null,error:x});n=v.session.access_token}const{header:i,payload:a,signature:o,raw:{header:c,payload:u}}=hf(n);r!=null&&r.allowExpired||uU(a.exp);const d=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,r!=null&&r.keys?{keys:r.keys}:r==null?void 0:r.jwks);if(!d){const{error:v}=await this.getUser(n);if(v)throw v;return{data:{claims:a,header:i,signature:o},error:null}}const p=dU(i.alg),f=await crypto.subtle.importKey("jwk",d,p,!0,["verify"]);if(!await crypto.subtle.verify(p,f,o,J8(`${c}.${u}`)))throw new ax("Invalid JWT signature");return{data:{claims:a,header:i,signature:o},error:null}}catch(n){if(be(n))return this._returnResult({data:null,error:n});throw n}}async signInWithPasskey(e){var r,n,i;qn(this.experimental);try{if(!Wf())return this._returnResult({data:null,error:new Xn("Browser does not support WebAuthn",null)});const{data:a,error:o}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.captchaToken}});if(o||!a)return this._returnResult({data:null,error:o});const c=jE(a.options),u=(i=(n=e==null?void 0:e.options)===null||n===void 0?void 0:n.signal)!==null&&i!==void 0?i:ox.createNewAbortSignal(),{data:d,error:p}=await yR({publicKey:c,signal:u});if(p||!d)return this._returnResult({data:null,error:p??new Xn("WebAuthn ceremony failed",null)});const f=NE(d);return this._verifyPasskeyAuthentication({challengeId:a.challenge_id,credential:f})}catch(a){if(be(a))return this._returnResult({data:null,error:a});throw a}}async registerPasskey(e){var r,n;qn(this.experimental);try{if(!Wf())return this._returnResult({data:null,error:new Xn("Browser does not support WebAuthn",null)});const{data:i,error:a}=await this._startPasskeyRegistration();if(a||!i)return this._returnResult({data:null,error:a});const o=TE(i.options),c=(n=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.signal)!==null&&n!==void 0?n:ox.createNewAbortSignal(),{data:u,error:d}=await gR({publicKey:o,signal:c});if(d||!u)return this._returnResult({data:null,error:d??new Xn("WebAuthn ceremony failed",null)});const p=CE(u);return this._verifyPasskeyRegistration({challengeId:i.challenge_id,credential:p})}catch(i){if(be(i))return this._returnResult({data:null,error:i});throw i}}async _startPasskeyRegistration(){qn(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;if(n)return this._returnResult({data:null,error:n});if(!r)return this._returnResult({data:null,error:new pr});const{data:i,error:a}=await Ne(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:r.access_token,body:{}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(e){if(be(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){qn(this.experimental);try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new pr});const{data:a,error:o}=await Ne(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:n.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:a,error:null})})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;qn(this.experimental);try{const{data:n,error:i}=await Ne(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.captchaToken}}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})}catch(n){if(be(n))return this._returnResult({data:null,error:n});throw n}}async _verifyPasskeyAuthentication(e){qn(this.experimental);try{const{data:r,error:n}=await Ne(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:On});return n?this._returnResult({data:null,error:n}):(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:r,error:null}))}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){qn(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:n}=e;if(n)return this._returnResult({data:null,error:n});if(!r)return this._returnResult({data:null,error:new pr});const{data:i,error:a}=await Ne(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:o=>({data:o,error:null})});return a?this._returnResult({data:null,error:a}):this._returnResult({data:i,error:null})})}catch(e){if(be(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){qn(this.experimental);try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new pr});const{data:a,error:o}=await Ne(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:n.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:a,error:null})})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){qn(this.experimental);try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new pr});const{error:a}=await Ne(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:n.access_token,noResolveJson:!0});return a?this._returnResult({data:null,error:a}):this._returnResult({data:null,error:null})})}catch(r){if(be(r))return this._returnResult({data:null,error:r});throw r}}}Gc.nextInstanceID={};const $U=Gc,MU="2.106.2";let Tc="";typeof Deno<"u"?Tc="deno":typeof document<"u"?Tc="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Tc="react-native":Tc="node";const LU={"X-Client-Info":`supabase-js-${Tc}/${MU}`},DU={headers:LU},zU={schema:"public"},BU={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},UU={},qU={enabled:!1,respectSamplingDecision:!0};function FU(t,e,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function c(p){try{d(n.next(p))}catch(f){o(f)}}function u(p){try{d(n.throw(p))}catch(f){o(f)}}function d(p){p.done?a(p.value):i(p.value).then(c,u)}d((n=n.apply(t,[])).next())})}let Rg=null;const HU="@opentelemetry/api";function WU(){return Rg===null&&(Rg=import(HU).catch(()=>null)),Rg}function GU(){return FU(this,void 0,void 0,function*(){try{const t=yield WU();if(!t||!t.propagation||!t.context)return null;const e={};t.propagation.inject(t.context.active(),e);const r=e.traceparent;return r?{traceparent:r,tracestate:e.tracestate,baggage:e.baggage}:null}catch{return null}})}function KU(t){if(!t||typeof t!="string")return null;const e=t.split("-");if(e.length!==4)return null;const[r,n,i,a]=e;if(r.length!==2||n.length!==32||i.length!==16||a.length!==2)return null;const o=/^[0-9a-f]+$/i;return!o.test(r)||!o.test(n)||!o.test(i)||!o.test(a)||n==="00000000000000000000000000000000"||i==="0000000000000000"?null:{version:r,traceId:n,parentId:i,traceFlags:a,isSampled:(parseInt(a,16)&1)===1}}function VU(t,e){if(!t||!e||e.length===0)return!1;let r;if(t instanceof URL)r=t;else try{r=new URL(t)}catch{return!1}for(const n of e)try{if(typeof n=="string"){if(XU(r.hostname,n))return!0}else if(n instanceof RegExp){if(n.test(r.hostname))return!0}else if(typeof n=="function"&&n(r))return!0}catch{continue}return!1}function XU(t,e){if(e===t)return!0;if(e.startsWith("*.")){const r=e.slice(2);if(t.endsWith(r)&&(t===r||t.endsWith("."+r)))return!0}return!1}function YU(t){const e=[];try{const r=new URL(t);e.push(r.hostname)}catch{}return e.push("*.supabase.co","*.supabase.in"),e.push("localhost","127.0.0.1","[::1]"),e}function Kc(t){"@babel/helpers - typeof";return Kc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Kc(t)}function JU(t,e){if(Kc(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(Kc(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function ZU(t){var e=JU(t,"string");return Kc(e)=="symbol"?e:e+""}function QU(t,e,r){return(e=ZU(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function RE(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function Ht(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?RE(Object(r),!0).forEach(function(n){QU(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):RE(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}const eq=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),tq=()=>Headers,rq=(t,e,r,n,i)=>{const a=eq(n),o=tq(),c=(i==null?void 0:i.enabled)===!0,u=(i==null?void 0:i.respectSamplingDecision)!==!1,d=c?YU(e):null;return async(p,f)=>{var g;const v=(g=await r())!==null&&g!==void 0?g:t;let x=new o(f==null?void 0:f.headers);if(x.has("apikey")||x.set("apikey",t),x.has("Authorization")||x.set("Authorization",`Bearer ${v}`),d){const w=await nq(p,d,u);w&&(w.traceparent&&!x.has("traceparent")&&x.set("traceparent",w.traceparent),w.tracestate&&!x.has("tracestate")&&x.set("tracestate",w.tracestate),w.baggage&&!x.has("baggage")&&x.set("baggage",w.baggage))}return a(p,Ht(Ht({},f),{},{headers:x}))}};async function nq(t,e,r){if(!VU(typeof t=="string"||t instanceof URL?t:t.url,e))return null;const n=await GU();if(!n||!n.traceparent)return null;if(r){const i=KU(n.traceparent);if(i&&!i.isSampled)return null}return n}function IE(t){return typeof t=="boolean"?{enabled:t}:t}function iq(t){return t.endsWith("/")?t:t+"/"}function aq(t,e){var r,n,i,a,o,c;const{db:u,auth:d,realtime:p,global:f}=t,{db:g,auth:v,realtime:x,global:w}=e,b=IE(t.tracePropagation),S=IE(e.tracePropagation),A={db:Ht(Ht({},g),u),auth:Ht(Ht({},v),d),realtime:Ht(Ht({},x),p),storage:{},global:Ht(Ht(Ht({},w),f),{},{headers:Ht(Ht({},(r=w==null?void 0:w.headers)!==null&&r!==void 0?r:{}),(n=f==null?void 0:f.headers)!==null&&n!==void 0?n:{})}),tracePropagation:{enabled:(i=(a=b==null?void 0:b.enabled)!==null&&a!==void 0?a:S==null?void 0:S.enabled)!==null&&i!==void 0?i:!1,respectSamplingDecision:(o=(c=b==null?void 0:b.respectSamplingDecision)!==null&&c!==void 0?c:S==null?void 0:S.respectSamplingDecision)!==null&&o!==void 0?o:!0},accessToken:async()=>""};return t.accessToken?A.accessToken=t.accessToken:delete A.accessToken,A}function oq(t){const e=t==null?void 0:t.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(iq(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var sq=class extends $U{constructor(t){super(t)}},lq=class{constructor(t,e,r){var n,i;this.supabaseUrl=t,this.supabaseKey=e;const a=oq(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const o=`sb-${a.hostname.split(".")[0]}-auth-token`,c={db:zU,realtime:UU,auth:Ht(Ht({},BU),{},{storageKey:o}),global:DU,tracePropagation:qU},u=aq(r??{},c);if(this.settings=u,this.storageKey=(n=u.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(i=u.global.headers)!==null&&i!==void 0?i:{},u.accessToken)this.accessToken=u.accessToken,this.auth=new Proxy({},{get:(p,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 d;this.auth=this._initSupabaseAuthClient((d=u.auth)!==null&&d!==void 0?d:{},this.headers,u.global.fetch)}this.fetch=rq(e,t,this._getAccessToken.bind(this),u.global.fetch,u.tracePropagation),this.realtime=this._initRealtimeClient(Ht({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},u.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(p=>this.realtime.setAuth(p)).catch(p=>console.warn("Failed to set initial Realtime auth token:",p)),this.rest=new k6(new URL("rest/v1",a).href,{headers:this.headers,schema:u.db.schema,fetch:this.fetch,timeout:u.db.timeout,urlLengthLimit:u.db.urlLengthLimit}),this.storage=new L8(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),u.accessToken||this._listenForAuthEvents()}get functions(){return new p6(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();const{data:n}=await t.auth.getSession();return(e=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,storageKey:a,flowType:o,lock:c,debug:u,throwOnError:d,experimental:p,lockAcquireTimeout:f,skipAutoInitialize:g},v,x){const w={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new sq({url:this.authUrl.href,headers:Ht(Ht({},w),v),storageKey:a,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,flowType:o,lock:c,debug:u,throwOnError:d,experimental:p,fetch:x,lockAcquireTimeout:f,skipAutoInitialize:g,hasCustomAuthorizationHeader:Object.keys(this.headers).some(b=>b.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new o8(this.realtimeUrl.href,Ht(Ht({},t),{},{params:Ht(Ht({},{apikey:this.supabaseKey}),t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const cq=(t,e,r)=>new lq(t,e,r);function uq(){if(typeof window<"u")return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}uq()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const vR=N.createContext({session:null,supabase:null,loading:!0,signIn:async()=>({error:"Not initialized"}),signOut:async()=>{}});function sp(){return N.useContext(vR)}function dq({children:t}){const[e,r]=N.useState(null),[n,i]=N.useState(null),[a,o]=N.useState(!0),c=N.useRef(null);N.useEffect(()=>{Y4(()=>{var f;return((f=c.current)==null?void 0:f.access_token)??null})},[]);const u=N.useRef(null);N.useEffect(()=>{J4(async()=>{const f=u.current;if(!f)return null;const{data:g,error:v}=await f.auth.refreshSession();return v||!g.session?null:(c.current=g.session,i(g.session),g.session.access_token)})},[]),N.useEffect(()=>{Ve.get("/config").then(({config:f})=>{if(f.supabase.projectUrl&&f.supabase.anonKey){const g=cq(f.supabase.projectUrl,f.supabase.anonKey);r(g),u.current=g,g.auth.getSession().then(({data:x})=>{c.current=x.session,i(x.session),o(!1)});const{data:{subscription:v}}=g.auth.onAuthStateChange((x,w)=>{c.current=w,i(w)});return()=>v.unsubscribe()}o(!1)}).catch(()=>{o(!1)})},[]);async function d(f,g){if(!e)return{error:"Supabase not configured"};const{error:v}=await e.auth.signInWithPassword({email:f,password:g});return{error:(v==null?void 0:v.message)??null}}async function p(){e&&(await e.auth.signOut(),c.current=null,i(null))}return y.jsx(vR.Provider,{value:{session:n,supabase:e,loading:a,signIn:d,signOut:p},children:t})}const fq=[{to:"/squads",icon:Zh,label:"Squads"},{to:"/skills",icon:qb,label:"Skills"},{to:"/schedules",icon:B5,label:"Schedules"},{to:"/wiki",icon:XN,label:"Wiki"},{to:"/usage",icon:q5,label:"Usage"}],hq=[{to:"/",icon:zw,label:"Chat"},{to:"/feed",icon:Bb,label:"Inbox"},{to:"/settings",icon:z4,label:"Settings"}];function $E({to:t,icon:e,label:r,collapsed:n,badge:i}){return y.jsxs(GN,{to:t,end:t==="/",title:n?r:void 0,className:({isActive:a})=>Oc("w-full flex items-center gap-2.5 px-2 py-2 rounded-xl text-[11px] font-mono transition-colors cursor-pointer relative",n?"justify-center":"",a?"text-[#E43A9C]":"text-zinc-600 hover:text-zinc-300 hover:bg-white/[0.04]"),style:({isActive:a})=>a?{background:"rgba(228,58,156,0.1)"}:void 0,children:[y.jsx(e,{className:"w-3.5 h-3.5 flex-shrink-0"}),!n&&r,i!=null&&i>0&&y.jsx("span",{className:"absolute top-1 right-1 min-w-[14px] h-[14px] flex items-center justify-center rounded-full bg-[#E43A9C] text-[9px] text-white font-mono px-1",children:i>99?"99+":i})]})}function pq(){const[t,e]=N.useState(!1),[r,n]=N.useState("..."),[i,a]=N.useState(0),{supabase:o}=sp();return N.useEffect(()=>{let c=!0;Ve.get("/version").then(({version:d})=>{c&&n(d)}).catch(()=>{c&&n("unknown")}),Ve.get("/inbox/unread-count").then(({count:d})=>{c&&a(d)}).catch(()=>{});const u=setInterval(()=>{Ve.get("/inbox/unread-count").then(({count:d})=>{c&&a(d)}).catch(()=>{})},3e4);return()=>{c=!1,clearInterval(u)}},[]),y.jsxs("div",{className:"flex h-screen overflow-hidden bg-background relative",children:[y.jsxs("div",{className:Oc("flex-shrink-0 flex flex-col border-r border-white/[0.06] bg-[#181818] transition-all duration-200",t?"w-[52px]":"w-[210px]"),children:[y.jsx("div",{className:Oc("h-[52px] flex items-center border-b border-white/[0.06] flex-shrink-0",t?"justify-center px-3":"justify-between pl-4 pr-3"),children:t?y.jsx(Ra,{height:26}):y.jsxs("div",{className:"flex items-center gap-2.5",children:[y.jsx(Ra,{height:26}),y.jsx("span",{className:"text-2xl text-white tracking-wider leading-none",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"IO"})]})}),y.jsx("nav",{className:"flex-1 py-2 px-1.5 space-y-0.5 overflow-y-auto",children:fq.map(c=>y.jsx($E,{collapsed:t,...c},c.to))}),y.jsxs("div",{className:"flex-shrink-0 border-t border-white/[0.06]",children:[y.jsx("div",{className:"py-1.5 px-1.5 space-y-0.5",children:hq.map(c=>y.jsx($E,{collapsed:t,badge:c.to==="/feed"?i:void 0,...c},c.to))}),y.jsxs("div",{className:"border-t border-white/[0.05] py-1.5 px-1.5 space-y-0.5",children:[y.jsxs("a",{href:`https://github.com/michaeljolley/io/releases/tag/v${r}`,target:"_blank",rel:"noreferrer",title:"GitHub",className:Oc("flex items-center gap-2.5 px-2 py-2 rounded-xl text-[11px] font-mono text-zinc-600 hover:text-zinc-300 hover:bg-white/[0.04] transition-colors cursor-pointer",t&&"justify-center"),children:[y.jsx(f4,{className:"w-3.5 h-3.5 flex-shrink-0"}),!t&&y.jsxs("span",{className:"text-zinc-700",children:["v",r]})]}),y.jsx("button",{type:"button",onClick:()=>e(!t),title:t?"Expand sidebar":"Collapse sidebar",className:Oc("w-full flex items-center gap-2.5 px-2 py-2 rounded-xl text-[11px] font-mono text-zinc-600 hover:text-zinc-300 hover:bg-white/[0.04] transition-colors cursor-pointer",t&&"justify-center"),children:t?y.jsx(Mw,{className:"w-3.5 h-3.5 flex-shrink-0"}):y.jsx(vl,{className:"w-3.5 h-3.5 flex-shrink-0"})})]})]})]}),y.jsxs("div",{className:"flex flex-col flex-1 min-w-0 overflow-hidden",children:[y.jsxs("div",{className:"h-[52px] flex-shrink-0 flex items-center justify-between px-4 border-b border-white/[0.06] bg-[#181818]",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx(l6,{status:"connected"}),y.jsx("span",{className:"text-[11px] font-mono text-green-400",children:"connected"})]}),y.jsxs("div",{className:"flex items-center gap-1.5",children:[y.jsx(iz,{}),o&&y.jsx("button",{type:"button",onClick:()=>o.auth.signOut(),className:"p-2 rounded-xl hover:bg-white/[0.05] text-zinc-600 hover:text-zinc-300 transition-colors cursor-pointer",title:"Sign out",children:y.jsx(x4,{className:"w-3.5 h-3.5"})})]})]}),y.jsxs("main",{className:"flex-1 overflow-hidden flex flex-col min-h-0 relative",children:[y.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",style:{zIndex:0},children:[y.jsx("div",{className:"orb orb-pink"}),y.jsx("div",{className:"orb orb-gray"})]}),y.jsx(yD,{})]})]})]})}function mq(){const{session:t}=sp(),e=qa(),{messages:r,streaming:n,isStreaming:i,isThinking:a,sendChatMessage:o,addUserMessage:c,uploadAttachment:u}=cP(),[d,p]=N.useState(""),[f,g]=N.useState(null),[v,x]=N.useState(null),w=N.useRef(null),b=N.useRef(null),S=N.useRef(null);N.useLayoutEffect(()=>{const E=w.current;E&&(E.scrollTop=E.scrollHeight)},[r,n,a]);async function A(){const E=d.trim();if(!E&&!f||i||a)return;const T=crypto.randomUUID(),P=f==null?void 0:f.name,R=[E,P?`Attachment: ${P}`:""].filter(Boolean).join(`
|
|
430
432
|
|
|
431
|
-
`);c({id:T,role:"user",content:E,timestamp:new Date().toISOString(),attachmentName:P}),p(""),g(null),S.current&&(S.current.value=""),b.current&&(b.current.style.height="auto");try{f&&await u(f,T),o(R)}catch{}}function O(E){E.key==="Enter"&&!E.shiftKey&&(E.preventDefault(),A())}function j(E){p(E.target.value),b.current&&(b.current.style.height="auto",b.current.style.height=`${Math.min(b.current.scrollHeight,160)}px`)}return y.jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[y.jsxs("div",{ref:w,className:"flex-1 overflow-y-auto px-5 py-5 space-y-5",children:[r.map(E=>{var T,P;return y.jsxs("div",{className:`flex gap-3 ${E.role==="user"?"flex-row-reverse":""}`,children:[y.jsx("div",{className:`flex-shrink-0 w-6 h-6 rounded-lg flex items-center justify-center text-[10px] font-mono mt-0.5 ${E.role==="user"?"border border-[#E43A9C]/30 text-[#E43A9C]":"bg-[#282828] border border-white/[0.07] text-zinc-500"}`,style:E.role==="user"?{background:"rgba(228,58,156,0.12)"}:void 0,children:E.role==="user"?((P=(T=t==null?void 0:t.user)==null?void 0:T.email)==null?void 0:P.charAt(0).toUpperCase())??"U":y.jsx(Ra,{height:12})}),y.jsxs("div",{className:`flex flex-col gap-1.5 max-w-[72%] ${E.role==="user"?"items-end":"items-start"}`,children:[E.toolCall&&y.jsxs("button",{type:"button",onClick:()=>x(v===E.id?null:E.id),className:"w-full text-left border border-white/[0.07] bg-[#1e1e1e] rounded-xl px-3 py-2 flex items-center gap-2 hover:border-[#E43A9C]/25 transition-colors",children:[y.jsx(Ds,{className:"w-3 h-3 text-[#E43A9C] flex-shrink-0"}),y.jsx("span",{className:"text-[11px] font-mono text-zinc-400 flex-1",children:E.toolCall.name}),y.jsx(jt,{variant:E.toolCall.status==="done"?"success":E.toolCall.status==="error"?"error":"warning",children:E.toolCall.status}),y.jsx(H5,{className:`w-3 h-3 text-zinc-600 transition-transform flex-shrink-0 ${v===E.id?"rotate-180":""}`})]}),E.toolCall&&v===E.id&&y.jsx("div",{className:"w-full bg-[#181818] border border-white/[0.06] rounded-xl px-3 py-2",children:y.jsx("p",{className:"text-[11px] font-mono text-zinc-500",children:E.toolCall.result})}),E.attachmentName&&y.jsx("div",{className:"rounded-xl border border-white/[0.08] bg-[#1e1e1e] px-3 py-2 text-[11px] font-mono text-zinc-400",children:E.attachmentName}),E.content&&y.jsx("div",{className:`rounded-2xl px-4 py-2.5 text-sm leading-relaxed ${E.role==="user"?"text-white rounded-tr-sm":"bg-[#222222] border border-white/[0.07] text-zinc-200 rounded-tl-sm"}`,style:E.role==="user"?{background:"linear-gradient(135deg, #D83333 0%, #C0285E 100%)"}:void 0,children:E.role==="user"?y.jsx("p",{className:"whitespace-pre-wrap",children:E.content}):y.jsx("div",{className:"prose-io",dangerouslySetInnerHTML:{__html:nt.parse(E.content)}})}),y.jsx("span",{className:"text-[11px] text-zinc-700 font-mono px-0.5",children:Qh(E.timestamp,e)})]})]},E.id)}),a&&y.jsxs("div",{className:"flex gap-3",children:[y.jsx("div",{className:"flex-shrink-0 w-6 h-6 rounded-lg flex items-center justify-center bg-[#282828] border border-white/[0.07] mt-0.5",children:y.jsx(Ra,{height:12})}),y.jsx("div",{className:"bg-[#222222] border border-white/[0.07] rounded-2xl rounded-tl-sm px-4 py-3 flex items-center gap-1.5",children:[0,120,240].map(E=>y.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#E43A9C] animate-bounce",style:{animationDelay:`${E}ms`}},E))})]}),i&&n&&y.jsxs("div",{className:"flex gap-3",children:[y.jsx("div",{className:"flex-shrink-0 w-6 h-6 rounded-lg flex items-center justify-center bg-[#282828] border border-white/[0.07] mt-0.5",children:y.jsx(Ra,{height:12})}),y.jsx("div",{className:"bg-[#222222] border border-white/[0.07] rounded-2xl rounded-tl-sm px-4 py-2.5 max-w-[72%]",children:y.jsx("div",{className:"prose-io text-sm",dangerouslySetInnerHTML:{__html:nt.parse(n)}})})]}),i&&!n&&y.jsxs("div",{className:"flex gap-3",children:[y.jsx("div",{className:"flex-shrink-0 w-6 h-6 rounded-lg flex items-center justify-center bg-[#282828] border border-white/[0.07] mt-0.5",children:y.jsx(Ra,{height:12})}),y.jsx("div",{className:"bg-[#222222] border border-white/[0.07] rounded-2xl rounded-tl-sm px-4 py-3 flex items-center gap-1.5",children:[0,120,240].map(E=>y.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#E43A9C] animate-bounce",style:{animationDelay:`${E}ms`}},E))})]})]}),y.jsxs("div",{className:"border-t border-white/[0.06] p-4 flex-shrink-0",children:[y.jsxs("div",{className:"bg-[#1e1e1e] border border-white/[0.08] rounded-2xl overflow-hidden transition-colors focus-within:border-[#E43A9C]/30",children:[y.jsx("input",{ref:S,type:"file",className:"hidden",onChange:E=>{var T;return g(((T=E.target.files)==null?void 0:T[0])??null)}}),f&&y.jsxs("div",{className:"px-4 pt-3 text-[11px] font-mono text-zinc-400",children:["Attached: ",f.name]}),y.jsx("textarea",{ref:b,value:d,onChange:j,onKeyDown:O,placeholder:"Message IO…",rows:1,className:"w-full bg-transparent px-4 pt-3 pb-1 text-sm text-zinc-200 placeholder:text-zinc-700 resize-none focus:outline-none",style:{minHeight:"42px",maxHeight:"160px",fontFamily:"Inter, sans-serif"}}),y.jsxs("div",{className:"flex items-center justify-between px-3 pb-2.5",children:[y.jsx("button",{type:"button",onClick:()=>{var E;return(E=S.current)==null?void 0:E.click()},className:"p-1.5 rounded-lg hover:bg-white/[0.05] text-zinc-700 hover:text-zinc-400 transition-colors",children:y.jsx(tP,{className:"w-4 h-4"})}),y.jsx("div",{className:"flex items-center gap-2",children:i?y.jsxs("button",{type:"button",onClick:()=>{},className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-zinc-800 hover:bg-zinc-700 text-[11px] font-mono text-zinc-300 transition-colors",children:[y.jsx(Jh,{className:"w-3 h-3"})," Stop"]}):y.jsx("button",{type:"button",onClick:A,disabled:!d.trim()&&!f||a,className:"p-2 rounded-xl text-white disabled:opacity-30 disabled:cursor-not-allowed transition-opacity hover:opacity-90",style:{background:"linear-gradient(135deg, #D83333, #E43A9C)"},children:y.jsx(nP,{className:"w-3.5 h-3.5"})})})]})]}),y.jsx("p",{className:"text-center text-[11px] text-zinc-800 font-mono mt-2",children:"IO may make mistakes. Verify important outputs."})]})]})}var Rg,IE;function JU(){if(IE)return Rg;IE=1;function t(D){return D instanceof Map?D.clear=D.delete=D.set=function(){throw new Error("map is read-only")}:D instanceof Set&&(D.add=D.clear=D.delete=function(){throw new Error("set is read-only")}),Object.freeze(D),Object.getOwnPropertyNames(D).forEach(ne=>{const de=D[ne],Re=typeof de;(Re==="object"||Re==="function")&&!Object.isFrozen(de)&&t(de)}),D}class e{constructor(ne){ne.data===void 0&&(ne.data={}),this.data=ne.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function r(D){return D.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function n(D,...ne){const de=Object.create(null);for(const Re in D)de[Re]=D[Re];return ne.forEach(function(Re){for(const ht in Re)de[ht]=Re[ht]}),de}const i="</span>",a=D=>!!D.scope,o=(D,{prefix:ne})=>{if(D.startsWith("language:"))return D.replace("language:","language-");if(D.includes(".")){const de=D.split(".");return[`${ne}${de.shift()}`,...de.map((Re,ht)=>`${Re}${"_".repeat(ht+1)}`)].join(" ")}return`${ne}${D}`};class c{constructor(ne,de){this.buffer="",this.classPrefix=de.classPrefix,ne.walk(this)}addText(ne){this.buffer+=r(ne)}openNode(ne){if(!a(ne))return;const de=o(ne.scope,{prefix:this.classPrefix});this.span(de)}closeNode(ne){a(ne)&&(this.buffer+=i)}value(){return this.buffer}span(ne){this.buffer+=`<span class="${ne}">`}}const u=(D={})=>{const ne={children:[]};return Object.assign(ne,D),ne};class d{constructor(){this.rootNode=u(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(ne){this.top.children.push(ne)}openNode(ne){const de=u({scope:ne});this.add(de),this.stack.push(de)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(ne){return this.constructor._walk(ne,this.rootNode)}static _walk(ne,de){return typeof de=="string"?ne.addText(de):de.children&&(ne.openNode(de),de.children.forEach(Re=>this._walk(ne,Re)),ne.closeNode(de)),ne}static _collapse(ne){typeof ne!="string"&&ne.children&&(ne.children.every(de=>typeof de=="string")?ne.children=[ne.children.join("")]:ne.children.forEach(de=>{d._collapse(de)}))}}class p extends d{constructor(ne){super(),this.options=ne}addText(ne){ne!==""&&this.add(ne)}startScope(ne){this.openNode(ne)}endScope(){this.closeNode()}__addSublanguage(ne,de){const Re=ne.root;de&&(Re.scope=`language:${de}`),this.add(Re)}toHTML(){return new c(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}}function f(D){return D?typeof D=="string"?D:D.source:null}function g(D){return w("(?=",D,")")}function v(D){return w("(?:",D,")*")}function x(D){return w("(?:",D,")?")}function w(...D){return D.map(de=>f(de)).join("")}function b(D){const ne=D[D.length-1];return typeof ne=="object"&&ne.constructor===Object?(D.splice(D.length-1,1),ne):{}}function S(...D){return"("+(b(D).capture?"":"?:")+D.map(Re=>f(Re)).join("|")+")"}function A(D){return new RegExp(D.toString()+"|").exec("").length-1}function O(D,ne){const de=D&&D.exec(ne);return de&&de.index===0}const j=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;function E(D,{joinWith:ne}){let de=0;return D.map(Re=>{de+=1;const ht=de;let Ke=f(Re),ye="";for(;Ke.length>0;){const we=j.exec(Ke);if(!we){ye+=Ke;break}ye+=Ke.substring(0,we.index),Ke=Ke.substring(we.index+we[0].length),we[0][0]==="\\"&&we[1]?ye+="\\"+String(Number(we[1])+ht):(ye+=we[0],we[0]==="("&&de++)}return ye}).map(Re=>`(${Re})`).join(ne)}const T=/\b\B/,P="[a-zA-Z]\\w*",R="[a-zA-Z_]\\w*",M="\\b\\d+(\\.\\d+)?",J="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",F="\\b(0b[01]+)",B="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",K=(D={})=>{const ne=/^#![ ]*\//;return D.binary&&(D.begin=w(ne,/.*\b/,D.binary,/\b.*/)),n({scope:"meta",begin:ne,end:/$/,relevance:0,"on:begin":(de,Re)=>{de.index!==0&&Re.ignoreMatch()}},D)},W={begin:"\\\\[\\s\\S]",relevance:0},X={scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[W]},Y={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[W]},te={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},H=function(D,ne,de={}){const Re=n({scope:"comment",begin:D,end:ne,contains:[]},de);Re.contains.push({scope:"doctag",begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0});const ht=S("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return Re.contains.push({begin:w(/[ ]+/,"(",ht,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),Re},Q=H("//","$"),U=H("/\\*","\\*/"),I=H("#","$"),$={scope:"number",begin:M,relevance:0},V={scope:"number",begin:J,relevance:0},oe={scope:"number",begin:F,relevance:0},le={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[W,{begin:/\[/,end:/\]/,relevance:0,contains:[W]}]},ve={scope:"title",begin:P,relevance:0},qe={scope:"title",begin:R,relevance:0},xe={begin:"\\.\\s*"+R,relevance:0};var Se=Object.freeze({__proto__:null,APOS_STRING_MODE:X,BACKSLASH_ESCAPE:W,BINARY_NUMBER_MODE:oe,BINARY_NUMBER_RE:F,COMMENT:H,C_BLOCK_COMMENT_MODE:U,C_LINE_COMMENT_MODE:Q,C_NUMBER_MODE:V,C_NUMBER_RE:J,END_SAME_AS_BEGIN:function(D){return Object.assign(D,{"on:begin":(ne,de)=>{de.data._beginMatch=ne[1]},"on:end":(ne,de)=>{de.data._beginMatch!==ne[1]&&de.ignoreMatch()}})},HASH_COMMENT_MODE:I,IDENT_RE:P,MATCH_NOTHING_RE:T,METHOD_GUARD:xe,NUMBER_MODE:$,NUMBER_RE:M,PHRASAL_WORDS_MODE:te,QUOTE_STRING_MODE:Y,REGEXP_MODE:le,RE_STARTERS_RE:B,SHEBANG:K,TITLE_MODE:ve,UNDERSCORE_IDENT_RE:R,UNDERSCORE_TITLE_MODE:qe});function Me(D,ne){D.input[D.index-1]==="."&&ne.ignoreMatch()}function se(D,ne){D.className!==void 0&&(D.scope=D.className,delete D.className)}function tt(D,ne){ne&&D.beginKeywords&&(D.begin="\\b("+D.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",D.__beforeBegin=Me,D.keywords=D.keywords||D.beginKeywords,delete D.beginKeywords,D.relevance===void 0&&(D.relevance=0))}function Fe(D,ne){Array.isArray(D.illegal)&&(D.illegal=S(...D.illegal))}function kt(D,ne){if(D.match){if(D.begin||D.end)throw new Error("begin & end are not supported with match");D.begin=D.match,delete D.match}}function wt(D,ne){D.relevance===void 0&&(D.relevance=1)}const Et=(D,ne)=>{if(!D.beforeMatch)return;if(D.starts)throw new Error("beforeMatch cannot be used with starts");const de=Object.assign({},D);Object.keys(D).forEach(Re=>{delete D[Re]}),D.keywords=de.keywords,D.begin=w(de.beforeMatch,g(de.begin)),D.starts={relevance:0,contains:[Object.assign(de,{endsParent:!0})]},D.relevance=0,delete de.beforeMatch},Sr=["of","and","for","in","not","or","if","then","parent","list","value"],Ut="keyword";function Rr(D,ne,de=Ut){const Re=Object.create(null);return typeof D=="string"?ht(de,D.split(" ")):Array.isArray(D)?ht(de,D):Object.keys(D).forEach(function(Ke){Object.assign(Re,Rr(D[Ke],ne,Ke))}),Re;function ht(Ke,ye){ne&&(ye=ye.map(we=>we.toLowerCase())),ye.forEach(function(we){const je=we.split("|");Re[je[0]]=[Ke,lr(je[0],je[1])]})}}function lr(D,ne){return ne?Number(ne):_t(D)?0:1}function _t(D){return Sr.includes(D.toLowerCase())}const kr={},Ir=D=>{console.error(D)},ni=(D,...ne)=>{console.log(`WARN: ${D}`,...ne)},Ur=(D,ne)=>{kr[`${D}/${ne}`]||(console.log(`Deprecated as of ${D}. ${ne}`),kr[`${D}/${ne}`]=!0)},ii=new Error;function ai(D,ne,{key:de}){let Re=0;const ht=D[de],Ke={},ye={};for(let we=1;we<=ne.length;we++)ye[we+Re]=ht[we],Ke[we+Re]=!0,Re+=A(ne[we-1]);D[de]=ye,D[de]._emit=Ke,D[de]._multi=!0}function aa(D){if(Array.isArray(D.begin)){if(D.skip||D.excludeBegin||D.returnBegin)throw Ir("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),ii;if(typeof D.beginScope!="object"||D.beginScope===null)throw Ir("beginScope must be object"),ii;ai(D,D.begin,{key:"beginScope"}),D.begin=E(D.begin,{joinWith:""})}}function qr(D){if(Array.isArray(D.end)){if(D.skip||D.excludeEnd||D.returnEnd)throw Ir("skip, excludeEnd, returnEnd not compatible with endScope: {}"),ii;if(typeof D.endScope!="object"||D.endScope===null)throw Ir("endScope must be object"),ii;ai(D,D.end,{key:"endScope"}),D.end=E(D.end,{joinWith:""})}}function oi(D){D.scope&&typeof D.scope=="object"&&D.scope!==null&&(D.beginScope=D.scope,delete D.scope)}function si(D){oi(D),typeof D.beginScope=="string"&&(D.beginScope={_wrap:D.beginScope}),typeof D.endScope=="string"&&(D.endScope={_wrap:D.endScope}),aa(D),qr(D)}function Go(D){function ne(ye,we){return new RegExp(f(ye),"m"+(D.case_insensitive?"i":"")+(D.unicodeRegex?"u":"")+(we?"g":""))}class de{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(we,je){je.position=this.position++,this.matchIndexes[this.matchAt]=je,this.regexes.push([je,we]),this.matchAt+=A(we)+1}compile(){this.regexes.length===0&&(this.exec=()=>null);const we=this.regexes.map(je=>je[1]);this.matcherRe=ne(E(we,{joinWith:"|"}),!0),this.lastIndex=0}exec(we){this.matcherRe.lastIndex=this.lastIndex;const je=this.matcherRe.exec(we);if(!je)return null;const ut=je.findIndex((cr,Ai)=>Ai>0&&cr!==void 0),gt=this.matchIndexes[ut];return je.splice(0,ut),Object.assign(je,gt)}}class Re{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(we){if(this.multiRegexes[we])return this.multiRegexes[we];const je=new de;return this.rules.slice(we).forEach(([ut,gt])=>je.addRule(ut,gt)),je.compile(),this.multiRegexes[we]=je,je}resumingScanAtSamePosition(){return this.regexIndex!==0}considerAll(){this.regexIndex=0}addRule(we,je){this.rules.push([we,je]),je.type==="begin"&&this.count++}exec(we){const je=this.getMatcher(this.regexIndex);je.lastIndex=this.lastIndex;let ut=je.exec(we);if(this.resumingScanAtSamePosition()&&!(ut&&ut.index===this.lastIndex)){const gt=this.getMatcher(0);gt.lastIndex=this.lastIndex+1,ut=gt.exec(we)}return ut&&(this.regexIndex+=ut.position+1,this.regexIndex===this.count&&this.considerAll()),ut}}function ht(ye){const we=new Re;return ye.contains.forEach(je=>we.addRule(je.begin,{rule:je,type:"begin"})),ye.terminatorEnd&&we.addRule(ye.terminatorEnd,{type:"end"}),ye.illegal&&we.addRule(ye.illegal,{type:"illegal"}),we}function Ke(ye,we){const je=ye;if(ye.isCompiled)return je;[se,kt,si,Et].forEach(gt=>gt(ye,we)),D.compilerExtensions.forEach(gt=>gt(ye,we)),ye.__beforeBegin=null,[tt,Fe,wt].forEach(gt=>gt(ye,we)),ye.isCompiled=!0;let ut=null;return typeof ye.keywords=="object"&&ye.keywords.$pattern&&(ye.keywords=Object.assign({},ye.keywords),ut=ye.keywords.$pattern,delete ye.keywords.$pattern),ut=ut||/\w+/,ye.keywords&&(ye.keywords=Rr(ye.keywords,D.case_insensitive)),je.keywordPatternRe=ne(ut,!0),we&&(ye.begin||(ye.begin=/\B|\b/),je.beginRe=ne(je.begin),!ye.end&&!ye.endsWithParent&&(ye.end=/\B|\b/),ye.end&&(je.endRe=ne(je.end)),je.terminatorEnd=f(je.end)||"",ye.endsWithParent&&we.terminatorEnd&&(je.terminatorEnd+=(ye.end?"|":"")+we.terminatorEnd)),ye.illegal&&(je.illegalRe=ne(ye.illegal)),ye.contains||(ye.contains=[]),ye.contains=[].concat(...ye.contains.map(function(gt){return Ko(gt==="self"?ye:gt)})),ye.contains.forEach(function(gt){Ke(gt,je)}),ye.starts&&Ke(ye.starts,we),je.matcher=ht(je),je}if(D.compilerExtensions||(D.compilerExtensions=[]),D.contains&&D.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return D.classNameAliases=n(D.classNameAliases||{}),Ke(D)}function Xa(D){return D?D.endsWithParent||Xa(D.starts):!1}function Ko(D){return D.variants&&!D.cachedVariants&&(D.cachedVariants=D.variants.map(function(ne){return n(D,{variants:null},ne)})),D.cachedVariants?D.cachedVariants:Xa(D)?n(D,{starts:D.starts?n(D.starts):null}):Object.isFrozen(D)?n(D):D}var oa="11.11.1";class Ya extends Error{constructor(ne,de){super(ne),this.name="HTMLInjectionError",this.html=de}}const Rn=r,$r=n,sa=Symbol("nomatch"),li=7,hn=function(D){const ne=Object.create(null),de=Object.create(null),Re=[];let ht=!0;const Ke="Could not find the language '{}', did you forget to load/include a language module?",ye={disableAutodetect:!0,name:"Plain text",contains:[]};let we={ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",cssSelector:"pre code",languages:null,__emitter:p};function je(he){return we.noHighlightRe.test(he)}function ut(he){let $e=he.className+" ";$e+=he.parentNode?he.parentNode.className:"";const Xe=we.languageDetectRe.exec($e);if(Xe){const Qe=In(Xe[1]);return Qe||(ni(Ke.replace("{}",Xe[1])),ni("Falling back to no-highlight mode for this block.",he)),Qe?Xe[1]:"no-highlight"}return $e.split(/\s+/).find(Qe=>je(Qe)||In(Qe))}function gt(he,$e,Xe){let Qe="",Gt="";typeof $e=="object"?(Qe=he,Xe=$e.ignoreIllegals,Gt=$e.language):(Ur("10.7.0","highlight(lang, code, ...args) has been deprecated."),Ur("10.7.0",`Please use highlight(code, options) instead.
|
|
432
|
-
https://github.com/highlightjs/highlight.js/issues/2277`),Gt=he,Qe=$e),Xe===void 0&&(Xe=!0);const Dt={code:Qe,language:Gt};Za("before:highlight",Dt);const ci=Dt.result?Dt.result:cr(Dt.language,Dt.code,Xe);return ci.code=Dt.code,Za("after:highlight",ci),ci}function cr(he,$e,Xe,Qe){const Gt=Object.create(null);function Dt(me,Ee){return me.keywords[Ee]}function ci(){if(!Ge.keywords){Kt.addText(yt);return}let me=0;Ge.keywordPatternRe.lastIndex=0;let Ee=Ge.keywordPatternRe.exec(yt),He="";for(;Ee;){He+=yt.substring(me,Ee.index);const rt=mn.case_insensitive?Ee[0].toLowerCase():Ee[0],qt=Dt(Ge,rt);if(qt){const[ur,Hp]=qt;if(Kt.addText(He),He="",Gt[rt]=(Gt[rt]||0)+1,Gt[rt]<=li&&(to+=Hp),ur.startsWith("_"))He+=Ee[0];else{const Zu=mn.classNameAliases[ur]||ur;Lr(Ee[0],Zu)}}else He+=Ee[0];me=Ge.keywordPatternRe.lastIndex,Ee=Ge.keywordPatternRe.exec(yt)}He+=yt.substring(me),Kt.addText(He)}function Yo(){if(yt==="")return;let me=null;if(typeof Ge.subLanguage=="string"){if(!ne[Ge.subLanguage]){Kt.addText(yt);return}me=cr(Ge.subLanguage,yt,!0,Il[Ge.subLanguage]),Il[Ge.subLanguage]=me._top}else me=Ja(yt,Ge.subLanguage.length?Ge.subLanguage:null);Ge.relevance>0&&(to+=me.relevance),Kt.__addSublanguage(me._emitter,me.language)}function Mr(){Ge.subLanguage!=null?Yo():ci(),yt=""}function Lr(me,Ee){me!==""&&(Kt.startScope(Ee),Kt.addText(me),Kt.endScope())}function Qa(me,Ee){let He=1;const rt=Ee.length-1;for(;He<=rt;){if(!me._emit[He]){He++;continue}const qt=mn.classNameAliases[me[He]]||me[He],ur=Ee[He];qt?Lr(ur,qt):(yt=ur,ci(),yt=""),He++}}function la(me,Ee){return me.scope&&typeof me.scope=="string"&&Kt.openNode(mn.classNameAliases[me.scope]||me.scope),me.beginScope&&(me.beginScope._wrap?(Lr(yt,mn.classNameAliases[me.beginScope._wrap]||me.beginScope._wrap),yt=""):me.beginScope._multi&&(Qa(me.beginScope,Ee),yt="")),Ge=Object.create(me,{parent:{value:Ge}}),Ge}function eo(me,Ee,He){let rt=O(me.endRe,He);if(rt){if(me["on:end"]){const qt=new e(me);me["on:end"](Ee,qt),qt.isMatchIgnored&&(rt=!1)}if(rt){for(;me.endsParent&&me.parent;)me=me.parent;return me}}if(me.endsWithParent)return eo(me.parent,Ee,He)}function qp(me){return Ge.matcher.regexIndex===0?(yt+=me[0],1):(da=!0,0)}function Fp(me){const Ee=me[0],He=me.rule,rt=new e(He),qt=[He.__beforeBegin,He["on:begin"]];for(const ur of qt)if(ur&&(ur(me,rt),rt.isMatchIgnored))return qp(Ee);return He.skip?yt+=Ee:(He.excludeBegin&&(yt+=Ee),Mr(),!He.returnBegin&&!He.excludeBegin&&(yt=Ee)),la(He,me),He.returnBegin?0:Ee.length}function Pl(me){const Ee=me[0],He=$e.substring(me.index),rt=eo(Ge,me,He);if(!rt)return sa;const qt=Ge;Ge.endScope&&Ge.endScope._wrap?(Mr(),Lr(Ee,Ge.endScope._wrap)):Ge.endScope&&Ge.endScope._multi?(Mr(),Qa(Ge.endScope,me)):qt.skip?yt+=Ee:(qt.returnEnd||qt.excludeEnd||(yt+=Ee),Mr(),qt.excludeEnd&&(yt=Ee));do Ge.scope&&Kt.closeNode(),!Ge.skip&&!Ge.subLanguage&&(to+=Ge.relevance),Ge=Ge.parent;while(Ge!==rt.parent);return rt.starts&&la(rt.starts,me),qt.returnEnd?0:Ee.length}function Ju(){const me=[];for(let Ee=Ge;Ee!==mn;Ee=Ee.parent)Ee.scope&&me.unshift(Ee.scope);me.forEach(Ee=>Kt.openNode(Ee))}let ca={};function ua(me,Ee){const He=Ee&&Ee[0];if(yt+=me,He==null)return Mr(),0;if(ca.type==="begin"&&Ee.type==="end"&&ca.index===Ee.index&&He===""){if(yt+=$e.slice(Ee.index,Ee.index+1),!ht){const rt=new Error(`0 width match regex (${he})`);throw rt.languageName=he,rt.badRule=ca.rule,rt}return 1}if(ca=Ee,Ee.type==="begin")return Fp(Ee);if(Ee.type==="illegal"&&!Xe){const rt=new Error('Illegal lexeme "'+He+'" for mode "'+(Ge.scope||"<unnamed>")+'"');throw rt.mode=Ge,rt}else if(Ee.type==="end"){const rt=Pl(Ee);if(rt!==sa)return rt}if(Ee.type==="illegal"&&He==="")return yt+=`
|
|
433
|
-
`,1;if(ro>1e5&&ro>Ee.index*3)throw new Error("potential infinite loop, way more iterations than matches");return yt+=He,He.length}const mn=In(he);if(!mn)throw Ir(Ke.replace("{}",he)),new Error('Unknown language: "'+he+'"');const Rl=Go(mn);let lt="",Ge=Qe||Rl;const Il={},Kt=new we.__emitter(we);Ju();let yt="",to=0,ui=0,ro=0,da=!1;try{if(mn.__emitTokens)mn.__emitTokens($e,Kt);else{for(Ge.matcher.considerAll();;){ro++,da?da=!1:Ge.matcher.considerAll(),Ge.matcher.lastIndex=ui;const me=Ge.matcher.exec($e);if(!me)break;const Ee=$e.substring(ui,me.index),He=ua(Ee,me);ui=me.index+He}ua($e.substring(ui))}return Kt.finalize(),lt=Kt.toHTML(),{language:he,value:lt,relevance:to,illegal:!1,_emitter:Kt,_top:Ge}}catch(me){if(me.message&&me.message.includes("Illegal"))return{language:he,value:Rn($e),illegal:!0,relevance:0,_illegalBy:{message:me.message,index:ui,context:$e.slice(ui-100,ui+100),mode:me.mode,resultSoFar:lt},_emitter:Kt};if(ht)return{language:he,value:Rn($e),illegal:!1,relevance:0,errorRaised:me,_emitter:Kt,_top:Ge};throw me}}function Ai(he){const $e={value:Rn(he),illegal:!1,relevance:0,_top:ye,_emitter:new we.__emitter(we)};return $e._emitter.addText(he),$e}function Ja(he,$e){$e=$e||we.languages||Object.keys(ne);const Xe=Ai(he),Qe=$e.filter(In).filter(Yu).map(Mr=>cr(Mr,he,!1));Qe.unshift(Xe);const Gt=Qe.sort((Mr,Lr)=>{if(Mr.relevance!==Lr.relevance)return Lr.relevance-Mr.relevance;if(Mr.language&&Lr.language){if(In(Mr.language).supersetOf===Lr.language)return 1;if(In(Lr.language).supersetOf===Mr.language)return-1}return 0}),[Dt,ci]=Gt,Yo=Dt;return Yo.secondBest=ci,Yo}function zp(he,$e,Xe){const Qe=$e&&de[$e]||Xe;he.classList.add("hljs"),he.classList.add(`language-${Qe}`)}function jl(he){let $e=null;const Xe=ut(he);if(je(Xe))return;if(Za("before:highlightElement",{el:he,language:Xe}),he.dataset.highlighted){console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",he);return}if(he.children.length>0&&(we.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),console.warn("The element with unescaped HTML:"),console.warn(he)),we.throwUnescapedHTML))throw new Ya("One of your code blocks includes unescaped HTML.",he.innerHTML);$e=he;const Qe=$e.textContent,Gt=Xe?gt(Qe,{language:Xe,ignoreIllegals:!0}):Ja(Qe);he.innerHTML=Gt.value,he.dataset.highlighted="yes",zp(he,Xe,Gt.language),he.result={language:Gt.language,re:Gt.relevance,relevance:Gt.relevance},Gt.secondBest&&(he.secondBest={language:Gt.secondBest.language,relevance:Gt.secondBest.relevance}),Za("after:highlightElement",{el:he,result:Gt,text:Qe})}function Bp(he){we=$r(we,he)}const Ti=()=>{Vo(),Ur("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")};function Wu(){Vo(),Ur("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.")}let Cl=!1;function Vo(){function he(){Vo()}if(document.readyState==="loading"){Cl||window.addEventListener("DOMContentLoaded",he,!1),Cl=!0;return}document.querySelectorAll(we.cssSelector).forEach(jl)}function Gu(he,$e){let Xe=null;try{Xe=$e(D)}catch(Qe){if(Ir("Language definition for '{}' could not be registered.".replace("{}",he)),ht)Ir(Qe);else throw Qe;Xe=ye}Xe.name||(Xe.name=he),ne[he]=Xe,Xe.rawDefinition=$e.bind(null,D),Xe.aliases&&Xu(Xe.aliases,{languageName:he})}function Ku(he){delete ne[he];for(const $e of Object.keys(de))de[$e]===he&&delete de[$e]}function Vu(){return Object.keys(ne)}function In(he){return he=(he||"").toLowerCase(),ne[he]||ne[de[he]]}function Xu(he,{languageName:$e}){typeof he=="string"&&(he=[he]),he.forEach(Xe=>{de[Xe.toLowerCase()]=$e})}function Yu(he){const $e=In(he);return $e&&!$e.disableAutodetect}function Lt(he){he["before:highlightBlock"]&&!he["before:highlightElement"]&&(he["before:highlightElement"]=$e=>{he["before:highlightBlock"](Object.assign({block:$e.el},$e))}),he["after:highlightBlock"]&&!he["after:highlightElement"]&&(he["after:highlightElement"]=$e=>{he["after:highlightBlock"](Object.assign({block:$e.el},$e))})}function Up(he){Lt(he),Re.push(he)}function Nl(he){const $e=Re.indexOf(he);$e!==-1&&Re.splice($e,1)}function Za(he,$e){const Xe=he;Re.forEach(function(Qe){Qe[Xe]&&Qe[Xe]($e)})}function Xo(he){return Ur("10.7.0","highlightBlock will be removed entirely in v12.0"),Ur("10.7.0","Please use highlightElement now."),jl(he)}Object.assign(D,{highlight:gt,highlightAuto:Ja,highlightAll:Vo,highlightElement:jl,highlightBlock:Xo,configure:Bp,initHighlighting:Ti,initHighlightingOnLoad:Wu,registerLanguage:Gu,unregisterLanguage:Ku,listLanguages:Vu,getLanguage:In,registerAliases:Xu,autoDetection:Yu,inherit:$r,addPlugin:Up,removePlugin:Nl}),D.debugMode=function(){ht=!1},D.safeMode=function(){ht=!0},D.versionString=oa,D.regex={concat:w,lookahead:g,either:S,optional:x,anyNumberOfTimes:v};for(const he in Se)typeof Se[he]=="object"&&t(Se[he]);return Object.assign(D,Se),D},pn=hn({});return pn.newInstance=()=>hn({}),Rg=pn,pn.HighlightJS=pn,pn.default=pn,Rg}var ZU=JU();const Qt=vt(ZU),QU=t=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:t.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[t.APOS_STRING_MODE,t.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:t.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),eq=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],tq=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],rq=[...eq,...tq],nq=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),iq=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),aq=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),oq=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();function sq(t){const e=t.regex,r=QU(t),n={begin:/-(webkit|moz|ms|o)-(?=[a-z])/},i="and or not only",a=/@-?\w[\w]*(-\w+)*/,o="[a-zA-Z-][a-zA-Z0-9_-]*",c=[t.APOS_STRING_MODE,t.QUOTE_STRING_MODE];return{name:"CSS",case_insensitive:!0,illegal:/[=|'\$]/,keywords:{keyframePosition:"from to"},classNameAliases:{keyframePosition:"selector-tag"},contains:[r.BLOCK_COMMENT,n,r.CSS_NUMBER_MODE,{className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0},{className:"selector-class",begin:"\\."+o,relevance:0},r.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{begin:":("+iq.join("|")+")"},{begin:":(:)?("+aq.join("|")+")"}]},r.CSS_VARIABLE,{className:"attribute",begin:"\\b("+oq.join("|")+")\\b"},{begin:/:/,end:/[;}{]/,contains:[r.BLOCK_COMMENT,r.HEXCOLOR,r.IMPORTANT,r.CSS_NUMBER_MODE,...c,{begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri"},contains:[...c,{className:"string",begin:/[^)]/,endsWithParent:!0,excludeEnd:!0}]},r.FUNCTION_DISPATCH]},{begin:e.lookahead(/@/),end:"[{;]",relevance:0,illegal:/:/,contains:[{className:"keyword",begin:a},{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{$pattern:/[a-z-]+/,keyword:i,attribute:nq.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...c,r.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+rq.join("|")+")\\b"}]}}function lq(t){const a={keyword:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],type:["bool","byte","complex64","complex128","error","float32","float64","int8","int16","int32","int64","string","uint8","uint16","uint32","uint64","int","uint","uintptr","rune"],literal:["true","false","iota","nil"],built_in:["append","cap","close","complex","copy","imag","len","make","new","panic","print","println","real","recover","delete"]};return{name:"Go",aliases:["golang"],keywords:a,illegal:"</",contains:[t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE,{className:"string",variants:[t.QUOTE_STRING_MODE,t.APOS_STRING_MODE,{begin:"`",end:"`"}]},{className:"number",variants:[{match:/-?\b0[xX]\.[a-fA-F0-9](_?[a-fA-F0-9])*[pP][+-]?\d(_?\d)*i?/,relevance:0},{match:/-?\b0[xX](_?[a-fA-F0-9])+((\.([a-fA-F0-9](_?[a-fA-F0-9])*)?)?[pP][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b0[oO](_?[0-7])*i?/,relevance:0},{match:/-?\.\d(_?\d)*([eE][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b\d(_?\d)*(\.(\d(_?\d)*)?)?([eE][+-]?\d(_?\d)*)?i?/,relevance:0}]},{begin:/:=/},{className:"function",beginKeywords:"func",end:"\\s*(\\{|$)",excludeEnd:!0,contains:[t.TITLE_MODE,{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:a,illegal:/["']/}]}]}}const $E="[A-Za-z$_][0-9A-Za-z$_]*",cq=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],uq=["true","false","null","undefined","NaN","Infinity"],iR=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],aR=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],oR=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],dq=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],fq=[].concat(oR,iR,aR);function sR(t){const e=t.regex,r=(H,{after:Q})=>{const U="</"+H[0].slice(1);return H.input.indexOf(U,Q)!==-1},n=$E,i={begin:"<>",end:"</>"},a=/<[A-Za-z0-9\\._:-]+\s*\/>/,o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(H,Q)=>{const U=H[0].length+H.index,I=H.input[U];if(I==="<"||I===","){Q.ignoreMatch();return}I===">"&&(r(H,{after:U})||Q.ignoreMatch());let $;const V=H.input.substring(U);if($=V.match(/^\s*=/)){Q.ignoreMatch();return}if(($=V.match(/^\s+extends\s+/))&&$.index===0){Q.ignoreMatch();return}}},c={$pattern:$E,keyword:cq,literal:uq,built_in:fq,"variable.language":dq},u="[0-9](_?[0-9])*",d=`\\.(${u})`,p="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",f={className:"number",variants:[{begin:`(\\b(${p})((${d})|\\.)?|(${d}))[eE][+-]?(${u})\\b`},{begin:`\\b(${p})\\b((${d})\\b|\\.)?|(${d})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},g={className:"subst",begin:"\\$\\{",end:"\\}",keywords:c,contains:[]},v={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,g],subLanguage:"xml"}},x={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,g],subLanguage:"css"}},w={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,g],subLanguage:"graphql"}},b={className:"string",begin:"`",end:"`",contains:[t.BACKSLASH_ESCAPE,g]},A={className:"comment",variants:[t.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:n+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),t.C_BLOCK_COMMENT_MODE,t.C_LINE_COMMENT_MODE]},O=[t.APOS_STRING_MODE,t.QUOTE_STRING_MODE,v,x,w,b,{match:/\$\d+/},f];g.contains=O.concat({begin:/\{/,end:/\}/,keywords:c,contains:["self"].concat(O)});const j=[].concat(A,g.contains),E=j.concat([{begin:/(\s*)\(/,end:/\)/,keywords:c,contains:["self"].concat(j)}]),T={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:c,contains:E},P={variants:[{match:[/class/,/\s+/,n,/\s+/,/extends/,/\s+/,e.concat(n,"(",e.concat(/\./,n),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,n],scope:{1:"keyword",3:"title.class"}}]},R={relevance:0,match:e.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...iR,...aR]}},M={label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},J={variants:[{match:[/function/,/\s+/,n,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[T],illegal:/%/},F={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function B(H){return e.concat("(?!",H.join("|"),")")}const K={match:e.concat(/\b/,B([...oR,"super","import"].map(H=>`${H}\\s*\\(`)),n,e.lookahead(/\s*\(/)),className:"title.function",relevance:0},W={begin:e.concat(/\./,e.lookahead(e.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},X={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},T]},Y="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+t.UNDERSCORE_IDENT_RE+")\\s*=>",te={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,e.lookahead(Y)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[T]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:c,exports:{PARAMS_CONTAINS:E,CLASS_REFERENCE:R},illegal:/#(?![$_A-z])/,contains:[t.SHEBANG({label:"shebang",binary:"node",relevance:5}),M,t.APOS_STRING_MODE,t.QUOTE_STRING_MODE,v,x,w,b,A,{match:/\$\d+/},f,R,{scope:"attr",match:n+e.lookahead(":"),relevance:0},te,{begin:"("+t.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[A,t.REGEXP_MODE,{className:"function",begin:Y,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:t.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:c,contains:E}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:i.begin,end:i.end},{match:a},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:"xml",contains:[{begin:o.begin,end:o.end,skip:!0,contains:["self"]}]}]},J,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+t.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[T,t.inherit(t.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},W,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[T]},K,F,P,X,{match:/\$[(.]/}]}}function hq(t){const e={className:"attr",begin:/"(\\.|[^\\"\r\n])*"(?=\s*:)/,relevance:1.01},r={match:/[{}[\],:]/,className:"punctuation",relevance:0},n=["true","false","null"],i={scope:"literal",beginKeywords:n.join(" ")};return{name:"JSON",aliases:["jsonc"],keywords:{literal:n},contains:[e,r,t.QUOTE_STRING_MODE,i,t.C_NUMBER_MODE,t.C_LINE_COMMENT_MODE,t.C_BLOCK_COMMENT_MODE],illegal:"\\S"}}function lR(t){const e=t.regex,r=new RegExp("[\\p{XID_Start}_]\\p{XID_Continue}*","u"),n=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],c={$pattern:/[A-Za-z]\w+|__\w+__/,keyword:n,built_in:["__import__","abs","all","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"],literal:["__debug__","Ellipsis","False","None","NotImplemented","True"],type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"]},u={className:"meta",begin:/^(>>>|\.\.\.) /},d={className:"subst",begin:/\{/,end:/\}/,keywords:c,illegal:/#/},p={begin:/\{\{/,relevance:0},f={className:"string",contains:[t.BACKSLASH_ESCAPE],variants:[{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,contains:[t.BACKSLASH_ESCAPE,u],relevance:10},{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,contains:[t.BACKSLASH_ESCAPE,u],relevance:10},{begin:/([fF][rR]|[rR][fF]|[fF])'''/,end:/'''/,contains:[t.BACKSLASH_ESCAPE,u,p,d]},{begin:/([fF][rR]|[rR][fF]|[fF])"""/,end:/"""/,contains:[t.BACKSLASH_ESCAPE,u,p,d]},{begin:/([uU]|[rR])'/,end:/'/,relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,end:/"/},{begin:/([fF][rR]|[rR][fF]|[fF])'/,end:/'/,contains:[t.BACKSLASH_ESCAPE,p,d]},{begin:/([fF][rR]|[rR][fF]|[fF])"/,end:/"/,contains:[t.BACKSLASH_ESCAPE,p,d]},t.APOS_STRING_MODE,t.QUOTE_STRING_MODE]},g="[0-9](_?[0-9])*",v=`(\\b(${g}))?\\.(${g})|\\b(${g})\\.`,x=`\\b|${n.join("|")}`,w={className:"number",relevance:0,variants:[{begin:`(\\b(${g})|(${v}))[eE][+-]?(${g})[jJ]?(?=${x})`},{begin:`(${v})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${x})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${x})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${x})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${x})`},{begin:`\\b(${g})[jJ](?=${x})`}]},b={className:"comment",begin:e.lookahead(/# type:/),end:/$/,keywords:c,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},S={className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:c,contains:["self",u,w,f,t.HASH_COMMENT_MODE]}]};return d.contains=[f,w,u],{name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:c,illegal:/(<\/|\?)|=>/,contains:[u,w,{scope:"variable.language",match:/\bself\b/},{beginKeywords:"if",relevance:0},{match:/\bor\b/,scope:"keyword"},f,b,t.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,r],scope:{1:"keyword",3:"title.function"},contains:[S]},{variants:[{match:[/\bclass/,/\s+/,r,/\s*/,/\(\s*/,r,/\s*\)/]},{match:[/\bclass/,/\s+/,r]}],scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[w,S,f]}]}}function pq(t){const e=t.regex,r=/(r#)?/,n=e.concat(r,t.UNDERSCORE_IDENT_RE),i=e.concat(r,t.IDENT_RE),a={className:"title.function.invoke",relevance:0,begin:e.concat(/\b/,/(?!let|for|while|if|else|match\b)/,i,e.lookahead(/\s*\(/))},o="([ui](8|16|32|64|128|size)|f(32|64))?",c=["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","ref","return","self","Self","static","struct","super","trait","true","try","type","typeof","union","unsafe","unsized","use","virtual","where","while","yield"],u=["true","false","Some","None","Ok","Err"],d=["drop ","Copy","Send","Sized","Sync","Drop","Fn","FnMut","FnOnce","ToOwned","Clone","Debug","PartialEq","PartialOrd","Eq","Ord","AsRef","AsMut","Into","From","Default","Iterator","Extend","IntoIterator","DoubleEndedIterator","ExactSizeIterator","SliceConcatExt","ToString","assert!","assert_eq!","bitflags!","bytes!","cfg!","col!","concat!","concat_idents!","debug_assert!","debug_assert_eq!","env!","eprintln!","panic!","file!","format!","format_args!","include_bytes!","include_str!","line!","local_data_key!","module_path!","option_env!","print!","println!","select!","stringify!","try!","unimplemented!","unreachable!","vec!","write!","writeln!","macro_rules!","assert_ne!","debug_assert_ne!"],p=["i8","i16","i32","i64","i128","isize","u8","u16","u32","u64","u128","usize","f32","f64","str","char","bool","Box","Option","Result","String","Vec"];return{name:"Rust",aliases:["rs"],keywords:{$pattern:t.IDENT_RE+"!?",type:p,keyword:c,literal:u,built_in:d},illegal:"</",contains:[t.C_LINE_COMMENT_MODE,t.COMMENT("/\\*","\\*/",{contains:["self"]}),t.inherit(t.QUOTE_STRING_MODE,{begin:/b?"/,illegal:null}),{className:"symbol",begin:/'[a-zA-Z_][a-zA-Z0-9_]*(?!')/},{scope:"string",variants:[{begin:/b?r(#*)"(.|\n)*?"\1(?!#)/},{begin:/b?'/,end:/'/,contains:[{scope:"char.escape",match:/\\('|\w|x\w{2}|u\w{4}|U\w{8})/}]}]},{className:"number",variants:[{begin:"\\b0b([01_]+)"+o},{begin:"\\b0o([0-7_]+)"+o},{begin:"\\b0x([A-Fa-f0-9_]+)"+o},{begin:"\\b(\\d[\\d_]*(\\.[0-9_]+)?([eE][+-]?[0-9_]+)?)"+o}],relevance:0},{begin:[/fn/,/\s+/,n],className:{1:"keyword",3:"title.function"}},{className:"meta",begin:"#!?\\[",end:"\\]",contains:[{className:"string",begin:/"/,end:/"/,contains:[t.BACKSLASH_ESCAPE]}]},{begin:[/let/,/\s+/,/(?:mut\s+)?/,n],className:{1:"keyword",3:"keyword",4:"variable"}},{begin:[/for/,/\s+/,n,/\s+/,/in/],className:{1:"keyword",3:"variable",5:"keyword"}},{begin:[/type/,/\s+/,n],className:{1:"keyword",3:"title.class"}},{begin:[/(?:trait|enum|struct|union|impl|for)/,/\s+/,n],className:{1:"keyword",3:"title.class"}},{begin:t.IDENT_RE+"::",keywords:{keyword:"Self",built_in:d,type:p}},{className:"punctuation",begin:"->"},a]}}function t1(t){return{name:"Shell Session",aliases:["console","shellsession"],contains:[{className:"meta.prompt",begin:/^\s{0,3}[/~\w\d[\]()@-]*[>%$#][ ]?/,starts:{end:/[^\\](?=\s*$)/,subLanguage:"bash"}}]}}const Gf="[A-Za-z$_][0-9A-Za-z$_]*",cR=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],uR=["true","false","null","undefined","NaN","Infinity"],dR=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],fR=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],hR=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],pR=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],mR=[].concat(hR,dR,fR);function mq(t){const e=t.regex,r=(H,{after:Q})=>{const U="</"+H[0].slice(1);return H.input.indexOf(U,Q)!==-1},n=Gf,i={begin:"<>",end:"</>"},a=/<[A-Za-z0-9\\._:-]+\s*\/>/,o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(H,Q)=>{const U=H[0].length+H.index,I=H.input[U];if(I==="<"||I===","){Q.ignoreMatch();return}I===">"&&(r(H,{after:U})||Q.ignoreMatch());let $;const V=H.input.substring(U);if($=V.match(/^\s*=/)){Q.ignoreMatch();return}if(($=V.match(/^\s+extends\s+/))&&$.index===0){Q.ignoreMatch();return}}},c={$pattern:Gf,keyword:cR,literal:uR,built_in:mR,"variable.language":pR},u="[0-9](_?[0-9])*",d=`\\.(${u})`,p="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",f={className:"number",variants:[{begin:`(\\b(${p})((${d})|\\.)?|(${d}))[eE][+-]?(${u})\\b`},{begin:`\\b(${p})\\b((${d})\\b|\\.)?|(${d})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},g={className:"subst",begin:"\\$\\{",end:"\\}",keywords:c,contains:[]},v={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,g],subLanguage:"xml"}},x={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,g],subLanguage:"css"}},w={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[t.BACKSLASH_ESCAPE,g],subLanguage:"graphql"}},b={className:"string",begin:"`",end:"`",contains:[t.BACKSLASH_ESCAPE,g]},A={className:"comment",variants:[t.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:n+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),t.C_BLOCK_COMMENT_MODE,t.C_LINE_COMMENT_MODE]},O=[t.APOS_STRING_MODE,t.QUOTE_STRING_MODE,v,x,w,b,{match:/\$\d+/},f];g.contains=O.concat({begin:/\{/,end:/\}/,keywords:c,contains:["self"].concat(O)});const j=[].concat(A,g.contains),E=j.concat([{begin:/(\s*)\(/,end:/\)/,keywords:c,contains:["self"].concat(j)}]),T={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:c,contains:E},P={variants:[{match:[/class/,/\s+/,n,/\s+/,/extends/,/\s+/,e.concat(n,"(",e.concat(/\./,n),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,n],scope:{1:"keyword",3:"title.class"}}]},R={relevance:0,match:e.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...dR,...fR]}},M={label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},J={variants:[{match:[/function/,/\s+/,n,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[T],illegal:/%/},F={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function B(H){return e.concat("(?!",H.join("|"),")")}const K={match:e.concat(/\b/,B([...hR,"super","import"].map(H=>`${H}\\s*\\(`)),n,e.lookahead(/\s*\(/)),className:"title.function",relevance:0},W={begin:e.concat(/\./,e.lookahead(e.concat(n,/(?![0-9A-Za-z$_(])/))),end:n,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},X={match:[/get|set/,/\s+/,n,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},T]},Y="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+t.UNDERSCORE_IDENT_RE+")\\s*=>",te={match:[/const|var|let/,/\s+/,n,/\s*/,/=\s*/,/(async\s*)?/,e.lookahead(Y)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[T]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:c,exports:{PARAMS_CONTAINS:E,CLASS_REFERENCE:R},illegal:/#(?![$_A-z])/,contains:[t.SHEBANG({label:"shebang",binary:"node",relevance:5}),M,t.APOS_STRING_MODE,t.QUOTE_STRING_MODE,v,x,w,b,A,{match:/\$\d+/},f,R,{scope:"attr",match:n+e.lookahead(":"),relevance:0},te,{begin:"("+t.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[A,t.REGEXP_MODE,{className:"function",begin:Y,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:t.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:c,contains:E}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:i.begin,end:i.end},{match:a},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:"xml",contains:[{begin:o.begin,end:o.end,skip:!0,contains:["self"]}]}]},J,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+t.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[T,t.inherit(t.TITLE_MODE,{begin:n,className:"title.function"})]},{match:/\.\.\./,relevance:0},W,{match:"\\$"+n,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[T]},K,F,P,X,{match:/\$[(.]/}]}}function gR(t){const e=t.regex,r=mq(t),n=Gf,i=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],a={begin:[/namespace/,/\s+/,t.IDENT_RE],beginScope:{1:"keyword",3:"title.class"}},o={beginKeywords:"interface",end:/\{/,excludeEnd:!0,keywords:{keyword:"interface extends",built_in:i},contains:[r.exports.CLASS_REFERENCE]},c={className:"meta",relevance:10,begin:/^\s*['"]use strict['"]/},u=["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"],d={$pattern:Gf,keyword:cR.concat(u),literal:uR,built_in:mR.concat(i),"variable.language":pR},p={className:"meta",begin:"@"+n},f=(w,b,S)=>{const A=w.contains.findIndex(O=>O.label===b);if(A===-1)throw new Error("can not find mode to replace");w.contains.splice(A,1,S)};Object.assign(r.keywords,d),r.exports.PARAMS_CONTAINS.push(p);const g=r.contains.find(w=>w.scope==="attr"),v=Object.assign({},g,{match:e.concat(n,e.lookahead(/\s*\?:/))});r.exports.PARAMS_CONTAINS.push([r.exports.CLASS_REFERENCE,g,v]),r.contains=r.contains.concat([p,a,o,v]),f(r,"shebang",t.SHEBANG()),f(r,"use_strict",c);const x=r.contains.find(w=>w.label==="func.def");return x.relevance=0,Object.assign(r,{name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),r}function yR(t){const e=t.regex,r=e.concat(/[\p{L}_]/u,e.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),n=/[\p{L}0-9._:-]+/u,i={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},a={begin:/\s/,contains:[{className:"keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},o=t.inherit(a,{begin:/\(/,end:/\)/}),c=t.inherit(t.APOS_STRING_MODE,{className:"string"}),u=t.inherit(t.QUOTE_STRING_MODE,{className:"string"}),d={endsWithParent:!0,illegal:/</,relevance:0,contains:[{className:"attr",begin:n,relevance:0},{begin:/=\s*/,relevance:0,contains:[{className:"string",endsParent:!0,variants:[{begin:/"/,end:/"/,contains:[i]},{begin:/'/,end:/'/,contains:[i]},{begin:/[^\s"'=<>`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,unicodeRegex:!0,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,relevance:10,contains:[a,u,c,o,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,contains:[a,o,u,c]}]}]},t.COMMENT(/<!--/,/-->/,{relevance:10}),{begin:/<!\[CDATA\[/,end:/\]\]>/,relevance:10},i,{className:"meta",end:/\?>/,variants:[{begin:/<\?xml/,relevance:10,contains:[u]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:"tag",begin:/<style(?=\s|>)/,end:/>/,keywords:{name:"style"},contains:[d],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:/<script(?=\s|>)/,end:/>/,keywords:{name:"script"},contains:[d],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:e.concat(/</,e.lookahead(e.concat(r,e.either(/\/>/,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:r,relevance:0,starts:d}]},{className:"tag",begin:e.concat(/<\//,e.lookahead(e.concat(r,/>/))),contains:[{className:"name",begin:r,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}function vR(t){const e="true false yes no null",r="[\\w#;/?:@&=+$,.~*'()[\\]]+",n={className:"attr",variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},i={className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]},a={className:"string",relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:"char.escape",relevance:0}]},o={className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[t.BACKSLASH_ESCAPE,i]},c=t.inherit(o,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),g={className:"number",begin:"\\b"+"[0-9]{4}(-[0-9][0-9]){0,2}"+"([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?"+"(\\.[0-9]*)?"+"([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?"+"\\b"},v={end:",",endsWithParent:!0,excludeEnd:!0,keywords:e,relevance:0},x={begin:/\{/,end:/\}/,contains:[v],illegal:"\\n",relevance:0},w={begin:"\\[",end:"\\]",contains:[v],illegal:"\\n",relevance:0},b=[n,{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+r},{className:"type",begin:"!<"+r+">"},{className:"type",begin:"!"+r},{className:"type",begin:"!!"+r},{className:"meta",begin:"&"+t.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+t.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},t.HASH_COMMENT_MODE,{beginKeywords:e,keywords:{literal:e}},g,{className:"number",begin:t.C_NUMBER_RE+"\\b",relevance:0},x,w,a,o],S=[...b];return S.pop(),S.push(c),v.contains=S,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:b}}Qt.registerLanguage("javascript",sR);Qt.registerLanguage("js",sR);Qt.registerLanguage("typescript",gR);Qt.registerLanguage("ts",gR);Qt.registerLanguage("python",lR);Qt.registerLanguage("py",lR);Qt.registerLanguage("rust",pq);Qt.registerLanguage("go",lq);Qt.registerLanguage("json",hq);Qt.registerLanguage("yaml",vR);Qt.registerLanguage("yml",vR);Qt.registerLanguage("shell",t1);Qt.registerLanguage("bash",t1);Qt.registerLanguage("sh",t1);Qt.registerLanguage("html",yR);Qt.registerLanguage("xml",yR);Qt.registerLanguage("css",sq);nt.use({renderer:{heading({tokens:t,depth:e}){const r=t.map(a=>a.raw).join(""),n=`h${e}`;return`<${n} style="background:linear-gradient(135deg, #D83333 0%, #E43A9C 50%, #F041FF 100%);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;font-size:${{1:"1.35em",2:"1.15em",3:"1em",4:"0.9em"}[e]??"1em"};font-weight:600;margin:1.1em 0 0.4em;line-height:1.4;">${r}</${n}>`},code({text:t,lang:e}){let r;return e&&Qt.getLanguage(e)?r=Qt.highlight(t,{language:e}).value:r=Qt.highlightAuto(t).value,`<pre style="background:#161616;border:1px solid rgba(255,255,255,0.07);border-radius:10px;padding:0.9em 1.1em;overflow-x:auto;margin:0.8em 0;"><code class="hljs" style="background:none;border:none;padding:0;color:#d4d4d8;font-size:0.85em;">${r}</code></pre>`}}});function sp({content:t,className:e=""}){const r=N.useMemo(()=>nt.parse(t),[t]);return y.jsx("div",{className:`prose-io ${e}`,style:{color:"#d4d4d8",fontSize:"0.875rem",lineHeight:"1.7"},dangerouslySetInnerHTML:{__html:r}})}const ME=["#38bdf8","#a78bfa","#34d399","#f59e0b","#f87171","#E43A9C"];function gq(t){let e=0;for(let r=0;r<t.length;r++)e=t.charCodeAt(r)+((e<<5)-e);return ME[Math.abs(e)%ME.length]}function LE({name:t,color:e}){const r=t.toLowerCase(),n=e??(r==="orchestrator"||r==="io"?"#71717a":gq(t));return y.jsx("span",{className:"inline-flex items-center px-1.5 py-px rounded text-[10px] font-mono border",style:{background:`${n}15`,color:n,borderColor:`${n}30`},children:t})}function yq(){const[t,e]=N.useState([]),[r,n]=N.useState(null),[i,a]=N.useState(new Set),[o,c]=N.useState("all"),u=qa();N.useEffect(()=>{Ve.get("/inbox").then(O=>e(O.entries)).catch(()=>{})},[]);const d=t.filter(O=>O.status==="unread").length,p=o==="unread"?t.filter(O=>O.status==="unread"):t,f=p.length>0&&p.every(O=>i.has(O.id)),g=i.size>0;function v(O){g||(n(O),O.status==="unread"&&(Ve.post(`/inbox/${O.id}/read`).catch(()=>{}),e(j=>j.map(E=>E.id===O.id?{...E,status:"read"}:E))))}function x(O,j){O.stopPropagation(),a(E=>{const T=new Set(E);return T.has(j)?T.delete(j):T.add(j),T})}function w(){a(f?new Set:new Set(p.map(O=>O.id)))}function b(){const O=Array.from(i);Ve.post("/inbox/bulk/read",{ids:O}).catch(()=>{}),e(j=>j.map(E=>i.has(E.id)?{...E,status:"read"}:E)),a(new Set)}function S(){const O=Array.from(i);Ve.post("/inbox/bulk/delete",{ids:O}).catch(()=>{}),e(j=>j.filter(E=>!i.has(E.id))),r&&i.has(r.id)&&n(null),a(new Set)}function A(O){Ve.delete(`/inbox/${O}`).catch(()=>{}),e(j=>j.filter(E=>E.id!==O)),(r==null?void 0:r.id)===O&&n(null)}return y.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:[y.jsxs("div",{className:"w-72 flex-shrink-0 border-r border-white/[0.06] flex flex-col overflow-hidden",children:[y.jsxs("div",{className:"px-4 py-3 border-b border-white/[0.06] flex-shrink-0 space-y-2",children:[y.jsxs("div",{className:"flex items-center justify-between",children:[y.jsx("span",{className:"text-lg tracking-wide text-zinc-200",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"Inbox"}),d>0&&y.jsxs(jt,{variant:"default",children:[d," unread"]})]}),y.jsx("div",{className:"flex gap-1",children:["all","unread"].map(O=>y.jsx("button",{type:"button",onClick:()=>{c(O),a(new Set)},className:`flex-1 py-1 text-[11px] font-mono rounded-lg transition-colors cursor-pointer ${o===O?"text-[#E43A9C]":"text-zinc-600 hover:text-zinc-300"}`,style:o===O?{background:"rgba(228,58,156,0.12)"}:void 0,children:O},O))})]}),g&&y.jsxs("div",{className:"px-3 py-2 border-b border-white/[0.06] flex items-center gap-1.5 flex-shrink-0",style:{background:"rgba(228,58,156,0.06)"},children:[y.jsxs("span",{className:"text-[10px] font-mono text-zinc-500 flex-1",children:[i.size," selected"]}),y.jsxs("button",{type:"button",onClick:b,className:"flex items-center gap-1 px-2 py-1 rounded-lg text-[10px] font-mono text-zinc-400 hover:text-zinc-200 hover:bg-white/[0.06] transition-colors cursor-pointer",children:[y.jsx(zb,{className:"w-3 h-3"}),"Mark read"]}),y.jsxs("button",{type:"button",onClick:S,className:"flex items-center gap-1 px-2 py-1 rounded-lg text-[10px] font-mono text-red-400 hover:text-red-300 hover:bg-red-500/10 transition-colors cursor-pointer",children:[y.jsx(Ma,{className:"w-3 h-3"}),"Delete"]})]}),p.length>0&&y.jsxs("div",{className:"px-4 py-1.5 border-b border-white/[0.04] flex items-center gap-2 flex-shrink-0",children:[y.jsx("button",{type:"button",onClick:w,className:`w-3.5 h-3.5 rounded border flex items-center justify-center flex-shrink-0 transition-colors cursor-pointer ${f?"border-[#E43A9C] bg-[#E43A9C]":"border-white/20 hover:border-white/40"}`,children:f&&y.jsx("svg",{className:"w-2 h-2 text-white",fill:"none",viewBox:"0 0 8 8",children:y.jsx("path",{d:"M1 4l2 2 4-4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),y.jsx("span",{className:"text-[10px] font-mono text-zinc-700",children:"Select all"})]}),y.jsxs("div",{className:"flex-1 overflow-y-auto",children:[p.map(O=>{const j=i.has(O.id),E=(r==null?void 0:r.id)===O.id&&!g;return y.jsxs("div",{onClick:()=>v(O),onKeyDown:T=>T.key==="Enter"&&v(O),className:`flex items-start gap-2.5 px-3 py-3 border-b border-white/[0.04] cursor-pointer transition-colors ${E?"border-l-2 border-l-[#E43A9C] pl-2.5":"hover:bg-white/[0.025]"} ${j?"bg-[#E43A9C]/5":""}`,style:E?{background:"rgba(228,58,156,0.05)"}:void 0,children:[y.jsx("button",{type:"button",onClick:T=>x(T,O.id),className:`mt-0.5 w-3.5 h-3.5 rounded border flex items-center justify-center flex-shrink-0 transition-colors cursor-pointer ${j?"border-[#E43A9C] bg-[#E43A9C]":"border-white/20 hover:border-white/50"}`,children:j&&y.jsx("svg",{className:"w-2 h-2 text-white",fill:"none",viewBox:"0 0 8 8",children:y.jsx("path",{d:"M1 4l2 2 4-4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),y.jsxs("div",{className:"flex-1 min-w-0",children:[y.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[O.status==="unread"&&y.jsx("div",{className:"w-1 h-1 rounded-full bg-[#E43A9C] flex-shrink-0"}),y.jsx(LE,{name:O.squadName??(O.squadId?O.squadId.slice(0,8):"Orchestrator"),color:O.squadColor})]}),y.jsx("p",{className:`text-[11px] truncate ${O.status==="unread"?"text-zinc-200":"text-zinc-500"}`,children:O.title}),y.jsx("p",{className:"text-[10px] text-zinc-700 font-mono mt-1",children:Ws(O.createdAt,u)})]})]},O.id)}),p.length===0&&y.jsxs("div",{className:"flex flex-col items-center justify-center py-12",children:[y.jsx(Bb,{size:32,className:"text-zinc-800 mb-2"}),y.jsx("p",{className:"text-[11px] font-mono text-zinc-700",children:o==="unread"?"All caught up":"No items yet"})]})]})]}),y.jsx("div",{className:"flex-1 flex flex-col overflow-hidden",children:r&&!g?y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:"px-6 py-4 border-b border-white/[0.06] flex items-start justify-between flex-shrink-0",children:[y.jsxs("div",{className:"flex-1 min-w-0 mr-4",children:[y.jsx(LE,{name:r.squadName??(r.squadId?r.squadId.slice(0,8):"Orchestrator"),color:r.squadColor}),y.jsx("h3",{className:"text-sm font-mono text-zinc-100 mt-1.5",children:r.title}),y.jsx("p",{className:"text-[11px] text-zinc-700 font-mono mt-0.5",children:Ws(r.createdAt,u)})]}),y.jsxs("button",{type:"button",onClick:()=>A(r.id),className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg font-mono text-[11px] text-zinc-400 bg-[#252525] hover:bg-red-500/10 hover:text-red-400 transition-colors cursor-pointer",children:[y.jsx(Ma,{className:"w-3 h-3"}),"Delete"]})]}),y.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-5",children:y.jsx(sp,{content:r.content})})]}):g?y.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center gap-4 text-center px-8",children:[y.jsx("div",{className:"w-10 h-10 rounded-2xl flex items-center justify-center border border-[#E43A9C]/20",style:{background:"rgba(228,58,156,0.08)"},children:y.jsx(Bb,{className:"w-4 h-4 text-[#E43A9C]"})}),y.jsxs("div",{children:[y.jsxs("p",{className:"text-sm font-mono text-zinc-300",children:[i.size," message",i.size!==1?"s":""," selected"]}),y.jsx("p",{className:"text-[11px] text-zinc-600 mt-1",children:"Use the actions above to mark as read or delete"})]}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsxs("button",{type:"button",onClick:b,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-mono text-zinc-300 border border-white/[0.1] hover:bg-white/[0.05] transition-colors cursor-pointer",children:[y.jsx(zb,{className:"w-3 h-3"}),"Mark read"]}),y.jsxs("button",{type:"button",onClick:S,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-mono text-red-400 border border-red-500/20 hover:bg-red-500/10 transition-colors cursor-pointer",children:[y.jsx(Ma,{className:"w-3 h-3"}),"Delete selected"]})]})]}):y.jsx("div",{className:"flex-1 flex items-center justify-center text-zinc-700 font-mono text-xs",children:"Select an item to read"})})]})}function vq(){const{signIn:t}=op(),[e,r]=N.useState(""),[n,i]=N.useState(""),[a,o]=N.useState(null),[c,u]=N.useState(!1);async function d(p){p.preventDefault(),o(null),u(!0);const{error:f}=await t(e,n);f&&o(f),u(!1)}return y.jsxs("div",{className:"min-h-screen bg-[#161616] flex items-center justify-center relative overflow-hidden",children:[y.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(circle, #E43A9C 1px, transparent 1px)",backgroundSize:"32px 32px"}}),y.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-[60%] w-[400px] h-[300px] rounded-full blur-3xl pointer-events-none",style:{background:"radial-gradient(ellipse, rgba(228,58,156,0.12) 0%, transparent 70%)"}}),y.jsxs("div",{className:"relative z-10 w-full max-w-[360px] mx-4",children:[y.jsxs("div",{className:"flex flex-col items-center mb-8 gap-3",children:[y.jsx(Ra,{height:52}),y.jsx("div",{className:"text-center",children:y.jsx("p",{className:"text-[11px] font-mono text-zinc-600 tracking-widest uppercase mt-1",children:"personal ai orchestrator"})})]}),y.jsxs("form",{onSubmit:d,className:"glass-card border border-white/[0.07] rounded-2xl p-6 space-y-4",children:[y.jsxs("div",{className:"space-y-1",children:[y.jsx("label",{className:"text-[11px] font-mono text-zinc-500 block",children:"Email"}),y.jsx("input",{type:"email",value:e,onChange:p=>r(p.target.value),required:!0,className:"w-full bg-[#161616] border border-white/[0.08] rounded-xl px-3 py-2.5 text-sm text-zinc-200 font-mono placeholder:text-zinc-700 focus:outline-none focus:border-[#E43A9C]/40 focus:ring-1 focus:ring-[#E43A9C]/15 transition-colors"})]}),y.jsxs("div",{className:"space-y-1",children:[y.jsx("label",{className:"text-[11px] font-mono text-zinc-500 block",children:"Password"}),y.jsx("input",{type:"password",value:n,onChange:p=>i(p.target.value),required:!0,placeholder:"••••••••",className:"w-full bg-[#161616] border border-white/[0.08] rounded-xl px-3 py-2.5 text-sm text-zinc-200 font-mono placeholder:text-zinc-700 focus:outline-none focus:border-[#E43A9C]/40 focus:ring-1 focus:ring-[#E43A9C]/15 transition-colors"})]}),a&&y.jsx("p",{className:"text-[11px] font-mono text-red-400",children:a}),y.jsx("button",{type:"submit",disabled:c,className:"w-full text-white font-mono text-sm rounded-xl py-3 mt-1 transition-opacity hover:opacity-90 disabled:opacity-50 flex items-center justify-center gap-2",style:{background:"linear-gradient(135deg, #D83333 0%, #E43A9C 55%, #F041FF 100%)"},children:c?y.jsxs(y.Fragment,{children:[y.jsx("span",{className:"w-3.5 h-3.5 border-2 border-white/30 border-t-white rounded-full animate-spin"}),"Authenticating…"]}):"Sign In"})]}),y.jsx("p",{className:"text-center text-[11px] text-zinc-700 font-mono mt-4",children:"Secured by Supabase Auth"})]})]})}const bR="w-full bg-[#161616] border border-white/[0.08] rounded-xl px-3 py-2 text-[11px] text-zinc-300 font-mono placeholder:text-zinc-700 focus:outline-none focus:border-[#E43A9C]/40 focus:ring-1 focus:ring-[#E43A9C]/10 transition-colors",Bs="bg-[#161616] border border-white/[0.08] rounded-xl px-3 py-2 text-[11px] text-zinc-300 font-mono placeholder:text-zinc-700 focus:outline-none focus:border-[#E43A9C]/40 focus:ring-1 focus:ring-[#E43A9C]/10 transition-colors";function qi({label:t,hint:e,align:r="center",children:n}){const i=r==="start"?"flex-1 min-w-0":"flex-1 flex justify-end items-center";return y.jsxs("div",{className:`glass-card border border-white/[0.07] rounded-2xl px-4 py-3.5 flex gap-4 ${r==="start"?"items-start":"items-center"}`,children:[y.jsxs("div",{className:"w-[140px] shrink-0",children:[y.jsx("span",{className:"text-[11px] font-mono text-zinc-400",children:t}),e&&y.jsxs("span",{className:"text-[10px] font-mono text-zinc-700 ml-1.5",children:["(",e,")"]})]}),y.jsx("div",{className:i,children:n})]})}function bq({onSave:t,onCancel:e,squads:r}){var x;const[n,i]=N.useState("io"),[a,o]=N.useState(((x=r[0])==null?void 0:x.id)??""),[c,u]=N.useState(""),[d,p]=N.useState(""),[f,g]=N.useState(""),v=()=>{!d.trim()||!f.trim()||!c.trim()||t({name:c.trim(),targetType:n==="io"?"orchestrator":"squad",targetId:n==="squad"?a:void 0,cron:d.trim(),prompt:f.trim()})};return y.jsx("div",{className:"fixed inset-0 z-40 flex items-center justify-center p-6",style:{background:"rgba(0,0,0,0.55)",backdropFilter:"blur(4px)"},children:y.jsxs("div",{className:"glass-card border border-white/[0.09] rounded-2xl w-full max-w-lg shadow-2xl flex flex-col",style:{maxHeight:"90vh"},children:[y.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-white/[0.06] flex-shrink-0",children:[y.jsx("h3",{className:"text-lg tracking-wide text-zinc-100",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"New Schedule"}),y.jsx("button",{type:"button",onClick:e,className:"p-1.5 rounded-lg text-zinc-600 hover:text-zinc-300 hover:bg-white/[0.06] transition-colors cursor-pointer",children:y.jsx(aP,{className:"w-4 h-4"})})]}),y.jsxs("div",{className:"overflow-y-auto flex-1 px-5 py-4 space-y-2",children:[y.jsx(qi,{label:"Name",children:y.jsx("input",{value:c,onChange:w=>u(w.target.value),placeholder:"Daily triage",className:`${Bs} w-48`})}),y.jsx(qi,{label:"Type",children:y.jsx("div",{className:"flex gap-2",children:["io","squad"].map(w=>y.jsx("button",{type:"button",onClick:()=>i(w),className:`px-4 py-1.5 rounded-xl text-[11px] font-mono capitalize transition-colors border cursor-pointer ${n===w?"text-[#E43A9C] border-[#E43A9C]/30":"text-zinc-500 border-white/[0.08] hover:text-zinc-300 hover:bg-white/[0.04]"}`,style:n===w?{background:"rgba(228,58,156,0.08)"}:void 0,children:w==="io"?"IO":"Squad"},w))})}),n==="squad"&&y.jsx(qi,{label:"Squad",children:y.jsx("select",{value:a,onChange:w=>o(w.target.value),className:`${Bs} w-48`,children:r.map(w=>y.jsx("option",{value:w.id,style:{background:"#1a1a1a",color:"#d4d4d8"},children:w.name},w.id))})}),y.jsx(qi,{label:"Cron Expression",children:y.jsx("input",{value:d,onChange:w=>p(w.target.value),placeholder:"0 9 * * 1-5",className:`${Bs} w-40`})}),y.jsx(qi,{label:"Prompt",hint:"supports Markdown",align:"start",children:y.jsx("textarea",{value:f,onChange:w=>g(w.target.value),placeholder:"Describe what IO or the squad should do when this schedule fires.",rows:8,className:`${bR} resize-none leading-relaxed`})})]}),y.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-3.5 border-t border-white/[0.06] flex-shrink-0",children:[y.jsx(_i,{onClick:e,children:"Cancel"}),y.jsxs(za,{onClick:v,className:"px-4 py-1.5",children:[y.jsx(Uw,{className:"w-3 h-3"}),"Create Schedule"]})]})]})})}function xq({sched:t,squads:e,onSave:r,onBack:n}){var x,w;const[i,a]=N.useState(t.name),[o,c]=N.useState(t.cron),[u,d]=N.useState(t.prompt),[p,f]=N.useState(t.targetId??((x=e[0])==null?void 0:x.id)??""),g=()=>{!o.trim()||!u.trim()||!i.trim()||r({name:i.trim(),cron:o.trim(),prompt:u.trim(),targetId:t.targetType==="squad"?p:void 0})},v=t.targetType==="orchestrator"?"IO Schedule":`Squad — ${((w=e.find(b=>b.id===t.targetId))==null?void 0:w.name)??"Unknown"}`;return y.jsxs("div",{className:"flex-1 overflow-y-auto p-6 max-w-3xl",children:[y.jsxs("div",{className:"flex items-center gap-2 mb-6",children:[y.jsxs("button",{type:"button",onClick:n,className:"flex items-center gap-1.5 text-[11px] font-mono text-zinc-600 hover:text-zinc-300 transition-colors cursor-pointer",children:[y.jsx(vl,{className:"w-3.5 h-3.5"}),"Schedules"]}),y.jsx("span",{className:"text-zinc-700 text-[11px]",children:"/"}),y.jsx("span",{className:"text-[11px] font-mono text-zinc-400",children:"Edit"})]}),y.jsxs("div",{className:"flex items-start justify-between mb-6",children:[y.jsxs("div",{children:[y.jsx("h2",{className:"text-2xl tracking-wide text-zinc-100",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"Edit Schedule"}),y.jsx("p",{className:"text-[11px] font-mono text-zinc-600 mt-0.5",children:v})]}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx(_i,{onClick:n,children:"Cancel"}),y.jsxs(za,{onClick:g,className:"px-4 py-1.5",children:[y.jsx(Uw,{className:"w-3 h-3"}),"Save Changes"]})]})]}),y.jsxs("div",{className:"space-y-3",children:[y.jsx(qi,{label:"Name",children:y.jsx("input",{value:i,onChange:b=>a(b.target.value),placeholder:"Schedule name",className:`${Bs} w-48`})}),t.targetType==="squad"&&y.jsx(qi,{label:"Squad",children:y.jsx("select",{value:p,onChange:b=>f(b.target.value),className:`${Bs} w-48`,children:e.map(b=>y.jsx("option",{value:b.id,style:{background:"#1a1a1a",color:"#d4d4d8"},children:b.name},b.id))})}),y.jsx(qi,{label:"Cron Expression",children:y.jsx("input",{value:o,onChange:b=>c(b.target.value),placeholder:"0 9 * * 1-5",className:`${Bs} w-40`})}),y.jsx(qi,{label:"Prompt",hint:"supports Markdown",align:"start",children:y.jsxs("div",{className:"space-y-1.5",children:[y.jsx("textarea",{value:u,onChange:b=>d(b.target.value),placeholder:"Describe what IO or the squad should do when this schedule fires.",className:`${bR} leading-relaxed resize-y`,style:{minHeight:"360px"}}),y.jsx("p",{className:"text-[10px] font-mono text-zinc-700",children:"Tip: use # headings and - lists to structure multi-step instructions."})]})})]})]})}function wq(){const[t,e]=N.useState("squad"),[r,n]=N.useState([]),[i,a]=N.useState([]),[o,c]=N.useState(!1),[u,d]=N.useState(null),p=qa();N.useEffect(()=>{f(),g()},[]);function f(){Ve.get("/schedules").then(R=>n(R.schedules)).catch(()=>{})}function g(){Ve.get("/squads").then(R=>a(R.squads)).catch(()=>{})}const v=r.filter(R=>R.targetType==="squad"),x=r.filter(R=>R.targetType==="orchestrator"),w=t==="squad"?v:x;async function b(R){try{await Ve.post("/schedules",R),at.success("Schedule created"),c(!1),f()}catch(M){at.error(M instanceof Error?M.message:"Failed to create")}}async function S(R){if(u)try{await Ve.patch(`/schedules/${u.id}`,R),at.success("Schedule saved"),d(null),f()}catch{at.error("Failed to save schedule")}}const[A,O]=N.useState(null);async function j(R,M){O(R);try{await Ve.patch(`/schedules/${R}`,{enabled:!M}),at.success(M?"Schedule paused":"Schedule resumed"),f()}catch{at.error("Failed to toggle schedule")}finally{O(null)}}async function E(R){O(R);try{await Ve.post(`/schedules/${R}/run`,{}),at.success("Schedule triggered")}catch{at.error("Failed to trigger schedule")}finally{O(null)}}async function T(R){O(R);try{await Ve.delete(`/schedules/${R}`),at.success("Schedule deleted"),f()}catch{at.error("Failed to delete")}finally{O(null)}}if(u)return y.jsx(xq,{sched:u,squads:i,onSave:S,onBack:()=>d(null)});const P=t==="squad"?["Squad","Name","Cron","Next Run","Status",""]:["Name","Cron","Next Run","Status",""];return y.jsxs("div",{className:"flex-1 overflow-y-auto p-6",children:[o&&y.jsx(bq,{onSave:b,onCancel:()=>c(!1),squads:i}),y.jsxs("div",{className:"flex items-center justify-between mb-5",children:[y.jsxs("div",{children:[y.jsx("h2",{className:"text-2xl tracking-wide text-zinc-100",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"Schedules"}),y.jsxs("p",{className:"text-[11px] text-zinc-600 font-mono mt-0.5",children:[r.filter(R=>R.enabled).length," active · ",r.filter(R=>!R.enabled).length," paused"]})]}),y.jsxs(za,{onClick:()=>c(!0),className:"px-3 py-1.5",children:[y.jsx(Bw,{className:"w-3.5 h-3.5"}),"Add Schedule"]})]}),y.jsx("div",{className:"flex gap-1 mb-4",children:[["squad","Squad Schedules"],["io","IO Schedules"]].map(([R,M])=>y.jsx("button",{type:"button",onClick:()=>e(R),className:`px-4 py-2 text-[11px] font-mono rounded-xl transition-colors cursor-pointer ${t===R?"text-[#E43A9C]":"text-zinc-600 hover:text-zinc-300 hover:bg-white/[0.04]"}`,style:t===R?{background:"rgba(228,58,156,0.12)"}:void 0,children:M},R))}),y.jsx("div",{className:"overflow-x-auto rounded-2xl border border-white/[0.07] glass-card",children:w.length===0?y.jsx("div",{className:"px-4 py-12 text-center text-zinc-600 font-mono text-sm",children:"No schedules for this category"}):y.jsxs("table",{className:"w-full text-[11px] font-mono min-w-[640px]",children:[y.jsx("thead",{children:y.jsx("tr",{className:"border-b border-white/[0.06]",style:{background:"rgba(20,20,20,0.6)"},children:P.map(R=>y.jsx("th",{className:"text-left px-4 py-2.5 text-zinc-600 font-medium",children:R},R))})}),y.jsx("tbody",{children:w.map(R=>{var M,J;return y.jsxs("tr",{className:`border-b border-white/[0.04] hover:bg-white/[0.015] transition-colors ${R.enabled?"":"opacity-50"}`,children:[t==="squad"?y.jsx("td",{className:"px-4 py-3",children:y.jsx(HB,{name:((M=i.find(F=>F.id===R.targetId))==null?void 0:M.name)??"Unknown",color:(J=i.find(F=>F.id===R.targetId))==null?void 0:J.color})}):null,y.jsx("td",{className:"px-4 py-3 text-zinc-300",children:R.name}),y.jsx("td",{className:"px-4 py-3 text-zinc-600 text-[10px]",children:R.cron}),y.jsx("td",{className:"px-4 py-3 text-zinc-600",children:y.jsxs("span",{className:"flex items-center gap-1",children:[y.jsx(Lw,{className:"w-3 h-3"}),R.enabled&&R.nextRun?Ws(R.nextRun,p):"—"]})}),y.jsx("td",{className:"px-4 py-3",children:y.jsx(jt,{variant:R.enabled?"success":"muted",children:R.enabled?"active":"paused"})}),y.jsx("td",{className:"px-4 py-3",children:y.jsxs("div",{className:`flex items-center gap-1 ${A===R.id?"opacity-50 pointer-events-none":""}`,children:[y.jsxs(_i,{onClick:()=>E(R.id),children:[y.jsx(N4,{className:"w-3 h-3"}),"Run now"]}),y.jsx(WB,{onClick:()=>j(R.id,R.enabled),children:R.enabled?y.jsxs(y.Fragment,{children:[y.jsx(O4,{className:"w-3 h-3"}),"Pause"]}):y.jsxs(y.Fragment,{children:[y.jsx(Ds,{className:"w-3 h-3"}),"Resume"]})}),y.jsxs(_i,{onClick:()=>d(R),children:[y.jsx(T4,{className:"w-3 h-3"}),"Edit"]}),y.jsxs(zf,{onClick:()=>T(R.id),children:[y.jsx(Ma,{className:"w-3 h-3"}),"Delete"]})]})})]},R.id)})})]})})]})}const _q=[{id:"general",label:"General"},{id:"telegram",label:"Telegram"},{id:"auth",label:"Auth"}],Uo="rounded-xl border border-white/[0.07] bg-white/[0.04] px-3 py-2 text-sm font-mono text-zinc-300 outline-none focus:border-[#E43A9C]/50",DE=`${Uo} w-[72px]`,Sq=`${Uo} w-[100px]`,zE=`${Uo} w-[200px]`,BE=`${Uo} w-[320px]`,kq=`${Uo} w-[140px] appearance-none bg-[url('data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2212%22%20height%3D%2212%22%20viewBox%3D%220%200%2012%2012%22%3E%3Cpath%20fill%3D%22%2371717a%22%20d%3D%22M3%204.5L6%208l3-3.5H3z%22%2F%3E%3C%2Fsvg%3E')] bg-[position:right_10px_center] bg-no-repeat pr-8`;function Eq(){const[t,e]=N.useState(null),[r,n]=N.useState("general");N.useEffect(()=>{Ve.get("/config").then(o=>e(o.config)).catch(()=>{})},[]);function i(o){t&&e({...t,...o})}async function a(){if(t)try{const{dataDir:o,...c}=t;await Ve.patch("/config",c),at.success("Settings saved")}catch{at.error("Failed to save settings")}}return t?y.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:y.jsxs("div",{className:"max-w-3xl",children:[y.jsx("h2",{className:"mb-6 text-2xl tracking-wide text-zinc-100",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"Settings"}),y.jsx("div",{className:"mb-6 flex gap-6 border-b border-white/[0.07]",children:_q.map(o=>y.jsx("button",{type:"button",onClick:()=>n(o.id),className:`-mb-px border-b-2 px-1 pb-3 text-[11px] font-mono transition-colors ${r===o.id?"border-[#E43A9C] text-[#E43A9C]":"border-transparent text-zinc-500 hover:text-zinc-300"}`,children:o.label},o.id))}),y.jsxs("div",{className:"glass-card rounded-2xl border border-white/[0.07] p-5",children:[r==="general"&&y.jsxs(y.Fragment,{children:[y.jsx(_n,{label:"Log Level",children:y.jsx("select",{value:t.logLevel,onChange:o=>i({logLevel:o.target.value}),className:kq,children:["trace","debug","info","warn","error","fatal"].map(o=>y.jsx("option",{value:o,children:o},o))})}),y.jsx(_n,{label:"Default Model",children:y.jsx("input",{type:"text",value:t.defaultModel,onChange:o=>i({defaultModel:o.target.value}),className:zE})}),y.jsx(_n,{label:"Timezone",children:y.jsx("select",{value:t.timezone,onChange:o=>i({timezone:o.target.value}),className:`${Uo} w-[200px] appearance-none bg-[url('data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2212%22%20height%3D%2212%22%20viewBox%3D%220%200%2012%2012%22%3E%3Cpath%20fill%3D%22%2371717a%22%20d%3D%22M3%204.5L6%208l3-3.5H3z%22%2F%3E%3C%2Fsvg%3E')] bg-[position:right_10px_center] bg-no-repeat pr-8`,children:Q4.map(o=>y.jsx("option",{value:o.value,children:o.label},o.value))})}),y.jsx(_n,{label:"Max Instances",children:y.jsx("input",{type:"number",value:t.maxInstancesPerSquad,onChange:o=>i({maxInstancesPerSquad:Number(o.target.value)}),className:DE,min:1,max:10})}),y.jsx(_n,{label:"API Port",children:y.jsx("input",{type:"number",value:t.apiPort,onChange:o=>i({apiPort:Number(o.target.value)}),className:DE})}),y.jsx(_n,{label:"Pricing Refresh (hrs)",children:y.jsx("input",{type:"number",value:t.pricing.refreshIntervalHours,onChange:o=>i({pricing:{refreshIntervalHours:Number(o.target.value)}}),className:Sq,min:1})}),y.jsx(_n,{label:"Data Dir",children:y.jsx("input",{type:"text",value:t.dataDir,readOnly:!0,className:`${BE} cursor-default text-zinc-500`})})]}),r==="telegram"&&y.jsxs(y.Fragment,{children:[y.jsx(_n,{label:"Bot Token",children:y.jsx(Ig,{value:t.telegram.botToken??"",onChange:o=>i({telegram:{...t.telegram,botToken:o||null}}),size:"lg"})}),y.jsx(_n,{label:"Allowed Chat IDs",children:y.jsx("input",{type:"text",value:t.telegram.allowedChatIds.join(", "),onChange:o=>i({telegram:{...t.telegram,allowedChatIds:o.target.value.split(",").map(c=>Number(c.trim())).filter(c=>!Number.isNaN(c))}}),className:zE})})]}),r==="auth"&&y.jsxs(y.Fragment,{children:[y.jsx(_n,{label:"Project URL",children:y.jsx("input",{type:"text",value:t.supabase.projectUrl??"",onChange:o=>i({supabase:{...t.supabase,projectUrl:o.target.value||null}}),className:BE})}),y.jsx(_n,{label:"Anon Key",children:y.jsx(Ig,{value:t.supabase.anonKey??"",onChange:o=>i({supabase:{...t.supabase,anonKey:o||null}}),size:"lg"})}),y.jsx(_n,{label:"JWT Secret",children:y.jsx(Ig,{value:t.supabase.jwtSecret??"",onChange:o=>i({supabase:{...t.supabase,jwtSecret:o||null}}),size:"lg"})})]}),y.jsx("div",{className:"flex justify-end pt-6",children:y.jsx(za,{onClick:a,className:"px-4 py-2.5",children:"Save Settings"})})]})]})}):y.jsx("div",{className:"flex h-full items-center justify-center text-zinc-600",children:"Loading..."})}function _n({label:t,children:e}){return y.jsxs("div",{className:"flex items-center justify-between gap-6 border-b border-white/[0.07] py-3",children:[y.jsx("label",{className:"text-[11px] font-mono text-zinc-400 shrink-0",children:t}),y.jsx("div",{className:"flex justify-end",children:e})]})}function Ig({value:t,onChange:e,size:r="lg"}){const[n,i]=N.useState(!1),a=r==="lg"?"w-[320px]":"w-[200px]";return y.jsxs("div",{className:"relative",children:[y.jsx("input",{type:n?"text":"password",value:t,onChange:o=>e(o.target.value),className:`${Uo} ${a} pr-9`}),y.jsx("button",{type:"button",onClick:()=>i(o=>!o),className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-zinc-600 transition-colors hover:text-zinc-400","aria-label":n?"Hide value":"Show value",children:n?y.jsx(n4,{size:14}):y.jsx(zb,{size:14})})]})}const Oq=[{id:"installed",label:"Installed"},{id:"awesome-copilot",label:"Awesome Copilot"},{id:"skillssh",label:"skills.sh"}];function UE(t){return t==="awesome-copilot"?"Awesome Copilot":"skills.sh"}function qE(t){return t?t>=1e6?`${(t/1e6).toFixed(1).replace(/\.0$/,"")}M installs`:t>=1e3?`${(t/1e3).toFixed(1).replace(/\.0$/,"")}K installs`:`${t} installs`:null}function Aq(t){const e=t.match(/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/);if(!e)return{frontMatter:{},body:t};const r=e[1]??"",n=e[2]??"",i={};let a="",o=null;for(const c of r.split(`
|
|
434
|
-
`)){const u=c.match(/^(\w[\w-]*)\s*:\s*(.*)$/);if(u){a&&o&&(i[a]=o,o=null),a=u[1]??"";const d=(u[2]??"").trim();d===""||d==="[]"?o=[]:d.startsWith("[")&&d.endsWith("]")?i[a]=d.slice(1,-1).split(",").map(p=>p.trim().replace(/^["']|["']$/g,"")):i[a]=d.replace(/^["']|["']$/g,"")}else c.match(/^\s+-\s+(.+)/)&&a&&(o||(o=[]),o.push(c.replace(/^\s+-\s+/,"").trim()))}return a&&o&&(i[a]=o),{frontMatter:i,body:n}}const FE=["name","description","version","author","license","argument_hint","argument-hint","use_when","use-when","enhancements","metadata","tags"];function Tq({content:t}){const{frontMatter:e,body:r}=Aq(t),n=FE.filter(o=>e[o]!==void 0),i=Object.keys(e).filter(o=>!FE.includes(o)),a=[...n,...i];return y.jsxs("div",{children:[a.length>0&&y.jsxs("div",{className:"border-b border-white/[0.05] pb-4 mb-4",children:[y.jsx("p",{className:"text-[10px] font-mono text-zinc-700 uppercase tracking-wider mb-3",children:"Front Matter"}),y.jsx("div",{className:"space-y-2",children:a.map(o=>{const c=e[o];return c==null||Array.isArray(c)&&c.length===0?null:y.jsxs("div",{className:"flex gap-3 items-start",children:[y.jsx("span",{className:"text-[10px] font-mono text-zinc-600 w-28 flex-shrink-0 pt-0.5",children:o}),y.jsx("div",{className:"flex-1 min-w-0",children:Array.isArray(c)?y.jsx("div",{className:"flex flex-wrap gap-1",children:c.map((u,d)=>y.jsx(jt,{variant:"muted",children:u},d))}):typeof c=="object"?y.jsx("div",{className:"space-y-0.5",children:Object.entries(c).map(([u,d])=>y.jsxs("p",{className:"text-[11px] font-mono text-zinc-400",children:[y.jsxs("span",{className:"text-zinc-600",children:[u,":"]})," ",d]},u))}):o==="use_when"||o==="use-when"?y.jsx("p",{className:"text-[11px] text-zinc-300 leading-relaxed",children:c}):o==="argument_hint"||o==="argument-hint"?y.jsx("code",{className:"text-[11px] font-mono text-[#E43A9C] bg-[#2d1a24] px-1.5 py-0.5 rounded",children:c}):y.jsx("span",{className:"text-[11px] font-mono text-zinc-300",children:c})})]},o)})})]}),r.trim()&&y.jsxs("div",{children:[y.jsx("p",{className:"text-[10px] font-mono text-zinc-700 uppercase tracking-wider mb-3",children:"Body"}),y.jsx(sp,{content:r})]})]})}function jq(){const[t,e]=N.useState("installed"),[r,n]=N.useState([]),[i,a]=N.useState([]),[o,c]=N.useState(null);function u($){return"url"in $&&$.url?$.url:$.name}const[d,p]=N.useState(null),[f,g]=N.useState(""),[v,x]=N.useState(!1),[w,b]=N.useState(!1),[S,A]=N.useState(!1),[O,j]=N.useState(""),[E,T]=N.useState(null),[P,R]=N.useState(null),M=N.useCallback(async()=>{try{const $=await Ve.get("/skills"),V=new Set($.skills.map(oe=>oe.name.toLowerCase()));n($.skills),a(oe=>oe.map(le=>({...le,installed:V.has(le.name.toLowerCase())})))}catch($){at.error($ instanceof Error?$.message:"Failed to load skills")}},[]),J=N.useCallback(async $=>{b(!0);try{const V=await Ve.get(`/skills/${encodeURIComponent($)}`);p(V),j(V.content)}catch(V){at.error(V instanceof Error?V.message:"Failed to load skill"),p(null)}finally{b(!1)}},[]);N.useEffect(()=>{M()},[M]),N.useEffect(()=>{if(t==="installed"){R(null);return}const $=f.trim();if(t==="skillssh"&&!$){a([]),R(null),x(!1);return}let V=!1;x(!0);const oe=window.setTimeout(async()=>{try{const le=await Ve.get(`/skills/discover?source=${t}&q=${encodeURIComponent($)}`);if(V)return;a(le.skills),R(null)}catch(le){if(V)return;a([]),R(le instanceof Error?le.message:"Discovery failed")}finally{V||x(!1)}},250);return()=>{V=!0,window.clearTimeout(oe)}},[f,t]);const F=N.useMemo(()=>{const $=f.trim().toLowerCase();return $?r.filter(V=>[V.name,V.description,V.preview].some(oe=>oe.toLowerCase().includes($))):r},[r,f]),B=t==="installed"?F:i,K=F.find($=>$.name===o)??null,W=i.find($=>u($)===o)??null,X=(K==null?void 0:K.name)??(W==null?void 0:W.name)??null;N.useEffect(()=>{if(A(!1),!B.length){c(null),t!=="installed"&&p(null);return}if(!o||!B.some($=>u($)===o)){const $=B[0];$&&c(u($))}},[o,t,B]),N.useEffect(()=>{if(t!=="installed"||!X){p(null);return}J(X)},[J,X,t]);async function Y($){if(!$.url&&!$.registrySource){at.error("Install source is not available for this skill yet");return}T($.name);try{await Ve.post("/skills/install",{name:$.name,source:$.source,url:$.url,registrySource:$.registrySource,skillId:$.skillId}),at.success(`Installed ${$.title||$.name}`),await M(),a(V=>V.map(oe=>oe.name===$.name?{...oe,installed:!0}:oe))}catch(V){at.error(V instanceof Error?V.message:"Install failed")}finally{T(null)}}async function te($){T($);try{await Ve.delete(`/skills/${encodeURIComponent($)}`),at.success(`Removed ${$}`),await M(),a(V=>V.map(oe=>oe.name===$?{...oe,installed:!1}:oe))}catch(V){at.error(V instanceof Error?V.message:"Failed to remove skill")}finally{T(null)}}async function H(){if(d){T(d.name);try{await Ve.put(`/skills/${encodeURIComponent(d.name)}`,{content:O}),at.success(`Updated ${d.name}`),A(!1),await Promise.all([M(),J(d.name)])}catch($){at.error($ instanceof Error?$.message:"Failed to save skill")}finally{T(null)}}}const Q=!!(K!=null&&K.activatedForOrchestrator),U=E===(d==null?void 0:d.name),I=E===(W==null?void 0:W.name);return y.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:[y.jsxs("div",{className:"w-64 flex-shrink-0 border-r border-white/[0.06] flex flex-col overflow-hidden",children:[y.jsxs("div",{className:"px-2.5 pt-2.5 pb-2 flex-shrink-0 border-b border-white/[0.06] space-y-2",children:[y.jsxs("div",{className:"relative",children:[y.jsx(rP,{className:"pointer-events-none absolute left-2.5 top-1/2 h-3 w-3 -translate-y-1/2 text-zinc-700"}),y.jsx("input",{type:"text",value:f,onChange:$=>g($.target.value),placeholder:"Search skills…",className:"w-full bg-[#181818] border border-white/[0.06] rounded-xl pl-7 pr-2 py-1.5 text-[11px] text-zinc-300 font-mono placeholder:text-zinc-700 focus:outline-none focus:border-[#E43A9C]/30 transition-colors"})]}),y.jsx("div",{className:"flex flex-col gap-0.5",children:Oq.map($=>y.jsxs("button",{type:"button",onClick:()=>e($.id),className:`w-full text-left px-2.5 py-1.5 rounded-lg text-[11px] font-mono transition-colors flex items-center justify-between cursor-pointer ${t===$.id?"text-[#E43A9C]":"text-zinc-500 hover:text-zinc-300 hover:bg-white/[0.04]"}`,style:t===$.id?{background:"rgba(228,58,156,0.10)"}:void 0,children:[y.jsx("span",{children:$.label}),$.id==="installed"&&y.jsx("span",{className:"text-[10px] text-zinc-600",children:r.length})]},$.id))})]}),y.jsxs("div",{className:"flex-1 overflow-y-auto py-1.5",children:[v&&t!=="installed"?y.jsxs("div",{className:"flex items-center gap-2 rounded-2xl border border-white/[0.08] bg-white/[0.03] px-3 py-3 font-mono text-[11px] text-zinc-500",children:[y.jsx(js,{className:"h-3.5 w-3.5 animate-spin"})," Searching registry..."]}):null,B.map($=>{const V=u($),oe=o===V,le=$.description||("preview"in $?$.preview:"No description available.");return y.jsxs("button",{type:"button",onClick:()=>{A(!1),c(V)},className:`w-full text-left px-3 py-2.5 border-b border-white/[0.03] transition-colors cursor-pointer ${oe?"border-l-2 border-l-[#E43A9C] bg-[#E43A9C]/5":"hover:bg-white/[0.03]"}`,children:[y.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[y.jsx("span",{className:"truncate font-mono text-[11px] text-zinc-200",children:$.name}),"installed"in $&&$.installed?y.jsx(jt,{variant:"success",children:"installed"}):null]}),y.jsx("p",{className:"line-clamp-2 font-mono text-[10px] leading-relaxed text-zinc-600",children:le})]},`${t}:${V}`)}),!v&&B.length===0?y.jsx("div",{className:"px-4 py-8",children:y.jsx("p",{className:"font-mono text-[11px] leading-relaxed text-zinc-500",children:P||(t==="skillssh"&&!f.trim()?"Start typing to search the skills.sh registry.":f.trim()?"No skills match your search.":"No skills available in this source.")})}):null]})]}),y.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto p-5",children:t==="installed"&&K?y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:"mb-5 flex items-start justify-between gap-4 border-b border-white/[0.06] pb-5",children:[y.jsxs("div",{className:"flex min-w-0 gap-4",children:[y.jsx("div",{className:"flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl bg-[#E43A9C]/12 text-[#E43A9C]",children:y.jsx(qb,{className:"h-6 w-6"})}),y.jsxs("div",{className:"min-w-0",children:[y.jsx("h3",{className:"truncate text-[34px] uppercase tracking-[0.08em] text-zinc-100",style:{fontFamily:"'Bebas Neue', sans-serif"},children:K.name}),y.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[y.jsx(jt,{variant:"success",children:"installed"}),Q?y.jsx(jt,{variant:"warning",children:"active"}):y.jsx(jt,{variant:"muted",children:"inactive"}),y.jsx(jt,{variant:"muted",children:"local skill"})]}),y.jsxs("div",{className:"mt-3 space-y-1 font-mono text-[11px] text-zinc-500",children:[y.jsxs("p",{children:["path: ",K.filePath]}),y.jsxs("p",{children:["orchestrator: ",Q?"enabled":"disabled"]})]})]})]}),y.jsxs("div",{className:"flex items-center gap-2",children:[S?y.jsxs(za,{onClick:H,disabled:U||O===(d==null?void 0:d.content),className:"px-3 py-2",children:[U?y.jsx(js,{className:"h-3.5 w-3.5 animate-spin"}):y.jsx(Ub,{className:"h-3.5 w-3.5"}),"Save"]}):y.jsxs(_i,{onClick:()=>A(!0),className:"px-3 py-2",children:[y.jsx(Ub,{className:"h-3.5 w-3.5"})," Edit"]}),y.jsxs(zf,{onClick:()=>te(K.name),className:"px-3 py-2",children:[U?y.jsx(js,{className:"h-3.5 w-3.5 animate-spin"}):y.jsx(Ma,{className:"h-3.5 w-3.5"}),"Remove"]})]})]}),y.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto pr-1",children:w&&!d?y.jsxs("div",{className:"flex items-center gap-2 font-mono text-[11px] text-zinc-500",children:[y.jsx(js,{className:"h-3.5 w-3.5 animate-spin"})," Loading skill..."]}):S?y.jsxs("div",{className:"space-y-3",children:[y.jsx("textarea",{value:O,onChange:$=>j($.target.value),className:"min-h-[440px] w-full rounded-2xl border border-white/[0.08] bg-black/30 p-4 font-mono text-[12px] leading-6 text-zinc-200 outline-none transition-colors focus:border-[#E43A9C]/50"}),y.jsxs("div",{className:"flex items-center justify-between font-mono text-[11px] text-zinc-500",children:[y.jsx("span",{children:"Editing raw SKILL.md"}),y.jsx(_i,{onClick:()=>{A(!1),j((d==null?void 0:d.content)??"")},className:"px-3 py-2",children:"Cancel"})]})]}):d?y.jsx(Tq,{content:d.content}):y.jsx("p",{className:"font-mono text-[11px] text-zinc-500",children:"Select an installed skill to inspect it."})})]}):t!=="installed"&&W?y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:"mb-5 flex items-start justify-between gap-4 border-b border-white/[0.06] pb-5",children:[y.jsxs("div",{className:"flex min-w-0 gap-4",children:[y.jsx("div",{className:"flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl bg-[#E43A9C]/12 text-[#E43A9C]",children:y.jsx(U4,{className:"h-6 w-6"})}),y.jsxs("div",{className:"min-w-0",children:[y.jsx("h3",{className:"truncate text-[34px] uppercase tracking-[0.08em] text-zinc-100",style:{fontFamily:"'Bebas Neue', sans-serif"},children:W.title||W.name}),y.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[y.jsx(jt,{variant:W.installed?"success":"default",children:W.installed?"installed":"available"}),y.jsx(jt,{variant:"muted",children:UE(W.source)}),qE(W.installs)?y.jsx(jt,{variant:"info",children:qE(W.installs)}):null]}),y.jsxs("div",{className:"mt-3 space-y-1 font-mono text-[11px] text-zinc-500",children:[y.jsxs("p",{children:["registry: ",UE(W.source)]}),W.registrySource?y.jsxs("p",{children:["source: ",W.registrySource]}):null,W.url?y.jsxs("p",{children:["url: ",W.url]}):null]})]})]}),y.jsx("div",{className:"flex items-center gap-2",children:W.installed?y.jsx(_i,{onClick:()=>{e("installed"),c(W.name)},className:"px-3 py-2",children:"Open installed"}):y.jsxs(za,{onClick:()=>Y(W),disabled:I||!W.url&&!W.registrySource,className:"px-3 py-2",children:[I?y.jsx(js,{className:"h-3.5 w-3.5 animate-spin"}):y.jsx(e4,{className:"h-3.5 w-3.5"}),"Install"]})})]}),y.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto pr-1",children:[y.jsx("div",{className:"rounded-2xl border border-white/[0.06] bg-white/[0.02] p-5",children:y.jsx("p",{className:"font-mono text-[12px] leading-7 text-zinc-300",children:W.description||"No registry description is available for this skill yet."})}),y.jsx("div",{className:"mt-4 rounded-2xl border border-dashed border-white/[0.08] bg-black/20 p-4 font-mono text-[11px] leading-6 text-zinc-500",children:"Install will fetch the skill definition from the selected registry source and add it to your local skills library."})]})]}):y.jsx("div",{className:"flex h-full items-center justify-center rounded-2xl border border-dashed border-white/[0.08] bg-white/[0.02] p-8 text-center",children:y.jsxs("div",{children:[y.jsx("div",{className:"mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-2xl bg-[#E43A9C]/12 text-[#E43A9C]",children:y.jsx(qb,{className:"h-6 w-6"})}),y.jsx("h3",{className:"text-[28px] uppercase tracking-[0.08em] text-zinc-100",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"Select a Skill"}),y.jsx("p",{className:"mt-2 font-mono text-[11px] leading-relaxed text-zinc-500",children:"Choose a skill from the left panel to inspect details, install registry entries, or edit local definitions."})]})})})]})}function Cq(t){let e=0;for(let n=0;n<t.length;n++)e=t.charCodeAt(n)+((e<<5)-e);return`hsl(${(e%360+360)%360}, 70%, 65%)`}function $g(){const{name:t,instanceId:e}=rD();return t&&e?y.jsx($q,{squadName:t,instanceId:e}):t?y.jsx(Rq,{name:t}):y.jsx(Nq,{})}function Nq(){const[t,e]=N.useState([]),[r,n]=N.useState(null),i=Nu();return N.useEffect(()=>{Promise.all([Ve.get("/squads"),Ve.get("/config")]).then(([a,o])=>{e(a.squads),n(o.config.maxInstancesPerSquad)}).catch(()=>{})},[]),y.jsxs("div",{className:"flex-1 overflow-y-auto p-6",children:[y.jsx("div",{className:"mb-6",children:y.jsxs("div",{children:[y.jsx("h2",{className:"text-2xl tracking-wide text-zinc-100",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"Squads"}),y.jsxs("p",{className:"text-[11px] text-zinc-600 font-mono mt-0.5",children:[t.length," squads · ",t.reduce((a,o)=>a+(o.activeInstances||0),0)," ","active instances"]})]})}),y.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3",children:[t.map(a=>{const o=a.color||"#38bdf8";return y.jsxs("button",{type:"button",onClick:()=>i(`/squads/${a.name}`),className:"text-left rounded-2xl p-5 transition-all group cursor-pointer",style:{border:`1px solid ${o}30`,background:`${o}08`,backdropFilter:"blur(20px)"},onMouseEnter:c=>{c.currentTarget.style.borderColor=`${o}70`,c.currentTarget.style.background=`${o}12`},onMouseLeave:c=>{c.currentTarget.style.borderColor=`${o}30`,c.currentTarget.style.background=`${o}08`},children:[y.jsxs("div",{className:"flex items-start justify-between mb-1",children:[y.jsx("h3",{className:"text-sm font-mono transition-colors",style:{color:o},children:a.name}),y.jsx(jt,{variant:Co(a.status),children:a.status})]}),y.jsxs("div",{className:"flex items-center justify-between mb-3",children:[y.jsx("p",{className:"text-[11px] text-zinc-600 font-mono",children:a.universe}),y.jsxs("span",{className:"text-[11px] text-zinc-600 font-mono flex items-center gap-1",children:[y.jsx(J5,{className:"w-3 h-3"}),a.activeInstances,"/",r??(a.totalInstances||a.memberCount)]})]}),a.repoUrl&&y.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-zinc-700 font-mono mb-4",children:[y.jsx(ZN,{className:"w-3 h-3 flex-shrink-0"}),y.jsx("span",{className:"truncate",children:a.repoUrl.replace("https://github.com/","")})]}),a.recentActivity&&a.recentActivity.length>0&&y.jsxs("div",{className:"border-t pt-3",style:{borderColor:`${o}15`},children:[y.jsx("p",{className:"text-[10px] font-mono uppercase tracking-wider mb-2",style:{color:`${o}80`},children:"Recent Work"}),y.jsx("ul",{className:"space-y-1.5",children:a.recentActivity.map(c=>{const u={className:"w-3.5 h-3.5 flex-shrink-0 mt-px"},d=Pq(c.status,u),p=c.objective?c.objective.length>60?`${c.objective.slice(0,60)}…`:c.objective:c.issueRef||"Instance";return y.jsxs("li",{className:"flex items-start gap-1.5 text-[11px] font-mono text-zinc-600",children:[d,y.jsx("span",{className:"truncate",children:p})]},c.id)})})]})]},a.id)}),t.length===0&&y.jsxs("div",{className:"col-span-full text-center py-12 text-zinc-600",children:[y.jsx(Zh,{size:48,className:"mx-auto mb-3 opacity-30"}),y.jsx("p",{className:"text-[11px] font-mono",children:"No squads hired yet. Ask IO to hire a squad for a project."})]})]})]})}function Pq(t,e){const r=t.toLowerCase();return r.includes("complete")||r.includes("success")||r.includes("done")?y.jsx(YN,{...e,style:{color:"#34d399"}}):r.includes("warning")||r.includes("review")?y.jsx(G4,{...e,style:{color:"#fbbf24"}}):r.includes("error")||r.includes("fail")?y.jsx(JN,{...e,style:{color:"#f87171"}}):r.includes("working")||r.includes("progress")||r.includes("running")?y.jsx(eP,{...e,style:{color:"#E43A9C"}}):y.jsx(g4,{...e,style:{color:"#60a5fa"}})}function Kf(t,e){const r="w-4 h-4",n={color:e},i=t.toLowerCase();return i.includes("lead")||i.includes("pm")||i.includes("technical")?y.jsx(Dw,{className:r,style:n}):i.includes("qa")||i.includes("test")?y.jsx(D5,{className:r,style:n}):i.includes("scribe")?y.jsx($4,{className:r,style:n}):y.jsx(Uc,{className:r,style:n})}function Rq({name:t}){const[e,r]=N.useState(null),[n,i]=N.useState("agents"),[a,o]=N.useState([]),[c,u]=N.useState(0),[d,p]=N.useState(null),[f,g]=N.useState([]),v=Nu(),x=qa();N.useEffect(()=>{Ve.get(`/squads/${t}`).then(r).catch(()=>{})},[t]),N.useEffect(()=>{n==="history"&&Ve.get(`/squads/${t}/history`).then(S=>{o(S.items),u(S.total)}).catch(()=>{}),n==="schedules"&&e&&Ve.get(`/schedules?targetId=${e.squad.id}`).then(S=>g(S.schedules)).catch(()=>{})},[n,t,e]);const w=S=>{Ve.get(`/squads/${t}/history/${S.id}`).then(p).catch(()=>at.error("Failed to load activity detail"))};if(!e)return y.jsx("div",{className:"h-full flex items-center justify-center text-zinc-600",children:"Loading..."});const b=e.squad.color||"#38bdf8";return d?y.jsx(Iq,{activity:d,squadColor:b,squadName:e.squad.name,onBack:()=>p(null)}):y.jsxs("div",{className:"flex-1 overflow-y-auto p-6",style:{background:`${b}06`},children:[y.jsxs("button",{type:"button",onClick:()=>v("/squads"),className:"flex items-center gap-1.5 text-[11px] text-zinc-600 hover:text-zinc-300 font-mono mb-5 transition-colors",children:[y.jsx(vl,{className:"w-3.5 h-3.5"})," All Squads"]}),y.jsxs("div",{className:"flex items-start justify-between mb-5",children:[y.jsxs("div",{children:[y.jsx("h2",{className:"text-3xl tracking-wide",style:{fontFamily:"'Bebas Neue', sans-serif",color:b},children:e.squad.name}),y.jsxs("p",{className:"text-[11px] text-zinc-600 font-mono",children:[e.squad.universe," · ",e.squad.autonomyTier||"standard"," autonomy"]}),e.squad.repoUrl&&y.jsxs("a",{href:e.squad.repoUrl,target:"_blank",rel:"noreferrer",className:"text-[11px] font-mono text-[#E43A9C] hover:text-[#F041FF] flex items-center gap-1 mt-1 transition-colors",children:[y.jsx(ZN,{className:"w-3 h-3"}),e.squad.repoUrl.replace("https://github.com/","")]})]}),y.jsx(jt,{variant:Co(e.squad.status),children:e.squad.status})]}),y.jsx("div",{className:"flex gap-0 mb-5 border-b border-white/[0.06]",children:["agents","instances","schedules","history"].map(S=>y.jsx("button",{type:"button",onClick:()=>i(S),className:`px-4 py-2 text-[11px] font-mono capitalize transition-colors border-b-2 -mb-px ${n===S?"text-[#E43A9C] border-[#E43A9C]":"text-zinc-600 hover:text-zinc-300 border-transparent"}`,children:S},S))}),n==="agents"&&y.jsx("div",{className:"space-y-2",children:e.members.map(S=>y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl p-4 flex items-center gap-3",children:[y.jsx("div",{className:"w-8 h-8 rounded-xl flex items-center justify-center flex-shrink-0",style:{border:`1px solid ${b}30`,background:`${b}12`},children:Kf(S.roleName||S.role,b)}),y.jsxs("div",{className:"flex-1 min-w-0",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("span",{className:"text-sm font-mono text-zinc-200",children:S.displayName}),y.jsx(jt,{variant:Co(S.status),children:S.status})]}),y.jsx("p",{className:"text-[11px] text-zinc-600 font-mono mt-0.5",children:S.role}),S.currentTask&&y.jsx("p",{className:"text-xs text-zinc-500 mt-1 truncate",children:S.currentTask})]})]},S.id))}),n==="instances"&&y.jsx("div",{className:"space-y-2",children:e.instances.length===0?y.jsx("div",{className:"text-center py-16 text-zinc-700 font-mono text-sm",children:"No active instances"}):e.instances.map(S=>y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl p-4 flex items-center gap-4",children:[y.jsxs("div",{className:"flex-1 grid grid-cols-2 gap-2 text-[11px] font-mono",children:[y.jsxs("div",{children:[y.jsx("span",{className:"text-zinc-700",children:"ID"}),y.jsx("p",{className:"text-zinc-300 mt-0.5 truncate",children:S.id.slice(0,8)})]}),y.jsxs("div",{children:[y.jsx("span",{className:"text-zinc-700",children:"Branch"}),y.jsx("p",{className:"text-zinc-300 mt-0.5 truncate",children:S.branch||"—"})]}),y.jsxs("div",{children:[y.jsx("span",{className:"text-zinc-700",children:"Status"}),y.jsx("p",{className:"text-zinc-300 mt-0.5",children:y.jsx(jt,{variant:Co(S.status),children:S.status})})]}),y.jsxs("div",{children:[y.jsx("span",{className:"text-zinc-700",children:"Tasks"}),y.jsxs("p",{className:"text-zinc-300 mt-0.5",children:[S.tasksComplete,"/",S.taskCount]})]})]}),y.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[y.jsx("button",{type:"button",onClick:()=>v(`/squads/${t}/instances/${S.id}`),title:"View instance agents",className:"p-2 rounded-xl hover:bg-white/[0.06] transition-colors cursor-pointer",style:{color:b},children:y.jsx(Ds,{className:"w-4 h-4"})}),y.jsx("button",{type:"button",onClick:()=>at.info("Stop not yet implemented"),title:"Stop instance",className:"p-2 rounded-xl hover:bg-red-500/10 text-zinc-600 hover:text-red-400 transition-colors cursor-pointer",children:y.jsx(Jh,{className:"w-4 h-4"})})]})]},S.id))}),n==="schedules"&&y.jsx("div",{className:"overflow-auto rounded-2xl border border-white/[0.07] glass-card",children:f.length===0?y.jsx("div",{className:"text-center py-16 text-zinc-700 font-mono text-sm",children:"No schedules for this squad"}):y.jsxs("table",{className:"w-full text-[11px] font-mono",children:[y.jsx("thead",{children:y.jsx("tr",{className:"border-b border-white/[0.06]",style:{background:"rgba(20,20,20,0.6)"},children:["Schedule","Next Run","Status"].map(S=>y.jsx("th",{className:"text-left px-4 py-2.5 text-zinc-600 font-medium",children:S},S))})}),y.jsx("tbody",{children:f.map(S=>y.jsxs("tr",{className:`border-b border-white/[0.04] hover:bg-white/[0.015] transition-colors ${S.enabled?"":"opacity-50"}`,children:[y.jsxs("td",{className:"px-4 py-3",children:[y.jsx("div",{className:"text-zinc-300",children:S.name||S.prompt}),y.jsx("div",{className:"text-zinc-700 text-[10px] mt-0.5",children:S.cron})]}),y.jsx("td",{className:"px-4 py-3 text-zinc-600",children:y.jsxs("span",{className:"flex items-center gap-1",children:[y.jsx(Lw,{className:"w-3 h-3"}),S.enabled&&S.nextRun?Ws(S.nextRun,x):"—"]})}),y.jsx("td",{className:"px-4 py-3",children:y.jsx(jt,{variant:S.enabled?"success":"muted",children:S.enabled?"active":"paused"})})]},S.id))})]})}),n==="history"&&y.jsxs("div",{className:"space-y-2",children:[a.length===0?y.jsx("div",{className:"text-center py-16 text-zinc-700 font-mono text-sm",children:"No history yet"}):a.map(S=>y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl px-4 py-3.5 flex items-center gap-3",children:[y.jsx("div",{className:"flex-shrink-0",children:S.status==="completed"?y.jsx(YN,{className:"w-4 h-4",style:{color:"#34d399"}}):y.jsx(JN,{className:"w-4 h-4",style:{color:"#f87171"}})}),y.jsxs("div",{className:"flex-1 min-w-0",children:[y.jsx("p",{className:"text-[12px] text-zinc-300 font-mono truncate",children:S.title}),y.jsxs("div",{className:"flex items-center gap-3 mt-0.5",children:[y.jsx("span",{className:"text-[10px] text-zinc-700 font-mono",children:Ws(S.completedAt||S.createdAt,x)}),y.jsxs("span",{className:"text-[10px] text-zinc-700 font-mono flex items-center gap-1",children:[y.jsx(Ds,{className:"w-2.5 h-2.5"}),S.duration||"—"]}),y.jsxs("span",{className:"text-[10px] text-zinc-700 font-mono flex items-center gap-1",children:[y.jsx(Uc,{className:"w-2.5 h-2.5"}),S.agentCount," agent",S.agentCount!==1?"s":""]})]})]}),y.jsx(jt,{variant:S.status==="completed"?"success":"error",children:S.status}),y.jsx("button",{type:"button",onClick:()=>w(S),title:"View activity detail",className:"p-2 rounded-xl hover:bg-white/[0.06] transition-colors flex-shrink-0 cursor-pointer",style:{color:b},children:y.jsx(Ds,{className:"w-4 h-4"})})]},S.id)),a.length<c&&y.jsx("button",{type:"button",onClick:()=>{Ve.get(`/squads/${t}/history?offset=${a.length}`).then(S=>{o(A=>[...A,...S.items])}).catch(()=>{})},className:"w-full text-center py-3 text-[11px] font-mono text-zinc-600 hover:text-zinc-300 transition-colors cursor-pointer",children:"Load more"})]})]})}function Iq({activity:t,squadColor:e,squadName:r,onBack:n}){const i=qa(),a=N.useMemo(()=>{const p={};for(const f of t.agentEntries)p[f.agentId]=Cq(f.agentName);return p},[t]),o={thought:{label:"Thinking",icon:zw},tool_call:{label:"Tool Call",icon:iP},tool_result:{label:"Tool Result",icon:QN},message:{label:"Message",icon:Uc},decision:{label:"Decision",icon:Dw}},c={label:"Message",icon:Uc},u=p=>o[p]??c,d=N.useMemo(()=>{const p=t.agentEntries.flatMap(f=>f.events.map(g=>({ev:g,entry:f})));return p.sort((f,g)=>f.ev.timestamp.localeCompare(g.ev.timestamp)),p},[t]);return y.jsxs("div",{className:"flex-1 overflow-y-auto p-6",style:{background:`${e}06`},children:[y.jsxs("button",{type:"button",onClick:n,className:"flex items-center gap-1.5 text-[11px] text-zinc-600 hover:text-zinc-300 font-mono mb-5 transition-colors cursor-pointer",children:[y.jsx(vl,{className:"w-3.5 h-3.5"})," Back to ",r]}),y.jsxs("div",{className:"flex items-start justify-between mb-5",children:[y.jsxs("div",{children:[y.jsx("h2",{className:"text-2xl tracking-wide",style:{fontFamily:"'Bebas Neue', sans-serif",color:e},children:t.title}),y.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[y.jsx("span",{className:"text-[11px] text-zinc-600 font-mono",children:Ws(t.completedAt||t.createdAt,i)}),y.jsxs("span",{className:"text-[11px] text-zinc-700 font-mono flex items-center gap-1",children:[y.jsx(Lw,{className:"w-3 h-3"}),t.duration||"—"]})]})]}),y.jsx(jt,{variant:t.status==="completed"?"success":"error",children:t.status})]}),y.jsx("div",{className:"flex flex-wrap gap-2 mb-6",children:t.agentEntries.map(p=>{const f=a[p.agentId];return y.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1.5 rounded-xl border",style:{borderColor:`${f}30`,background:`${f}10`},children:[Kf(p.roleType||p.role,f),y.jsx("span",{className:"text-[11px] font-mono",style:{color:f},children:p.agentName}),y.jsxs("span",{className:"text-[10px] font-mono text-zinc-500",children:["— ",p.role]})]},p.agentId)})}),y.jsxs("div",{className:"relative pl-10",children:[y.jsx("div",{className:"absolute left-[15px] top-0 bottom-0 w-px bg-white/[0.06]"}),y.jsx("div",{className:"space-y-3",children:d.map(({ev:p,entry:f})=>{const g=a[f.agentId],{label:v,icon:x}=u(p.kind),w=p.kind==="tool_call"||p.kind==="tool_result";return y.jsxs("div",{className:"relative",children:[y.jsx("div",{className:"absolute -left-10 top-3 w-[30px] h-[30px] rounded-full flex items-center justify-center",style:{background:`${g}15`,border:`1px solid ${g}35`},children:y.jsx(x,{className:"w-3.5 h-3.5",style:{color:g}})}),y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl px-4 py-3",children:[y.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[y.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[y.jsxs("div",{className:"flex items-center gap-1",children:[Kf(f.roleType||f.role,g),y.jsx("span",{className:"text-[10px] font-mono",style:{color:g},children:f.agentName})]}),y.jsx("span",{className:"text-zinc-700 text-[10px]",children:"·"}),y.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-zinc-500",children:v}),p.label&&y.jsx("span",{className:"text-[10px] font-mono text-zinc-600 border border-white/[0.08] rounded px-1.5 py-px bg-white/[0.03]",children:p.label}),p.status==="error"&&y.jsx(jt,{variant:"error",children:"failed"}),p.status==="ok"&&p.kind==="tool_result"&&y.jsx(jt,{variant:"success",children:"ok"})]}),y.jsx("span",{className:"text-[10px] font-mono text-zinc-700 flex-shrink-0 ml-2",children:Qh(p.timestamp,i)})]}),w?y.jsx("pre",{className:"text-[11px] font-mono text-zinc-400 whitespace-pre-wrap leading-relaxed overflow-x-auto rounded-lg p-2 mt-1 bg-black/20",children:p.content}):y.jsx(sp,{content:p.content,className:"text-[12px] [&_pre]:text-[10px]"})]})]},p.id)})})]})]})}function $q({squadName:t,instanceId:e}){const[r,n]=N.useState(null),[i,a]=N.useState(null),o=Nu();if(N.useEffect(()=>{Ve.get(`/squads/${t}/instances/${e}`).then(n).catch(()=>{at.error("Failed to load instance")})},[t,e]),!r)return y.jsx("div",{className:"h-full flex items-center justify-center text-zinc-600",children:"Loading..."});const c=r.squadColor||"#38bdf8";if(i){const u=r.members.find(p=>p.roleName===i),d=r.activity.filter(p=>p.agent===i);return y.jsx(Dq,{agentName:(u==null?void 0:u.displayName)||i,agentRole:i,agentStatus:(u==null?void 0:u.status)||"idle",currentTask:(u==null?void 0:u.currentTask)||null,events:d,color:c,onBack:()=>a(null),squadName:t})}return y.jsxs("div",{className:"flex-1 overflow-y-auto p-6",style:{background:`${c}06`},children:[y.jsxs("button",{type:"button",onClick:()=>o(`/squads/${t}`),className:"flex items-center gap-1.5 text-[11px] text-zinc-600 hover:text-zinc-300 font-mono mb-5 transition-colors",children:[y.jsx(vl,{className:"w-3.5 h-3.5"})," Back to ",t]}),y.jsxs("div",{className:"flex items-start justify-between mb-6",children:[y.jsxs("div",{children:[y.jsx("h2",{className:"text-2xl tracking-wide",style:{fontFamily:"'Bebas Neue', sans-serif",color:c},children:"Instance"}),y.jsx("p",{className:"text-[11px] text-zinc-600 font-mono mt-0.5",children:r.instance.id.slice(0,8)}),r.instance.branch&&y.jsx("p",{className:"text-[11px] text-zinc-700 font-mono mt-0.5",children:r.instance.branch})]}),y.jsx(jt,{variant:Co(r.instance.status),children:r.instance.status})]}),y.jsx("div",{className:"space-y-2",children:r.members.map(u=>y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl p-4 flex items-center gap-3",children:[y.jsx("div",{className:"w-8 h-8 rounded-xl flex items-center justify-center flex-shrink-0",style:{border:`1px solid ${c}30`,background:`${c}12`},children:Kf(u.roleName||u.role,c)}),y.jsxs("div",{className:"flex-1 min-w-0",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("span",{className:"text-sm font-mono text-zinc-200",children:u.displayName}),y.jsx(jt,{variant:Co(u.status),children:u.status})]}),y.jsx("p",{className:"text-[11px] text-zinc-600 font-mono mt-0.5",children:u.role}),u.currentTask&&y.jsx("p",{className:"text-xs text-zinc-500 mt-1 truncate",children:u.currentTask})]}),(u.status==="working"||u.status==="in meeting")&&y.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[y.jsx("button",{type:"button",onClick:()=>a(u.roleName||u.role),title:"View work in progress",className:"p-2 rounded-xl hover:bg-white/[0.06] transition-colors cursor-pointer",style:{color:c},children:y.jsx(Ds,{className:"w-4 h-4"})}),u.status==="working"&&y.jsx("button",{type:"button",onClick:()=>at.success(`${u.displayName} stopped`),title:"Stop agent",className:"p-2 rounded-xl hover:bg-red-500/10 text-zinc-600 hover:text-red-400 transition-colors cursor-pointer",children:y.jsx(Jh,{className:"w-4 h-4"})})]})]},u.id))}),(r.instance.status==="meeting"||r.instance.status==="planning")&&r.instance.meetingLog&&r.instance.meetingLog.length>0&&y.jsxs("div",{className:"mt-6",children:[y.jsx("h3",{className:"text-lg tracking-wide mb-3",style:{fontFamily:"'Bebas Neue', sans-serif",color:c},children:"Meeting Discussion"}),y.jsx("div",{className:"space-y-2",children:r.instance.meetingLog.map((u,d)=>{const p=u.match(/^\[([^\]]+)\]\s*(.*)/s),f=p?p[1]:"unknown",g=p?p[2]??u:u;return y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-xl px-4 py-3",children:[y.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[y.jsx(Zh,{className:"w-3.5 h-3.5",style:{color:"#818cf8"}}),y.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-indigo-400",children:f})]}),y.jsx(sp,{content:g,className:"text-xs [&_pre]:text-[10px]"})]},`meeting-${d}`)})})]})]})}const Mq={thought:{label:"Thinking",icon:zw,color:"#a78bfa",bg:"rgba(167,139,250,0.1)"},tool_call:{label:"Tool Call",icon:iP,color:"#38bdf8",bg:"rgba(56,189,248,0.1)"},tool_result:{label:"Tool Result",icon:QN,color:"#34d399",bg:"rgba(52,211,153,0.1)"},message:{label:"Message",icon:Uc,color:"#E43A9C",bg:"rgba(228,58,156,0.15)"},decision:{label:"Decision",icon:Dw,color:"#fbbf24",bg:"rgba(251,191,36,0.1)"},meeting:{label:"Meeting",icon:Zh,color:"#818cf8",bg:"rgba(129,140,248,0.1)"}};function Lq(t){const e=t.toLowerCase();return e.includes("meeting")?"meeting":e.includes("tool_call")||e.includes("tool-call")?"tool_call":e.includes("tool_result")||e.includes("tool-result")?"tool_result":e.includes("thought")||e.includes("thinking")||e.includes("reason")?"thought":e.includes("decision")?"decision":"message"}function Dq({agentName:t,agentRole:e,agentStatus:r,currentTask:n,events:i,color:a,onBack:o,squadName:c}){const u=qa();return y.jsxs("div",{className:"flex-1 overflow-y-auto p-6",style:{background:`${a}06`},children:[y.jsxs("button",{type:"button",onClick:o,className:"flex items-center gap-1.5 text-[11px] text-zinc-600 hover:text-zinc-300 font-mono mb-5 transition-colors",children:[y.jsx(vl,{className:"w-3.5 h-3.5"})," Back to ",c]}),y.jsxs("div",{className:"flex items-start justify-between mb-6",children:[y.jsxs("div",{children:[y.jsx("h2",{className:"text-2xl tracking-wide",style:{fontFamily:"'Bebas Neue', sans-serif",color:a},children:t}),y.jsx("p",{className:"text-[11px] text-zinc-600 font-mono mt-0.5",children:e}),n&&y.jsx("p",{className:"text-sm text-zinc-400 mt-1",children:n})]}),y.jsx(jt,{variant:Co(r),children:r})]}),y.jsxs("div",{className:"relative",children:[y.jsx("div",{className:"absolute left-[15px] top-0 bottom-0 w-px bg-white/[0.06]"}),y.jsxs("div",{className:"space-y-3 pl-10",children:[i.length===0&&y.jsx("div",{className:"text-center py-12 text-zinc-700 font-mono text-sm",children:"No activity recorded yet"}),i.map(d=>{const p=Lq(d.type),f=Mq[p],g=f.icon,v=p==="tool_call"||p==="tool_result",x=d.type.toLowerCase().includes("error")||d.type.toLowerCase().includes("fail");return y.jsxs("div",{className:"relative",children:[y.jsx("div",{className:"absolute -left-10 top-3 w-[30px] h-[30px] rounded-full flex items-center justify-center",style:{background:f.bg,border:`1px solid ${f.color}30`},children:y.jsx(g,{className:"w-3.5 h-3.5",style:{color:f.color}})}),y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl px-4 py-3",children:[y.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider",style:{color:f.color},children:f.label}),d.model&&y.jsx("span",{className:"text-[10px] font-mono text-zinc-600 border border-white/[0.08] rounded px-1.5 py-px bg-white/[0.03]",children:d.model}),x&&y.jsx(jt,{variant:"error",children:"failed"})]}),y.jsx("span",{className:"text-[10px] font-mono text-zinc-700",children:Qh(d.timestamp,u)})]}),v?y.jsx("pre",{className:"text-[11px] font-mono text-zinc-400 whitespace-pre-wrap leading-relaxed overflow-x-auto rounded-lg p-2.5 bg-black/20",children:d.content}):y.jsx("p",{className:"text-[12px] text-zinc-400 leading-relaxed",children:d.content})]})]},d.id)}),y.jsxs("div",{className:"relative",children:[y.jsx("div",{className:"absolute -left-10 top-3 w-[30px] h-[30px] rounded-full flex items-center justify-center",style:{background:`${a}15`,border:`1px solid ${a}40`},children:y.jsx(eP,{className:"w-3.5 h-3.5 animate-spin",style:{color:a}})}),y.jsx("div",{className:"glass-card border rounded-2xl px-4 py-3",style:{borderColor:`${a}20`},children:y.jsx("span",{className:"text-[11px] font-mono",style:{color:a},children:"Agent is working…"})})]})]})]})]})}var Mg,HE;function Zr(){if(HE)return Mg;HE=1;var t=Array.isArray;return Mg=t,Mg}var Lg,WE;function xR(){if(WE)return Lg;WE=1;var t=typeof Zd=="object"&&Zd&&Zd.Object===Object&&Zd;return Lg=t,Lg}var Dg,GE;function Oi(){if(GE)return Dg;GE=1;var t=xR(),e=typeof self=="object"&&self&&self.Object===Object&&self,r=t||e||Function("return this")();return Dg=r,Dg}var zg,KE;function $u(){if(KE)return zg;KE=1;var t=Oi(),e=t.Symbol;return zg=e,zg}var Bg,VE;function zq(){if(VE)return Bg;VE=1;var t=$u(),e=Object.prototype,r=e.hasOwnProperty,n=e.toString,i=t?t.toStringTag:void 0;function a(o){var c=r.call(o,i),u=o[i];try{o[i]=void 0;var d=!0}catch{}var p=n.call(o);return d&&(c?o[i]=u:delete o[i]),p}return Bg=a,Bg}var Ug,XE;function Bq(){if(XE)return Ug;XE=1;var t=Object.prototype,e=t.toString;function r(n){return e.call(n)}return Ug=r,Ug}var qg,YE;function ra(){if(YE)return qg;YE=1;var t=$u(),e=zq(),r=Bq(),n="[object Null]",i="[object Undefined]",a=t?t.toStringTag:void 0;function o(c){return c==null?c===void 0?i:n:a&&a in Object(c)?e(c):r(c)}return qg=o,qg}var Fg,JE;function na(){if(JE)return Fg;JE=1;function t(e){return e!=null&&typeof e=="object"}return Fg=t,Fg}var Hg,ZE;function wl(){if(ZE)return Hg;ZE=1;var t=ra(),e=na(),r="[object Symbol]";function n(i){return typeof i=="symbol"||e(i)&&t(i)==r}return Hg=n,Hg}var Wg,QE;function r1(){if(QE)return Wg;QE=1;var t=Zr(),e=wl(),r=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,n=/^\w*$/;function i(a,o){if(t(a))return!1;var c=typeof a;return c=="number"||c=="symbol"||c=="boolean"||a==null||e(a)?!0:n.test(a)||!r.test(a)||o!=null&&a in Object(o)}return Wg=i,Wg}var Gg,eO;function Ha(){if(eO)return Gg;eO=1;function t(e){var r=typeof e;return e!=null&&(r=="object"||r=="function")}return Gg=t,Gg}var Kg,tO;function n1(){if(tO)return Kg;tO=1;var t=ra(),e=Ha(),r="[object AsyncFunction]",n="[object Function]",i="[object GeneratorFunction]",a="[object Proxy]";function o(c){if(!e(c))return!1;var u=t(c);return u==n||u==i||u==r||u==a}return Kg=o,Kg}var Vg,rO;function Uq(){if(rO)return Vg;rO=1;var t=Oi(),e=t["__core-js_shared__"];return Vg=e,Vg}var Xg,nO;function qq(){if(nO)return Xg;nO=1;var t=Uq(),e=(function(){var n=/[^.]+$/.exec(t&&t.keys&&t.keys.IE_PROTO||"");return n?"Symbol(src)_1."+n:""})();function r(n){return!!e&&e in n}return Xg=r,Xg}var Yg,iO;function wR(){if(iO)return Yg;iO=1;var t=Function.prototype,e=t.toString;function r(n){if(n!=null){try{return e.call(n)}catch{}try{return n+""}catch{}}return""}return Yg=r,Yg}var Jg,aO;function Fq(){if(aO)return Jg;aO=1;var t=n1(),e=qq(),r=Ha(),n=wR(),i=/[\\^$.*+?()[\]{}|]/g,a=/^\[object .+?Constructor\]$/,o=Function.prototype,c=Object.prototype,u=o.toString,d=c.hasOwnProperty,p=RegExp("^"+u.call(d).replace(i,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function f(g){if(!r(g)||e(g))return!1;var v=t(g)?p:a;return v.test(n(g))}return Jg=f,Jg}var Zg,oO;function Hq(){if(oO)return Zg;oO=1;function t(e,r){return e==null?void 0:e[r]}return Zg=t,Zg}var Qg,sO;function qo(){if(sO)return Qg;sO=1;var t=Fq(),e=Hq();function r(n,i){var a=e(n,i);return t(a)?a:void 0}return Qg=r,Qg}var ey,lO;function lp(){if(lO)return ey;lO=1;var t=qo(),e=t(Object,"create");return ey=e,ey}var ty,cO;function Wq(){if(cO)return ty;cO=1;var t=lp();function e(){this.__data__=t?t(null):{},this.size=0}return ty=e,ty}var ry,uO;function Gq(){if(uO)return ry;uO=1;function t(e){var r=this.has(e)&&delete this.__data__[e];return this.size-=r?1:0,r}return ry=t,ry}var ny,dO;function Kq(){if(dO)return ny;dO=1;var t=lp(),e="__lodash_hash_undefined__",r=Object.prototype,n=r.hasOwnProperty;function i(a){var o=this.__data__;if(t){var c=o[a];return c===e?void 0:c}return n.call(o,a)?o[a]:void 0}return ny=i,ny}var iy,fO;function Vq(){if(fO)return iy;fO=1;var t=lp(),e=Object.prototype,r=e.hasOwnProperty;function n(i){var a=this.__data__;return t?a[i]!==void 0:r.call(a,i)}return iy=n,iy}var ay,hO;function Xq(){if(hO)return ay;hO=1;var t=lp(),e="__lodash_hash_undefined__";function r(n,i){var a=this.__data__;return this.size+=this.has(n)?0:1,a[n]=t&&i===void 0?e:i,this}return ay=r,ay}var oy,pO;function Yq(){if(pO)return oy;pO=1;var t=Wq(),e=Gq(),r=Kq(),n=Vq(),i=Xq();function a(o){var c=-1,u=o==null?0:o.length;for(this.clear();++c<u;){var d=o[c];this.set(d[0],d[1])}}return a.prototype.clear=t,a.prototype.delete=e,a.prototype.get=r,a.prototype.has=n,a.prototype.set=i,oy=a,oy}var sy,mO;function Jq(){if(mO)return sy;mO=1;function t(){this.__data__=[],this.size=0}return sy=t,sy}var ly,gO;function i1(){if(gO)return ly;gO=1;function t(e,r){return e===r||e!==e&&r!==r}return ly=t,ly}var cy,yO;function cp(){if(yO)return cy;yO=1;var t=i1();function e(r,n){for(var i=r.length;i--;)if(t(r[i][0],n))return i;return-1}return cy=e,cy}var uy,vO;function Zq(){if(vO)return uy;vO=1;var t=cp(),e=Array.prototype,r=e.splice;function n(i){var a=this.__data__,o=t(a,i);if(o<0)return!1;var c=a.length-1;return o==c?a.pop():r.call(a,o,1),--this.size,!0}return uy=n,uy}var dy,bO;function Qq(){if(bO)return dy;bO=1;var t=cp();function e(r){var n=this.__data__,i=t(n,r);return i<0?void 0:n[i][1]}return dy=e,dy}var fy,xO;function e9(){if(xO)return fy;xO=1;var t=cp();function e(r){return t(this.__data__,r)>-1}return fy=e,fy}var hy,wO;function t9(){if(wO)return hy;wO=1;var t=cp();function e(r,n){var i=this.__data__,a=t(i,r);return a<0?(++this.size,i.push([r,n])):i[a][1]=n,this}return hy=e,hy}var py,_O;function up(){if(_O)return py;_O=1;var t=Jq(),e=Zq(),r=Qq(),n=e9(),i=t9();function a(o){var c=-1,u=o==null?0:o.length;for(this.clear();++c<u;){var d=o[c];this.set(d[0],d[1])}}return a.prototype.clear=t,a.prototype.delete=e,a.prototype.get=r,a.prototype.has=n,a.prototype.set=i,py=a,py}var my,SO;function a1(){if(SO)return my;SO=1;var t=qo(),e=Oi(),r=t(e,"Map");return my=r,my}var gy,kO;function r9(){if(kO)return gy;kO=1;var t=Yq(),e=up(),r=a1();function n(){this.size=0,this.__data__={hash:new t,map:new(r||e),string:new t}}return gy=n,gy}var yy,EO;function n9(){if(EO)return yy;EO=1;function t(e){var r=typeof e;return r=="string"||r=="number"||r=="symbol"||r=="boolean"?e!=="__proto__":e===null}return yy=t,yy}var vy,OO;function dp(){if(OO)return vy;OO=1;var t=n9();function e(r,n){var i=r.__data__;return t(n)?i[typeof n=="string"?"string":"hash"]:i.map}return vy=e,vy}var by,AO;function i9(){if(AO)return by;AO=1;var t=dp();function e(r){var n=t(this,r).delete(r);return this.size-=n?1:0,n}return by=e,by}var xy,TO;function a9(){if(TO)return xy;TO=1;var t=dp();function e(r){return t(this,r).get(r)}return xy=e,xy}var wy,jO;function o9(){if(jO)return wy;jO=1;var t=dp();function e(r){return t(this,r).has(r)}return wy=e,wy}var _y,CO;function s9(){if(CO)return _y;CO=1;var t=dp();function e(r,n){var i=t(this,r),a=i.size;return i.set(r,n),this.size+=i.size==a?0:1,this}return _y=e,_y}var Sy,NO;function o1(){if(NO)return Sy;NO=1;var t=r9(),e=i9(),r=a9(),n=o9(),i=s9();function a(o){var c=-1,u=o==null?0:o.length;for(this.clear();++c<u;){var d=o[c];this.set(d[0],d[1])}}return a.prototype.clear=t,a.prototype.delete=e,a.prototype.get=r,a.prototype.has=n,a.prototype.set=i,Sy=a,Sy}var ky,PO;function _R(){if(PO)return ky;PO=1;var t=o1(),e="Expected a function";function r(n,i){if(typeof n!="function"||i!=null&&typeof i!="function")throw new TypeError(e);var a=function(){var o=arguments,c=i?i.apply(this,o):o[0],u=a.cache;if(u.has(c))return u.get(c);var d=n.apply(this,o);return a.cache=u.set(c,d)||u,d};return a.cache=new(r.Cache||t),a}return r.Cache=t,ky=r,ky}var Ey,RO;function l9(){if(RO)return Ey;RO=1;var t=_R(),e=500;function r(n){var i=t(n,function(o){return a.size===e&&a.clear(),o}),a=i.cache;return i}return Ey=r,Ey}var Oy,IO;function c9(){if(IO)return Oy;IO=1;var t=l9(),e=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,r=/\\(\\)?/g,n=t(function(i){var a=[];return i.charCodeAt(0)===46&&a.push(""),i.replace(e,function(o,c,u,d){a.push(u?d.replace(r,"$1"):c||o)}),a});return Oy=n,Oy}var Ay,$O;function s1(){if($O)return Ay;$O=1;function t(e,r){for(var n=-1,i=e==null?0:e.length,a=Array(i);++n<i;)a[n]=r(e[n],n,e);return a}return Ay=t,Ay}var Ty,MO;function u9(){if(MO)return Ty;MO=1;var t=$u(),e=s1(),r=Zr(),n=wl(),i=t?t.prototype:void 0,a=i?i.toString:void 0;function o(c){if(typeof c=="string")return c;if(r(c))return e(c,o)+"";if(n(c))return a?a.call(c):"";var u=c+"";return u=="0"&&1/c==-1/0?"-0":u}return Ty=o,Ty}var jy,LO;function SR(){if(LO)return jy;LO=1;var t=u9();function e(r){return r==null?"":t(r)}return jy=e,jy}var Cy,DO;function kR(){if(DO)return Cy;DO=1;var t=Zr(),e=r1(),r=c9(),n=SR();function i(a,o){return t(a)?a:e(a,o)?[a]:r(n(a))}return Cy=i,Cy}var Ny,zO;function fp(){if(zO)return Ny;zO=1;var t=wl();function e(r){if(typeof r=="string"||t(r))return r;var n=r+"";return n=="0"&&1/r==-1/0?"-0":n}return Ny=e,Ny}var Py,BO;function l1(){if(BO)return Py;BO=1;var t=kR(),e=fp();function r(n,i){i=t(i,n);for(var a=0,o=i.length;n!=null&&a<o;)n=n[e(i[a++])];return a&&a==o?n:void 0}return Py=r,Py}var Ry,UO;function ER(){if(UO)return Ry;UO=1;var t=l1();function e(r,n,i){var a=r==null?void 0:t(r,n);return a===void 0?i:a}return Ry=e,Ry}var d9=ER();const Tn=vt(d9);var Iy,qO;function f9(){if(qO)return Iy;qO=1;function t(e){return e==null}return Iy=t,Iy}var h9=f9();const et=vt(h9);var $y,FO;function p9(){if(FO)return $y;FO=1;var t=ra(),e=Zr(),r=na(),n="[object String]";function i(a){return typeof a=="string"||!e(a)&&r(a)&&t(a)==n}return $y=i,$y}var m9=p9();const Io=vt(m9);var g9=n1();const Je=vt(g9);var y9=Ha();const _l=vt(y9);var My={exports:{}},pt={};/**
|
|
433
|
+
`);c({id:T,role:"user",content:E,timestamp:new Date().toISOString(),attachmentName:P}),p(""),g(null),S.current&&(S.current.value=""),b.current&&(b.current.style.height="auto");try{f&&await u(f,T),o(R)}catch{}}function O(E){E.key==="Enter"&&!E.shiftKey&&(E.preventDefault(),A())}function j(E){p(E.target.value),b.current&&(b.current.style.height="auto",b.current.style.height=`${Math.min(b.current.scrollHeight,160)}px`)}return y.jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[y.jsxs("div",{ref:w,className:"flex-1 overflow-y-auto px-5 py-5 space-y-5",children:[r.map(E=>{var T,P;return y.jsxs("div",{className:`flex gap-3 ${E.role==="user"?"flex-row-reverse":""}`,children:[y.jsx("div",{className:`flex-shrink-0 w-6 h-6 rounded-lg flex items-center justify-center text-[10px] font-mono mt-0.5 ${E.role==="user"?"border border-[#E43A9C]/30 text-[#E43A9C]":"bg-[#282828] border border-white/[0.07] text-zinc-500"}`,style:E.role==="user"?{background:"rgba(228,58,156,0.12)"}:void 0,children:E.role==="user"?((P=(T=t==null?void 0:t.user)==null?void 0:T.email)==null?void 0:P.charAt(0).toUpperCase())??"U":y.jsx(Ra,{height:12})}),y.jsxs("div",{className:`flex flex-col gap-1.5 max-w-[72%] ${E.role==="user"?"items-end":"items-start"}`,children:[E.toolCall&&y.jsxs("button",{type:"button",onClick:()=>x(v===E.id?null:E.id),className:"w-full text-left border border-white/[0.07] bg-[#1e1e1e] rounded-xl px-3 py-2 flex items-center gap-2 hover:border-[#E43A9C]/25 transition-colors",children:[y.jsx(Ds,{className:"w-3 h-3 text-[#E43A9C] flex-shrink-0"}),y.jsx("span",{className:"text-[11px] font-mono text-zinc-400 flex-1",children:E.toolCall.name}),y.jsx(jt,{variant:E.toolCall.status==="done"?"success":E.toolCall.status==="error"?"error":"warning",children:E.toolCall.status}),y.jsx(H5,{className:`w-3 h-3 text-zinc-600 transition-transform flex-shrink-0 ${v===E.id?"rotate-180":""}`})]}),E.toolCall&&v===E.id&&y.jsx("div",{className:"w-full bg-[#181818] border border-white/[0.06] rounded-xl px-3 py-2",children:y.jsx("p",{className:"text-[11px] font-mono text-zinc-500",children:E.toolCall.result})}),E.attachmentName&&y.jsx("div",{className:"rounded-xl border border-white/[0.08] bg-[#1e1e1e] px-3 py-2 text-[11px] font-mono text-zinc-400",children:E.attachmentName}),E.content&&y.jsx("div",{className:`rounded-2xl px-4 py-2.5 text-sm leading-relaxed ${E.role==="user"?"text-white rounded-tr-sm":"bg-[#222222] border border-white/[0.07] text-zinc-200 rounded-tl-sm"}`,style:E.role==="user"?{background:"linear-gradient(135deg, #D83333 0%, #C0285E 100%)"}:void 0,children:E.role==="user"?y.jsx("p",{className:"whitespace-pre-wrap",children:E.content}):y.jsx("div",{className:"prose-io",dangerouslySetInnerHTML:{__html:nt.parse(E.content)}})}),y.jsx("span",{className:"text-[11px] text-zinc-700 font-mono px-0.5",children:Qh(E.timestamp,e)})]})]},E.id)}),a&&y.jsxs("div",{className:"flex gap-3",children:[y.jsx("div",{className:"flex-shrink-0 w-6 h-6 rounded-lg flex items-center justify-center bg-[#282828] border border-white/[0.07] mt-0.5",children:y.jsx(Ra,{height:12})}),y.jsx("div",{className:"bg-[#222222] border border-white/[0.07] rounded-2xl rounded-tl-sm px-4 py-3 flex items-center gap-1.5",children:[0,120,240].map(E=>y.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#E43A9C] animate-bounce",style:{animationDelay:`${E}ms`}},E))})]}),i&&n&&y.jsxs("div",{className:"flex gap-3",children:[y.jsx("div",{className:"flex-shrink-0 w-6 h-6 rounded-lg flex items-center justify-center bg-[#282828] border border-white/[0.07] mt-0.5",children:y.jsx(Ra,{height:12})}),y.jsx("div",{className:"bg-[#222222] border border-white/[0.07] rounded-2xl rounded-tl-sm px-4 py-2.5 max-w-[72%]",children:y.jsx("div",{className:"prose-io text-sm",dangerouslySetInnerHTML:{__html:nt.parse(n)}})})]}),i&&!n&&y.jsxs("div",{className:"flex gap-3",children:[y.jsx("div",{className:"flex-shrink-0 w-6 h-6 rounded-lg flex items-center justify-center bg-[#282828] border border-white/[0.07] mt-0.5",children:y.jsx(Ra,{height:12})}),y.jsx("div",{className:"bg-[#222222] border border-white/[0.07] rounded-2xl rounded-tl-sm px-4 py-3 flex items-center gap-1.5",children:[0,120,240].map(E=>y.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-[#E43A9C] animate-bounce",style:{animationDelay:`${E}ms`}},E))})]})]}),y.jsxs("div",{className:"border-t border-white/[0.06] p-4 flex-shrink-0",children:[y.jsxs("div",{className:"bg-[#1e1e1e] border border-white/[0.08] rounded-2xl overflow-hidden transition-colors focus-within:border-[#E43A9C]/30",children:[y.jsx("input",{ref:S,type:"file",className:"hidden",onChange:E=>{var T;return g(((T=E.target.files)==null?void 0:T[0])??null)}}),f&&y.jsxs("div",{className:"px-4 pt-3 text-[11px] font-mono text-zinc-400",children:["Attached: ",f.name]}),y.jsx("textarea",{ref:b,value:d,onChange:j,onKeyDown:O,placeholder:"Message IO…",rows:1,className:"w-full bg-transparent px-4 pt-3 pb-1 text-sm text-zinc-200 placeholder:text-zinc-700 resize-none focus:outline-none",style:{minHeight:"42px",maxHeight:"160px",fontFamily:"Inter, sans-serif"}}),y.jsxs("div",{className:"flex items-center justify-between px-3 pb-2.5",children:[y.jsx("button",{type:"button",onClick:()=>{var E;return(E=S.current)==null?void 0:E.click()},className:"p-1.5 rounded-lg hover:bg-white/[0.05] text-zinc-700 hover:text-zinc-400 transition-colors",children:y.jsx(tP,{className:"w-4 h-4"})}),y.jsx("div",{className:"flex items-center gap-2",children:i?y.jsxs("button",{type:"button",onClick:()=>{},className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-zinc-800 hover:bg-zinc-700 text-[11px] font-mono text-zinc-300 transition-colors",children:[y.jsx(Jh,{className:"w-3 h-3"})," Stop"]}):y.jsx("button",{type:"button",onClick:A,disabled:!d.trim()&&!f||a,className:"p-2 rounded-xl text-white disabled:opacity-30 disabled:cursor-not-allowed transition-opacity hover:opacity-90",style:{background:"linear-gradient(135deg, #D83333, #E43A9C)"},children:y.jsx(nP,{className:"w-3.5 h-3.5"})})})]})]}),y.jsx("p",{className:"text-center text-[11px] text-zinc-800 font-mono mt-2",children:"IO may make mistakes. Verify important outputs."})]})]})}const ME=["#38bdf8","#a78bfa","#34d399","#f59e0b","#f87171","#E43A9C"];function gq(t){let e=0;for(let r=0;r<t.length;r++)e=t.charCodeAt(r)+((e<<5)-e);return ME[Math.abs(e)%ME.length]}function LE({name:t,color:e}){const r=t.toLowerCase(),n=e??(r==="orchestrator"||r==="io"?"#71717a":gq(t));return y.jsx("span",{className:"inline-flex items-center px-1.5 py-px rounded text-[10px] font-mono border",style:{background:`${n}15`,color:n,borderColor:`${n}30`},children:t})}function yq(){const[t,e]=N.useState([]),[r,n]=N.useState(null),[i,a]=N.useState(new Set),[o,c]=N.useState("all"),u=qa();N.useEffect(()=>{Ve.get("/inbox").then(O=>e(O.entries)).catch(()=>{})},[]);const d=t.filter(O=>O.status==="unread").length,p=o==="unread"?t.filter(O=>O.status==="unread"):t,f=p.length>0&&p.every(O=>i.has(O.id)),g=i.size>0;function v(O){g||(n(O),O.status==="unread"&&(Ve.post(`/inbox/${O.id}/read`).catch(()=>{}),e(j=>j.map(E=>E.id===O.id?{...E,status:"read"}:E))))}function x(O,j){O.stopPropagation(),a(E=>{const T=new Set(E);return T.has(j)?T.delete(j):T.add(j),T})}function w(){a(f?new Set:new Set(p.map(O=>O.id)))}function b(){const O=Array.from(i);Ve.post("/inbox/bulk/read",{ids:O}).catch(()=>{}),e(j=>j.map(E=>i.has(E.id)?{...E,status:"read"}:E)),a(new Set)}function S(){const O=Array.from(i);Ve.post("/inbox/bulk/delete",{ids:O}).catch(()=>{}),e(j=>j.filter(E=>!i.has(E.id))),r&&i.has(r.id)&&n(null),a(new Set)}function A(O){Ve.delete(`/inbox/${O}`).catch(()=>{}),e(j=>j.filter(E=>E.id!==O)),(r==null?void 0:r.id)===O&&n(null)}return y.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:[y.jsxs("div",{className:"w-72 flex-shrink-0 border-r border-white/[0.06] flex flex-col overflow-hidden",children:[y.jsxs("div",{className:"px-4 py-3 border-b border-white/[0.06] flex-shrink-0 space-y-2",children:[y.jsxs("div",{className:"flex items-center justify-between",children:[y.jsx("span",{className:"text-lg tracking-wide text-zinc-200",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"Inbox"}),d>0&&y.jsxs(jt,{variant:"default",children:[d," unread"]})]}),y.jsx("div",{className:"flex gap-1",children:["all","unread"].map(O=>y.jsx("button",{type:"button",onClick:()=>{c(O),a(new Set)},className:`flex-1 py-1 text-[11px] font-mono rounded-lg transition-colors cursor-pointer ${o===O?"text-[#E43A9C]":"text-zinc-600 hover:text-zinc-300"}`,style:o===O?{background:"rgba(228,58,156,0.12)"}:void 0,children:O},O))})]}),g&&y.jsxs("div",{className:"px-3 py-2 border-b border-white/[0.06] flex items-center gap-1.5 flex-shrink-0",style:{background:"rgba(228,58,156,0.06)"},children:[y.jsxs("span",{className:"text-[10px] font-mono text-zinc-500 flex-1",children:[i.size," selected"]}),y.jsxs("button",{type:"button",onClick:b,className:"flex items-center gap-1 px-2 py-1 rounded-lg text-[10px] font-mono text-zinc-400 hover:text-zinc-200 hover:bg-white/[0.06] transition-colors cursor-pointer",children:[y.jsx(zb,{className:"w-3 h-3"}),"Mark read"]}),y.jsxs("button",{type:"button",onClick:S,className:"flex items-center gap-1 px-2 py-1 rounded-lg text-[10px] font-mono text-red-400 hover:text-red-300 hover:bg-red-500/10 transition-colors cursor-pointer",children:[y.jsx(Ma,{className:"w-3 h-3"}),"Delete"]})]}),p.length>0&&y.jsxs("div",{className:"px-4 py-1.5 border-b border-white/[0.04] flex items-center gap-2 flex-shrink-0",children:[y.jsx("button",{type:"button",onClick:w,className:`w-3.5 h-3.5 rounded border flex items-center justify-center flex-shrink-0 transition-colors cursor-pointer ${f?"border-[#E43A9C] bg-[#E43A9C]":"border-white/20 hover:border-white/40"}`,children:f&&y.jsx("svg",{className:"w-2 h-2 text-white",fill:"none",viewBox:"0 0 8 8",children:y.jsx("path",{d:"M1 4l2 2 4-4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),y.jsx("span",{className:"text-[10px] font-mono text-zinc-700",children:"Select all"})]}),y.jsxs("div",{className:"flex-1 overflow-y-auto",children:[p.map(O=>{const j=i.has(O.id),E=(r==null?void 0:r.id)===O.id&&!g;return y.jsxs("div",{onClick:()=>v(O),onKeyDown:T=>T.key==="Enter"&&v(O),className:`flex items-start gap-2.5 px-3 py-3 border-b border-white/[0.04] cursor-pointer transition-colors ${E?"border-l-2 border-l-[#E43A9C] pl-2.5":"hover:bg-white/[0.025]"} ${j?"bg-[#E43A9C]/5":""}`,style:E?{background:"rgba(228,58,156,0.05)"}:void 0,children:[y.jsx("button",{type:"button",onClick:T=>x(T,O.id),className:`mt-0.5 w-3.5 h-3.5 rounded border flex items-center justify-center flex-shrink-0 transition-colors cursor-pointer ${j?"border-[#E43A9C] bg-[#E43A9C]":"border-white/20 hover:border-white/50"}`,children:j&&y.jsx("svg",{className:"w-2 h-2 text-white",fill:"none",viewBox:"0 0 8 8",children:y.jsx("path",{d:"M1 4l2 2 4-4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),y.jsxs("div",{className:"flex-1 min-w-0",children:[y.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[O.status==="unread"&&y.jsx("div",{className:"w-1 h-1 rounded-full bg-[#E43A9C] flex-shrink-0"}),y.jsx(LE,{name:O.squadName??(O.squadId?O.squadId.slice(0,8):"Orchestrator"),color:O.squadColor})]}),y.jsx("p",{className:`text-[11px] truncate ${O.status==="unread"?"text-zinc-200":"text-zinc-500"}`,children:O.title}),y.jsx("p",{className:"text-[10px] text-zinc-700 font-mono mt-1",children:Ws(O.createdAt,u)})]})]},O.id)}),p.length===0&&y.jsxs("div",{className:"flex flex-col items-center justify-center py-12",children:[y.jsx(Bb,{size:32,className:"text-zinc-800 mb-2"}),y.jsx("p",{className:"text-[11px] font-mono text-zinc-700",children:o==="unread"?"All caught up":"No items yet"})]})]})]}),y.jsx("div",{className:"flex-1 flex flex-col overflow-hidden",children:r&&!g?y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:"px-6 py-4 border-b border-white/[0.06] flex items-start justify-between flex-shrink-0",children:[y.jsxs("div",{className:"flex-1 min-w-0 mr-4",children:[y.jsx(LE,{name:r.squadName??(r.squadId?r.squadId.slice(0,8):"Orchestrator"),color:r.squadColor}),y.jsx("h3",{className:"text-sm font-mono text-zinc-100 mt-1.5",children:r.title}),y.jsx("p",{className:"text-[11px] text-zinc-700 font-mono mt-0.5",children:Ws(r.createdAt,u)})]}),y.jsxs("button",{type:"button",onClick:()=>A(r.id),className:"flex items-center gap-1.5 px-2.5 py-1 rounded-lg font-mono text-[11px] text-zinc-400 bg-[#252525] hover:bg-red-500/10 hover:text-red-400 transition-colors cursor-pointer",children:[y.jsx(Ma,{className:"w-3 h-3"}),"Delete"]})]}),y.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-5",children:y.jsx(rp,{content:r.content})})]}):g?y.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center gap-4 text-center px-8",children:[y.jsx("div",{className:"w-10 h-10 rounded-2xl flex items-center justify-center border border-[#E43A9C]/20",style:{background:"rgba(228,58,156,0.08)"},children:y.jsx(Bb,{className:"w-4 h-4 text-[#E43A9C]"})}),y.jsxs("div",{children:[y.jsxs("p",{className:"text-sm font-mono text-zinc-300",children:[i.size," message",i.size!==1?"s":""," selected"]}),y.jsx("p",{className:"text-[11px] text-zinc-600 mt-1",children:"Use the actions above to mark as read or delete"})]}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsxs("button",{type:"button",onClick:b,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-mono text-zinc-300 border border-white/[0.1] hover:bg-white/[0.05] transition-colors cursor-pointer",children:[y.jsx(zb,{className:"w-3 h-3"}),"Mark read"]}),y.jsxs("button",{type:"button",onClick:S,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-mono text-red-400 border border-red-500/20 hover:bg-red-500/10 transition-colors cursor-pointer",children:[y.jsx(Ma,{className:"w-3 h-3"}),"Delete selected"]})]})]}):y.jsx("div",{className:"flex-1 flex items-center justify-center text-zinc-700 font-mono text-xs",children:"Select an item to read"})})]})}function vq(){const{signIn:t}=sp(),[e,r]=N.useState(""),[n,i]=N.useState(""),[a,o]=N.useState(null),[c,u]=N.useState(!1);async function d(p){p.preventDefault(),o(null),u(!0);const{error:f}=await t(e,n);f&&o(f),u(!1)}return y.jsxs("div",{className:"min-h-screen bg-[#161616] flex items-center justify-center relative overflow-hidden",children:[y.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(circle, #E43A9C 1px, transparent 1px)",backgroundSize:"32px 32px"}}),y.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-[60%] w-[400px] h-[300px] rounded-full blur-3xl pointer-events-none",style:{background:"radial-gradient(ellipse, rgba(228,58,156,0.12) 0%, transparent 70%)"}}),y.jsxs("div",{className:"relative z-10 w-full max-w-[360px] mx-4",children:[y.jsxs("div",{className:"flex flex-col items-center mb-8 gap-3",children:[y.jsx(Ra,{height:52}),y.jsx("div",{className:"text-center",children:y.jsx("p",{className:"text-[11px] font-mono text-zinc-600 tracking-widest uppercase mt-1",children:"personal ai orchestrator"})})]}),y.jsxs("form",{onSubmit:d,className:"glass-card border border-white/[0.07] rounded-2xl p-6 space-y-4",children:[y.jsxs("div",{className:"space-y-1",children:[y.jsx("label",{className:"text-[11px] font-mono text-zinc-500 block",children:"Email"}),y.jsx("input",{type:"email",value:e,onChange:p=>r(p.target.value),required:!0,className:"w-full bg-[#161616] border border-white/[0.08] rounded-xl px-3 py-2.5 text-sm text-zinc-200 font-mono placeholder:text-zinc-700 focus:outline-none focus:border-[#E43A9C]/40 focus:ring-1 focus:ring-[#E43A9C]/15 transition-colors"})]}),y.jsxs("div",{className:"space-y-1",children:[y.jsx("label",{className:"text-[11px] font-mono text-zinc-500 block",children:"Password"}),y.jsx("input",{type:"password",value:n,onChange:p=>i(p.target.value),required:!0,placeholder:"••••••••",className:"w-full bg-[#161616] border border-white/[0.08] rounded-xl px-3 py-2.5 text-sm text-zinc-200 font-mono placeholder:text-zinc-700 focus:outline-none focus:border-[#E43A9C]/40 focus:ring-1 focus:ring-[#E43A9C]/15 transition-colors"})]}),a&&y.jsx("p",{className:"text-[11px] font-mono text-red-400",children:a}),y.jsx("button",{type:"submit",disabled:c,className:"w-full text-white font-mono text-sm rounded-xl py-3 mt-1 transition-opacity hover:opacity-90 disabled:opacity-50 flex items-center justify-center gap-2",style:{background:"linear-gradient(135deg, #D83333 0%, #E43A9C 55%, #F041FF 100%)"},children:c?y.jsxs(y.Fragment,{children:[y.jsx("span",{className:"w-3.5 h-3.5 border-2 border-white/30 border-t-white rounded-full animate-spin"}),"Authenticating…"]}):"Sign In"})]}),y.jsx("p",{className:"text-center text-[11px] text-zinc-700 font-mono mt-4",children:"Secured by Supabase Auth"})]})]})}const bR="w-full bg-[#161616] border border-white/[0.08] rounded-xl px-3 py-2 text-[11px] text-zinc-300 font-mono placeholder:text-zinc-700 focus:outline-none focus:border-[#E43A9C]/40 focus:ring-1 focus:ring-[#E43A9C]/10 transition-colors",Bs="bg-[#161616] border border-white/[0.08] rounded-xl px-3 py-2 text-[11px] text-zinc-300 font-mono placeholder:text-zinc-700 focus:outline-none focus:border-[#E43A9C]/40 focus:ring-1 focus:ring-[#E43A9C]/10 transition-colors";function qi({label:t,hint:e,align:r="center",children:n}){const i=r==="start"?"flex-1 min-w-0":"flex-1 flex justify-end items-center";return y.jsxs("div",{className:`glass-card border border-white/[0.07] rounded-2xl px-4 py-3.5 flex gap-4 ${r==="start"?"items-start":"items-center"}`,children:[y.jsxs("div",{className:"w-[140px] shrink-0",children:[y.jsx("span",{className:"text-[11px] font-mono text-zinc-400",children:t}),e&&y.jsxs("span",{className:"text-[10px] font-mono text-zinc-700 ml-1.5",children:["(",e,")"]})]}),y.jsx("div",{className:i,children:n})]})}function bq({onSave:t,onCancel:e,squads:r}){var x;const[n,i]=N.useState("io"),[a,o]=N.useState(((x=r[0])==null?void 0:x.id)??""),[c,u]=N.useState(""),[d,p]=N.useState(""),[f,g]=N.useState(""),v=()=>{!d.trim()||!f.trim()||!c.trim()||t({name:c.trim(),targetType:n==="io"?"orchestrator":"squad",targetId:n==="squad"?a:void 0,cron:d.trim(),prompt:f.trim()})};return y.jsx("div",{className:"fixed inset-0 z-40 flex items-center justify-center p-6",style:{background:"rgba(0,0,0,0.55)",backdropFilter:"blur(4px)"},children:y.jsxs("div",{className:"glass-card border border-white/[0.09] rounded-2xl w-full max-w-lg shadow-2xl flex flex-col",style:{maxHeight:"90vh"},children:[y.jsxs("div",{className:"flex items-center justify-between px-5 py-4 border-b border-white/[0.06] flex-shrink-0",children:[y.jsx("h3",{className:"text-lg tracking-wide text-zinc-100",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"New Schedule"}),y.jsx("button",{type:"button",onClick:e,className:"p-1.5 rounded-lg text-zinc-600 hover:text-zinc-300 hover:bg-white/[0.06] transition-colors cursor-pointer",children:y.jsx(aP,{className:"w-4 h-4"})})]}),y.jsxs("div",{className:"overflow-y-auto flex-1 px-5 py-4 space-y-2",children:[y.jsx(qi,{label:"Name",children:y.jsx("input",{value:c,onChange:w=>u(w.target.value),placeholder:"Daily triage",className:`${Bs} w-48`})}),y.jsx(qi,{label:"Type",children:y.jsx("div",{className:"flex gap-2",children:["io","squad"].map(w=>y.jsx("button",{type:"button",onClick:()=>i(w),className:`px-4 py-1.5 rounded-xl text-[11px] font-mono capitalize transition-colors border cursor-pointer ${n===w?"text-[#E43A9C] border-[#E43A9C]/30":"text-zinc-500 border-white/[0.08] hover:text-zinc-300 hover:bg-white/[0.04]"}`,style:n===w?{background:"rgba(228,58,156,0.08)"}:void 0,children:w==="io"?"IO":"Squad"},w))})}),n==="squad"&&y.jsx(qi,{label:"Squad",children:y.jsx("select",{value:a,onChange:w=>o(w.target.value),className:`${Bs} w-48`,children:r.map(w=>y.jsx("option",{value:w.id,style:{background:"#1a1a1a",color:"#d4d4d8"},children:w.name},w.id))})}),y.jsx(qi,{label:"Cron Expression",children:y.jsx("input",{value:d,onChange:w=>p(w.target.value),placeholder:"0 9 * * 1-5",className:`${Bs} w-40`})}),y.jsx(qi,{label:"Prompt",hint:"supports Markdown",align:"start",children:y.jsx("textarea",{value:f,onChange:w=>g(w.target.value),placeholder:"Describe what IO or the squad should do when this schedule fires.",rows:8,className:`${bR} resize-none leading-relaxed`})})]}),y.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-3.5 border-t border-white/[0.06] flex-shrink-0",children:[y.jsx(_i,{onClick:e,children:"Cancel"}),y.jsxs(za,{onClick:v,className:"px-4 py-1.5",children:[y.jsx(Uw,{className:"w-3 h-3"}),"Create Schedule"]})]})]})})}function xq({sched:t,squads:e,onSave:r,onBack:n}){var x,w;const[i,a]=N.useState(t.name),[o,c]=N.useState(t.cron),[u,d]=N.useState(t.prompt),[p,f]=N.useState(t.targetId??((x=e[0])==null?void 0:x.id)??""),g=()=>{!o.trim()||!u.trim()||!i.trim()||r({name:i.trim(),cron:o.trim(),prompt:u.trim(),targetId:t.targetType==="squad"?p:void 0})},v=t.targetType==="orchestrator"?"IO Schedule":`Squad — ${((w=e.find(b=>b.id===t.targetId))==null?void 0:w.name)??"Unknown"}`;return y.jsxs("div",{className:"flex-1 overflow-y-auto p-6 max-w-3xl",children:[y.jsxs("div",{className:"flex items-center gap-2 mb-6",children:[y.jsxs("button",{type:"button",onClick:n,className:"flex items-center gap-1.5 text-[11px] font-mono text-zinc-600 hover:text-zinc-300 transition-colors cursor-pointer",children:[y.jsx(vl,{className:"w-3.5 h-3.5"}),"Schedules"]}),y.jsx("span",{className:"text-zinc-700 text-[11px]",children:"/"}),y.jsx("span",{className:"text-[11px] font-mono text-zinc-400",children:"Edit"})]}),y.jsxs("div",{className:"flex items-start justify-between mb-6",children:[y.jsxs("div",{children:[y.jsx("h2",{className:"text-2xl tracking-wide text-zinc-100",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"Edit Schedule"}),y.jsx("p",{className:"text-[11px] font-mono text-zinc-600 mt-0.5",children:v})]}),y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx(_i,{onClick:n,children:"Cancel"}),y.jsxs(za,{onClick:g,className:"px-4 py-1.5",children:[y.jsx(Uw,{className:"w-3 h-3"}),"Save Changes"]})]})]}),y.jsxs("div",{className:"space-y-3",children:[y.jsx(qi,{label:"Name",children:y.jsx("input",{value:i,onChange:b=>a(b.target.value),placeholder:"Schedule name",className:`${Bs} w-48`})}),t.targetType==="squad"&&y.jsx(qi,{label:"Squad",children:y.jsx("select",{value:p,onChange:b=>f(b.target.value),className:`${Bs} w-48`,children:e.map(b=>y.jsx("option",{value:b.id,style:{background:"#1a1a1a",color:"#d4d4d8"},children:b.name},b.id))})}),y.jsx(qi,{label:"Cron Expression",children:y.jsx("input",{value:o,onChange:b=>c(b.target.value),placeholder:"0 9 * * 1-5",className:`${Bs} w-40`})}),y.jsx(qi,{label:"Prompt",hint:"supports Markdown",align:"start",children:y.jsxs("div",{className:"space-y-1.5",children:[y.jsx("textarea",{value:u,onChange:b=>d(b.target.value),placeholder:"Describe what IO or the squad should do when this schedule fires.",className:`${bR} leading-relaxed resize-y`,style:{minHeight:"360px"}}),y.jsx("p",{className:"text-[10px] font-mono text-zinc-700",children:"Tip: use # headings and - lists to structure multi-step instructions."})]})})]})]})}function wq(){const[t,e]=N.useState("squad"),[r,n]=N.useState([]),[i,a]=N.useState([]),[o,c]=N.useState(!1),[u,d]=N.useState(null),p=qa();N.useEffect(()=>{f(),g()},[]);function f(){Ve.get("/schedules").then(R=>n(R.schedules)).catch(()=>{})}function g(){Ve.get("/squads").then(R=>a(R.squads)).catch(()=>{})}const v=r.filter(R=>R.targetType==="squad"),x=r.filter(R=>R.targetType==="orchestrator"),w=t==="squad"?v:x;async function b(R){try{await Ve.post("/schedules",R),at.success("Schedule created"),c(!1),f()}catch(M){at.error(M instanceof Error?M.message:"Failed to create")}}async function S(R){if(u)try{await Ve.patch(`/schedules/${u.id}`,R),at.success("Schedule saved"),d(null),f()}catch{at.error("Failed to save schedule")}}const[A,O]=N.useState(null);async function j(R,M){O(R);try{await Ve.patch(`/schedules/${R}`,{enabled:!M}),at.success(M?"Schedule paused":"Schedule resumed"),f()}catch{at.error("Failed to toggle schedule")}finally{O(null)}}async function E(R){O(R);try{await Ve.post(`/schedules/${R}/run`,{}),at.success("Schedule triggered")}catch{at.error("Failed to trigger schedule")}finally{O(null)}}async function T(R){O(R);try{await Ve.delete(`/schedules/${R}`),at.success("Schedule deleted"),f()}catch{at.error("Failed to delete")}finally{O(null)}}if(u)return y.jsx(xq,{sched:u,squads:i,onSave:S,onBack:()=>d(null)});const P=t==="squad"?["Squad","Name","Cron","Next Run","Status",""]:["Name","Cron","Next Run","Status",""];return y.jsxs("div",{className:"flex-1 overflow-y-auto p-6",children:[o&&y.jsx(bq,{onSave:b,onCancel:()=>c(!1),squads:i}),y.jsxs("div",{className:"flex items-center justify-between mb-5",children:[y.jsxs("div",{children:[y.jsx("h2",{className:"text-2xl tracking-wide text-zinc-100",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"Schedules"}),y.jsxs("p",{className:"text-[11px] text-zinc-600 font-mono mt-0.5",children:[r.filter(R=>R.enabled).length," active · ",r.filter(R=>!R.enabled).length," paused"]})]}),y.jsxs(za,{onClick:()=>c(!0),className:"px-3 py-1.5",children:[y.jsx(Bw,{className:"w-3.5 h-3.5"}),"Add Schedule"]})]}),y.jsx("div",{className:"flex gap-1 mb-4",children:[["squad","Squad Schedules"],["io","IO Schedules"]].map(([R,M])=>y.jsx("button",{type:"button",onClick:()=>e(R),className:`px-4 py-2 text-[11px] font-mono rounded-xl transition-colors cursor-pointer ${t===R?"text-[#E43A9C]":"text-zinc-600 hover:text-zinc-300 hover:bg-white/[0.04]"}`,style:t===R?{background:"rgba(228,58,156,0.12)"}:void 0,children:M},R))}),y.jsx("div",{className:"overflow-x-auto rounded-2xl border border-white/[0.07] glass-card",children:w.length===0?y.jsx("div",{className:"px-4 py-12 text-center text-zinc-600 font-mono text-sm",children:"No schedules for this category"}):y.jsxs("table",{className:"w-full text-[11px] font-mono min-w-[640px]",children:[y.jsx("thead",{children:y.jsx("tr",{className:"border-b border-white/[0.06]",style:{background:"rgba(20,20,20,0.6)"},children:P.map(R=>y.jsx("th",{className:"text-left px-4 py-2.5 text-zinc-600 font-medium",children:R},R))})}),y.jsx("tbody",{children:w.map(R=>{var M,J;return y.jsxs("tr",{className:`border-b border-white/[0.04] hover:bg-white/[0.015] transition-colors ${R.enabled?"":"opacity-50"}`,children:[t==="squad"?y.jsx("td",{className:"px-4 py-3",children:y.jsx(c6,{name:((M=i.find(F=>F.id===R.targetId))==null?void 0:M.name)??"Unknown",color:(J=i.find(F=>F.id===R.targetId))==null?void 0:J.color})}):null,y.jsx("td",{className:"px-4 py-3 text-zinc-300",children:R.name}),y.jsx("td",{className:"px-4 py-3 text-zinc-600 text-[10px]",children:R.cron}),y.jsx("td",{className:"px-4 py-3 text-zinc-600",children:y.jsxs("span",{className:"flex items-center gap-1",children:[y.jsx(Lw,{className:"w-3 h-3"}),R.enabled&&R.nextRun?Ws(R.nextRun,p):"—"]})}),y.jsx("td",{className:"px-4 py-3",children:y.jsx(jt,{variant:R.enabled?"success":"muted",children:R.enabled?"active":"paused"})}),y.jsx("td",{className:"px-4 py-3",children:y.jsxs("div",{className:`flex items-center gap-1 ${A===R.id?"opacity-50 pointer-events-none":""}`,children:[y.jsxs(_i,{onClick:()=>E(R.id),children:[y.jsx(N4,{className:"w-3 h-3"}),"Run now"]}),y.jsx(u6,{onClick:()=>j(R.id,R.enabled),children:R.enabled?y.jsxs(y.Fragment,{children:[y.jsx(O4,{className:"w-3 h-3"}),"Pause"]}):y.jsxs(y.Fragment,{children:[y.jsx(Ds,{className:"w-3 h-3"}),"Resume"]})}),y.jsxs(_i,{onClick:()=>d(R),children:[y.jsx(T4,{className:"w-3 h-3"}),"Edit"]}),y.jsxs(Bf,{onClick:()=>T(R.id),children:[y.jsx(Ma,{className:"w-3 h-3"}),"Delete"]})]})})]},R.id)})})]})})]})}const _q=[{id:"general",label:"General"},{id:"telegram",label:"Telegram"},{id:"auth",label:"Auth"}],Uo="rounded-xl border border-white/[0.07] bg-white/[0.04] px-3 py-2 text-sm font-mono text-zinc-300 outline-none focus:border-[#E43A9C]/50",DE=`${Uo} w-[72px]`,Sq=`${Uo} w-[100px]`,zE=`${Uo} w-[200px]`,BE=`${Uo} w-[320px]`,kq=`${Uo} w-[140px] appearance-none bg-[url('data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2212%22%20height%3D%2212%22%20viewBox%3D%220%200%2012%2012%22%3E%3Cpath%20fill%3D%22%2371717a%22%20d%3D%22M3%204.5L6%208l3-3.5H3z%22%2F%3E%3C%2Fsvg%3E')] bg-[position:right_10px_center] bg-no-repeat pr-8`;function Eq(){const[t,e]=N.useState(null),[r,n]=N.useState("general");N.useEffect(()=>{Ve.get("/config").then(o=>e(o.config)).catch(()=>{})},[]);function i(o){t&&e({...t,...o})}async function a(){if(t)try{const{dataDir:o,...c}=t;await Ve.patch("/config",c),at.success("Settings saved")}catch{at.error("Failed to save settings")}}return t?y.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:y.jsxs("div",{className:"max-w-3xl",children:[y.jsx("h2",{className:"mb-6 text-2xl tracking-wide text-zinc-100",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"Settings"}),y.jsx("div",{className:"mb-6 flex gap-6 border-b border-white/[0.07]",children:_q.map(o=>y.jsx("button",{type:"button",onClick:()=>n(o.id),className:`-mb-px border-b-2 px-1 pb-3 text-[11px] font-mono transition-colors ${r===o.id?"border-[#E43A9C] text-[#E43A9C]":"border-transparent text-zinc-500 hover:text-zinc-300"}`,children:o.label},o.id))}),y.jsxs("div",{className:"glass-card rounded-2xl border border-white/[0.07] p-5",children:[r==="general"&&y.jsxs(y.Fragment,{children:[y.jsx(_n,{label:"Log Level",children:y.jsx("select",{value:t.logLevel,onChange:o=>i({logLevel:o.target.value}),className:kq,children:["trace","debug","info","warn","error","fatal"].map(o=>y.jsx("option",{value:o,children:o},o))})}),y.jsx(_n,{label:"Default Model",children:y.jsx("input",{type:"text",value:t.defaultModel,onChange:o=>i({defaultModel:o.target.value}),className:zE})}),y.jsx(_n,{label:"Timezone",children:y.jsx("select",{value:t.timezone,onChange:o=>i({timezone:o.target.value}),className:`${Uo} w-[200px] appearance-none bg-[url('data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2212%22%20height%3D%2212%22%20viewBox%3D%220%200%2012%2012%22%3E%3Cpath%20fill%3D%22%2371717a%22%20d%3D%22M3%204.5L6%208l3-3.5H3z%22%2F%3E%3C%2Fsvg%3E')] bg-[position:right_10px_center] bg-no-repeat pr-8`,children:Q4.map(o=>y.jsx("option",{value:o.value,children:o.label},o.value))})}),y.jsx(_n,{label:"Max Instances",children:y.jsx("input",{type:"number",value:t.maxInstancesPerSquad,onChange:o=>i({maxInstancesPerSquad:Number(o.target.value)}),className:DE,min:1,max:10})}),y.jsx(_n,{label:"API Port",children:y.jsx("input",{type:"number",value:t.apiPort,onChange:o=>i({apiPort:Number(o.target.value)}),className:DE})}),y.jsx(_n,{label:"Pricing Refresh (hrs)",children:y.jsx("input",{type:"number",value:t.pricing.refreshIntervalHours,onChange:o=>i({pricing:{refreshIntervalHours:Number(o.target.value)}}),className:Sq,min:1})}),y.jsx(_n,{label:"Data Dir",children:y.jsx("input",{type:"text",value:t.dataDir,readOnly:!0,className:`${BE} cursor-default text-zinc-500`})})]}),r==="telegram"&&y.jsxs(y.Fragment,{children:[y.jsx(_n,{label:"Bot Token",children:y.jsx(Ig,{value:t.telegram.botToken??"",onChange:o=>i({telegram:{...t.telegram,botToken:o||null}}),size:"lg"})}),y.jsx(_n,{label:"Allowed Chat IDs",children:y.jsx("input",{type:"text",value:t.telegram.allowedChatIds.join(", "),onChange:o=>i({telegram:{...t.telegram,allowedChatIds:o.target.value.split(",").map(c=>Number(c.trim())).filter(c=>!Number.isNaN(c))}}),className:zE})})]}),r==="auth"&&y.jsxs(y.Fragment,{children:[y.jsx(_n,{label:"Project URL",children:y.jsx("input",{type:"text",value:t.supabase.projectUrl??"",onChange:o=>i({supabase:{...t.supabase,projectUrl:o.target.value||null}}),className:BE})}),y.jsx(_n,{label:"Anon Key",children:y.jsx(Ig,{value:t.supabase.anonKey??"",onChange:o=>i({supabase:{...t.supabase,anonKey:o||null}}),size:"lg"})}),y.jsx(_n,{label:"JWT Secret",children:y.jsx(Ig,{value:t.supabase.jwtSecret??"",onChange:o=>i({supabase:{...t.supabase,jwtSecret:o||null}}),size:"lg"})})]}),y.jsx("div",{className:"flex justify-end pt-6",children:y.jsx(za,{onClick:a,className:"px-4 py-2.5",children:"Save Settings"})})]})]})}):y.jsx("div",{className:"flex h-full items-center justify-center text-zinc-600",children:"Loading..."})}function _n({label:t,children:e}){return y.jsxs("div",{className:"flex items-center justify-between gap-6 border-b border-white/[0.07] py-3",children:[y.jsx("label",{className:"text-[11px] font-mono text-zinc-400 shrink-0",children:t}),y.jsx("div",{className:"flex justify-end",children:e})]})}function Ig({value:t,onChange:e,size:r="lg"}){const[n,i]=N.useState(!1),a=r==="lg"?"w-[320px]":"w-[200px]";return y.jsxs("div",{className:"relative",children:[y.jsx("input",{type:n?"text":"password",value:t,onChange:o=>e(o.target.value),className:`${Uo} ${a} pr-9`}),y.jsx("button",{type:"button",onClick:()=>i(o=>!o),className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-zinc-600 transition-colors hover:text-zinc-400","aria-label":n?"Hide value":"Show value",children:n?y.jsx(n4,{size:14}):y.jsx(zb,{size:14})})]})}const Oq=[{id:"installed",label:"Installed"},{id:"awesome-copilot",label:"Awesome Copilot"},{id:"skillssh",label:"skills.sh"}];function UE(t){return t==="awesome-copilot"?"Awesome Copilot":"skills.sh"}function qE(t){return t?t>=1e6?`${(t/1e6).toFixed(1).replace(/\.0$/,"")}M installs`:t>=1e3?`${(t/1e3).toFixed(1).replace(/\.0$/,"")}K installs`:`${t} installs`:null}function Aq(t){const e=t.match(/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/);if(!e)return{frontMatter:{},body:t};const r=e[1]??"",n=e[2]??"",i={};let a="",o=null;for(const c of r.split(`
|
|
434
|
+
`)){const u=c.match(/^(\w[\w-]*)\s*:\s*(.*)$/);if(u){a&&o&&(i[a]=o,o=null),a=u[1]??"";const d=(u[2]??"").trim();d===""||d==="[]"?o=[]:d.startsWith("[")&&d.endsWith("]")?i[a]=d.slice(1,-1).split(",").map(p=>p.trim().replace(/^["']|["']$/g,"")):i[a]=d.replace(/^["']|["']$/g,"")}else c.match(/^\s+-\s+(.+)/)&&a&&(o||(o=[]),o.push(c.replace(/^\s+-\s+/,"").trim()))}return a&&o&&(i[a]=o),{frontMatter:i,body:n}}const FE=["name","description","version","author","license","argument_hint","argument-hint","use_when","use-when","enhancements","metadata","tags"];function Tq({content:t}){const{frontMatter:e,body:r}=Aq(t),n=FE.filter(o=>e[o]!==void 0),i=Object.keys(e).filter(o=>!FE.includes(o)),a=[...n,...i];return y.jsxs("div",{children:[a.length>0&&y.jsxs("div",{className:"border-b border-white/[0.05] pb-4 mb-4",children:[y.jsx("p",{className:"text-[10px] font-mono text-zinc-700 uppercase tracking-wider mb-3",children:"Front Matter"}),y.jsx("div",{className:"space-y-2",children:a.map(o=>{const c=e[o];return c==null||Array.isArray(c)&&c.length===0?null:y.jsxs("div",{className:"flex gap-3 items-start",children:[y.jsx("span",{className:"text-[10px] font-mono text-zinc-600 w-28 flex-shrink-0 pt-0.5",children:o}),y.jsx("div",{className:"flex-1 min-w-0",children:Array.isArray(c)?y.jsx("div",{className:"flex flex-wrap gap-1",children:c.map((u,d)=>y.jsx(jt,{variant:"muted",children:u},d))}):typeof c=="object"?y.jsx("div",{className:"space-y-0.5",children:Object.entries(c).map(([u,d])=>y.jsxs("p",{className:"text-[11px] font-mono text-zinc-400",children:[y.jsxs("span",{className:"text-zinc-600",children:[u,":"]})," ",d]},u))}):o==="use_when"||o==="use-when"?y.jsx("p",{className:"text-[11px] text-zinc-300 leading-relaxed",children:c}):o==="argument_hint"||o==="argument-hint"?y.jsx("code",{className:"text-[11px] font-mono text-[#E43A9C] bg-[#2d1a24] px-1.5 py-0.5 rounded",children:c}):y.jsx("span",{className:"text-[11px] font-mono text-zinc-300",children:c})})]},o)})})]}),r.trim()&&y.jsxs("div",{children:[y.jsx("p",{className:"text-[10px] font-mono text-zinc-700 uppercase tracking-wider mb-3",children:"Body"}),y.jsx(rp,{content:r})]})]})}function jq(){const[t,e]=N.useState("installed"),[r,n]=N.useState([]),[i,a]=N.useState([]),[o,c]=N.useState(null);function u($){return"url"in $&&$.url?$.url:$.name}const[d,p]=N.useState(null),[f,g]=N.useState(""),[v,x]=N.useState(!1),[w,b]=N.useState(!1),[S,A]=N.useState(!1),[O,j]=N.useState(""),[E,T]=N.useState(null),[P,R]=N.useState(null),M=N.useCallback(async()=>{try{const $=await Ve.get("/skills"),V=new Set($.skills.map(oe=>oe.name.toLowerCase()));n($.skills),a(oe=>oe.map(le=>({...le,installed:V.has(le.name.toLowerCase())})))}catch($){at.error($ instanceof Error?$.message:"Failed to load skills")}},[]),J=N.useCallback(async $=>{b(!0);try{const V=await Ve.get(`/skills/${encodeURIComponent($)}`);p(V),j(V.content)}catch(V){at.error(V instanceof Error?V.message:"Failed to load skill"),p(null)}finally{b(!1)}},[]);N.useEffect(()=>{M()},[M]),N.useEffect(()=>{if(t==="installed"){R(null);return}const $=f.trim();if(t==="skillssh"&&!$){a([]),R(null),x(!1);return}let V=!1;x(!0);const oe=window.setTimeout(async()=>{try{const le=await Ve.get(`/skills/discover?source=${t}&q=${encodeURIComponent($)}`);if(V)return;a(le.skills),R(null)}catch(le){if(V)return;a([]),R(le instanceof Error?le.message:"Discovery failed")}finally{V||x(!1)}},250);return()=>{V=!0,window.clearTimeout(oe)}},[f,t]);const F=N.useMemo(()=>{const $=f.trim().toLowerCase();return $?r.filter(V=>[V.name,V.description,V.preview].some(oe=>oe.toLowerCase().includes($))):r},[r,f]),B=t==="installed"?F:i,K=F.find($=>$.name===o)??null,W=i.find($=>u($)===o)??null,X=(K==null?void 0:K.name)??(W==null?void 0:W.name)??null;N.useEffect(()=>{if(A(!1),!B.length){c(null),t!=="installed"&&p(null);return}if(!o||!B.some($=>u($)===o)){const $=B[0];$&&c(u($))}},[o,t,B]),N.useEffect(()=>{if(t!=="installed"||!X){p(null);return}J(X)},[J,X,t]);async function Y($){if(!$.url&&!$.registrySource){at.error("Install source is not available for this skill yet");return}T($.name);try{await Ve.post("/skills/install",{name:$.name,source:$.source,url:$.url,registrySource:$.registrySource,skillId:$.skillId}),at.success(`Installed ${$.title||$.name}`),await M(),a(V=>V.map(oe=>oe.name===$.name?{...oe,installed:!0}:oe))}catch(V){at.error(V instanceof Error?V.message:"Install failed")}finally{T(null)}}async function te($){T($);try{await Ve.delete(`/skills/${encodeURIComponent($)}`),at.success(`Removed ${$}`),await M(),a(V=>V.map(oe=>oe.name===$?{...oe,installed:!1}:oe))}catch(V){at.error(V instanceof Error?V.message:"Failed to remove skill")}finally{T(null)}}async function H(){if(d){T(d.name);try{await Ve.put(`/skills/${encodeURIComponent(d.name)}`,{content:O}),at.success(`Updated ${d.name}`),A(!1),await Promise.all([M(),J(d.name)])}catch($){at.error($ instanceof Error?$.message:"Failed to save skill")}finally{T(null)}}}const Q=!!(K!=null&&K.activatedForOrchestrator),U=E===(d==null?void 0:d.name),I=E===(W==null?void 0:W.name);return y.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:[y.jsxs("div",{className:"w-64 flex-shrink-0 border-r border-white/[0.06] flex flex-col overflow-hidden",children:[y.jsxs("div",{className:"px-2.5 pt-2.5 pb-2 flex-shrink-0 border-b border-white/[0.06] space-y-2",children:[y.jsxs("div",{className:"relative",children:[y.jsx(rP,{className:"pointer-events-none absolute left-2.5 top-1/2 h-3 w-3 -translate-y-1/2 text-zinc-700"}),y.jsx("input",{type:"text",value:f,onChange:$=>g($.target.value),placeholder:"Search skills…",className:"w-full bg-[#181818] border border-white/[0.06] rounded-xl pl-7 pr-2 py-1.5 text-[11px] text-zinc-300 font-mono placeholder:text-zinc-700 focus:outline-none focus:border-[#E43A9C]/30 transition-colors"})]}),y.jsx("div",{className:"flex flex-col gap-0.5",children:Oq.map($=>y.jsxs("button",{type:"button",onClick:()=>e($.id),className:`w-full text-left px-2.5 py-1.5 rounded-lg text-[11px] font-mono transition-colors flex items-center justify-between cursor-pointer ${t===$.id?"text-[#E43A9C]":"text-zinc-500 hover:text-zinc-300 hover:bg-white/[0.04]"}`,style:t===$.id?{background:"rgba(228,58,156,0.10)"}:void 0,children:[y.jsx("span",{children:$.label}),$.id==="installed"&&y.jsx("span",{className:"text-[10px] text-zinc-600",children:r.length})]},$.id))})]}),y.jsxs("div",{className:"flex-1 overflow-y-auto py-1.5",children:[v&&t!=="installed"?y.jsxs("div",{className:"flex items-center gap-2 rounded-2xl border border-white/[0.08] bg-white/[0.03] px-3 py-3 font-mono text-[11px] text-zinc-500",children:[y.jsx(js,{className:"h-3.5 w-3.5 animate-spin"})," Searching registry..."]}):null,B.map($=>{const V=u($),oe=o===V,le=$.description||("preview"in $?$.preview:"No description available.");return y.jsxs("button",{type:"button",onClick:()=>{A(!1),c(V)},className:`w-full text-left px-3 py-2.5 border-b border-white/[0.03] transition-colors cursor-pointer ${oe?"border-l-2 border-l-[#E43A9C] bg-[#E43A9C]/5":"hover:bg-white/[0.03]"}`,children:[y.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[y.jsx("span",{className:"truncate font-mono text-[11px] text-zinc-200",children:$.name}),"installed"in $&&$.installed?y.jsx(jt,{variant:"success",children:"installed"}):null]}),y.jsx("p",{className:"line-clamp-2 font-mono text-[10px] leading-relaxed text-zinc-600",children:le})]},`${t}:${V}`)}),!v&&B.length===0?y.jsx("div",{className:"px-4 py-8",children:y.jsx("p",{className:"font-mono text-[11px] leading-relaxed text-zinc-500",children:P||(t==="skillssh"&&!f.trim()?"Start typing to search the skills.sh registry.":f.trim()?"No skills match your search.":"No skills available in this source.")})}):null]})]}),y.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto p-5",children:t==="installed"&&K?y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:"mb-5 flex items-start justify-between gap-4 border-b border-white/[0.06] pb-5",children:[y.jsxs("div",{className:"flex min-w-0 gap-4",children:[y.jsx("div",{className:"flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl bg-[#E43A9C]/12 text-[#E43A9C]",children:y.jsx(qb,{className:"h-6 w-6"})}),y.jsxs("div",{className:"min-w-0",children:[y.jsx("h3",{className:"truncate text-[34px] uppercase tracking-[0.08em] text-zinc-100",style:{fontFamily:"'Bebas Neue', sans-serif"},children:K.name}),y.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[y.jsx(jt,{variant:"success",children:"installed"}),Q?y.jsx(jt,{variant:"warning",children:"active"}):y.jsx(jt,{variant:"muted",children:"inactive"}),y.jsx(jt,{variant:"muted",children:"local skill"})]}),y.jsxs("div",{className:"mt-3 space-y-1 font-mono text-[11px] text-zinc-500",children:[y.jsxs("p",{children:["path: ",K.filePath]}),y.jsxs("p",{children:["orchestrator: ",Q?"enabled":"disabled"]})]})]})]}),y.jsxs("div",{className:"flex items-center gap-2",children:[S?y.jsxs(za,{onClick:H,disabled:U||O===(d==null?void 0:d.content),className:"px-3 py-2",children:[U?y.jsx(js,{className:"h-3.5 w-3.5 animate-spin"}):y.jsx(Ub,{className:"h-3.5 w-3.5"}),"Save"]}):y.jsxs(_i,{onClick:()=>A(!0),className:"px-3 py-2",children:[y.jsx(Ub,{className:"h-3.5 w-3.5"})," Edit"]}),y.jsxs(Bf,{onClick:()=>te(K.name),className:"px-3 py-2",children:[U?y.jsx(js,{className:"h-3.5 w-3.5 animate-spin"}):y.jsx(Ma,{className:"h-3.5 w-3.5"}),"Remove"]})]})]}),y.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto pr-1",children:w&&!d?y.jsxs("div",{className:"flex items-center gap-2 font-mono text-[11px] text-zinc-500",children:[y.jsx(js,{className:"h-3.5 w-3.5 animate-spin"})," Loading skill..."]}):S?y.jsxs("div",{className:"space-y-3",children:[y.jsx("textarea",{value:O,onChange:$=>j($.target.value),className:"min-h-[440px] w-full rounded-2xl border border-white/[0.08] bg-black/30 p-4 font-mono text-[12px] leading-6 text-zinc-200 outline-none transition-colors focus:border-[#E43A9C]/50"}),y.jsxs("div",{className:"flex items-center justify-between font-mono text-[11px] text-zinc-500",children:[y.jsx("span",{children:"Editing raw SKILL.md"}),y.jsx(_i,{onClick:()=>{A(!1),j((d==null?void 0:d.content)??"")},className:"px-3 py-2",children:"Cancel"})]})]}):d?y.jsx(Tq,{content:d.content}):y.jsx("p",{className:"font-mono text-[11px] text-zinc-500",children:"Select an installed skill to inspect it."})})]}):t!=="installed"&&W?y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:"mb-5 flex items-start justify-between gap-4 border-b border-white/[0.06] pb-5",children:[y.jsxs("div",{className:"flex min-w-0 gap-4",children:[y.jsx("div",{className:"flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl bg-[#E43A9C]/12 text-[#E43A9C]",children:y.jsx(U4,{className:"h-6 w-6"})}),y.jsxs("div",{className:"min-w-0",children:[y.jsx("h3",{className:"truncate text-[34px] uppercase tracking-[0.08em] text-zinc-100",style:{fontFamily:"'Bebas Neue', sans-serif"},children:W.title||W.name}),y.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[y.jsx(jt,{variant:W.installed?"success":"default",children:W.installed?"installed":"available"}),y.jsx(jt,{variant:"muted",children:UE(W.source)}),qE(W.installs)?y.jsx(jt,{variant:"info",children:qE(W.installs)}):null]}),y.jsxs("div",{className:"mt-3 space-y-1 font-mono text-[11px] text-zinc-500",children:[y.jsxs("p",{children:["registry: ",UE(W.source)]}),W.registrySource?y.jsxs("p",{children:["source: ",W.registrySource]}):null,W.url?y.jsxs("p",{children:["url: ",W.url]}):null]})]})]}),y.jsx("div",{className:"flex items-center gap-2",children:W.installed?y.jsx(_i,{onClick:()=>{e("installed"),c(W.name)},className:"px-3 py-2",children:"Open installed"}):y.jsxs(za,{onClick:()=>Y(W),disabled:I||!W.url&&!W.registrySource,className:"px-3 py-2",children:[I?y.jsx(js,{className:"h-3.5 w-3.5 animate-spin"}):y.jsx(e4,{className:"h-3.5 w-3.5"}),"Install"]})})]}),y.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto pr-1",children:[y.jsx("div",{className:"rounded-2xl border border-white/[0.06] bg-white/[0.02] p-5",children:y.jsx("p",{className:"font-mono text-[12px] leading-7 text-zinc-300",children:W.description||"No registry description is available for this skill yet."})}),y.jsx("div",{className:"mt-4 rounded-2xl border border-dashed border-white/[0.08] bg-black/20 p-4 font-mono text-[11px] leading-6 text-zinc-500",children:"Install will fetch the skill definition from the selected registry source and add it to your local skills library."})]})]}):y.jsx("div",{className:"flex h-full items-center justify-center rounded-2xl border border-dashed border-white/[0.08] bg-white/[0.02] p-8 text-center",children:y.jsxs("div",{children:[y.jsx("div",{className:"mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-2xl bg-[#E43A9C]/12 text-[#E43A9C]",children:y.jsx(qb,{className:"h-6 w-6"})}),y.jsx("h3",{className:"text-[28px] uppercase tracking-[0.08em] text-zinc-100",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"Select a Skill"}),y.jsx("p",{className:"mt-2 font-mono text-[11px] leading-relaxed text-zinc-500",children:"Choose a skill from the left panel to inspect details, install registry entries, or edit local definitions."})]})})})]})}function Cq(t){let e=0;for(let n=0;n<t.length;n++)e=t.charCodeAt(n)+((e<<5)-e);return`hsl(${(e%360+360)%360}, 70%, 65%)`}function $g(){const{name:t,instanceId:e}=rD();return t&&e?y.jsx($q,{squadName:t,instanceId:e}):t?y.jsx(Rq,{name:t}):y.jsx(Nq,{})}function Nq(){const[t,e]=N.useState([]),[r,n]=N.useState(null),i=Nu();return N.useEffect(()=>{Promise.all([Ve.get("/squads"),Ve.get("/config")]).then(([a,o])=>{e(a.squads),n(o.config.maxInstancesPerSquad)}).catch(()=>{})},[]),y.jsxs("div",{className:"flex-1 overflow-y-auto p-6",children:[y.jsx("div",{className:"mb-6",children:y.jsxs("div",{children:[y.jsx("h2",{className:"text-2xl tracking-wide text-zinc-100",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"Squads"}),y.jsxs("p",{className:"text-[11px] text-zinc-600 font-mono mt-0.5",children:[t.length," squads · ",t.reduce((a,o)=>a+(o.activeInstances||0),0)," ","active instances"]})]})}),y.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3",children:[t.map(a=>{const o=a.color||"#38bdf8";return y.jsxs("button",{type:"button",onClick:()=>i(`/squads/${a.name}`),className:"text-left rounded-2xl p-5 transition-all group cursor-pointer",style:{border:`1px solid ${o}30`,background:`${o}08`,backdropFilter:"blur(20px)"},onMouseEnter:c=>{c.currentTarget.style.borderColor=`${o}70`,c.currentTarget.style.background=`${o}12`},onMouseLeave:c=>{c.currentTarget.style.borderColor=`${o}30`,c.currentTarget.style.background=`${o}08`},children:[y.jsxs("div",{className:"flex items-start justify-between mb-1",children:[y.jsx("h3",{className:"text-sm font-mono transition-colors",style:{color:o},children:a.name}),y.jsx(jt,{variant:Co(a.status),children:a.status})]}),y.jsxs("div",{className:"flex items-center justify-between mb-3",children:[y.jsx("p",{className:"text-[11px] text-zinc-600 font-mono",children:a.universe}),y.jsxs("span",{className:"text-[11px] text-zinc-600 font-mono flex items-center gap-1",children:[y.jsx(J5,{className:"w-3 h-3"}),a.activeInstances,"/",r??(a.totalInstances||a.memberCount)]})]}),a.repoUrl&&y.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-zinc-700 font-mono mb-4",children:[y.jsx(ZN,{className:"w-3 h-3 flex-shrink-0"}),y.jsx("span",{className:"truncate",children:a.repoUrl.replace("https://github.com/","")})]}),a.recentActivity&&a.recentActivity.length>0&&y.jsxs("div",{className:"border-t pt-3",style:{borderColor:`${o}15`},children:[y.jsx("p",{className:"text-[10px] font-mono uppercase tracking-wider mb-2",style:{color:`${o}80`},children:"Recent Work"}),y.jsx("ul",{className:"space-y-1.5",children:a.recentActivity.map(c=>{const u={className:"w-3.5 h-3.5 flex-shrink-0 mt-px"},d=Pq(c.status,u),p=c.objective?c.objective.length>60?`${c.objective.slice(0,60)}…`:c.objective:c.issueRef||"Instance";return y.jsxs("li",{className:"flex items-start gap-1.5 text-[11px] font-mono text-zinc-600",children:[d,y.jsx("span",{className:"truncate",children:p})]},c.id)})})]})]},a.id)}),t.length===0&&y.jsxs("div",{className:"col-span-full text-center py-12 text-zinc-600",children:[y.jsx(Zh,{size:48,className:"mx-auto mb-3 opacity-30"}),y.jsx("p",{className:"text-[11px] font-mono",children:"No squads hired yet. Ask IO to hire a squad for a project."})]})]})]})}function Pq(t,e){const r=t.toLowerCase();return r.includes("complete")||r.includes("success")||r.includes("done")?y.jsx(YN,{...e,style:{color:"#34d399"}}):r.includes("warning")||r.includes("review")?y.jsx(G4,{...e,style:{color:"#fbbf24"}}):r.includes("error")||r.includes("fail")?y.jsx(JN,{...e,style:{color:"#f87171"}}):r.includes("working")||r.includes("progress")||r.includes("running")?y.jsx(eP,{...e,style:{color:"#E43A9C"}}):y.jsx(g4,{...e,style:{color:"#60a5fa"}})}function Kf(t,e){const r="w-4 h-4",n={color:e},i=t.toLowerCase();return i.includes("lead")||i.includes("pm")||i.includes("technical")?y.jsx(Dw,{className:r,style:n}):i.includes("qa")||i.includes("test")?y.jsx(D5,{className:r,style:n}):i.includes("scribe")?y.jsx($4,{className:r,style:n}):y.jsx(Uc,{className:r,style:n})}function Rq({name:t}){const[e,r]=N.useState(null),[n,i]=N.useState("agents"),[a,o]=N.useState([]),[c,u]=N.useState(0),[d,p]=N.useState(null),[f,g]=N.useState([]),v=Nu(),x=qa();N.useEffect(()=>{Ve.get(`/squads/${t}`).then(r).catch(()=>{})},[t]),N.useEffect(()=>{n==="history"&&Ve.get(`/squads/${t}/history`).then(S=>{o(S.items),u(S.total)}).catch(()=>{}),n==="schedules"&&e&&Ve.get(`/schedules?targetId=${e.squad.id}`).then(S=>g(S.schedules)).catch(()=>{})},[n,t,e]);const w=S=>{Ve.get(`/squads/${t}/history/${S.id}`).then(p).catch(()=>at.error("Failed to load activity detail"))};if(!e)return y.jsx("div",{className:"h-full flex items-center justify-center text-zinc-600",children:"Loading..."});const b=e.squad.color||"#38bdf8";return d?y.jsx(Iq,{activity:d,squadColor:b,squadName:e.squad.name,onBack:()=>p(null)}):y.jsxs("div",{className:"flex-1 overflow-y-auto p-6",style:{background:`${b}06`},children:[y.jsxs("button",{type:"button",onClick:()=>v("/squads"),className:"flex items-center gap-1.5 text-[11px] text-zinc-600 hover:text-zinc-300 font-mono mb-5 transition-colors",children:[y.jsx(vl,{className:"w-3.5 h-3.5"})," All Squads"]}),y.jsxs("div",{className:"flex items-start justify-between mb-5",children:[y.jsxs("div",{children:[y.jsx("h2",{className:"text-3xl tracking-wide",style:{fontFamily:"'Bebas Neue', sans-serif",color:b},children:e.squad.name}),y.jsxs("p",{className:"text-[11px] text-zinc-600 font-mono",children:[e.squad.universe," · ",e.squad.autonomyTier||"standard"," autonomy"]}),e.squad.repoUrl&&y.jsxs("a",{href:e.squad.repoUrl,target:"_blank",rel:"noreferrer",className:"text-[11px] font-mono text-[#E43A9C] hover:text-[#F041FF] flex items-center gap-1 mt-1 transition-colors",children:[y.jsx(ZN,{className:"w-3 h-3"}),e.squad.repoUrl.replace("https://github.com/","")]})]}),y.jsx(jt,{variant:Co(e.squad.status),children:e.squad.status})]}),y.jsx("div",{className:"flex gap-0 mb-5 border-b border-white/[0.06]",children:["agents","instances","schedules","history"].map(S=>y.jsx("button",{type:"button",onClick:()=>i(S),className:`px-4 py-2 text-[11px] font-mono capitalize transition-colors border-b-2 -mb-px ${n===S?"text-[#E43A9C] border-[#E43A9C]":"text-zinc-600 hover:text-zinc-300 border-transparent"}`,children:S},S))}),n==="agents"&&y.jsx("div",{className:"space-y-2",children:e.members.map(S=>y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl p-4 flex items-center gap-3",children:[y.jsx("div",{className:"w-8 h-8 rounded-xl flex items-center justify-center flex-shrink-0",style:{border:`1px solid ${b}30`,background:`${b}12`},children:Kf(S.roleName||S.role,b)}),y.jsxs("div",{className:"flex-1 min-w-0",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("span",{className:"text-sm font-mono text-zinc-200",children:S.displayName}),y.jsx(jt,{variant:Co(S.status),children:S.status})]}),y.jsx("p",{className:"text-[11px] text-zinc-600 font-mono mt-0.5",children:S.role}),S.currentTask&&y.jsx("p",{className:"text-xs text-zinc-500 mt-1 truncate",children:S.currentTask})]})]},S.id))}),n==="instances"&&y.jsx("div",{className:"space-y-2",children:e.instances.length===0?y.jsx("div",{className:"text-center py-16 text-zinc-700 font-mono text-sm",children:"No active instances"}):e.instances.map(S=>y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl p-4 flex items-center gap-4",children:[y.jsxs("div",{className:"flex-1 grid grid-cols-2 gap-2 text-[11px] font-mono",children:[y.jsxs("div",{children:[y.jsx("span",{className:"text-zinc-700",children:"ID"}),y.jsx("p",{className:"text-zinc-300 mt-0.5 truncate",children:S.id.slice(0,8)})]}),y.jsxs("div",{children:[y.jsx("span",{className:"text-zinc-700",children:"Branch"}),y.jsx("p",{className:"text-zinc-300 mt-0.5 truncate",children:S.branch||"—"})]}),y.jsxs("div",{children:[y.jsx("span",{className:"text-zinc-700",children:"Status"}),y.jsx("p",{className:"text-zinc-300 mt-0.5",children:y.jsx(jt,{variant:Co(S.status),children:S.status})})]}),y.jsxs("div",{children:[y.jsx("span",{className:"text-zinc-700",children:"Tasks"}),y.jsxs("p",{className:"text-zinc-300 mt-0.5",children:[S.tasksComplete,"/",S.taskCount]})]})]}),y.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[y.jsx("button",{type:"button",onClick:()=>v(`/squads/${t}/instances/${S.id}`),title:"View instance agents",className:"p-2 rounded-xl hover:bg-white/[0.06] transition-colors cursor-pointer",style:{color:b},children:y.jsx(Ds,{className:"w-4 h-4"})}),y.jsx("button",{type:"button",onClick:()=>at.info("Stop not yet implemented"),title:"Stop instance",className:"p-2 rounded-xl hover:bg-red-500/10 text-zinc-600 hover:text-red-400 transition-colors cursor-pointer",children:y.jsx(Jh,{className:"w-4 h-4"})})]})]},S.id))}),n==="schedules"&&y.jsx("div",{className:"overflow-auto rounded-2xl border border-white/[0.07] glass-card",children:f.length===0?y.jsx("div",{className:"text-center py-16 text-zinc-700 font-mono text-sm",children:"No schedules for this squad"}):y.jsxs("table",{className:"w-full text-[11px] font-mono",children:[y.jsx("thead",{children:y.jsx("tr",{className:"border-b border-white/[0.06]",style:{background:"rgba(20,20,20,0.6)"},children:["Schedule","Next Run","Status"].map(S=>y.jsx("th",{className:"text-left px-4 py-2.5 text-zinc-600 font-medium",children:S},S))})}),y.jsx("tbody",{children:f.map(S=>y.jsxs("tr",{className:`border-b border-white/[0.04] hover:bg-white/[0.015] transition-colors ${S.enabled?"":"opacity-50"}`,children:[y.jsxs("td",{className:"px-4 py-3",children:[y.jsx("div",{className:"text-zinc-300",children:S.name||S.prompt}),y.jsx("div",{className:"text-zinc-700 text-[10px] mt-0.5",children:S.cron})]}),y.jsx("td",{className:"px-4 py-3 text-zinc-600",children:y.jsxs("span",{className:"flex items-center gap-1",children:[y.jsx(Lw,{className:"w-3 h-3"}),S.enabled&&S.nextRun?Ws(S.nextRun,x):"—"]})}),y.jsx("td",{className:"px-4 py-3",children:y.jsx(jt,{variant:S.enabled?"success":"muted",children:S.enabled?"active":"paused"})})]},S.id))})]})}),n==="history"&&y.jsxs("div",{className:"space-y-2",children:[a.length===0?y.jsx("div",{className:"text-center py-16 text-zinc-700 font-mono text-sm",children:"No history yet"}):a.map(S=>y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl px-4 py-3.5 flex items-center gap-3",children:[y.jsx("div",{className:"flex-shrink-0",children:S.status==="completed"?y.jsx(YN,{className:"w-4 h-4",style:{color:"#34d399"}}):y.jsx(JN,{className:"w-4 h-4",style:{color:"#f87171"}})}),y.jsxs("div",{className:"flex-1 min-w-0",children:[y.jsx("p",{className:"text-[12px] text-zinc-300 font-mono truncate",children:S.title}),y.jsxs("div",{className:"flex items-center gap-3 mt-0.5",children:[y.jsx("span",{className:"text-[10px] text-zinc-700 font-mono",children:Ws(S.completedAt||S.createdAt,x)}),y.jsxs("span",{className:"text-[10px] text-zinc-700 font-mono flex items-center gap-1",children:[y.jsx(Ds,{className:"w-2.5 h-2.5"}),S.duration||"—"]}),y.jsxs("span",{className:"text-[10px] text-zinc-700 font-mono flex items-center gap-1",children:[y.jsx(Uc,{className:"w-2.5 h-2.5"}),S.agentCount," agent",S.agentCount!==1?"s":""]})]})]}),y.jsx(jt,{variant:S.status==="completed"?"success":"error",children:S.status}),y.jsx("button",{type:"button",onClick:()=>w(S),title:"View activity detail",className:"p-2 rounded-xl hover:bg-white/[0.06] transition-colors flex-shrink-0 cursor-pointer",style:{color:b},children:y.jsx(Ds,{className:"w-4 h-4"})})]},S.id)),a.length<c&&y.jsx("button",{type:"button",onClick:()=>{Ve.get(`/squads/${t}/history?offset=${a.length}`).then(S=>{o(A=>[...A,...S.items])}).catch(()=>{})},className:"w-full text-center py-3 text-[11px] font-mono text-zinc-600 hover:text-zinc-300 transition-colors cursor-pointer",children:"Load more"})]})]})}function Iq({activity:t,squadColor:e,squadName:r,onBack:n}){const i=qa(),a=N.useMemo(()=>{const p={};for(const f of t.agentEntries)p[f.agentId]=Cq(f.agentName);return p},[t]),o={thought:{label:"Thinking",icon:zw},tool_call:{label:"Tool Call",icon:iP},tool_result:{label:"Tool Result",icon:QN},message:{label:"Message",icon:Uc},decision:{label:"Decision",icon:Dw}},c={label:"Message",icon:Uc},u=p=>o[p]??c,d=N.useMemo(()=>{const p=t.agentEntries.flatMap(f=>f.events.map(g=>({ev:g,entry:f})));return p.sort((f,g)=>f.ev.timestamp.localeCompare(g.ev.timestamp)),p},[t]);return y.jsxs("div",{className:"flex-1 overflow-y-auto p-6",style:{background:`${e}06`},children:[y.jsxs("button",{type:"button",onClick:n,className:"flex items-center gap-1.5 text-[11px] text-zinc-600 hover:text-zinc-300 font-mono mb-5 transition-colors cursor-pointer",children:[y.jsx(vl,{className:"w-3.5 h-3.5"})," Back to ",r]}),y.jsxs("div",{className:"flex items-start justify-between mb-5",children:[y.jsxs("div",{children:[y.jsx("h2",{className:"text-2xl tracking-wide",style:{fontFamily:"'Bebas Neue', sans-serif",color:e},children:t.title}),y.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[y.jsx("span",{className:"text-[11px] text-zinc-600 font-mono",children:Ws(t.completedAt||t.createdAt,i)}),y.jsxs("span",{className:"text-[11px] text-zinc-700 font-mono flex items-center gap-1",children:[y.jsx(Lw,{className:"w-3 h-3"}),t.duration||"—"]})]})]}),y.jsx(jt,{variant:t.status==="completed"?"success":"error",children:t.status})]}),y.jsx("div",{className:"flex flex-wrap gap-2 mb-6",children:t.agentEntries.map(p=>{const f=a[p.agentId];return y.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1.5 rounded-xl border",style:{borderColor:`${f}30`,background:`${f}10`},children:[Kf(p.roleType||p.role,f),y.jsx("span",{className:"text-[11px] font-mono",style:{color:f},children:p.agentName}),y.jsxs("span",{className:"text-[10px] font-mono text-zinc-500",children:["— ",p.role]})]},p.agentId)})}),y.jsxs("div",{className:"relative pl-10",children:[y.jsx("div",{className:"absolute left-[15px] top-0 bottom-0 w-px bg-white/[0.06]"}),y.jsx("div",{className:"space-y-3",children:d.map(({ev:p,entry:f})=>{const g=a[f.agentId],{label:v,icon:x}=u(p.kind),w=p.kind==="tool_call"||p.kind==="tool_result";return y.jsxs("div",{className:"relative",children:[y.jsx("div",{className:"absolute -left-10 top-3 w-[30px] h-[30px] rounded-full flex items-center justify-center",style:{background:`${g}15`,border:`1px solid ${g}35`},children:y.jsx(x,{className:"w-3.5 h-3.5",style:{color:g}})}),y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl px-4 py-3",children:[y.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[y.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[y.jsxs("div",{className:"flex items-center gap-1",children:[Kf(f.roleType||f.role,g),y.jsx("span",{className:"text-[10px] font-mono",style:{color:g},children:f.agentName})]}),y.jsx("span",{className:"text-zinc-700 text-[10px]",children:"·"}),y.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-zinc-500",children:v}),p.label&&y.jsx("span",{className:"text-[10px] font-mono text-zinc-600 border border-white/[0.08] rounded px-1.5 py-px bg-white/[0.03]",children:p.label}),p.status==="error"&&y.jsx(jt,{variant:"error",children:"failed"}),p.status==="ok"&&p.kind==="tool_result"&&y.jsx(jt,{variant:"success",children:"ok"})]}),y.jsx("span",{className:"text-[10px] font-mono text-zinc-700 flex-shrink-0 ml-2",children:Qh(p.timestamp,i)})]}),w?y.jsx("pre",{className:"text-[11px] font-mono text-zinc-400 whitespace-pre-wrap leading-relaxed overflow-x-auto rounded-lg p-2 mt-1 bg-black/20",children:p.content}):y.jsx(rp,{content:p.content,className:"text-[12px] [&_pre]:text-[10px]"})]})]},p.id)})})]})]})}function $q({squadName:t,instanceId:e}){const[r,n]=N.useState(null),[i,a]=N.useState(null),o=Nu();if(N.useEffect(()=>{Ve.get(`/squads/${t}/instances/${e}`).then(n).catch(()=>{at.error("Failed to load instance")})},[t,e]),!r)return y.jsx("div",{className:"h-full flex items-center justify-center text-zinc-600",children:"Loading..."});const c=r.squadColor||"#38bdf8";if(i){const u=r.members.find(p=>p.roleName===i),d=r.activity.filter(p=>p.agent===i);return y.jsx(Dq,{agentName:(u==null?void 0:u.displayName)||i,agentRole:i,agentStatus:(u==null?void 0:u.status)||"idle",currentTask:(u==null?void 0:u.currentTask)||null,events:d,color:c,onBack:()=>a(null),squadName:t})}return y.jsxs("div",{className:"flex-1 overflow-y-auto p-6",style:{background:`${c}06`},children:[y.jsxs("button",{type:"button",onClick:()=>o(`/squads/${t}`),className:"flex items-center gap-1.5 text-[11px] text-zinc-600 hover:text-zinc-300 font-mono mb-5 transition-colors",children:[y.jsx(vl,{className:"w-3.5 h-3.5"})," Back to ",t]}),y.jsxs("div",{className:"flex items-start justify-between mb-6",children:[y.jsxs("div",{children:[y.jsx("h2",{className:"text-2xl tracking-wide",style:{fontFamily:"'Bebas Neue', sans-serif",color:c},children:"Instance"}),y.jsx("p",{className:"text-[11px] text-zinc-600 font-mono mt-0.5",children:r.instance.id.slice(0,8)}),r.instance.branch&&y.jsx("p",{className:"text-[11px] text-zinc-700 font-mono mt-0.5",children:r.instance.branch})]}),y.jsx(jt,{variant:Co(r.instance.status),children:r.instance.status})]}),y.jsx("div",{className:"space-y-2",children:r.members.map(u=>y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl p-4 flex items-center gap-3",children:[y.jsx("div",{className:"w-8 h-8 rounded-xl flex items-center justify-center flex-shrink-0",style:{border:`1px solid ${c}30`,background:`${c}12`},children:Kf(u.roleName||u.role,c)}),y.jsxs("div",{className:"flex-1 min-w-0",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("span",{className:"text-sm font-mono text-zinc-200",children:u.displayName}),y.jsx(jt,{variant:Co(u.status),children:u.status})]}),y.jsx("p",{className:"text-[11px] text-zinc-600 font-mono mt-0.5",children:u.role}),u.currentTask&&y.jsx("p",{className:"text-xs text-zinc-500 mt-1 truncate",children:u.currentTask})]}),(u.status==="working"||u.status==="in meeting")&&y.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[y.jsx("button",{type:"button",onClick:()=>a(u.roleName||u.role),title:"View work in progress",className:"p-2 rounded-xl hover:bg-white/[0.06] transition-colors cursor-pointer",style:{color:c},children:y.jsx(Ds,{className:"w-4 h-4"})}),u.status==="working"&&y.jsx("button",{type:"button",onClick:()=>at.success(`${u.displayName} stopped`),title:"Stop agent",className:"p-2 rounded-xl hover:bg-red-500/10 text-zinc-600 hover:text-red-400 transition-colors cursor-pointer",children:y.jsx(Jh,{className:"w-4 h-4"})})]})]},u.id))}),(r.instance.status==="meeting"||r.instance.status==="planning")&&r.instance.meetingLog&&r.instance.meetingLog.length>0&&y.jsxs("div",{className:"mt-6",children:[y.jsx("h3",{className:"text-lg tracking-wide mb-3",style:{fontFamily:"'Bebas Neue', sans-serif",color:c},children:"Meeting Discussion"}),y.jsx("div",{className:"space-y-2",children:r.instance.meetingLog.map((u,d)=>{const p=u.match(/^\[([^\]]+)\]\s*(.*)/s),f=p?p[1]:"unknown",g=p?p[2]??u:u;return y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-xl px-4 py-3",children:[y.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[y.jsx(Zh,{className:"w-3.5 h-3.5",style:{color:"#818cf8"}}),y.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider text-indigo-400",children:f})]}),y.jsx(rp,{content:g,className:"text-xs [&_pre]:text-[10px]"})]},`meeting-${d}`)})})]})]})}const Mq={thought:{label:"Thinking",icon:zw,color:"#a78bfa",bg:"rgba(167,139,250,0.1)"},tool_call:{label:"Tool Call",icon:iP,color:"#38bdf8",bg:"rgba(56,189,248,0.1)"},tool_result:{label:"Tool Result",icon:QN,color:"#34d399",bg:"rgba(52,211,153,0.1)"},message:{label:"Message",icon:Uc,color:"#E43A9C",bg:"rgba(228,58,156,0.15)"},decision:{label:"Decision",icon:Dw,color:"#fbbf24",bg:"rgba(251,191,36,0.1)"},meeting:{label:"Meeting",icon:Zh,color:"#818cf8",bg:"rgba(129,140,248,0.1)"}};function Lq(t){const e=t.toLowerCase();return e.includes("meeting")?"meeting":e.includes("tool_call")||e.includes("tool-call")?"tool_call":e.includes("tool_result")||e.includes("tool-result")?"tool_result":e.includes("thought")||e.includes("thinking")||e.includes("reason")?"thought":e.includes("decision")?"decision":"message"}function Dq({agentName:t,agentRole:e,agentStatus:r,currentTask:n,events:i,color:a,onBack:o,squadName:c}){const u=qa();return y.jsxs("div",{className:"flex-1 overflow-y-auto p-6",style:{background:`${a}06`},children:[y.jsxs("button",{type:"button",onClick:o,className:"flex items-center gap-1.5 text-[11px] text-zinc-600 hover:text-zinc-300 font-mono mb-5 transition-colors",children:[y.jsx(vl,{className:"w-3.5 h-3.5"})," Back to ",c]}),y.jsxs("div",{className:"flex items-start justify-between mb-6",children:[y.jsxs("div",{children:[y.jsx("h2",{className:"text-2xl tracking-wide",style:{fontFamily:"'Bebas Neue', sans-serif",color:a},children:t}),y.jsx("p",{className:"text-[11px] text-zinc-600 font-mono mt-0.5",children:e}),n&&y.jsx("p",{className:"text-sm text-zinc-400 mt-1",children:n})]}),y.jsx(jt,{variant:Co(r),children:r})]}),y.jsxs("div",{className:"relative",children:[y.jsx("div",{className:"absolute left-[15px] top-0 bottom-0 w-px bg-white/[0.06]"}),y.jsxs("div",{className:"space-y-3 pl-10",children:[i.length===0&&y.jsx("div",{className:"text-center py-12 text-zinc-700 font-mono text-sm",children:"No activity recorded yet"}),i.map(d=>{const p=Lq(d.type),f=Mq[p],g=f.icon,v=p==="tool_call"||p==="tool_result",x=d.type.toLowerCase().includes("error")||d.type.toLowerCase().includes("fail");return y.jsxs("div",{className:"relative",children:[y.jsx("div",{className:"absolute -left-10 top-3 w-[30px] h-[30px] rounded-full flex items-center justify-center",style:{background:f.bg,border:`1px solid ${f.color}30`},children:y.jsx(g,{className:"w-3.5 h-3.5",style:{color:f.color}})}),y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl px-4 py-3",children:[y.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("span",{className:"text-[10px] font-mono uppercase tracking-wider",style:{color:f.color},children:f.label}),d.model&&y.jsx("span",{className:"text-[10px] font-mono text-zinc-600 border border-white/[0.08] rounded px-1.5 py-px bg-white/[0.03]",children:d.model}),x&&y.jsx(jt,{variant:"error",children:"failed"})]}),y.jsx("span",{className:"text-[10px] font-mono text-zinc-700",children:Qh(d.timestamp,u)})]}),v?y.jsx("pre",{className:"text-[11px] font-mono text-zinc-400 whitespace-pre-wrap leading-relaxed overflow-x-auto rounded-lg p-2.5 bg-black/20",children:d.content}):y.jsx("p",{className:"text-[12px] text-zinc-400 leading-relaxed",children:d.content})]})]},d.id)}),y.jsxs("div",{className:"relative",children:[y.jsx("div",{className:"absolute -left-10 top-3 w-[30px] h-[30px] rounded-full flex items-center justify-center",style:{background:`${a}15`,border:`1px solid ${a}40`},children:y.jsx(eP,{className:"w-3.5 h-3.5 animate-spin",style:{color:a}})}),y.jsx("div",{className:"glass-card border rounded-2xl px-4 py-3",style:{borderColor:`${a}20`},children:y.jsx("span",{className:"text-[11px] font-mono",style:{color:a},children:"Agent is working…"})})]})]})]})]})}var Mg,HE;function Zr(){if(HE)return Mg;HE=1;var t=Array.isArray;return Mg=t,Mg}var Lg,WE;function xR(){if(WE)return Lg;WE=1;var t=typeof Zd=="object"&&Zd&&Zd.Object===Object&&Zd;return Lg=t,Lg}var Dg,GE;function Oi(){if(GE)return Dg;GE=1;var t=xR(),e=typeof self=="object"&&self&&self.Object===Object&&self,r=t||e||Function("return this")();return Dg=r,Dg}var zg,KE;function $u(){if(KE)return zg;KE=1;var t=Oi(),e=t.Symbol;return zg=e,zg}var Bg,VE;function zq(){if(VE)return Bg;VE=1;var t=$u(),e=Object.prototype,r=e.hasOwnProperty,n=e.toString,i=t?t.toStringTag:void 0;function a(o){var c=r.call(o,i),u=o[i];try{o[i]=void 0;var d=!0}catch{}var p=n.call(o);return d&&(c?o[i]=u:delete o[i]),p}return Bg=a,Bg}var Ug,XE;function Bq(){if(XE)return Ug;XE=1;var t=Object.prototype,e=t.toString;function r(n){return e.call(n)}return Ug=r,Ug}var qg,YE;function ra(){if(YE)return qg;YE=1;var t=$u(),e=zq(),r=Bq(),n="[object Null]",i="[object Undefined]",a=t?t.toStringTag:void 0;function o(c){return c==null?c===void 0?i:n:a&&a in Object(c)?e(c):r(c)}return qg=o,qg}var Fg,JE;function na(){if(JE)return Fg;JE=1;function t(e){return e!=null&&typeof e=="object"}return Fg=t,Fg}var Hg,ZE;function wl(){if(ZE)return Hg;ZE=1;var t=ra(),e=na(),r="[object Symbol]";function n(i){return typeof i=="symbol"||e(i)&&t(i)==r}return Hg=n,Hg}var Wg,QE;function r1(){if(QE)return Wg;QE=1;var t=Zr(),e=wl(),r=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,n=/^\w*$/;function i(a,o){if(t(a))return!1;var c=typeof a;return c=="number"||c=="symbol"||c=="boolean"||a==null||e(a)?!0:n.test(a)||!r.test(a)||o!=null&&a in Object(o)}return Wg=i,Wg}var Gg,eO;function Ha(){if(eO)return Gg;eO=1;function t(e){var r=typeof e;return e!=null&&(r=="object"||r=="function")}return Gg=t,Gg}var Kg,tO;function n1(){if(tO)return Kg;tO=1;var t=ra(),e=Ha(),r="[object AsyncFunction]",n="[object Function]",i="[object GeneratorFunction]",a="[object Proxy]";function o(c){if(!e(c))return!1;var u=t(c);return u==n||u==i||u==r||u==a}return Kg=o,Kg}var Vg,rO;function Uq(){if(rO)return Vg;rO=1;var t=Oi(),e=t["__core-js_shared__"];return Vg=e,Vg}var Xg,nO;function qq(){if(nO)return Xg;nO=1;var t=Uq(),e=(function(){var n=/[^.]+$/.exec(t&&t.keys&&t.keys.IE_PROTO||"");return n?"Symbol(src)_1."+n:""})();function r(n){return!!e&&e in n}return Xg=r,Xg}var Yg,iO;function wR(){if(iO)return Yg;iO=1;var t=Function.prototype,e=t.toString;function r(n){if(n!=null){try{return e.call(n)}catch{}try{return n+""}catch{}}return""}return Yg=r,Yg}var Jg,aO;function Fq(){if(aO)return Jg;aO=1;var t=n1(),e=qq(),r=Ha(),n=wR(),i=/[\\^$.*+?()[\]{}|]/g,a=/^\[object .+?Constructor\]$/,o=Function.prototype,c=Object.prototype,u=o.toString,d=c.hasOwnProperty,p=RegExp("^"+u.call(d).replace(i,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function f(g){if(!r(g)||e(g))return!1;var v=t(g)?p:a;return v.test(n(g))}return Jg=f,Jg}var Zg,oO;function Hq(){if(oO)return Zg;oO=1;function t(e,r){return e==null?void 0:e[r]}return Zg=t,Zg}var Qg,sO;function qo(){if(sO)return Qg;sO=1;var t=Fq(),e=Hq();function r(n,i){var a=e(n,i);return t(a)?a:void 0}return Qg=r,Qg}var ey,lO;function lp(){if(lO)return ey;lO=1;var t=qo(),e=t(Object,"create");return ey=e,ey}var ty,cO;function Wq(){if(cO)return ty;cO=1;var t=lp();function e(){this.__data__=t?t(null):{},this.size=0}return ty=e,ty}var ry,uO;function Gq(){if(uO)return ry;uO=1;function t(e){var r=this.has(e)&&delete this.__data__[e];return this.size-=r?1:0,r}return ry=t,ry}var ny,dO;function Kq(){if(dO)return ny;dO=1;var t=lp(),e="__lodash_hash_undefined__",r=Object.prototype,n=r.hasOwnProperty;function i(a){var o=this.__data__;if(t){var c=o[a];return c===e?void 0:c}return n.call(o,a)?o[a]:void 0}return ny=i,ny}var iy,fO;function Vq(){if(fO)return iy;fO=1;var t=lp(),e=Object.prototype,r=e.hasOwnProperty;function n(i){var a=this.__data__;return t?a[i]!==void 0:r.call(a,i)}return iy=n,iy}var ay,hO;function Xq(){if(hO)return ay;hO=1;var t=lp(),e="__lodash_hash_undefined__";function r(n,i){var a=this.__data__;return this.size+=this.has(n)?0:1,a[n]=t&&i===void 0?e:i,this}return ay=r,ay}var oy,pO;function Yq(){if(pO)return oy;pO=1;var t=Wq(),e=Gq(),r=Kq(),n=Vq(),i=Xq();function a(o){var c=-1,u=o==null?0:o.length;for(this.clear();++c<u;){var d=o[c];this.set(d[0],d[1])}}return a.prototype.clear=t,a.prototype.delete=e,a.prototype.get=r,a.prototype.has=n,a.prototype.set=i,oy=a,oy}var sy,mO;function Jq(){if(mO)return sy;mO=1;function t(){this.__data__=[],this.size=0}return sy=t,sy}var ly,gO;function i1(){if(gO)return ly;gO=1;function t(e,r){return e===r||e!==e&&r!==r}return ly=t,ly}var cy,yO;function cp(){if(yO)return cy;yO=1;var t=i1();function e(r,n){for(var i=r.length;i--;)if(t(r[i][0],n))return i;return-1}return cy=e,cy}var uy,vO;function Zq(){if(vO)return uy;vO=1;var t=cp(),e=Array.prototype,r=e.splice;function n(i){var a=this.__data__,o=t(a,i);if(o<0)return!1;var c=a.length-1;return o==c?a.pop():r.call(a,o,1),--this.size,!0}return uy=n,uy}var dy,bO;function Qq(){if(bO)return dy;bO=1;var t=cp();function e(r){var n=this.__data__,i=t(n,r);return i<0?void 0:n[i][1]}return dy=e,dy}var fy,xO;function e9(){if(xO)return fy;xO=1;var t=cp();function e(r){return t(this.__data__,r)>-1}return fy=e,fy}var hy,wO;function t9(){if(wO)return hy;wO=1;var t=cp();function e(r,n){var i=this.__data__,a=t(i,r);return a<0?(++this.size,i.push([r,n])):i[a][1]=n,this}return hy=e,hy}var py,_O;function up(){if(_O)return py;_O=1;var t=Jq(),e=Zq(),r=Qq(),n=e9(),i=t9();function a(o){var c=-1,u=o==null?0:o.length;for(this.clear();++c<u;){var d=o[c];this.set(d[0],d[1])}}return a.prototype.clear=t,a.prototype.delete=e,a.prototype.get=r,a.prototype.has=n,a.prototype.set=i,py=a,py}var my,SO;function a1(){if(SO)return my;SO=1;var t=qo(),e=Oi(),r=t(e,"Map");return my=r,my}var gy,kO;function r9(){if(kO)return gy;kO=1;var t=Yq(),e=up(),r=a1();function n(){this.size=0,this.__data__={hash:new t,map:new(r||e),string:new t}}return gy=n,gy}var yy,EO;function n9(){if(EO)return yy;EO=1;function t(e){var r=typeof e;return r=="string"||r=="number"||r=="symbol"||r=="boolean"?e!=="__proto__":e===null}return yy=t,yy}var vy,OO;function dp(){if(OO)return vy;OO=1;var t=n9();function e(r,n){var i=r.__data__;return t(n)?i[typeof n=="string"?"string":"hash"]:i.map}return vy=e,vy}var by,AO;function i9(){if(AO)return by;AO=1;var t=dp();function e(r){var n=t(this,r).delete(r);return this.size-=n?1:0,n}return by=e,by}var xy,TO;function a9(){if(TO)return xy;TO=1;var t=dp();function e(r){return t(this,r).get(r)}return xy=e,xy}var wy,jO;function o9(){if(jO)return wy;jO=1;var t=dp();function e(r){return t(this,r).has(r)}return wy=e,wy}var _y,CO;function s9(){if(CO)return _y;CO=1;var t=dp();function e(r,n){var i=t(this,r),a=i.size;return i.set(r,n),this.size+=i.size==a?0:1,this}return _y=e,_y}var Sy,NO;function o1(){if(NO)return Sy;NO=1;var t=r9(),e=i9(),r=a9(),n=o9(),i=s9();function a(o){var c=-1,u=o==null?0:o.length;for(this.clear();++c<u;){var d=o[c];this.set(d[0],d[1])}}return a.prototype.clear=t,a.prototype.delete=e,a.prototype.get=r,a.prototype.has=n,a.prototype.set=i,Sy=a,Sy}var ky,PO;function _R(){if(PO)return ky;PO=1;var t=o1(),e="Expected a function";function r(n,i){if(typeof n!="function"||i!=null&&typeof i!="function")throw new TypeError(e);var a=function(){var o=arguments,c=i?i.apply(this,o):o[0],u=a.cache;if(u.has(c))return u.get(c);var d=n.apply(this,o);return a.cache=u.set(c,d)||u,d};return a.cache=new(r.Cache||t),a}return r.Cache=t,ky=r,ky}var Ey,RO;function l9(){if(RO)return Ey;RO=1;var t=_R(),e=500;function r(n){var i=t(n,function(o){return a.size===e&&a.clear(),o}),a=i.cache;return i}return Ey=r,Ey}var Oy,IO;function c9(){if(IO)return Oy;IO=1;var t=l9(),e=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,r=/\\(\\)?/g,n=t(function(i){var a=[];return i.charCodeAt(0)===46&&a.push(""),i.replace(e,function(o,c,u,d){a.push(u?d.replace(r,"$1"):c||o)}),a});return Oy=n,Oy}var Ay,$O;function s1(){if($O)return Ay;$O=1;function t(e,r){for(var n=-1,i=e==null?0:e.length,a=Array(i);++n<i;)a[n]=r(e[n],n,e);return a}return Ay=t,Ay}var Ty,MO;function u9(){if(MO)return Ty;MO=1;var t=$u(),e=s1(),r=Zr(),n=wl(),i=t?t.prototype:void 0,a=i?i.toString:void 0;function o(c){if(typeof c=="string")return c;if(r(c))return e(c,o)+"";if(n(c))return a?a.call(c):"";var u=c+"";return u=="0"&&1/c==-1/0?"-0":u}return Ty=o,Ty}var jy,LO;function SR(){if(LO)return jy;LO=1;var t=u9();function e(r){return r==null?"":t(r)}return jy=e,jy}var Cy,DO;function kR(){if(DO)return Cy;DO=1;var t=Zr(),e=r1(),r=c9(),n=SR();function i(a,o){return t(a)?a:e(a,o)?[a]:r(n(a))}return Cy=i,Cy}var Ny,zO;function fp(){if(zO)return Ny;zO=1;var t=wl();function e(r){if(typeof r=="string"||t(r))return r;var n=r+"";return n=="0"&&1/r==-1/0?"-0":n}return Ny=e,Ny}var Py,BO;function l1(){if(BO)return Py;BO=1;var t=kR(),e=fp();function r(n,i){i=t(i,n);for(var a=0,o=i.length;n!=null&&a<o;)n=n[e(i[a++])];return a&&a==o?n:void 0}return Py=r,Py}var Ry,UO;function ER(){if(UO)return Ry;UO=1;var t=l1();function e(r,n,i){var a=r==null?void 0:t(r,n);return a===void 0?i:a}return Ry=e,Ry}var d9=ER();const Tn=vt(d9);var Iy,qO;function f9(){if(qO)return Iy;qO=1;function t(e){return e==null}return Iy=t,Iy}var h9=f9();const et=vt(h9);var $y,FO;function p9(){if(FO)return $y;FO=1;var t=ra(),e=Zr(),r=na(),n="[object String]";function i(a){return typeof a=="string"||!e(a)&&r(a)&&t(a)==n}return $y=i,$y}var m9=p9();const Io=vt(m9);var g9=n1();const Je=vt(g9);var y9=Ha();const _l=vt(y9);var My={exports:{}},pt={};/**
|
|
435
435
|
* @license React
|
|
436
436
|
* react-is.production.min.js
|
|
437
437
|
*
|
|
@@ -501,5 +501,5 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
501
501
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function cne(t,e){var r=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r!=null){var n,i,a,o,c=[],u=!0,d=!1;try{if(a=(r=r.call(t)).next,e!==0)for(;!(u=(n=a.call(r)).done)&&(c.push(n.value),c.length!==e);u=!0);}catch(p){d=!0,i=p}finally{try{if(!u&&r.return!=null&&(o=r.return(),Object(o)!==o))return}finally{if(d)throw i}}return c}}function une(t){if(Array.isArray(t))return t}function _N(t,e){if(t==null)return{};var r=dne(t,e),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);for(i=0;i<a.length;i++)n=a[i],!(e.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function dne(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function fne(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function hne(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,SM(n.key),n)}}function pne(t,e,r){return e&&hne(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}function mne(t,e,r){return e=Gh(e),gne(t,wM()?Reflect.construct(e,r||[],Gh(t).constructor):e.apply(t,r))}function gne(t,e){if(e&&(hl(e)==="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return yne(t)}function yne(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function wM(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(wM=function(){return!!t})()}function Gh(t){return Gh=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Gh(t)}function vne(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&_w(t,e)}function _w(t,e){return _w=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},_w(t,e)}function pl(t){return wne(t)||xne(t)||_M(t)||bne()}function bne(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
502
502
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _M(t,e){if(t){if(typeof t=="string")return Sw(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Sw(t,e)}}function xne(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function wne(t){if(Array.isArray(t))return Sw(t)}function Sw(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function SN(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function ie(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?SN(Object(r),!0).forEach(function(n){ze(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):SN(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}function ze(t,e,r){return e=SM(e),e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function SM(t){var e=_ne(t,"string");return hl(e)=="symbol"?e:e+""}function _ne(t,e){if(hl(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(hl(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}var Sne={xAxis:["bottom","top"],yAxis:["left","right"]},kne={width:"100%",height:"100%"},kM={x:0,y:0};function Of(t){return t}var Ene=function(e,r){return r==="horizontal"?e.x:r==="vertical"?e.y:r==="centric"?e.angle:e.radius},One=function(e,r,n,i){var a=r.find(function(p){return p&&p.index===n});if(a){if(e==="horizontal")return{x:a.coordinate,y:i.y};if(e==="vertical")return{x:i.x,y:a.coordinate};if(e==="centric"){var o=a.coordinate,c=i.radius;return ie(ie(ie({},i),_r(i.cx,i.cy,c,o)),{},{angle:o,radius:c})}var u=a.coordinate,d=i.angle;return ie(ie(ie({},i),_r(i.cx,i.cy,u,d)),{},{angle:d,radius:u})}return kM},Dp=function(e,r){var n=r.graphicalItems,i=r.dataStartIndex,a=r.dataEndIndex,o=(n??[]).reduce(function(c,u){var d=u.props.data;return d&&d.length?[].concat(pl(c),pl(d)):c},[]);return o.length>0?o:e&&e.length&&ge(i)&&ge(a)?e.slice(i,a+1):[]};function EM(t){return t==="number"?[0,"auto"]:void 0}var kw=function(e,r,n,i){var a=e.graphicalItems,o=e.tooltipAxis,c=Dp(r,e);return n<0||!a||!a.length||n>=c.length?null:a.reduce(function(u,d){var p,f=(p=d.props.data)!==null&&p!==void 0?p:r;f&&e.dataStartIndex+e.dataEndIndex!==0&&e.dataEndIndex-e.dataStartIndex>=n&&(f=f.slice(e.dataStartIndex,e.dataEndIndex+1));var g;if(o.dataKey&&!o.allowDuplicatedCategory){var v=f===void 0?c:f;g=Vf(v,o.dataKey,i)}else g=f&&f[n]||c[n];return g?[].concat(pl(u),[E$(d,g)]):u},[])},kN=function(e,r,n,i){var a=i||{x:e.chartX,y:e.chartY},o=Ene(a,n),c=e.orderedTooltipTicks,u=e.tooltipAxis,d=e.tooltipTicks,p=MX(o,c,d,u);if(p>=0&&d){var f=d[p]&&d[p].value,g=kw(e,r,p,f),v=One(n,c,p,a);return{activeTooltipIndex:p,activeLabel:f,activePayload:g,activeCoordinate:v}}return null},Ane=function(e,r){var n=r.axes,i=r.graphicalItems,a=r.axisType,o=r.axisIdKey,c=r.stackGroups,u=r.dataStartIndex,d=r.dataEndIndex,p=e.layout,f=e.children,g=e.stackOffset,v=_$(p,a);return n.reduce(function(x,w){var b,S=w.type.defaultProps!==void 0?ie(ie({},w.type.defaultProps),w.props):w.props,A=S.type,O=S.dataKey,j=S.allowDataOverflow,E=S.allowDuplicatedCategory,T=S.scale,P=S.ticks,R=S.includeHidden,M=S[o];if(x[M])return x;var J=Dp(e.data,{graphicalItems:i.filter(function($){var V,oe=o in $.props?$.props[o]:(V=$.type.defaultProps)===null||V===void 0?void 0:V[o];return oe===M}),dataStartIndex:u,dataEndIndex:d}),F=J.length,B,K,W;Qre(S.domain,j,A)&&(B=Ux(S.domain,null,j),v&&(A==="number"||T!=="auto")&&(W=Lc(J,O,"category")));var X=EM(A);if(!B||B.length===0){var Y,te=(Y=S.domain)!==null&&Y!==void 0?Y:X;if(O){if(B=Lc(J,O,A),A==="category"&&v){var H=A9(B);E&&H?(K=B,B=Rh(0,F)):E||(B=Dj(te,B,w).reduce(function($,V){return $.indexOf(V)>=0?$:[].concat(pl($),[V])},[]))}else if(A==="category")E?B=B.filter(function($){return $!==""&&!et($)}):B=Dj(te,B,w).reduce(function($,V){return $.indexOf(V)>=0||V===""||et(V)?$:[].concat(pl($),[V])},[]);else if(A==="number"){var Q=UX(J,i.filter(function($){var V,oe,le=o in $.props?$.props[o]:(V=$.type.defaultProps)===null||V===void 0?void 0:V[o],ve="hide"in $.props?$.props.hide:(oe=$.type.defaultProps)===null||oe===void 0?void 0:oe.hide;return le===M&&(R||!ve)}),O,a,p);Q&&(B=Q)}v&&(A==="number"||T!=="auto")&&(W=Lc(J,O,"category"))}else v?B=Rh(0,F):c&&c[M]&&c[M].hasStack&&A==="number"?B=g==="expand"?[0,1]:k$(c[M].stackGroups,u,d):B=w$(J,i.filter(function($){var V=o in $.props?$.props[o]:$.type.defaultProps[o],oe="hide"in $.props?$.props.hide:$.type.defaultProps.hide;return V===M&&(R||!oe)}),A,p,!0);if(A==="number")B=ww(f,B,M,a,P),te&&(B=Ux(te,B,j));else if(A==="category"&&te){var U=te,I=B.every(function($){return U.indexOf($)>=0});I&&(B=U)}}return ie(ie({},x),{},ze({},M,ie(ie({},S),{},{axisType:a,domain:B,categoricalDomain:W,duplicateDomain:K,originalDomain:(b=S.domain)!==null&&b!==void 0?b:X,isCategorical:v,layout:p})))},{})},Tne=function(e,r){var n=r.graphicalItems,i=r.Axis,a=r.axisType,o=r.axisIdKey,c=r.stackGroups,u=r.dataStartIndex,d=r.dataEndIndex,p=e.layout,f=e.children,g=Dp(e.data,{graphicalItems:n,dataStartIndex:u,dataEndIndex:d}),v=g.length,x=_$(p,a),w=-1;return n.reduce(function(b,S){var A=S.type.defaultProps!==void 0?ie(ie({},S.type.defaultProps),S.props):S.props,O=A[o],j=EM("number");if(!b[O]){w++;var E;return x?E=Rh(0,v):c&&c[O]&&c[O].hasStack?(E=k$(c[O].stackGroups,u,d),E=ww(f,E,O,a)):(E=Ux(j,w$(g,n.filter(function(T){var P,R,M=o in T.props?T.props[o]:(P=T.type.defaultProps)===null||P===void 0?void 0:P[o],J="hide"in T.props?T.props.hide:(R=T.type.defaultProps)===null||R===void 0?void 0:R.hide;return M===O&&!J}),"number",p),i.defaultProps.allowDataOverflow),E=ww(f,E,O,a)),ie(ie({},b),{},ze({},O,ie(ie({axisType:a},i.defaultProps),{},{hide:!0,orientation:Tn(Sne,"".concat(a,".").concat(w%2),null),domain:E,originalDomain:j,isCategorical:x,layout:p})))}return b},{})},jne=function(e,r){var n=r.axisType,i=n===void 0?"xAxis":n,a=r.AxisComp,o=r.graphicalItems,c=r.stackGroups,u=r.dataStartIndex,d=r.dataEndIndex,p=e.children,f="".concat(i,"Id"),g=jn(p,a),v={};return g&&g.length?v=Ane(e,{axes:g,graphicalItems:o,axisType:i,axisIdKey:f,stackGroups:c,dataStartIndex:u,dataEndIndex:d}):o&&o.length&&(v=Tne(e,{Axis:a,graphicalItems:o,axisType:i,axisIdKey:f,stackGroups:c,dataStartIndex:u,dataEndIndex:d})),v},Cne=function(e){var r=Pa(e),n=Wi(r,!1,!0);return{tooltipTicks:n,orderedTooltipTicks:_1(n,function(i){return i.coordinate}),tooltipAxis:r,tooltipAxisBandSize:Sh(r,n)}},EN=function(e){var r=e.children,n=e.defaultShowTooltip,i=sn(r,il),a=0,o=0;return e.data&&e.data.length!==0&&(o=e.data.length-1),i&&i.props&&(i.props.startIndex>=0&&(a=i.props.startIndex),i.props.endIndex>=0&&(o=i.props.endIndex)),{chartX:0,chartY:0,dataStartIndex:a,dataEndIndex:o,activeTooltipIndex:-1,isTooltipActive:!!n}},Nne=function(e){return!e||!e.length?!1:e.some(function(r){var n=Gi(r&&r.type);return n&&n.indexOf("Bar")>=0})},ON=function(e){return e==="horizontal"?{numericAxisName:"yAxis",cateAxisName:"xAxis"}:e==="vertical"?{numericAxisName:"xAxis",cateAxisName:"yAxis"}:e==="centric"?{numericAxisName:"radiusAxis",cateAxisName:"angleAxis"}:{numericAxisName:"angleAxis",cateAxisName:"radiusAxis"}},Pne=function(e,r){var n=e.props,i=e.graphicalItems,a=e.xAxisMap,o=a===void 0?{}:a,c=e.yAxisMap,u=c===void 0?{}:c,d=n.width,p=n.height,f=n.children,g=n.margin||{},v=sn(f,il),x=sn(f,qs),w=Object.keys(u).reduce(function(E,T){var P=u[T],R=P.orientation;return!P.mirror&&!P.hide?ie(ie({},E),{},ze({},R,E[R]+P.width)):E},{left:g.left||0,right:g.right||0}),b=Object.keys(o).reduce(function(E,T){var P=o[T],R=P.orientation;return!P.mirror&&!P.hide?ie(ie({},E),{},ze({},R,Tn(E,"".concat(R))+P.height)):E},{top:g.top||0,bottom:g.bottom||0}),S=ie(ie({},b),w),A=S.bottom;v&&(S.bottom+=v.props.height||il.defaultProps.height),x&&r&&(S=zX(S,i,n,r));var O=d-S.left-S.right,j=p-S.top-S.bottom;return ie(ie({brushBottom:A},S),{},{width:Math.max(O,0),height:Math.max(j,0)})},Rne=function(e,r){if(r==="xAxis")return e[r].width;if(r==="yAxis")return e[r].height},OM=function(e){var r=e.chartName,n=e.GraphicalChild,i=e.defaultTooltipEventType,a=i===void 0?"axis":i,o=e.validateTooltipEventTypes,c=o===void 0?["axis"]:o,u=e.axisComponents,d=e.legendContent,p=e.formatAxisMap,f=e.defaultProps,g=function(S,A){var O=A.graphicalItems,j=A.stackGroups,E=A.offset,T=A.updateId,P=A.dataStartIndex,R=A.dataEndIndex,M=S.barSize,J=S.layout,F=S.barGap,B=S.barCategoryGap,K=S.maxBarSize,W=ON(J),X=W.numericAxisName,Y=W.cateAxisName,te=Nne(O),H=[];return O.forEach(function(Q,U){var I=Dp(S.data,{graphicalItems:[Q],dataStartIndex:P,dataEndIndex:R}),$=Q.type.defaultProps!==void 0?ie(ie({},Q.type.defaultProps),Q.props):Q.props,V=$.dataKey,oe=$.maxBarSize,le=$["".concat(X,"Id")],ve=$["".concat(Y,"Id")],qe={},xe=u.reduce(function(lr,_t){var kr=A["".concat(_t.axisType,"Map")],Ir=$["".concat(_t.axisType,"Id")];kr&&kr[Ir]||_t.axisType==="zAxis"||Lo();var ni=kr[Ir];return ie(ie({},lr),{},ze(ze({},_t.axisType,ni),"".concat(_t.axisType,"Ticks"),Wi(ni)))},qe),ae=xe[Y],Se=xe["".concat(Y,"Ticks")],Me=j&&j[le]&&j[le].hasStack&&QX(Q,j[le].stackGroups),se=Gi(Q.type).indexOf("Bar")>=0,tt=Sh(ae,Se),Fe=[],kt=te&&LX({barSize:M,stackGroups:j,totalSize:Rne(xe,Y)});if(se){var wt,Et,Sr=et(oe)?K:oe,Ut=(wt=(Et=Sh(ae,Se,!0))!==null&&Et!==void 0?Et:Sr)!==null&&wt!==void 0?wt:0;Fe=DX({barGap:F,barCategoryGap:B,bandSize:Ut!==tt?Ut:tt,sizeList:kt[ve],maxBarSize:Sr}),Ut!==tt&&(Fe=Fe.map(function(lr){return ie(ie({},lr),{},{position:ie(ie({},lr.position),{},{offset:lr.position.offset-Ut/2})})}))}var Rr=Q&&Q.type&&Q.type.getComposedData;Rr&&H.push({props:ie(ie({},Rr(ie(ie({},xe),{},{displayedData:I,props:S,dataKey:V,item:Q,bandSize:tt,barPosition:Fe,offset:E,stackedData:Me,layout:J,dataStartIndex:P,dataEndIndex:R}))),{},ze(ze(ze({key:Q.key||"item-".concat(U)},X,xe[X]),Y,xe[Y]),"animationId",T)),childIndex:B9(Q,S.children),item:Q})}),H},v=function(S,A){var O=S.props,j=S.dataStartIndex,E=S.dataEndIndex,T=S.updateId;if(!ZO({props:O}))return null;var P=O.children,R=O.layout,M=O.stackOffset,J=O.data,F=O.reverseStackOrder,B=ON(R),K=B.numericAxisName,W=B.cateAxisName,X=jn(P,n),Y=YX(J,X,"".concat(K,"Id"),"".concat(W,"Id"),M,F),te=u.reduce(function($,V){var oe="".concat(V.axisType,"Map");return ie(ie({},$),{},ze({},oe,jne(O,ie(ie({},V),{},{graphicalItems:X,stackGroups:V.axisType===K&&Y,dataStartIndex:j,dataEndIndex:E}))))},{}),H=Pne(ie(ie({},te),{},{props:O,graphicalItems:X}),A==null?void 0:A.legendBBox);Object.keys(te).forEach(function($){te[$]=p(O,te[$],H,$.replace("Map",""),r)});var Q=te["".concat(W,"Map")],U=Cne(Q),I=g(O,ie(ie({},te),{},{dataStartIndex:j,dataEndIndex:E,updateId:T,graphicalItems:X,stackGroups:Y,offset:H}));return ie(ie({formattedGraphicalItems:I,graphicalItems:X,offset:H,stackGroups:Y},U),te)},x=(function(b){function S(A){var O,j,E;return fne(this,S),E=mne(this,S,[A]),ze(E,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),ze(E,"accessibilityManager",new Zre),ze(E,"handleLegendBBoxUpdate",function(T){if(T){var P=E.state,R=P.dataStartIndex,M=P.dataEndIndex,J=P.updateId;E.setState(ie({legendBBox:T},v({props:E.props,dataStartIndex:R,dataEndIndex:M,updateId:J},ie(ie({},E.state),{},{legendBBox:T}))))}}),ze(E,"handleReceiveSyncEvent",function(T,P,R){if(E.props.syncId===T){if(R===E.eventEmitterSymbol&&typeof E.props.syncMethod!="function")return;E.applySyncEvent(P)}}),ze(E,"handleBrushChange",function(T){var P=T.startIndex,R=T.endIndex;if(P!==E.state.dataStartIndex||R!==E.state.dataEndIndex){var M=E.state.updateId;E.setState(function(){return ie({dataStartIndex:P,dataEndIndex:R},v({props:E.props,dataStartIndex:P,dataEndIndex:R,updateId:M},E.state))}),E.triggerSyncEvent({dataStartIndex:P,dataEndIndex:R})}}),ze(E,"handleMouseEnter",function(T){var P=E.getMouseInfo(T);if(P){var R=ie(ie({},P),{},{isTooltipActive:!0});E.setState(R),E.triggerSyncEvent(R);var M=E.props.onMouseEnter;Je(M)&&M(R,T)}}),ze(E,"triggeredAfterMouseMove",function(T){var P=E.getMouseInfo(T),R=P?ie(ie({},P),{},{isTooltipActive:!0}):{isTooltipActive:!1};E.setState(R),E.triggerSyncEvent(R);var M=E.props.onMouseMove;Je(M)&&M(R,T)}),ze(E,"handleItemMouseEnter",function(T){E.setState(function(){return{isTooltipActive:!0,activeItem:T,activePayload:T.tooltipPayload,activeCoordinate:T.tooltipPosition||{x:T.cx,y:T.cy}}})}),ze(E,"handleItemMouseLeave",function(){E.setState(function(){return{isTooltipActive:!1}})}),ze(E,"handleMouseMove",function(T){T.persist(),E.throttleTriggeredAfterMouseMove(T)}),ze(E,"handleMouseLeave",function(T){E.throttleTriggeredAfterMouseMove.cancel();var P={isTooltipActive:!1};E.setState(P),E.triggerSyncEvent(P);var R=E.props.onMouseLeave;Je(R)&&R(P,T)}),ze(E,"handleOuterEvent",function(T){var P=z9(T),R=Tn(E.props,"".concat(P));if(P&&Je(R)){var M,J;/.*touch.*/i.test(P)?J=E.getMouseInfo(T.changedTouches[0]):J=E.getMouseInfo(T),R((M=J)!==null&&M!==void 0?M:{},T)}}),ze(E,"handleClick",function(T){var P=E.getMouseInfo(T);if(P){var R=ie(ie({},P),{},{isTooltipActive:!0});E.setState(R),E.triggerSyncEvent(R);var M=E.props.onClick;Je(M)&&M(R,T)}}),ze(E,"handleMouseDown",function(T){var P=E.props.onMouseDown;if(Je(P)){var R=E.getMouseInfo(T);P(R,T)}}),ze(E,"handleMouseUp",function(T){var P=E.props.onMouseUp;if(Je(P)){var R=E.getMouseInfo(T);P(R,T)}}),ze(E,"handleTouchMove",function(T){T.changedTouches!=null&&T.changedTouches.length>0&&E.throttleTriggeredAfterMouseMove(T.changedTouches[0])}),ze(E,"handleTouchStart",function(T){T.changedTouches!=null&&T.changedTouches.length>0&&E.handleMouseDown(T.changedTouches[0])}),ze(E,"handleTouchEnd",function(T){T.changedTouches!=null&&T.changedTouches.length>0&&E.handleMouseUp(T.changedTouches[0])}),ze(E,"handleDoubleClick",function(T){var P=E.props.onDoubleClick;if(Je(P)){var R=E.getMouseInfo(T);P(R,T)}}),ze(E,"handleContextMenu",function(T){var P=E.props.onContextMenu;if(Je(P)){var R=E.getMouseInfo(T);P(R,T)}}),ze(E,"triggerSyncEvent",function(T){E.props.syncId!==void 0&&Rb.emit(Ib,E.props.syncId,T,E.eventEmitterSymbol)}),ze(E,"applySyncEvent",function(T){var P=E.props,R=P.layout,M=P.syncMethod,J=E.state.updateId,F=T.dataStartIndex,B=T.dataEndIndex;if(T.dataStartIndex!==void 0||T.dataEndIndex!==void 0)E.setState(ie({dataStartIndex:F,dataEndIndex:B},v({props:E.props,dataStartIndex:F,dataEndIndex:B,updateId:J},E.state)));else if(T.activeTooltipIndex!==void 0){var K=T.chartX,W=T.chartY,X=T.activeTooltipIndex,Y=E.state,te=Y.offset,H=Y.tooltipTicks;if(!te)return;if(typeof M=="function")X=M(H,T);else if(M==="value"){X=-1;for(var Q=0;Q<H.length;Q++)if(H[Q].value===T.activeLabel){X=Q;break}}var U=ie(ie({},te),{},{x:te.left,y:te.top}),I=Math.min(K,U.x+U.width),$=Math.min(W,U.y+U.height),V=H[X]&&H[X].value,oe=kw(E.state,E.props.data,X),le=H[X]?{x:R==="horizontal"?H[X].coordinate:I,y:R==="horizontal"?$:H[X].coordinate}:kM;E.setState(ie(ie({},T),{},{activeLabel:V,activeCoordinate:le,activePayload:oe,activeTooltipIndex:X}))}else E.setState(T)}),ze(E,"renderCursor",function(T){var P,R=E.state,M=R.isTooltipActive,J=R.activeCoordinate,F=R.activePayload,B=R.offset,K=R.activeTooltipIndex,W=R.tooltipAxisBandSize,X=E.getTooltipEventType(),Y=(P=T.props.active)!==null&&P!==void 0?P:M,te=E.props.layout,H=T.key||"_recharts-cursor";return L.createElement(ane,{key:H,activeCoordinate:J,activePayload:F,activeTooltipIndex:K,chartName:r,element:T,isActive:Y,layout:te,offset:B,tooltipAxisBandSize:W,tooltipEventType:X})}),ze(E,"renderPolarAxis",function(T,P,R){var M=Tn(T,"type.axisType"),J=Tn(E.state,"".concat(M,"Map")),F=T.type.defaultProps,B=F!==void 0?ie(ie({},F),T.props):T.props,K=J&&J[B["".concat(M,"Id")]];return N.cloneElement(T,ie(ie({},K),{},{className:ot(M,K.className),key:T.key||"".concat(P,"-").concat(R),ticks:Wi(K,!0)}))}),ze(E,"renderPolarGrid",function(T){var P=T.props,R=P.radialLines,M=P.polarAngles,J=P.polarRadius,F=E.state,B=F.radiusAxisMap,K=F.angleAxisMap,W=Pa(B),X=Pa(K),Y=X.cx,te=X.cy,H=X.innerRadius,Q=X.outerRadius;return N.cloneElement(T,{polarAngles:Array.isArray(M)?M:Wi(X,!0).map(function(U){return U.coordinate}),polarRadius:Array.isArray(J)?J:Wi(W,!0).map(function(U){return U.coordinate}),cx:Y,cy:te,innerRadius:H,outerRadius:Q,key:T.key||"polar-grid",radialLines:R})}),ze(E,"renderLegend",function(){var T=E.state.formattedGraphicalItems,P=E.props,R=P.children,M=P.width,J=P.height,F=E.props.margin||{},B=M-(F.left||0)-(F.right||0),K=b$({children:R,formattedGraphicalItems:T,legendWidth:B,legendContent:d});if(!K)return null;var W=K.item,X=_N(K,one);return N.cloneElement(W,ie(ie({},X),{},{chartWidth:M,chartHeight:J,margin:F,onBBoxUpdate:E.handleLegendBBoxUpdate}))}),ze(E,"renderTooltip",function(){var T,P=E.props,R=P.children,M=P.accessibilityLayer,J=sn(R,ln);if(!J)return null;var F=E.state,B=F.isTooltipActive,K=F.activeCoordinate,W=F.activePayload,X=F.activeLabel,Y=F.offset,te=(T=J.props.active)!==null&&T!==void 0?T:B;return N.cloneElement(J,{viewBox:ie(ie({},Y),{},{x:Y.left,y:Y.top}),active:te,label:X,payload:te?W:[],coordinate:K,accessibilityLayer:M})}),ze(E,"renderBrush",function(T){var P=E.props,R=P.margin,M=P.data,J=E.state,F=J.offset,B=J.dataStartIndex,K=J.dataEndIndex,W=J.updateId;return N.cloneElement(T,{key:T.key||"_recharts-brush",onChange:wf(E.handleBrushChange,T.props.onChange),data:M,x:ge(T.props.x)?T.props.x:F.left,y:ge(T.props.y)?T.props.y:F.top+F.height+F.brushBottom-(R.bottom||0),width:ge(T.props.width)?T.props.width:F.width,startIndex:B,endIndex:K,updateId:"brush-".concat(W)})}),ze(E,"renderReferenceElement",function(T,P,R){if(!T)return null;var M=E,J=M.clipPathId,F=E.state,B=F.xAxisMap,K=F.yAxisMap,W=F.offset,X=T.type.defaultProps||{},Y=T.props,te=Y.xAxisId,H=te===void 0?X.xAxisId:te,Q=Y.yAxisId,U=Q===void 0?X.yAxisId:Q;return N.cloneElement(T,{key:T.key||"".concat(P,"-").concat(R),xAxis:B[H],yAxis:K[U],viewBox:{x:W.left,y:W.top,width:W.width,height:W.height},clipPathId:J})}),ze(E,"renderActivePoints",function(T){var P=T.item,R=T.activePoint,M=T.basePoint,J=T.childIndex,F=T.isRange,B=[],K=P.props.key,W=P.item.type.defaultProps!==void 0?ie(ie({},P.item.type.defaultProps),P.item.props):P.item.props,X=W.activeDot,Y=W.dataKey,te=ie(ie({index:J,dataKey:Y,cx:R.x,cy:R.y,r:4,fill:V1(P.item),strokeWidth:2,stroke:"#fff",payload:R.payload,value:R.value},it(X,!1)),Xf(X));return B.push(S.renderActiveDot(X,te,"".concat(K,"-activePoint-").concat(J))),M?B.push(S.renderActiveDot(X,ie(ie({},te),{},{cx:M.x,cy:M.y}),"".concat(K,"-basePoint-").concat(J))):F&&B.push(null),B}),ze(E,"renderGraphicChild",function(T,P,R){var M=E.filterFormatItem(T,P,R);if(!M)return null;var J=E.getTooltipEventType(),F=E.state,B=F.isTooltipActive,K=F.tooltipAxis,W=F.activeTooltipIndex,X=F.activeLabel,Y=E.props.children,te=sn(Y,ln),H=M.props,Q=H.points,U=H.isRange,I=H.baseLine,$=M.item.type.defaultProps!==void 0?ie(ie({},M.item.type.defaultProps),M.item.props):M.item.props,V=$.activeDot,oe=$.hide,le=$.activeBar,ve=$.activeShape,qe=!!(!oe&&B&&te&&(V||le||ve)),xe={};J!=="axis"&&te&&te.props.trigger==="click"?xe={onClick:wf(E.handleItemMouseEnter,T.props.onClick)}:J!=="axis"&&(xe={onMouseLeave:wf(E.handleItemMouseLeave,T.props.onMouseLeave),onMouseEnter:wf(E.handleItemMouseEnter,T.props.onMouseEnter)});var ae=N.cloneElement(T,ie(ie({},M.props),xe));function Se(_t){return typeof K.dataKey=="function"?K.dataKey(_t.payload):null}if(qe)if(W>=0){var Me,se;if(K.dataKey&&!K.allowDuplicatedCategory){var tt=typeof K.dataKey=="function"?Se:"payload.".concat(K.dataKey.toString());Me=Vf(Q,tt,X),se=U&&I&&Vf(I,tt,X)}else Me=Q==null?void 0:Q[W],se=U&&I&&I[W];if(ve||le){var Fe=T.props.activeIndex!==void 0?T.props.activeIndex:W;return[N.cloneElement(T,ie(ie(ie({},M.props),xe),{},{activeIndex:Fe})),null,null]}if(!et(Me))return[ae].concat(pl(E.renderActivePoints({item:M,activePoint:Me,basePoint:se,childIndex:W,isRange:U})))}else{var kt,wt=(kt=E.getItemByXY(E.state.activeCoordinate))!==null&&kt!==void 0?kt:{graphicalItem:ae},Et=wt.graphicalItem,Sr=Et.item,Ut=Sr===void 0?T:Sr,Rr=Et.childIndex,lr=ie(ie(ie({},M.props),xe),{},{activeIndex:Rr});return[N.cloneElement(Ut,lr),null,null]}return U?[ae,null,null]:[ae,null]}),ze(E,"renderCustomized",function(T,P,R){return N.cloneElement(T,ie(ie({key:"recharts-customized-".concat(R)},E.props),E.state))}),ze(E,"renderMap",{CartesianGrid:{handler:Of,once:!0},ReferenceArea:{handler:E.renderReferenceElement},ReferenceLine:{handler:Of},ReferenceDot:{handler:E.renderReferenceElement},XAxis:{handler:Of},YAxis:{handler:Of},Brush:{handler:E.renderBrush,once:!0},Bar:{handler:E.renderGraphicChild},Line:{handler:E.renderGraphicChild},Area:{handler:E.renderGraphicChild},Radar:{handler:E.renderGraphicChild},RadialBar:{handler:E.renderGraphicChild},Scatter:{handler:E.renderGraphicChild},Pie:{handler:E.renderGraphicChild},Funnel:{handler:E.renderGraphicChild},Tooltip:{handler:E.renderCursor,once:!0},PolarGrid:{handler:E.renderPolarGrid,once:!0},PolarAngleAxis:{handler:E.renderPolarAxis},PolarRadiusAxis:{handler:E.renderPolarAxis},Customized:{handler:E.renderCustomized}}),E.clipPathId="".concat((O=A.id)!==null&&O!==void 0?O:Lu("recharts"),"-clip"),E.throttleTriggeredAfterMouseMove=bI(E.triggeredAfterMouseMove,(j=A.throttleDelay)!==null&&j!==void 0?j:1e3/60),E.state={},E}return vne(S,b),pne(S,[{key:"componentDidMount",value:function(){var O,j;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(O=this.props.margin.left)!==null&&O!==void 0?O:0,top:(j=this.props.margin.top)!==null&&j!==void 0?j:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var O=this.props,j=O.children,E=O.data,T=O.height,P=O.layout,R=sn(j,ln);if(R){var M=R.props.defaultIndex;if(!(typeof M!="number"||M<0||M>this.state.tooltipTicks.length-1)){var J=this.state.tooltipTicks[M]&&this.state.tooltipTicks[M].value,F=kw(this.state,E,M,J),B=this.state.tooltipTicks[M].coordinate,K=(this.state.offset.top+T)/2,W=P==="horizontal",X=W?{x:B,y:K}:{y:B,x:K},Y=this.state.formattedGraphicalItems.find(function(H){var Q=H.item;return Q.type.name==="Scatter"});Y&&(X=ie(ie({},X),Y.props.points[M].tooltipPosition),F=Y.props.points[M].tooltipPayload);var te={activeTooltipIndex:M,isTooltipActive:!0,activeLabel:J,activePayload:F,activeCoordinate:X};this.setState(te),this.renderCursor(R),this.accessibilityManager.setIndex(M)}}}},{key:"getSnapshotBeforeUpdate",value:function(O,j){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==j.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==O.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==O.margin){var E,T;this.accessibilityManager.setDetails({offset:{left:(E=this.props.margin.left)!==null&&E!==void 0?E:0,top:(T=this.props.margin.top)!==null&&T!==void 0?T:0}})}return null}},{key:"componentDidUpdate",value:function(O){cx([sn(O.children,ln)],[sn(this.props.children,ln)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var O=sn(this.props.children,ln);if(O&&typeof O.props.shared=="boolean"){var j=O.props.shared?"axis":"item";return c.indexOf(j)>=0?j:a}return a}},{key:"getMouseInfo",value:function(O){if(!this.container)return null;var j=this.container,E=j.getBoundingClientRect(),T=OW(E),P={chartX:Math.round(O.pageX-T.left),chartY:Math.round(O.pageY-T.top)},R=E.width/j.offsetWidth||1,M=this.inRange(P.chartX,P.chartY,R);if(!M)return null;var J=this.state,F=J.xAxisMap,B=J.yAxisMap,K=this.getTooltipEventType(),W=kN(this.state,this.props.data,this.props.layout,M);if(K!=="axis"&&F&&B){var X=Pa(F).scale,Y=Pa(B).scale,te=X&&X.invert?X.invert(P.chartX):null,H=Y&&Y.invert?Y.invert(P.chartY):null;return ie(ie({},P),{},{xValue:te,yValue:H},W)}return W?ie(ie({},P),W):null}},{key:"inRange",value:function(O,j){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,T=this.props.layout,P=O/E,R=j/E;if(T==="horizontal"||T==="vertical"){var M=this.state.offset,J=P>=M.left&&P<=M.left+M.width&&R>=M.top&&R<=M.top+M.height;return J?{x:P,y:R}:null}var F=this.state,B=F.angleAxisMap,K=F.radiusAxisMap;if(B&&K){var W=Pa(B);return Uj({x:P,y:R},W)}return null}},{key:"parseEventsOfWrapper",value:function(){var O=this.props.children,j=this.getTooltipEventType(),E=sn(O,ln),T={};E&&j==="axis"&&(E.props.trigger==="click"?T={onClick:this.handleClick}:T={onMouseEnter:this.handleMouseEnter,onDoubleClick:this.handleDoubleClick,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,onTouchEnd:this.handleTouchEnd,onContextMenu:this.handleContextMenu});var P=Xf(this.props,this.handleOuterEvent);return ie(ie({},P),T)}},{key:"addListener",value:function(){Rb.on(Ib,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){Rb.removeListener(Ib,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(O,j,E){for(var T=this.state.formattedGraphicalItems,P=0,R=T.length;P<R;P++){var M=T[P];if(M.item===O||M.props.key===O.key||j===Gi(M.item.type)&&E===M.childIndex)return M}return null}},{key:"renderClipPath",value:function(){var O=this.clipPathId,j=this.state.offset,E=j.left,T=j.top,P=j.height,R=j.width;return L.createElement("defs",null,L.createElement("clipPath",{id:O},L.createElement("rect",{x:E,y:T,height:P,width:R})))}},{key:"getXScales",value:function(){var O=this.state.xAxisMap;return O?Object.entries(O).reduce(function(j,E){var T=wN(E,2),P=T[0],R=T[1];return ie(ie({},j),{},ze({},P,R.scale))},{}):null}},{key:"getYScales",value:function(){var O=this.state.yAxisMap;return O?Object.entries(O).reduce(function(j,E){var T=wN(E,2),P=T[0],R=T[1];return ie(ie({},j),{},ze({},P,R.scale))},{}):null}},{key:"getXScaleByAxisId",value:function(O){var j;return(j=this.state.xAxisMap)===null||j===void 0||(j=j[O])===null||j===void 0?void 0:j.scale}},{key:"getYScaleByAxisId",value:function(O){var j;return(j=this.state.yAxisMap)===null||j===void 0||(j=j[O])===null||j===void 0?void 0:j.scale}},{key:"getItemByXY",value:function(O){var j=this.state,E=j.formattedGraphicalItems,T=j.activeItem;if(E&&E.length)for(var P=0,R=E.length;P<R;P++){var M=E[P],J=M.props,F=M.item,B=F.type.defaultProps!==void 0?ie(ie({},F.type.defaultProps),F.props):F.props,K=Gi(F.type);if(K==="Bar"){var W=(J.data||[]).find(function(H){return KZ(O,H)});if(W)return{graphicalItem:M,payload:W}}else if(K==="RadialBar"){var X=(J.data||[]).find(function(H){return Uj(O,H)});if(X)return{graphicalItem:M,payload:X}}else if(Np(M,T)||Pp(M,T)||_u(M,T)){var Y=LQ({graphicalItem:M,activeTooltipItem:T,itemData:B.data}),te=B.activeIndex===void 0?Y:B.activeIndex;return{graphicalItem:ie(ie({},M),{},{childIndex:te}),payload:_u(M,T)?B.data[Y]:M.props.data[Y]}}}return null}},{key:"render",value:function(){var O=this;if(!ZO(this))return null;var j=this.props,E=j.children,T=j.className,P=j.width,R=j.height,M=j.style,J=j.compact,F=j.title,B=j.desc,K=_N(j,sne),W=it(K,!1);if(J)return L.createElement(rN,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},L.createElement(dx,Ls({},W,{width:P,height:R,title:F,desc:B}),this.renderClipPath(),eA(E,this.renderMap)));if(this.props.accessibilityLayer){var X,Y;W.tabIndex=(X=this.props.tabIndex)!==null&&X!==void 0?X:0,W.role=(Y=this.props.role)!==null&&Y!==void 0?Y:"application",W.onKeyDown=function(H){O.accessibilityManager.keyboardEvent(H)},W.onFocus=function(){O.accessibilityManager.focus()}}var te=this.parseEventsOfWrapper();return L.createElement(rN,{state:this.state,width:this.props.width,height:this.props.height,clipPathId:this.clipPathId},L.createElement("div",Ls({className:ot("recharts-wrapper",T),style:ie({position:"relative",cursor:"default",width:P,height:R},M)},te,{ref:function(Q){O.container=Q}}),L.createElement(dx,Ls({},W,{width:P,height:R,title:F,desc:B,style:kne}),this.renderClipPath(),eA(E,this.renderMap)),this.renderLegend(),this.renderTooltip()))}}])})(N.Component);ze(x,"displayName",r),ze(x,"defaultProps",ie({layout:"horizontal",stackOffset:"none",barCategoryGap:"10%",barGap:4,margin:{top:5,right:5,bottom:5,left:5},reverseStackOrder:!1,syncMethod:"index"},f)),ze(x,"getDerivedStateFromProps",function(b,S){var A=b.dataKey,O=b.data,j=b.children,E=b.width,T=b.height,P=b.layout,R=b.stackOffset,M=b.margin,J=S.dataStartIndex,F=S.dataEndIndex;if(S.updateId===void 0){var B=EN(b);return ie(ie(ie({},B),{},{updateId:0},v(ie(ie({props:b},B),{},{updateId:0}),S)),{},{prevDataKey:A,prevData:O,prevWidth:E,prevHeight:T,prevLayout:P,prevStackOffset:R,prevMargin:M,prevChildren:j})}if(A!==S.prevDataKey||O!==S.prevData||E!==S.prevWidth||T!==S.prevHeight||P!==S.prevLayout||R!==S.prevStackOffset||!Us(M,S.prevMargin)){var K=EN(b),W={chartX:S.chartX,chartY:S.chartY,isTooltipActive:S.isTooltipActive},X=ie(ie({},kN(S,O,P)),{},{updateId:S.updateId+1}),Y=ie(ie(ie({},K),W),X);return ie(ie(ie({},Y),v(ie({props:b},Y),S)),{},{prevDataKey:A,prevData:O,prevWidth:E,prevHeight:T,prevLayout:P,prevStackOffset:R,prevMargin:M,prevChildren:j})}if(!cx(j,S.prevChildren)){var te,H,Q,U,I=sn(j,il),$=I&&(te=(H=I.props)===null||H===void 0?void 0:H.startIndex)!==null&&te!==void 0?te:J,V=I&&(Q=(U=I.props)===null||U===void 0?void 0:U.endIndex)!==null&&Q!==void 0?Q:F,oe=$!==J||V!==F,le=!et(O),ve=le&&!oe?S.updateId:S.updateId+1;return ie(ie({updateId:ve},v(ie(ie({props:b},S),{},{updateId:ve,dataStartIndex:$,dataEndIndex:V}),S)),{},{prevChildren:j,dataStartIndex:$,dataEndIndex:V})}return null}),ze(x,"renderActiveDot",function(b,S,A){var O;return N.isValidElement(b)?O=N.cloneElement(b,S):Je(b)?O=b(S):O=L.createElement(Y1,S),L.createElement(Xt,{className:"recharts-active-dot",key:A},O)});var w=N.forwardRef(function(S,A){return L.createElement(x,Ls({},S,{ref:A}))});return w.displayName=x.displayName,w},Ine=OM({chartName:"LineChart",GraphicalChild:Hu,axisComponents:[{axisType:"xAxis",AxisComp:Ba},{axisType:"yAxis",AxisComp:Ua}],formatAxisMap:W$}),Ew=OM({chartName:"BarChart",GraphicalChild:ea,defaultTooltipEventType:"axis",validateTooltipEventTypes:["axis","item"],axisComponents:[{axisType:"xAxis",AxisComp:Ba},{axisType:"yAxis",AxisComp:Ua}],formatAxisMap:W$});const Kh={backgroundColor:"#1e1e1e",border:"1px solid rgba(255,255,255,0.08)",borderRadius:"12px",color:"#e4e0dc",fontSize:"11px",fontFamily:"JetBrains Mono, monospace"};function It(t){return t>=1e6?`${(t/1e6).toFixed(2)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(Math.round(t))}function Zn(t){return`$${t.toFixed(2)}`}function $a({label:t,value:e,sub:r,accent:n}){return y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl px-5 py-4",children:[y.jsx("p",{className:"text-[11px] font-mono text-zinc-600 mb-1",children:t}),y.jsx("p",{className:`text-xl font-mono font-medium ${n?"text-[#E43A9C]":"text-zinc-100"}`,children:e}),r&&y.jsx("p",{className:"text-[10px] font-mono text-zinc-600 mt-0.5",children:r})]})}const $ne={summary:"Summary","by squad":"By Squad","by agent":"By Agent",io:"IO",timeline:"Timeline"};function Mne({tabs:t,active:e,onChange:r}){return y.jsx("div",{className:"flex gap-0 border-b border-white/[0.06] mb-5",children:t.map(n=>y.jsx("button",{type:"button",onClick:()=>r(n),className:`px-4 py-2 text-[11px] font-mono transition-colors border-b-2 -mb-px cursor-pointer ${e===n?"text-[#E43A9C] border-[#E43A9C]":"text-zinc-600 hover:text-zinc-300 border-transparent"}`,children:$ne[n]??n},n))})}function Lne({records:t,totals:e}){const r=e.totalInputTokens+e.totalOutputTokens,n=new Map;for(const o of t){const c=o.squadId??"__io__",u=o.squadName??(o.squadId?`${o.squadId.slice(0,8)} (deleted)`:"IO Orchestrator"),d=n.get(c)??{name:u,inputTokens:0,outputTokens:0,calls:0,cost:0};d.inputTokens+=o.inputTokens,d.outputTokens+=o.outputTokens,d.calls+=1,d.cost+=o.estimatedCostUsd??0,n.set(c,d)}const i=Array.from(n.values()).sort((o,c)=>c.cost-o.cost),a=i.map(o=>({name:o.name.length>12?`${o.name.slice(0,12)}…`:o.name,cost:Number.parseFloat(o.cost.toFixed(2)),tokens:Math.round((o.inputTokens+o.outputTokens)/1e3)}));return y.jsxs("div",{className:"space-y-5",children:[y.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[y.jsx($a,{label:"Total Tokens",value:It(r),sub:`${It(e.totalInputTokens)} in · ${It(e.totalOutputTokens)} out`}),y.jsx($a,{label:"Total Cost",value:Zn(e.totalCostUsd),accent:!0}),y.jsx($a,{label:"API Calls",value:It(e.callCount),sub:"across all entities"}),y.jsx($a,{label:"Avg Cost / Call",value:e.callCount>0?Zn(e.totalCostUsd/e.callCount):"$0.00",sub:`over ${e.callCount} calls`})]}),y.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:[y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl p-4",children:[y.jsx("p",{className:"text-[11px] font-mono text-zinc-500 mb-3",children:"Cost by entity"}),a.length>0?y.jsx(oh,{width:"100%",height:180,children:y.jsxs(Ew,{data:a,barCategoryGap:"35%",children:[y.jsx(Au,{vertical:!1,stroke:"rgba(255,255,255,0.04)"}),y.jsx(Ba,{dataKey:"name",tick:{fill:"#52525b",fontSize:10,fontFamily:"JetBrains Mono, monospace"},axisLine:!1,tickLine:!1}),y.jsx(Ua,{tick:{fill:"#52525b",fontSize:10,fontFamily:"JetBrains Mono, monospace"},axisLine:!1,tickLine:!1,tickFormatter:o=>`$${o}`,width:40}),y.jsx(ln,{contentStyle:Kh,cursor:{fill:"rgba(255,255,255,0.03)"},formatter:o=>[`$${o.toFixed(2)}`,"Cost"]}),y.jsx(ea,{dataKey:"cost",fill:"url(#costGrad)",radius:[6,6,0,0]}),y.jsx("defs",{children:y.jsxs("linearGradient",{id:"costGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[y.jsx("stop",{offset:"0%",stopColor:"#E43A9C"}),y.jsx("stop",{offset:"100%",stopColor:"#D83333",stopOpacity:.7})]})})]})}):y.jsx("div",{className:"h-[180px] flex items-center justify-center text-zinc-700 text-[11px] font-mono",children:"No data"})]}),y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl p-4",children:[y.jsx("p",{className:"text-[11px] font-mono text-zinc-500 mb-3",children:"Tokens by entity (k)"}),a.length>0?y.jsx(oh,{width:"100%",height:180,children:y.jsxs(Ew,{data:a,barCategoryGap:"35%",children:[y.jsx(Au,{vertical:!1,stroke:"rgba(255,255,255,0.04)"}),y.jsx(Ba,{dataKey:"name",tick:{fill:"#52525b",fontSize:10,fontFamily:"JetBrains Mono, monospace"},axisLine:!1,tickLine:!1}),y.jsx(Ua,{tick:{fill:"#52525b",fontSize:10,fontFamily:"JetBrains Mono, monospace"},axisLine:!1,tickLine:!1,tickFormatter:o=>`${o}k`,width:40}),y.jsx(ln,{contentStyle:Kh,cursor:{fill:"rgba(255,255,255,0.03)"},formatter:o=>[`${o}k`,"Tokens"]}),y.jsx(ea,{dataKey:"tokens",fill:"url(#tokenGrad)",radius:[6,6,0,0]}),y.jsx("defs",{children:y.jsxs("linearGradient",{id:"tokenGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[y.jsx("stop",{offset:"0%",stopColor:"#818cf8"}),y.jsx("stop",{offset:"100%",stopColor:"#6366f1",stopOpacity:.7})]})})]})}):y.jsx("div",{className:"h-[180px] flex items-center justify-center text-zinc-700 text-[11px] font-mono",children:"No data"})]})]}),y.jsx("div",{className:"overflow-auto rounded-2xl border border-white/[0.07] glass-card",children:y.jsxs("table",{className:"w-full text-[11px] font-mono",children:[y.jsx("thead",{children:y.jsx("tr",{className:"border-b border-white/[0.06] bg-[#1a1a1a]",children:["Entity","Input","Output","Calls","Cost"].map(o=>y.jsx("th",{className:`text-left px-4 py-2.5 text-zinc-600 font-medium ${o==="Cost"?"text-right":""}`,children:o},o))})}),y.jsxs("tbody",{children:[i.map(o=>y.jsxs("tr",{className:"border-b border-white/[0.04] hover:bg-white/[0.015] transition-colors",children:[y.jsx("td",{className:"px-4 py-3 text-zinc-300",children:o.name}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:It(o.inputTokens)}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:It(o.outputTokens)}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:o.calls}),y.jsx("td",{className:"px-4 py-3 text-right text-[#E43A9C]",children:Zn(o.cost)})]},o.name)),y.jsxs("tr",{className:"bg-[#1a1a1a]",children:[y.jsx("td",{className:"px-4 py-3 text-zinc-200 font-medium",children:"Total"}),y.jsx("td",{className:"px-4 py-3 text-zinc-300",children:It(e.totalInputTokens)}),y.jsx("td",{className:"px-4 py-3 text-zinc-300",children:It(e.totalOutputTokens)}),y.jsx("td",{className:"px-4 py-3 text-zinc-300",children:e.callCount}),y.jsx("td",{className:"px-4 py-3 text-right text-[#E43A9C] font-medium",children:Zn(e.totalCostUsd)})]})]})]})})]})}function Dne({records:t}){const[e,r]=N.useState([]),[n,i]=N.useState("cost"),[a,o]=N.useState("desc");function c(f){f===n?o(g=>g==="asc"?"desc":"asc"):(i(f),o("desc"))}const u=N.useMemo(()=>{const f=new Map;for(const v of t){if(!v.squadId)continue;const x=f.get(v.squadId)??{id:v.squadId,name:v.squadName??`${v.squadId.slice(0,8)} (deleted)`,agents:new Map,inputTokens:0,outputTokens:0,calls:0,cost:0};x.inputTokens+=v.inputTokens,x.outputTokens+=v.outputTokens,x.calls+=1,x.cost+=v.estimatedCostUsd??0;const w=`${v.agentRole??"unknown"}:${v.model}`,b=x.agents.get(w)??{role:v.agentRole??"unknown",model:v.model,inputTokens:0,outputTokens:0,calls:0,cost:0};b.inputTokens+=v.inputTokens,b.outputTokens+=v.outputTokens,b.calls+=1,b.cost+=v.estimatedCostUsd??0,x.agents.set(w,b),f.set(v.squadId,x)}return[...Array.from(f.values())].sort((v,x)=>{const w=v[n],b=x[n],S=typeof w=="string"?w.localeCompare(b):w-b;return a==="desc"?-S:S})},[t,n,a]),d=f=>r(g=>g.includes(f)?g.filter(v=>v!==f):[...g,f]),p=[{key:"name",label:"Squad"},{key:"inputTokens",label:"In"},{key:"outputTokens",label:"Out"},{key:"calls",label:"Calls"},{key:"cost",label:"Cost"}];return u.length===0?y.jsx("div",{className:"text-center py-12 text-zinc-700 text-[11px] font-mono",children:"No squad usage data"}):y.jsxs("div",{className:"space-y-2",children:[y.jsxs("div",{className:"flex items-center gap-1 px-1 mb-1",children:[y.jsx("span",{className:"text-[10px] font-mono text-zinc-700 mr-1",children:"sort by"}),p.map(f=>y.jsxs("button",{type:"button",onClick:()=>c(f.key),className:`flex items-center gap-0.5 px-2 py-1 rounded-lg text-[10px] font-mono transition-colors ${n===f.key?"text-[#E43A9C]":"text-zinc-600 hover:text-zinc-400 hover:bg-white/[0.04]"}`,style:n===f.key?{background:"rgba(228,58,156,0.1)"}:void 0,children:[f.label,n===f.key&&y.jsx("span",{className:"text-[9px]",children:a==="desc"?"↓":"↑"})]},f.key))]}),u.map(f=>{const g=e.includes(f.id),v=Array.from(f.agents.values());return y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl overflow-hidden",children:[y.jsxs("button",{type:"button",onClick:()=>d(f.id),className:"w-full flex items-center gap-3 px-4 py-3.5 hover:bg-white/[0.02] transition-colors text-left cursor-pointer",children:[y.jsx("div",{className:`transition-transform ${g?"rotate-90":""}`,children:y.jsx(Mw,{className:"w-3.5 h-3.5 text-zinc-600"})}),y.jsx("span",{className:"text-sm font-mono text-zinc-100 flex-1",children:f.name}),y.jsxs("div",{className:"flex items-center gap-6 text-[11px] font-mono",children:[y.jsxs("span",{className:"text-zinc-500 hidden sm:block",children:[y.jsx("span",{className:"text-zinc-700 mr-1",children:"in"}),It(f.inputTokens)]}),y.jsxs("span",{className:"text-zinc-500 hidden sm:block",children:[y.jsx("span",{className:"text-zinc-700 mr-1",children:"out"}),It(f.outputTokens)]}),y.jsxs("span",{className:"text-zinc-500",children:[y.jsx("span",{className:"text-zinc-700 mr-1",children:"calls"}),f.calls]}),y.jsx("span",{className:"text-[#E43A9C] font-medium w-16 text-right",children:Zn(f.cost)})]})]}),g&&y.jsx("div",{className:"border-t border-white/[0.05]",children:y.jsxs("table",{className:"w-full text-[11px] font-mono",children:[y.jsx("thead",{children:y.jsx("tr",{className:"bg-[#191919]",children:["Agent","Model","Input","Output","Calls","Cost"].map(x=>y.jsx("th",{className:`text-left px-4 py-2 text-zinc-700 font-medium ${x==="Cost"?"text-right":""}`,children:x},x))})}),y.jsx("tbody",{children:v.map(x=>y.jsxs("tr",{className:"border-t border-white/[0.04] hover:bg-white/[0.015] transition-colors",children:[y.jsx("td",{className:"px-4 py-2.5 text-zinc-300",children:x.role}),y.jsx("td",{className:"px-4 py-2.5 text-zinc-600",children:x.model}),y.jsx("td",{className:"px-4 py-2.5 text-zinc-500",children:It(x.inputTokens)}),y.jsx("td",{className:"px-4 py-2.5 text-zinc-500",children:It(x.outputTokens)}),y.jsx("td",{className:"px-4 py-2.5 text-zinc-500",children:x.calls}),y.jsx("td",{className:"px-4 py-2.5 text-right text-[#E43A9C]",children:Zn(x.cost)})]},x.role))})]})})]},f.id)})]})}function zne({records:t}){const e=N.useMemo(()=>{const n=new Map;for(const i of t){const a=`${i.squadId??"io"}:${i.agentRole??"orchestrator"}:${i.model}`,o=n.get(a)??{name:i.agentRole??"orchestrator",squad:i.squadName??(i.squadId?i.squadId.slice(0,8):"IO"),model:i.model,inputTokens:0,outputTokens:0,calls:0,cost:0};o.inputTokens+=i.inputTokens,o.outputTokens+=i.outputTokens,o.calls+=1,o.cost+=i.estimatedCostUsd??0,n.set(a,o)}return Array.from(n.values()).sort((i,a)=>a.cost-i.cost)},[t]),r=e.reduce((n,i)=>n+i.cost,0);return y.jsx("div",{className:"overflow-auto rounded-2xl border border-white/[0.07] glass-card",children:y.jsxs("table",{className:"w-full text-[11px] font-mono",children:[y.jsx("thead",{children:y.jsx("tr",{className:"border-b border-white/[0.06] bg-[#1a1a1a]",children:["Agent","Squad","Model","Input","Output","Calls","Cost","% of total"].map(n=>y.jsx("th",{className:`text-left px-4 py-2.5 text-zinc-600 font-medium ${n==="Cost"?"text-right":""}`,children:n},n))})}),y.jsx("tbody",{children:e.map(n=>y.jsxs("tr",{className:"border-b border-white/[0.04] hover:bg-white/[0.015] transition-colors",children:[y.jsx("td",{className:"px-4 py-3 text-zinc-300",children:n.name}),y.jsx("td",{className:"px-4 py-3 text-zinc-600",children:n.squad}),y.jsx("td",{className:"px-4 py-3 text-zinc-600",children:n.model}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:It(n.inputTokens)}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:It(n.outputTokens)}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:n.calls}),y.jsx("td",{className:"px-4 py-3 text-right text-[#E43A9C]",children:Zn(n.cost)}),y.jsx("td",{className:"px-4 py-3",children:y.jsxs("div",{className:"flex items-center gap-2",children:[y.jsx("div",{className:"w-16 h-1.5 rounded-full bg-[#252525] overflow-hidden",children:y.jsx("div",{className:"h-full bg-[#E43A9C] rounded-full",style:{width:`${r>0?n.cost/r*100:0}%`}})}),y.jsx("span",{className:"text-zinc-600 text-[10px]",children:r>0?`${(n.cost/r*100).toFixed(1)}%`:"0%"})]})})]},`${n.squad}:${n.name}`))})]})})}function Bne({records:t}){const e=N.useMemo(()=>t.filter(o=>!o.squadId),[t]),r=N.useMemo(()=>{const o=new Map;for(const c of e){const u=`${c.agentRole??"orchestrator"}:${c.model}`,d=o.get(u)??{name:c.agentRole??"orchestrator",model:c.model,inputTokens:0,outputTokens:0,calls:0,cost:0};d.inputTokens+=c.inputTokens,d.outputTokens+=c.outputTokens,d.calls+=1,d.cost+=c.estimatedCostUsd??0,o.set(u,d)}return Array.from(o.values()).sort((c,u)=>u.cost-c.cost)},[e]),n=e.reduce((o,c)=>o+c.inputTokens,0),i=e.reduce((o,c)=>o+c.outputTokens,0),a=e.reduce((o,c)=>o+(c.estimatedCostUsd??0),0);return y.jsxs("div",{className:"space-y-5",children:[y.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[y.jsx($a,{label:"IO Tokens",value:It(n+i),sub:`${It(n)} in · ${It(i)} out`}),y.jsx($a,{label:"IO Cost",value:Zn(a),accent:!0}),y.jsx($a,{label:"IO Calls",value:It(e.length)}),y.jsx($a,{label:"IO Roles",value:String(r.length)})]}),y.jsx("div",{className:"overflow-auto rounded-2xl border border-white/[0.07] glass-card",children:y.jsxs("table",{className:"w-full text-[11px] font-mono",children:[y.jsx("thead",{children:y.jsx("tr",{className:"border-b border-white/[0.06] bg-[#1a1a1a]",children:["Role","Model","Input","Output","Calls","Cost"].map(o=>y.jsx("th",{className:`text-left px-4 py-2.5 text-zinc-600 font-medium ${o==="Cost"?"text-right":""}`,children:o},o))})}),y.jsx("tbody",{children:r.map(o=>y.jsxs("tr",{className:"border-b border-white/[0.04] hover:bg-white/[0.015] transition-colors",children:[y.jsx("td",{className:"px-4 py-3 text-zinc-300",children:o.name}),y.jsx("td",{className:"px-4 py-3 text-zinc-600",children:o.model}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:It(o.inputTokens)}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:It(o.outputTokens)}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:o.calls}),y.jsx("td",{className:"px-4 py-3 text-right text-[#E43A9C]",children:Zn(o.cost)})]},o.name))})]})})]})}function Une({records:t}){const e=qa(),r=N.useMemo(()=>{const i=new Map;for(const a of t){const o=a.timestamp.slice(0,10),c=i.get(o)??{date:o,inputTokens:0,outputTokens:0,cost:0,calls:0};c.inputTokens+=a.inputTokens,c.outputTokens+=a.outputTokens,c.cost+=a.estimatedCostUsd??0,c.calls+=1,i.set(o,c)}return Array.from(i.values()).sort((a,o)=>a.date.localeCompare(o.date))},[t]),n=r.map(i=>({...i,label:ez(i.date,e),tokens:i.inputTokens+i.outputTokens}));return y.jsxs("div",{className:"space-y-5",children:[y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl p-5",children:[y.jsx("p",{className:"text-[11px] font-mono text-zinc-500 mb-3",children:"Tokens per day"}),n.length>0?y.jsx(oh,{width:"100%",height:220,children:y.jsxs(Ine,{data:n,children:[y.jsx(Au,{vertical:!1,stroke:"rgba(255,255,255,0.04)"}),y.jsx(Ba,{dataKey:"label",tick:{fill:"#52525b",fontSize:10,fontFamily:"JetBrains Mono, monospace"},axisLine:!1,tickLine:!1}),y.jsx(Ua,{tick:{fill:"#52525b",fontSize:10,fontFamily:"JetBrains Mono, monospace"},axisLine:!1,tickLine:!1,tickFormatter:It,width:44}),y.jsx(ln,{contentStyle:Kh,cursor:{fill:"rgba(255,255,255,0.03)"},formatter:i=>[It(i),"Tokens"]}),y.jsx(Hu,{type:"monotone",dataKey:"tokens",stroke:"#E43A9C",strokeWidth:2,dot:!1})]})}):y.jsx("div",{className:"h-[220px] flex items-center justify-center text-zinc-700 text-[11px] font-mono",children:"No data"})]}),y.jsxs("div",{className:"glass-card border border-white/[0.07] rounded-2xl p-5",children:[y.jsx("p",{className:"text-[11px] font-mono text-zinc-500 mb-3",children:"Cost per day"}),n.length>0?y.jsx(oh,{width:"100%",height:180,children:y.jsxs(Ew,{data:n,barCategoryGap:"20%",children:[y.jsx(Au,{vertical:!1,stroke:"rgba(255,255,255,0.04)"}),y.jsx(Ba,{dataKey:"label",tick:{fill:"#52525b",fontSize:10,fontFamily:"JetBrains Mono, monospace"},axisLine:!1,tickLine:!1}),y.jsx(Ua,{tick:{fill:"#52525b",fontSize:10,fontFamily:"JetBrains Mono, monospace"},axisLine:!1,tickLine:!1,tickFormatter:i=>`$${i.toFixed(2)}`,width:44}),y.jsx(ln,{contentStyle:Kh,cursor:{fill:"rgba(255,255,255,0.03)"},formatter:i=>[Zn(i),"Cost"]}),y.jsx(ea,{dataKey:"cost",fill:"url(#costGradTl)",radius:[4,4,0,0]}),y.jsx("defs",{children:y.jsxs("linearGradient",{id:"costGradTl",x1:"0",y1:"0",x2:"0",y2:"1",children:[y.jsx("stop",{offset:"0%",stopColor:"#E43A9C"}),y.jsx("stop",{offset:"100%",stopColor:"#D83333",stopOpacity:.7})]})})]})}):y.jsx("div",{className:"h-[180px] flex items-center justify-center text-zinc-700 text-[11px] font-mono",children:"No data"})]}),y.jsx("div",{className:"overflow-auto rounded-2xl border border-white/[0.07] glass-card",children:y.jsxs("table",{className:"w-full text-[11px] font-mono",children:[y.jsx("thead",{children:y.jsx("tr",{className:"border-b border-white/[0.06] bg-[#1a1a1a]",children:["Date","Input","Output","Calls","Cost"].map(i=>y.jsx("th",{className:`text-left px-4 py-2.5 text-zinc-600 font-medium ${i==="Cost"?"text-right":""}`,children:i},i))})}),y.jsx("tbody",{children:r.map(i=>y.jsxs("tr",{className:"border-b border-white/[0.04] hover:bg-white/[0.015] transition-colors",children:[y.jsx("td",{className:"px-4 py-3 text-zinc-300",children:i.date}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:It(i.inputTokens)}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:It(i.outputTokens)}),y.jsx("td",{className:"px-4 py-3 text-zinc-500",children:i.calls}),y.jsx("td",{className:"px-4 py-3 text-right text-[#E43A9C]",children:Zn(i.cost)})]},i.date))})]})})]})}function qne(){const[t,e]=N.useState("summary"),[r,n]=N.useState(null),[i,a]=N.useState("14d"),o=["summary","by squad","by agent","io","timeline"];if(N.useEffect(()=>{const u=new Date;i==="7d"?u.setDate(u.getDate()-7):i==="14d"?u.setDate(u.getDate()-14):i==="30d"?u.setDate(u.getDate()-30):u.setDate(u.getDate()-1),Ve.get(`/usage?since=${u.toISOString()}`).then(n).catch(()=>{})},[i]),!r)return y.jsx("div",{className:"h-full flex items-center justify-center text-zinc-600 font-mono text-[11px]",children:"Loading..."});const c=i==="1d"?"Today":`Last ${i}`;return y.jsxs("div",{className:"flex-1 overflow-y-auto p-6",children:[y.jsxs("div",{className:"flex items-start justify-between mb-5 gap-4 flex-wrap",children:[y.jsxs("div",{children:[y.jsx("h2",{className:"text-2xl tracking-wide text-zinc-100",style:{fontFamily:"'Bebas Neue', sans-serif"},children:"Usage"}),y.jsx("p",{className:"text-[11px] text-zinc-600 font-mono mt-0.5",children:c})]}),y.jsx("div",{className:"flex gap-1 p-1 rounded-xl bg-white/[0.03] border border-white/[0.07]",children:["1d","7d","14d","30d"].map(u=>y.jsx("button",{type:"button",onClick:()=>a(u),className:`px-3 py-1.5 rounded-lg text-[11px] font-mono transition-colors cursor-pointer ${i===u?"text-[#E43A9C]":"text-zinc-600 hover:text-zinc-400"}`,style:i===u?{background:"rgba(228,58,156,0.12)"}:void 0,children:u},u))})]}),y.jsx(Mne,{tabs:o,active:t,onChange:u=>e(u)}),t==="summary"&&y.jsx(Lne,{records:r.records,totals:r.totals}),t==="by squad"&&y.jsx(Dne,{records:r.records}),t==="by agent"&&y.jsx(zne,{records:r.records}),t==="io"&&y.jsx(Bne,{records:r.records}),t==="timeline"&&y.jsx(Une,{records:r.records})]})}function AM(t){return[...t].sort((e,r)=>e.isDir!==r.isDir?e.isDir?-1:1:e.name.localeCompare(r.name)).map(e=>({...e,children:AM(e.children)}))}function Fne(t){const e=[];for(const r of t){const n=r.path.split("/").filter(Boolean);let i=e,a="";if(r.isDir){for(const o of n){a=a?`${a}/${o}`:o;let c=i.find(u=>u.path===a);c||(c={name:o,path:a,isDir:!0,children:[]},i.push(c)),i=c.children}continue}for(const[o,c]of n.entries()){const u=o===n.length-1;a=a?`${a}/${c}`:c;let d=i.find(p=>p.path===a);d||(d={name:u&&r.name||c,path:a,isDir:!u,children:[]},i.push(d)),i=d.children}}return AM(e)}function TM(t,e){return e?t.flatMap(r=>{const n=r.name.toLowerCase().includes(e)||r.path.toLowerCase().includes(e);if(!r.isDir)return n?[r]:[];if(n)return[r];const i=TM(r.children,e);return i.length?[{...r,children:i}]:[]}):t}function Ow(t){const e=new Set;for(const r of t)if(r.isDir){e.add(r.path);for(const n of Ow(r.children))e.add(n)}return e}function Hne(t){const e=t.split("/").filter(Boolean),r=[];let n="";for(const i of e.slice(0,-1))n=n?`${n}/${i}`:i,r.push(n);return r}function jM({node:t,depth:e,selectedPage:r,expandedPaths:n,autoExpandedPaths:i,onToggle:a,onSelect:o,onAddToFolder:c,onDeleteFolder:u}){const d=r===t.path,p=t.isDir&&(n.has(t.path)||i.has(t.path)),f=12+e*16,g=t.isDir&&["io","shared","squads","templates"].includes(t.path);return t.isDir?y.jsxs("div",{children:[y.jsxs("div",{className:"flex w-full items-center group rounded-lg py-2 pr-3 text-left text-[11px] font-mono text-zinc-400 transition-colors hover:bg-white/[0.04] hover:text-zinc-200",style:{paddingLeft:f},children:[y.jsxs("button",{type:"button",onClick:()=>a(t.path),className:"flex items-center gap-2 flex-1 min-w-0",children:[y.jsx(Mw,{size:14,className:`shrink-0 transition-transform ${p?"rotate-90":""}`}),p?y.jsx(l4,{size:14,className:"shrink-0 text-zinc-500"}):y.jsx(u4,{size:14,className:"shrink-0 text-zinc-500"}),y.jsx("span",{className:"truncate",children:t.name})]}),y.jsxs("div",{className:"flex items-center gap-0.5",children:[!g&&y.jsx("button",{type:"button",onClick:v=>{v.stopPropagation(),u(t.path)},className:"opacity-0 group-hover:opacity-100 p-0.5 rounded hover:bg-red-500/20 transition-opacity text-zinc-600 hover:text-red-400",title:`Delete ${t.name}`,children:y.jsx(Ma,{size:12})}),y.jsx("button",{type:"button",onClick:v=>{v.stopPropagation(),c(t.path)},className:"opacity-0 group-hover:opacity-100 p-0.5 rounded hover:bg-white/[0.08] transition-opacity text-zinc-600 hover:text-zinc-300",title:`Add page to ${t.name}`,children:y.jsx(Bw,{size:12})})]})]}),p&&y.jsx("div",{children:t.children.map(v=>y.jsx(jM,{node:v,depth:e+1,selectedPage:r,expandedPaths:n,autoExpandedPaths:i,onToggle:a,onSelect:o,onAddToFolder:c,onDeleteFolder:u},v.path))})]}):y.jsxs("button",{type:"button",onClick:()=>o(t.path),className:`flex w-full items-center gap-2 rounded-lg py-2 pr-3 text-left text-[11px] font-mono transition-colors ${d?"border-l-2 border-[#E43A9C] bg-[#E43A9C]/10 text-[#E43A9C]":"text-zinc-500 hover:bg-white/[0.04] hover:text-zinc-300"}`,style:{paddingLeft:f},children:[y.jsx(o4,{size:14,className:"shrink-0"}),y.jsx("span",{className:"truncate",children:t.name})]})}function Wne(){const[t,e]=N.useState([]),[r,n]=N.useState(null),[i,a]=N.useState(""),[o,c]=N.useState(!1),[u,d]=N.useState(""),[p,f]=N.useState(""),[g,v]=N.useState(""),[x,w]=N.useState(new Set),[b,S]=N.useState(!1),[A,O]=N.useState(null),j=N.useRef(null);N.useEffect(()=>{F()},[]);const E=N.useMemo(()=>Fne(t),[t]),T=g.trim().toLowerCase(),P=N.useMemo(()=>TM(E,T),[E,T]),R=N.useMemo(()=>{const I=T?Ow(P):new Set;if(r)for(const $ of Hne(r))I.add($);return I},[P,T,r]),M=r?(function I($){for(const V of $){if(V.path===r)return V;const oe=I(V.children);if(oe)return oe}return null})(P):null,J=(M==null?void 0:M.name)??(r?r.split("/").pop()??"":"");N.useEffect(()=>{const I=Ow(E);w($=>new Set([...$,...I]))},[E]);async function F(){try{const I=await Ve.get("/wiki/all");e(I.pages)}catch{e([])}}function B(I){if(I.startsWith("squads/")){const $=I.split("/"),V=$[1]??"",oe=$.slice(2).join("/");return{scope:V,relativePath:oe}}return I.startsWith("templates/")?{scope:"templates",relativePath:I.slice(10)}:I.startsWith("io/")?{scope:"io",relativePath:I.slice(3)}:I.startsWith("shared/")?{scope:"shared",relativePath:I.slice(7)}:{scope:"shared",relativePath:I}}async function K(I){try{const{scope:$,relativePath:V}=B(I),oe=await Ve.get(`/wiki/${$}/${V}`);a(oe.content),d(oe.content),n(I),c(!1)}catch{at.error("Failed to load page")}}async function W(){if(r)try{const{scope:I,relativePath:$}=B(r);await Ve.put(`/wiki/${I}/${$}`,{content:u}),a(u),c(!1),at.success("Page saved")}catch{at.error("Failed to save page")}}async function X(){if(r)try{const{scope:I,relativePath:$}=B(r);await Ve.delete(`/wiki/${I}/${$}`),at.success("Page deleted"),n(null),a(""),d(""),c(!1),F()}catch{at.error("Failed to delete page")}}function Y(I){f(`${I}/`),setTimeout(()=>{const $=j.current;$&&($.focus(),$.setSelectionRange($.value.length,$.value.length))},0)}function te(I){O(I)}async function H(){if(A)try{await Ve.delete(`/wiki/dir/${A}`),at.success(`Deleted ${A}`),r!=null&&r.startsWith(A)&&(n(null),a(""),d(""),c(!1)),F()}catch{at.error("Failed to delete directory")}finally{O(null)}}async function Q(){let I=p.trim().replace(/^\/+|\/+$/g,"");if(!I)return;I=I.replace(/\.md$/i,"");const $=I.startsWith("io/")||I.startsWith("shared/")||I.startsWith("squads/")?I:`shared/${I}`;S(!0);try{const{scope:V,relativePath:oe}=B($),le=oe.split("/").slice(-1)[0]??oe;await Ve.put(`/wiki/${V}/${oe}`,{content:`# ${le}
|
|
503
503
|
|
|
504
|
-
`}),at.success("Page created"),f(""),await F(),await K($)}catch{at.error("Failed to create page")}finally{S(!1)}}function U(I){w($=>{const V=new Set($);return V.has(I)?V.delete(I):V.add(I),V})}return y.jsxs("div",{className:"flex h-full",children:[y.jsxs("div",{className:"flex h-full w-64 flex-col border-r border-white/[0.07] bg-[#181818]",children:[y.jsx("div",{className:"border-b border-white/[0.07] p-3",children:y.jsxs("div",{className:"relative",children:[y.jsx(rP,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-zinc-600"}),y.jsx("input",{type:"text",value:g,onChange:I=>v(I.target.value),placeholder:"Search pages...",className:"w-full rounded-lg border border-white/[0.07] bg-white/[0.04] py-2 pl-8 pr-3 text-[11px] font-mono text-zinc-300 outline-none placeholder:text-zinc-700 focus:border-[#E43A9C]/50"})]})}),y.jsx("div",{className:"flex-1 overflow-y-auto px-2 py-3",children:P.length>0?P.map(I=>y.jsx(jM,{node:I,depth:0,selectedPage:r,expandedPaths:x,autoExpandedPaths:R,onToggle:U,onSelect:K,onAddToFolder:Y,onDeleteFolder:te},I.path)):y.jsx("p",{className:"py-4 text-center font-mono text-[11px] text-zinc-700",children:"No pages found"})}),y.jsx("div",{className:"border-t border-white/[0.07] p-3",children:y.jsxs("div",{className:"space-y-2",children:[y.jsx("input",{ref:j,type:"text",value:p,onChange:I=>f(I.target.value),onKeyDown:I=>{I.key==="Enter"&&Q(),I.key==="Escape"&&f("")},placeholder:"folder/new-page",className:"w-full rounded-lg border border-white/[0.07] bg-white/[0.04] px-3 py-2 text-[11px] font-mono text-zinc-300 outline-none placeholder:text-zinc-700 focus:border-[#E43A9C]/50"}),y.jsx(za,{onClick:Q,disabled:!p.trim()||b,className:"w-full justify-center px-3 py-2",children:b?y.jsxs(y.Fragment,{children:[y.jsx(js,{size:13,className:"animate-spin"})," Creating..."]}):y.jsxs(y.Fragment,{children:[y.jsx(Bw,{size:13})," Add Page"]})})]})})]}),y.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:r?y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:"flex h-14 shrink-0 items-center justify-between border-b border-white/[0.07] px-6",children:[y.jsxs("div",{className:"min-w-0",children:[y.jsx("h3",{className:"truncate font-mono text-sm text-zinc-100",children:J}),y.jsxs("p",{className:"truncate font-mono text-[11px] text-zinc-500",children:[r,".md"]})]}),y.jsxs("div",{className:"flex items-center gap-2",children:[o?y.jsxs(y.Fragment,{children:[y.jsxs(za,{onClick:W,className:"px-3 py-1.5",children:[y.jsx(Uw,{size:12})," Save"]}),y.jsx(_i,{onClick:()=>{c(!1),d(i)},className:"px-3 py-1.5",children:"Cancel"})]}):y.jsxs(_i,{onClick:()=>{c(!0),d(i)},className:"px-3 py-1.5",children:[y.jsx(Ub,{size:12})," Edit"]}),y.jsxs(
|
|
505
|
-
//# sourceMappingURL=index-
|
|
504
|
+
`}),at.success("Page created"),f(""),await F(),await K($)}catch{at.error("Failed to create page")}finally{S(!1)}}function U(I){w($=>{const V=new Set($);return V.has(I)?V.delete(I):V.add(I),V})}return y.jsxs("div",{className:"flex h-full",children:[y.jsxs("div",{className:"flex h-full w-64 flex-col border-r border-white/[0.07] bg-[#181818]",children:[y.jsx("div",{className:"border-b border-white/[0.07] p-3",children:y.jsxs("div",{className:"relative",children:[y.jsx(rP,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-zinc-600"}),y.jsx("input",{type:"text",value:g,onChange:I=>v(I.target.value),placeholder:"Search pages...",className:"w-full rounded-lg border border-white/[0.07] bg-white/[0.04] py-2 pl-8 pr-3 text-[11px] font-mono text-zinc-300 outline-none placeholder:text-zinc-700 focus:border-[#E43A9C]/50"})]})}),y.jsx("div",{className:"flex-1 overflow-y-auto px-2 py-3",children:P.length>0?P.map(I=>y.jsx(jM,{node:I,depth:0,selectedPage:r,expandedPaths:x,autoExpandedPaths:R,onToggle:U,onSelect:K,onAddToFolder:Y,onDeleteFolder:te},I.path)):y.jsx("p",{className:"py-4 text-center font-mono text-[11px] text-zinc-700",children:"No pages found"})}),y.jsx("div",{className:"border-t border-white/[0.07] p-3",children:y.jsxs("div",{className:"space-y-2",children:[y.jsx("input",{ref:j,type:"text",value:p,onChange:I=>f(I.target.value),onKeyDown:I=>{I.key==="Enter"&&Q(),I.key==="Escape"&&f("")},placeholder:"folder/new-page",className:"w-full rounded-lg border border-white/[0.07] bg-white/[0.04] px-3 py-2 text-[11px] font-mono text-zinc-300 outline-none placeholder:text-zinc-700 focus:border-[#E43A9C]/50"}),y.jsx(za,{onClick:Q,disabled:!p.trim()||b,className:"w-full justify-center px-3 py-2",children:b?y.jsxs(y.Fragment,{children:[y.jsx(js,{size:13,className:"animate-spin"})," Creating..."]}):y.jsxs(y.Fragment,{children:[y.jsx(Bw,{size:13})," Add Page"]})})]})})]}),y.jsx("div",{className:"flex flex-1 flex-col overflow-hidden",children:r?y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:"flex h-14 shrink-0 items-center justify-between border-b border-white/[0.07] px-6",children:[y.jsxs("div",{className:"min-w-0",children:[y.jsx("h3",{className:"truncate font-mono text-sm text-zinc-100",children:J}),y.jsxs("p",{className:"truncate font-mono text-[11px] text-zinc-500",children:[r,".md"]})]}),y.jsxs("div",{className:"flex items-center gap-2",children:[o?y.jsxs(y.Fragment,{children:[y.jsxs(za,{onClick:W,className:"px-3 py-1.5",children:[y.jsx(Uw,{size:12})," Save"]}),y.jsx(_i,{onClick:()=>{c(!1),d(i)},className:"px-3 py-1.5",children:"Cancel"})]}):y.jsxs(_i,{onClick:()=>{c(!0),d(i)},className:"px-3 py-1.5",children:[y.jsx(Ub,{size:12})," Edit"]}),y.jsxs(Bf,{onClick:X,className:"px-3 py-1.5",children:[y.jsx(Ma,{size:12})," Delete"]})]})]}),y.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:o?y.jsx("textarea",{value:u,onChange:I=>d(I.target.value),className:"h-full min-h-[320px] w-full resize-none rounded-xl border border-white/[0.07] bg-[#181818] p-4 font-mono text-sm text-zinc-300 outline-none focus:border-[#E43A9C]/50"}):y.jsx("div",{className:"mx-auto max-w-4xl",children:y.jsx("div",{className:"prose-io text-sm text-zinc-300",dangerouslySetInnerHTML:{__html:nt.parse(i)}})})})]}):y.jsx("div",{className:"flex h-full items-center justify-center",children:y.jsxs("div",{className:"text-center",children:[y.jsx(XN,{size:48,className:"mx-auto mb-3 text-zinc-800"}),y.jsx("p",{className:"font-mono text-[11px] text-zinc-700",children:"Select a page to view"})]})})}),A&&y.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",children:y.jsxs("div",{className:"w-full max-w-sm rounded-2xl border border-white/[0.07] bg-[#1a1a1a] p-6 shadow-2xl",children:[y.jsx("h3",{className:"mb-2 text-sm font-medium text-zinc-100",children:"Delete directory?"}),y.jsxs("p",{className:"mb-4 text-xs text-zinc-400",children:["This will permanently delete ",y.jsx("span",{className:"font-mono text-zinc-200",children:A})," and all its contents."]}),y.jsxs("div",{className:"flex justify-end gap-2",children:[y.jsx(_i,{onClick:()=>O(null),className:"px-3 py-1.5",children:"Cancel"}),y.jsxs(Bf,{onClick:H,className:"px-3 py-1.5",children:[y.jsx(Ma,{size:12})," Delete"]})]})]})})]})}function Gne({children:t}){const{session:e,supabase:r,loading:n}=sp();return n?y.jsx("div",{className:"min-h-screen flex items-center justify-center text-[var(--color-muted-foreground)]",children:"Loading..."}):r?e?y.jsx(y.Fragment,{children:t}):y.jsx(vq,{}):y.jsx(y.Fragment,{children:t})}function Kne(){const{pathname:t}=ti(),e=t==="/"||t==="/chat"||t.startsWith("/chat/");return y.jsxs(y.Fragment,{children:[y.jsx(bD,{children:y.jsxs(nn,{element:y.jsx(pq,{}),children:[y.jsx(nn,{index:!0,element:y.jsx(mq,{})}),y.jsx(nn,{path:"squads",element:y.jsx($g,{})}),y.jsx(nn,{path:"squads/:name",element:y.jsx($g,{})}),y.jsx(nn,{path:"squads/:name/instances/:instanceId",element:y.jsx($g,{})}),y.jsx(nn,{path:"feed",element:y.jsx(yq,{})}),y.jsx(nn,{path:"skills",element:y.jsx(jq,{})}),y.jsx(nn,{path:"schedules",element:y.jsx(wq,{})}),y.jsx(nn,{path:"wiki",element:y.jsx(Wne,{})}),y.jsx(nn,{path:"settings",element:y.jsx(Eq,{})}),y.jsx(nn,{path:"usage",element:y.jsx(qne,{})}),y.jsx(nn,{path:"*",element:y.jsx(gD,{to:"/",replace:!0})})]})}),!e&&y.jsx(gB,{})]})}function Vne(){return y.jsx(dq,{children:y.jsx(Gne,{children:y.jsx(Z4,{children:y.jsx(cz,{children:y.jsx(Kne,{})})})})})}gL.createRoot(document.getElementById("root")).render(y.jsx(N.StrictMode,{children:y.jsxs(FD,{children:[y.jsx(Vne,{}),y.jsx(O5,{theme:"dark",position:"bottom-right"})]})}));
|
|
505
|
+
//# sourceMappingURL=index-DJBKkz8R.js.map
|